2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MT4/MT5のHTMLレポートをJavaScriptでパースする方法

2
Posted at

はじめに

MetaTrader 4/5 は取引履歴を HTML 形式でエクスポートできます。
このHTMLをJavaScriptでパースしてグラフ化する実装を解説します。

MT4 HTMLレポートの構造

MT4のHTMLレポートはテーブル形式で取引履歴が格納されています。

<table>
  <tr>
    <td>2024.01.15 09:30</td>  <!-- 日時 -->
    <td>123456789</td>          <!-- チケット番号 -->
    <td>buy</td>                <!-- 売買 -->
    <td>0.10</td>               <!-- ロット数 -->
    <td>USDJPY</td>             <!-- 通貨ペア -->
    <td>147.50</td>             <!-- 開始価格 -->
    <td>148.20</td>             <!-- 終了価格 -->
    <td>7000</td>               <!-- 損益(円) -->
  </tr>
</table>

DOMParser を使ったパース

export function parseMT4Html(htmlString) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, 'text/html')
  const rows = doc.querySelectorAll('table tr')
  const trades = []

  rows.forEach(row => {
    const cells = row.querySelectorAll('td')
    if (cells.length < 8) return

    const type = cells[2].textContent.trim().toLowerCase()
    if (!['buy', 'sell'].includes(type)) return

    trades.push({
      openTime:  parseDate(cells[0].textContent.trim()),
      ticket:    cells[1].textContent.trim(),
      type,
      lots:      parseFloat(cells[3].textContent),
      symbol:    cells[4].textContent.trim(),
      openPrice: parseFloat(cells[5].textContent),
      closePrice: parseFloat(cells[6].textContent),
      profit:    parseFloat(cells[7].textContent.replace(/,/g, '')),
    })
  })

  return trades
}

エクイティカーブの計算

export function calcEquityCurve(trades, initialBalance = 100000) {
  let balance = initialBalance
  return trades
    .sort((a, b) => a.closeTime - b.closeTime)
    .map(trade => {
      balance += trade.profit
      return { time: trade.closeTime, balance }
    })
}

まとめ

DOMParser を使えばブラウザだけでHTMLレポートをパースできます。
サーバーサイドの処理が不要なので、純粋なフロントエンドアプリとして実装できました。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?