strategy.equity and netprofit in MQL5: account values

Short answer

Read the account: strategy.equity is AccountInfoDouble(ACCOUNT_EQUITY), strategy.openprofit is AccountInfoDouble(ACCOUNT_PROFIT), and strategy.netprofit is ACCOUNT_BALANCE minus the balance your EA recorded in OnInit. They are in the account's deposit currency.

strategy.equity is the simulated account's value including open trades; strategy.netprofit is the profit of closed trades; strategy.openprofit is the floating profit of open trades; and strategy.initial_capital is the starting balance. In MQL5 the account itself supplies them: AccountInfoDouble(ACCOUNT_EQUITY), AccountInfoDouble(ACCOUNT_PROFIT), and AccountInfoDouble(ACCOUNT_BALANCE) minus the balance your EA recorded in OnInit. They are in the account's deposit currency, not the strategy's currency.

What strategy.equity and netprofit compute

The emulator keeps one identity: strategy.equity = strategy.initial_capital + strategy.netprofit + strategy.openprofit. netprofit changes only when a trade closes and includes commission; openprofit is marked to the current bar's close, so it moves on every bar while a trade is open and is 0 when flat. Values are in the currency argument of strategy(), which defaults to the symbol's currency; TradingView converts the trade results with the daily rate when it differs. Because the script runs once per bar, all four are snapshots at bar close. Scripts use them for equity-based guards, as in the drawdown example below, and for sizing.

The MQL5 equivalent

//@version=6
strategy("Equity guard demo", overlay = true, initial_capital = 10000, default_qty_type = strategy.fixed, default_qty_value = 1)
maxDdPct = input.float(15.0, "Max drawdown %")
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
// equity = initial_capital + netprofit + openprofit
var float peak = strategy.initial_capital
peak := math.max(peak, strategy.equity)
drawdownPct = (peak - strategy.equity) / peak * 100
halted = drawdownPct >= maxDdPct
if halted
    strategy.close_all()
if ta.crossover(fast, slow) and not halted
    strategy.entry("L", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("L")
realized = strategy.netprofit
floating = strategy.openprofit

The EA records the starting balance and equity in OnInit, because MetaTrader has no concept of a strategy's own capital: the account is the strategy's account. Its NetProfit is the balance change since the EA started, which equals closed-trade profit only when nothing else trades on the account and no deposits or withdrawals happen.

#include <Trade/Trade.mqh>
input double InpLots     = 0.10;
input double InpMaxDdPct = 15.0;    // Max drawdown %
input long   InpMagic    = 60020;
CTrade trade;
int    hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE;
double startBalance = 0.0;          // strategy.initial_capital
double peakEquity   = 0.0;

int OnInit()
  {
   hFast = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
   hSlow = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
   if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
      return INIT_FAILED;
   trade.SetExpertMagicNumber(InpMagic);
   trade.SetTypeFillingBySymbol(_Symbol);
   // MT5 has no "initial capital": remember the balance the EA started with
   startBalance = AccountInfoDouble(ACCOUNT_BALANCE);
   peakEquity   = AccountInfoDouble(ACCOUNT_EQUITY);
   return INIT_SUCCEEDED;
  }

bool IsNewBar()
  {
   static datetime last = 0;
   const datetime t = iTime(_Symbol, _Period, 0);
   if(t == last)
      return false;
   last = t;
   return true;
  }

// strategy.equity      -> ACCOUNT_EQUITY   (balance + floating P&L)
// strategy.openprofit  -> ACCOUNT_PROFIT   (floating P&L of open positions)
// strategy.netprofit   -> balance now - balance at start (realised P&L)
double Equity()     { return AccountInfoDouble(ACCOUNT_EQUITY); }
double OpenProfit() { return AccountInfoDouble(ACCOUNT_PROFIT); }
double NetProfit()  { return AccountInfoDouble(ACCOUNT_BALANCE) - startBalance; }

void CloseAll()
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      const ulong ticket = PositionGetTicket(i);
      if(ticket != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
         && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         trade.PositionClose(ticket);
     }
  }

void OnTick()
  {
   if(!IsNewBar())
      return;
   double f[2], s[2];
   if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2)
      return;
   peakEquity = MathMax(peakEquity, Equity());
   const double drawdownPct = (peakEquity - Equity()) / peakEquity * 100.0;
   const bool halted = drawdownPct >= InpMaxDdPct;
   if(halted)
      CloseAll();
   if(f[1] > s[1] && f[0] <= s[0] && !halted && PositionsTotal() == 0)
      trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
   if(f[1] < s[1] && f[0] >= s[0])
      CloseAll();
   Comment(StringFormat("equity %.2f  net %.2f  open %.2f  dd %.1f%% %s %s",
           Equity(), NetProfit(), OpenProfit(), drawdownPct,
           AccountInfoString(ACCOUNT_CURRENCY), halted ? "HALTED" : ""));
  }

startBalance resets whenever the EA is re-initialised (timeframe change, terminal restart). In live trading store it in a global variable of the terminal (GlobalVariableSet) if the guard must survive restarts, or compute closed profit from the deal history filtered by magic number instead.

Where the two differ

PineMQL5Difference
strategy.equityACCOUNT_EQUITYMT5 marks open positions to the current bid/ask, every tick; Pine to the bar close
strategy.openprofitACCOUNT_PROFITaccount-wide, all symbols; per position: POSITION_PROFIT
strategy.netprofitbalance − start balanceincludes deposits, withdrawals, swaps and other EAs unless you sum deals by magic
strategy.initial_capitaltester Deposit, or the balance recorded in OnInitno built-in value
CurrencyACCOUNT_CURRENCYPine uses strategy(currency=...); MT5 converts each deal to the deposit currency at the time of the deal
Commissionseparate DEAL_COMMISSIONPine nets it into profit; MT5 balance includes it, DEAL_PROFIT does not

What the Stratlate converter emits

The converter emits strategy.equity as AccountEquity(), a runtime shim for AccountInfoDouble(ACCOUNT_EQUITY). Both strategy.openprofit and strategy.netprofit are emitted as (AccountEquity() - AccountBalance()), which is the floating profit of open positions: correct for openprofit, but for netprofit it is not the realised profit Pine means, and it is not flagged in the report. strategy.initial_capital is emitted as AccountBalance(), the current balance, not the starting one. In the script above that makes var float peak = strategy.initial_capital start at the current balance, which is the same thing on the first bar, so the drawdown guard still works. A script that reads strategy.netprofit or compares against strategy.initial_capital later in the run should be reviewed by hand against the helpers shown here, then compiled and backtested.

Pitfalls

  • Using ACCOUNT_PROFIT as net profit. Symptom: the "profit target reached" condition is true only while a trade is open and resets to 0 when it closes.
  • Running a balance-based guard on an account with several EAs. Symptom: another EA's losses halt this one.
  • Comparing equity with Pine's in a different currency. Symptom: a EUR deposit in the tester against a USD strategy shows the same trades but different P&L every day.
  • Forgetting Pine's default initial_capital of 1,000,000. Symptom: percentage guards that never trigger in Pine trigger at once on a 10,000 tester deposit.

FAQ

What is the MQL5 equivalent of strategy.equity?

AccountInfoDouble(ACCOUNT_EQUITY): balance plus the floating profit of every open position on the account. It updates on every tick, not once per bar.

How do I get only my EA's net profit?

Select the history with HistorySelect, loop the deals, keep those with your DEAL_MAGIC and symbol, and sum DEAL_PROFIT + DEAL_SWAP + DEAL_COMMISSION. That ignores deposits and other EAs.

Why do Pine and MT5 report different profit for the same trades?

Spread and actual fill prices, commission rules, swap on positions held overnight, and currency conversion. Compare the trade list first; once entries and exits match, the remaining difference is costs.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related