strategy.opentrades and closedtrades in MQL5
Short answer
Open trades are positions, read with PositionsTotal(), PositionGetTicket(i) and PositionGetDouble. Closed trades are deals in the account history, read with HistorySelect, HistoryDealsTotal() and HistoryDealGetDouble, keeping the closing deals (DEAL_ENTRY_OUT).
strategy.opentrades is the number of trades currently open and strategy.closedtrades the number already closed; the strategy.opentrades.*(n) and strategy.closedtrades.*(n) functions read one trade's entry price, exit price, size, profit and times, with index 0 the oldest. In MQL5 open trades are positions, read with PositionsTotal(), PositionGetTicket(i) and PositionGetDouble; closed trades are deals in the account history, read with HistorySelect, HistoryDealsTotal() and HistoryDealGetDouble, keeping the closing deals (DEAL_ENTRY_OUT).
What strategy.opentrades and closedtrades compute
Pine records a trade per entry fill. With pyramiding = 3 three long entries are three open trades, even though the net position is one. A partial close splits a trade: the closed part becomes a closed trade and the remainder stays open. Indexes run oldest first, so the most recent closed trade is strategy.closedtrades - 1; an index past the end returns na. Each accessor is per trade: entry_price, exit_price, size (signed: negative for a short), profit (in the strategy's currency, after commission), entry_time/exit_time in milliseconds and entry_bar_index/exit_bar_index. Counts change when the fills happen, at the next bar's open by default. Scripts use them for loss streak filters, as in the example, and for reading the current trade's entry.
The MQL5 equivalent
//@version=6
strategy("Trade history demo", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
// pause after three consecutive losing trades
lastN = 3
losses = 0
for i = 0 to lastN - 1
idx = strategy.closedtrades - 1 - i
if idx >= 0 and strategy.closedtrades.profit(idx) < 0
losses += 1
paused = losses == lastN
if ta.crossover(fast, slow) and not paused
strategy.entry("L", strategy.long)
if ta.crossunder(fast, slow)
strategy.close("L")
// facts about the open trade
inTrade = strategy.opentrades > 0
entry = inTrade ? strategy.opentrades.entry_price(0) : na
floating = inTrade ? strategy.opentrades.profit(0) : naThe EA's OpenTrades collects this EA's position tickets oldest first, and ClosedTrades walks the deal history and keeps one profit per closing deal, adding swap and commission so the number is comparable with Pine's net trade profit.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 60019;
input int InpLastN = 3; // pause after this many losses in a row
CTrade trade;
int hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE;
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);
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.opentrades: this EA's open positions on this symbol, oldest
// first. Fills `tickets`; returns the count.
int OpenTrades(ulong &tickets[])
{
ArrayResize(tickets, 0);
for(int i = 0; i < PositionsTotal(); i++)
{
const ulong t = PositionGetTicket(i);
if(t != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic)
{
const int n = ArraySize(tickets);
ArrayResize(tickets, n + 1);
tickets[n] = t;
}
}
return ArraySize(tickets);
}
// strategy.closedtrades and closedtrades.profit(i): every closing deal
// (DEAL_ENTRY_OUT or DEAL_ENTRY_INOUT) of this EA on this symbol, oldest
// first, with profit + swap + commission as Pine's trade profit.
int ClosedTrades(double &profits[])
{
ArrayResize(profits, 0);
if(!HistorySelect(0, TimeCurrent()))
return 0;
for(int i = 0; i < HistoryDealsTotal(); i++)
{
const ulong d = HistoryDealGetTicket(i);
if(d == 0 || HistoryDealGetString(d, DEAL_SYMBOL) != _Symbol
|| HistoryDealGetInteger(d, DEAL_MAGIC) != InpMagic)
continue;
const ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(d, DEAL_ENTRY);
if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_INOUT)
continue;
const int n = ArraySize(profits);
ArrayResize(profits, n + 1);
profits[n] = HistoryDealGetDouble(d, DEAL_PROFIT)
+ HistoryDealGetDouble(d, DEAL_SWAP)
+ HistoryDealGetDouble(d, DEAL_COMMISSION);
}
return ArraySize(profits);
}
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;
// consecutive losses among the last N closed trades
double profits[];
const int closed = ClosedTrades(profits);
int losses = 0;
for(int i = 0; i < InpLastN; i++)
{
const int idx = closed - 1 - i;
if(idx >= 0 && profits[idx] < 0)
losses++;
}
const bool paused = losses == InpLastN;
ulong open[];
const int nOpen = OpenTrades(open);
if(f[1] > s[1] && f[0] <= s[0] && !paused && nOpen == 0)
trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
if(f[1] < s[1] && f[0] >= s[0])
for(int i = nOpen - 1; i >= 0; i--)
trade.PositionClose(open[i]);
// strategy.opentrades.entry_price(0) and .profit(0)
if(nOpen > 0 && PositionSelectByTicket(open[0]))
Comment("entry ", DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), _Digits),
" floating ", DoubleToString(PositionGetDouble(POSITION_PROFIT), 2),
" closed trades ", closed, paused ? " PAUSED" : "");
}History has to be loaded with HistorySelect(from, to) before HistoryDealsTotal() means anything; HistorySelect(0, TimeCurrent()) loads all of it. On a long-running live account that loop grows with every trade, so cache the count and only rescan when it changes, or narrow the date range.
Where the two differ
| Topic | Pine | MQL5 |
|---|---|---|
| Open trade | one per entry fill | hedging: one position per entry; netting: one position per symbol however many entries |
| Closed trade | one per closed entry (or part) | one DEAL_ENTRY_OUT deal per close; a netting reversal is a single DEAL_ENTRY_INOUT deal |
| Profit | after commission | DEAL_PROFIT excludes it; add DEAL_COMMISSION and DEAL_SWAP |
| Size | signed contracts | DEAL_VOLUME/POSITION_VOLUME, unsigned lots; sign from the type |
| Entry price of a closed trade | stored on the trade | on the opening deal: match DEAL_POSITION_ID of the closing deal to a DEAL_ENTRY_IN deal |
| Times | milliseconds | seconds (datetime) |
| Scope | this strategy | the whole account; filter by DEAL_SYMBOL and DEAL_MAGIC |
| Missing index | na | array out of range unless you check |
What the Stratlate converter emits
The converter routes both counters through the runtime: strategy.opentrades becomes pine_opentrades_total(), which is PositionsTotal() in MQL5, and strategy.closedtrades becomes pine_closedtrades_total(), which selects the full history and counts DEAL_ENTRY_OUT deals. Each accessor becomes a helper of the same name, for example strategy.closedtrades.profit(idx) → pine_closedtrade_profit((int)(idx)), which returns the n-th closing deal's DEAL_PROFIT, and strategy.opentrades.entry_price(0) → pine_opentrade_entry_price((int)(0)), which reads POSITION_PRICE_OPEN; an index past the end returns the runtime's na. These are treated as exact and the script above converts CLEAN. Three things to know when comparing: the helpers do not filter by symbol or magic number, closed-trade profit is DEAL_PROFIT without commission or swap, and a netting-account reversal (DEAL_ENTRY_INOUT) is not counted. Compile and backtest the output before trading it.
Pitfalls
- Calling
HistoryDealsTotal()withoutHistorySelect. Symptom: it returns 0 and the loss-streak filter never triggers. - Counting every deal instead of closing deals. Symptom:
closedtradesis roughly twice Pine's, because opening deals and balance operations are in the same pool. - Comparing
DEAL_PROFITwith Pine's trade profit on a broker that charges commission. Symptom: small winners in MT5 are small losers in Pine, or the reverse. - Indexing
profits[closed - 1 - i]without theidx >= 0check. Symptom: "array out of range" in the first trades of a backtest. - Expecting several open trades on a netting account. Symptom:
opentradesstays at 1 while Pine shows 3 pyramided entries.
FAQ
What is the MQL5 equivalent of strategy.closedtrades?
The number of closing deals of your EA in the account history: HistorySelect(0, TimeCurrent()), then loop HistoryDealsTotal() and count deals whose DEAL_ENTRY is DEAL_ENTRY_OUT (and DEAL_ENTRY_INOUT for netting reversals), filtered by symbol and magic.
How do I get the entry price of a closed trade in MQL5?
Take the closing deal's DEAL_POSITION_ID, find the deal with the same position id and DEAL_ENTRY_IN, and read its DEAL_PRICE. The closing deal's own DEAL_PRICE is the exit price.
Is strategy.opentrades the same as PositionsTotal()?
Only on a hedging account with no other positions. PositionsTotal() counts every open position in the account on every symbol, and on a netting account several entries share one position.
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