strategy() in MQL5: declaration arguments as EA inputs
Short answer
An MQL5 Expert Advisor has no strategy() declaration. Sizing, pyramiding and slippage become input variables enforced in code; initial_capital and commission become Strategy Tester and broker settings; calc_on_every_tick and process_orders_on_close are reproduced by how OnTick is structured.
The strategy() declaration configures TradingView's broker emulator: how big orders are, how many may stack, what the simulated account starts with and what it pays per trade. An MQL5 Expert Advisor has no such declaration. The arguments split three ways: sizing, pyramiding and slippage become input variables that you enforce in code; initial_capital and commission become Strategy Tester and broker settings; overlay, calc_on_every_tick and process_orders_on_close describe behaviour that your OnTick structure must reproduce.
What strategy() computes
The declaration is evaluated once and sets the emulator's rules for the whole run:
initial_capital(default 1,000,000 incurrency) is the starting balance thatstrategy.equityand percent-of-equity sizing build on.default_qty_type(strategy.fixed,strategy.cashorstrategy.percent_of_equity) anddefault_qty_value(default 1) size everystrategy.entryorstrategy.orderthat passes noqty.pyramiding(default 0) is the number of entries allowed in the same direction; 0 and 1 both mean one.commission_typeandcommission_valuecharge a percentage, an amount per contract or an amount per order on every fill;slippagemoves every market and stop fill against you by that many ticks.calc_on_every_tick(default false) andprocess_orders_on_close(default false) decide when the script runs and when its orders fill: by default on bar close, with fills at the next bar's open.
The MQL5 equivalent
//@version=6
strategy("MA cross", overlay = true, initial_capital = 10000,
default_qty_type = strategy.fixed, default_qty_value = 1,
pyramiding = 1, commission_type = strategy.commission.percent,
commission_value = 0.05, slippage = 2,
calc_on_every_tick = false, process_orders_on_close = false)
fastLen = input.int(10, "Fast")
slowLen = input.int(30, "Slow")
fast = ta.sma(close, fastLen)
slow = ta.sma(close, slowLen)
if ta.crossover(fast, slow)
strategy.entry("L", strategy.long)
if ta.crossunder(fast, slow)
strategy.close("L")The same strategy as an EA. Every declaration argument that affects trading is now either an input or a comment telling the tester operator what to set:
// strategy("MA cross", overlay = true, initial_capital = 10000,
// default_qty_type = strategy.fixed, default_qty_value = 1,
// pyramiding = 1, commission_type = strategy.commission.percent,
// commission_value = 0.05, slippage = 2)
// -> the inputs below. initial_capital and commission are Strategy Tester
// settings, not code. overlay has no meaning for an EA.
#include <Trade/Trade.mqh>
input double InpLots = 0.10; // default_qty_value, in lots
input int InpPyramiding = 1; // pyramiding: max entries per direction
input int InpDeviation = 20; // slippage, in points
input long InpMagic = 60011; // marks this EA's own trades
input int InpFast = 10; // Fast
input int InpSlow = 30; // Slow
CTrade trade;
int hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE;
int OnInit()
{
hFast = iMA(_Symbol, _Period, InpFast, 0, MODE_SMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, InpSlow, 0, MODE_SMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(InpMagic);
trade.SetDeviationInPoints(InpDeviation);
trade.SetTypeFillingBySymbol(_Symbol);
return INIT_SUCCEEDED;
}
// calc_on_every_tick = false: evaluate once, on the first tick of a new bar
bool IsNewBar()
{
static datetime last = 0;
const datetime t = iTime(_Symbol, _Period, 0);
if(t == last)
return false;
last = t;
return true;
}
// how many of this EA's positions of one type are open on this symbol
int OwnPositions(const ENUM_POSITION_TYPE type)
{
int n = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(PositionGetTicket(i) == 0)
continue;
if(PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic
&& PositionGetInteger(POSITION_TYPE) == type)
n++;
}
return n;
}
void OnTick()
{
if(!IsNewBar())
return;
double f[2], s[2]; // shift 1 and 2, returned oldest first
if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2)
return;
const bool crossUp = f[1] > s[1] && f[0] <= s[0];
const bool crossDown = f[1] < s[1] && f[0] >= s[0];
// strategy.entry("L", strategy.long), limited by pyramiding
if(crossUp && OwnPositions(POSITION_TYPE_BUY) < InpPyramiding)
trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
// strategy.close("L")
if(crossDown)
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
const ulong ticket = PositionGetTicket(i);
if(ticket != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic
&& PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
trade.PositionClose(ticket);
}
}In the Strategy Tester, set Deposit to 10000 (the initial_capital) and the deposit currency to the strategy's currency. The tester charges whatever commission the symbol specification carries; to model Pine's commission_value exactly, create a custom symbol from the real one and set its commission rules, or deduct it when you compare reports. The Delays setting is the closest thing to slippage; the InpDeviation input only caps how far a market order may fill from the requested price.
Where the two differ
| Pine argument | MQL5 | Note |
|---|---|---|
default_qty_value | input double InpLots | Pine counts contracts or units; MT5 counts lots. 1 unit of EURUSD is 0.00001 lot. See default_qty_type. |
pyramiding | count your own positions before entering | Nothing in MT5 limits entries. On a netting account a second buy enlarges the one position. |
initial_capital | tester Deposit | Live, the balance is whatever the account holds; AccountInfoDouble(ACCOUNT_BALANCE) reads it. |
commission_* | symbol specification or custom symbol | Not settable from code. |
slippage | tester Delays; SetDeviationInPoints | Pine slippage is a guaranteed adverse fill; MT5 deviation is a limit on the fill, not a penalty. |
calc_on_every_tick | presence of a new-bar gate in OnTick | Default false: gate on iTime(_Symbol, _Period, 0) changing and read shift 1. |
process_orders_on_close | when you send the order | False: send on the first tick of the next bar (fills at its open). True: there is no later tick on the closed bar in MT5; the first tick of the next bar is the closest you get. |
What the Stratlate converter emits
The converter reads the named arguments of strategy() and emits an Expert Advisor with a new-bar gate in OnTick. A strategy.fixed default_qty_value is used verbatim as the order volume (the script above is emitted with OrderSend(..., OP_BUY, 1.0, ...), i.e. 1.0 lot); percent_of_equity and cash sizing are computed per order at run time by the runtime helpers pine_qty_percent_equity and pine_qty_from_cash and noted in the report as PM303; pyramiding above 1 sets the runtime's __pinePyramiding limit in OnInit and is noted as PM302. initial_capital, commission_*, slippage, calc_on_every_tick and process_orders_on_close produce no code: the EA always runs the bar-close model, and its market orders go out through CTrade with a deviation of 3 points and magic number 0. Set the deposit and commission in the tester yourself, then compile and backtest the output.
Pitfalls
- Copying
default_qty_value = 1asInpLots = 1.0on a forex pair. Symptom: the EA trades 100,000 units where Pine traded one, and the tester stops on insufficient margin. - Leaving the tester deposit at its default while Pine used
initial_capital = 10000. Symptom: percent-of-equity sizes, drawdown percentages and margin calls no longer match. - Omitting the magic number. Symptom: the EA's position counting and closing act on positions opened by hand or by another EA on the same symbol.
- Treating
InpDeviationas Pine'sslippage. Symptom: the MT5 backtest fills at the exact price while the TradingView report is worse byslippageticks per fill.
FAQ
Does an MQL5 EA have anything like the strategy() declaration?
No. An EA is declared by containing OnTick; everything the Pine declaration configures is either an input you enforce in code or a setting of the Strategy Tester and the broker account.
Where do I set initial_capital in MetaTrader 5?
In the Strategy Tester's Settings tab, in the Deposit field, together with the deposit currency and leverage. In live trading the balance is the account's real balance.
Can commission be set in MQL5 code?
No. The tester applies the commission in the symbol's specification. Use a custom symbol with your own commission rules to match commission_value, or subtract it when you compare the two reports.
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