Commission and slippage in MQL5: tester and broker settings
Short answer
An MQL5 EA cannot set commission or slippage in code. Commission comes from the broker's symbol specification and slippage from real fills, or the spread and Delays setting in the Strategy Tester. To compare with Pine, use a custom symbol with the same commission or apply Pine's cost model to the tester's deals.
In Pine, trading costs are two declaration arguments: commission_type/commission_value charge every fill, and slippage moves every market and stop fill against you by a number of ticks. An MQL5 EA cannot set either. In MetaTrader 5 commission comes from the broker's symbol specification and appears on each deal as DEAL_COMMISSION; slippage is whatever the real fill was, plus the spread, and in the Strategy Tester it comes from the spread and the Delays setting. To compare with a Pine report, either configure a custom symbol with the same commission or apply Pine's cost model to the tester's deals yourself, for example in OnTester.
What commission and slippage compute
commission_type is one of strategy.commission.percent (a percentage of the traded value), strategy.commission.cash_per_contract (an amount per contract) or strategy.commission.cash_per_order (a flat amount per order); commission_value is the rate, default 0. It is charged on entry and exit fills alike and deducted from each trade's profit. slippage, in ticks, default 0, worsens the fill price of market and stop orders by that many syminfo.mintick; limit orders are not slipped. TradingView's emulator has no spread, so on forex these two settings are the only costs in a Pine backtest unless the script models them. Both are fixed for the whole run and identical on every bar.
The MQL5 equivalent
//@version=6
strategy("Costs demo", overlay = true, initial_capital = 10000,
default_qty_type = strategy.fixed, default_qty_value = 10000,
commission_type = strategy.commission.percent, commission_value = 0.01,
slippage = 2)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
if ta.crossover(fast, slow)
strategy.entry("L", strategy.long)
if ta.crossunder(fast, slow)
strategy.close("L")The EA trades normally and sets a deviation, which only limits how far from the requested price a market order may fill. The cost comparison happens in OnTester, which runs once at the end of a tester pass: it walks this EA's deals and applies Pine's percent commission and tick slippage to each fill, so the custom result is directly comparable with the TradingView net profit.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input double InpCommissionPct = 0.01; // Pine commission_value (percent)
input int InpSlippageTicks = 2; // Pine slippage (ticks per fill)
input int InpDeviation = 10; // max distance from the requested price
input long InpMagic = 60025;
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.SetDeviationInPoints(InpDeviation); // a limit, not a cost
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;
}
ulong LongTicket()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
const ulong t = PositionGetTicket(i);
if(t != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic)
return t;
}
return 0;
}
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;
const ulong ticket = LongTicket();
if(f[1] > s[1] && f[0] <= s[0] && ticket == 0)
trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
if(f[1] < s[1] && f[0] >= s[0] && ticket != 0)
trade.PositionClose(ticket);
}
// Strategy Tester: net profit with Pine's cost model applied on top of
// what the tester charged. Pick "Custom max" as the optimisation criterion
// or read the value in the tester journal.
double OnTester()
{
const double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
const double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double net = 0.0, pineCosts = 0.0, brokerCosts = 0.0;
if(!HistorySelect(0, TimeCurrent()) || tickSize <= 0.0)
return 0.0;
for(int i = 0; i < HistoryDealsTotal(); i++)
{
const ulong d = HistoryDealGetTicket(i);
if(d == 0 || HistoryDealGetInteger(d, DEAL_MAGIC) != InpMagic)
continue;
const double vol = HistoryDealGetDouble(d, DEAL_VOLUME);
const double price = HistoryDealGetDouble(d, DEAL_PRICE);
net += HistoryDealGetDouble(d, DEAL_PROFIT) + HistoryDealGetDouble(d, DEAL_SWAP);
brokerCosts += HistoryDealGetDouble(d, DEAL_COMMISSION);
// per fill: percent of the traded value, plus N ticks against us
const double notional = vol * price / tickSize * tickValue;
pineCosts += notional * InpCommissionPct / 100.0
+ InpSlippageTicks * tickValue * vol;
}
PrintFormat("gross %.2f broker commission %.2f Pine-model costs %.2f",
net, brokerCosts, pineCosts);
return net + brokerCosts - pineCosts;
}The custom value removes the tester's own commission and replaces it with Pine's, but the spread the tester charged is still in the result; TradingView has none. For a fair comparison test with a fixed spread close to zero (custom symbol or the tester's spread setting where the broker allows it), or keep the spread and add it mentally to Pine's slippage. The tick value is read once at the end, so for symbols whose quote currency differs from the deposit currency the converted costs are approximate.
Where the two differ
| Cost | Pine | MQL5 |
|---|---|---|
| Commission | commission_type/value in code | symbol specification; per deal in DEAL_COMMISSION; custom symbols can define their own |
| Slippage | fixed ticks on market and stop fills | real fills; tester: spread and Delays; SetDeviationInPoints is a maximum, not a cost |
| Spread | none | always, buys at ask and sells at bid |
| Swap | none | charged overnight as DEAL_SWAP/POSITION_SWAP |
| In the reported profit | trade profit is net of commission | DEAL_PROFIT excludes commission and swap; the balance includes them |
| Settable by the EA | yes, it is the script's declaration | no |
What the Stratlate converter emits
The converter reads commission_type and commission_value from the declaration but emits nothing for them, and it does not read slippage; no report note mentions them. The emitted orders use a fixed deviation of 3 points through the runtime's OrderSend shim. Costs in the converted EA's backtest are therefore the broker's: spread, the symbol's commission and swap. Also check the order volume: a strategy.fixed default_qty_value is carried as lots, so the default_qty_value = 10000 above is emitted as 10000.0 lots and should be changed to the lot size you mean. Compile, set the volume, and backtest.
Pitfalls
- Looking for a commission input in the EA. Symptom: none exists; the tester silently uses the symbol's commission, which may be zero on a demo server.
- Treating
SetDeviationInPointsas slippage. Symptom: MT5 fills at the exact quote while the Pine report is worse byslippageticks per fill. - Comparing net profit without removing the spread. Symptom: every MT5 trade is a few points worse and short-term strategies flip from profit to loss.
- Reading only
DEAL_PROFIT. Symptom: MT5 looks more profitable than Pine on a commission account, because commission sits in a separate field. - Applying Pine's percent commission to lots instead of traded value. Symptom: costs off by the contract size; multiply by price and tick value as in
OnTester.
FAQ
Can I set commission in an MQL5 Expert Advisor?
No. Commission is part of the symbol's trading conditions on the server. In the tester you can use a custom symbol with your own commission settings, or compute the costs from the deal history as above.
What is the MQL5 equivalent of Pine's slippage?
There is none in code. Live, slippage is the difference between the requested and the filled price; in the tester, enable random or fixed Delays to simulate it, or add Pine's tick slippage to each fill in OnTester.
Why does my converted EA make less than the TradingView backtest?
Mostly costs: MT5 charges the spread on every trade and swap on positions held overnight, neither of which exists in Pine unless modelled. Compare trade lists first, then 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