CTrade and OrderSend in Pine Script: strategy.entry/exit

Short answer

A buy with stop-loss and take-profit is two calls: strategy.entry("long", strategy.long, qty) and strategy.exit("x", "long", stop = sl, limit = tp). Closing a position is strategy.close or strategy.close_all.

In MQL5 an Expert Advisor trades by calling OrderSend with a filled MqlTradeRequest, or more often through the standard library's CTrade class: trade.Buy(lots, symbol, price, sl, tp), trade.Sell(…), trade.PositionClose(symbol), trade.PositionModify(…). A Pine Script strategy places simulated orders with strategy.entry, attaches stop-loss and take-profit with strategy.exit and closes with strategy.close or strategy.close_all. A buy with SL and TP is two calls in Pine: strategy.entry("long", strategy.long, qty) and strategy.exit("x", "long", stop = sl, limit = tp).

What CTrade.Buy and OrderSend compute

trade.Buy(volume, symbol, price, sl, tp, comment) builds a TRADE_ACTION_DEAL request of type ORDER_TYPE_BUY and sends it to the server. price 0 means the current Ask; sl and tp are absolute prices (0 for none) that the server attaches to the resulting position and that must respect the symbol's stop level. Volume is in lots and must be a multiple of the symbol's volume step. The call returns true when the request was accepted, after which trade.ResultRetcode() and ResultDeal() say what happened. On a netting account a buy against an open short reduces or reverses it; on a hedging account it opens a second, independent position.

OrderSend(request, result) is the raw form: you fill action, symbol, volume, type, price, sl, tp, deviation, magic and type_filling, and read result.retcode. Pending orders use TRADE_ACTION_PENDING with ORDER_TYPE_BUY_LIMIT, BUY_STOP and so on.

A Pine strategy is a backtest and alert engine: orders never reach a broker from the script. strategy.entry queues a market order (or a limit/stop order with limit=/stop=) that fills on the next bar; strategy.exit queues a bracket linked to an entry id; the strategy's position is net by default, with pyramiding controlling how many same-direction entries may stack.

The Pine Script equivalent

An EMA-cross EA that buys with absolute SL/TP prices and closes on the opposite cross, and the matching strategy.

//@version=6
strategy("EMA cross with SL/TP", overlay = true, pyramiding = 0,
     default_qty_type = strategy.fixed, default_qty_value = 10000)

qty     = input.float(10000, "Quantity (units; 0.10 lot of a forex pair = 10000)")
fastLen = input.int(9, "Fast EMA")
slowLen = input.int(21, "Slow EMA")
stopPts = input.int(300, "Stop loss, ticks")
takePts = input.int(600, "Take profit, ticks")

fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)

// trade.PositionClose(_Symbol) for a long position
if ta.crossunder(fast, slow) and strategy.position_size > 0
    strategy.close("long", comment = "cross down")

// trade.Buy(lots, _Symbol, ask, sl, tp): an entry plus a bracket exit
if ta.crossover(fast, slow) and strategy.position_size == 0
    strategy.entry("long", strategy.long, qty = qty, comment = "ema cross")
    // Absolute prices, like the EA's sl/tp. close is the reference because the order
    // fills at the next open; profit/loss in ticks would measure from the actual fill.
    strategy.exit("long exit", from_entry = "long",
         stop  = close - stopPts * syminfo.mintick,
         limit = close + takePts * syminfo.mintick)
#include <Trade\Trade.mqh>

input double InpLots    = 0.10;   // Lots
input int    InpFast    = 9;      // Fast EMA
input int    InpSlow    = 21;     // Slow EMA
input int    InpStopPts = 300;    // Stop loss, points
input int    InpTakePts = 600;    // Take profit, points

CTrade   trade;
int      fastH, slowH;
datetime lastBar = 0;

int OnInit()
{
   fastH = iMA(_Symbol, _Period, InpFast, 0, MODE_EMA, PRICE_CLOSE);
   slowH = iMA(_Symbol, _Period, InpSlow, 0, MODE_EMA, PRICE_CLOSE);
   if(fastH == INVALID_HANDLE || slowH == INVALID_HANDLE)
      return(INIT_FAILED);
   trade.SetExpertMagicNumber(9021);
   trade.SetDeviationInPoints(10);
   return(INIT_SUCCEEDED);
}

void OnTick()
{
   datetime t = iTime(_Symbol, _Period, 0);
   if(t == lastBar) return;
   lastBar = t;

   double f[], s[];
   ArraySetAsSeries(f, true);
   ArraySetAsSeries(s, true);
   if(CopyBuffer(fastH, 0, 1, 2, f) < 2 || CopyBuffer(slowH, 0, 1, 2, s) < 2) return;

   bool crossUp = f[0] > s[0] && f[1] <= s[1];   // on the last closed bar
   bool crossDn = f[0] < s[0] && f[1] >= s[1];

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(crossDn && PositionSelect(_Symbol) && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
      trade.PositionClose(_Symbol);

   if(crossUp && !PositionSelect(_Symbol))
   {
      double sl = NormalizeDouble(ask - InpStopPts * _Point, _Digits);   // absolute prices
      double tp = NormalizeDouble(ask + InpTakePts * _Point, _Digits);
      if(!trade.Buy(InpLots, _Symbol, ask, sl, tp, "ema cross"))
         Print("Buy failed: ", trade.ResultRetcode());
   }
}
MQL5Pine
trade.Buy(lots, sym, 0, sl, tp)strategy.entry(id, strategy.long, qty) + strategy.exit(xid, id, stop = sl, limit = tp)
trade.Sell(…)strategy.entry(id, strategy.short, qty); exit with stop above, limit below
trade.BuyLimit(lots, price, …)strategy.entry(id, strategy.long, qty, limit = price)
trade.BuyStop(lots, price, …)strategy.entry(id, strategy.long, qty, stop = price)
trade.PositionClose(sym)strategy.close(id) or strategy.close_all()
trade.PositionModify(sym, sl, tp)Call strategy.exit again with the same id and new prices
trade.OrderDelete(ticket)strategy.cancel(id)
SL/TP in points from entrystrategy.exit(…, loss = pts, profit = pts) in ticks
SetExpertMagicNumber, SetDeviationInPointsNo equivalent; slippage in strategy() models fill cost

Where the two differ

Lots versus quantity. MQL5 volume is in lots; Pine qty is in the symbol's units: shares, contracts, or for forex the base currency amount. On TradingView forex symbols 1 standard lot is 100,000 units, so 0.10 lot is qty = 10000. A conversion that keeps qty = 0.1 trades a tenth of one unit and shows near-zero profit.

Fill price and time. The EA's market order fills at the Ask on the first tick of the new bar. Pine's fills at the next bar's open, without spread unless slippage is set. Stops and limits are checked against the bar's high/low; when both are inside one bar, Pine assumes an intrabar path from the open (towards the nearer extreme first), so results on such bars can differ from MetaTrader's tick model.

SL/TP reference. The EA computes SL from the Ask at send time. In Pine the order is queued at the close and filled at the next open; stop = close - x is anchored to the close, while loss = ticks is measured from the actual fill. Pick the one that matches the original's intent.

Netting. Pine strategies are net per symbol. An entry in the opposite direction reverses the position (closes and opens), and two independent hedged positions cannot exist. EAs written for hedging accounts need to be redesigned.

Rejections. MQL5 calls can fail (stop level, no money, market closed) and code checks the return. Pine orders fill if the price reaches them; there is no retcode to check, only margin rules if margin_long/margin_short are set.

What the Stratlate converter emits

The MQL5 to Pine engine emits strategy("…", overlay=true, pyramiding=100) for an EA and routes every trade.Buy, trade.Sell, BuyLimit, BuyStop (and their sell forms) and OrderSend through the runtime helper f_order_send(cmd, qty, price, sl, tp). The helper gives each order its own id ("p1", "p2", …), calls strategy.entry(id, side, qty, limit=…, stop=…) with the trigger price for limit and stop types, and adds strategy.exit(id + "_exit", id, stop=sl, limit=tp) when SL or TP is non-zero (PinePrelude). The MqlTradeRequest struct-field idiom is recognised and rewritten to the same helper (BodyLowering rewriteMqlTradeRequestPattern). trade.PositionClose becomes f_order_close, which calls strategy.close_all(); PositionModify becomes f_order_modify, which re-issues an exit for the entry id "trade"; because the helper names entries "p1", "p2", that modified stop does not attach to the position, so move stops by hand with the entry's id. The lot volume is passed through unchanged as qty, so a 0.10-lot EA becomes a 0.1-unit strategy: set the quantity for the symbol yourself. Ask and Bid are read as close, and magic number and deviation calls are reported as approximations. EAs that keep simultaneous long and short ticket books or pending-order grids, which a net strategy cannot represent, are refused with MQLE0520 rather than converted. Compile the strategy and compare its trade list with the Strategy Tester's before relying on it.

Pitfalls

  • Leaving qty in lots. Symptom: trades of 0.1 units and a net profit of a few cents over years of data.
  • Calling strategy.exit without from_entry when several entries exist; it then applies to all of them. Use the entry's id.
  • Putting strategy.exit only on the entry bar while SL/TP move later. Exits with a constant price set once are fine; trailing levels must be re-issued on every bar with the same exit id.
  • Expecting two buys to make two positions with separate stops. With pyramiding = 0 the second buy is ignored; with pyramiding raised, give each entry its own id and its own exit.
  • Translating trade.Sell as strategy.close. A sell order opens a short (or reverses); closing a long is strategy.close.

FAQ

Can a Pine strategy send real orders to my broker like OrderSend?

Not by itself. TradingView can trade through integrated brokers from the chart, and alerts from strategy.* fills (with alert_message) can be sent by webhook to a bridge that places orders. The script itself only simulates.

How do I set SL and TP in points like the EA?

Use strategy.exit("x", "long", loss = stopPts, profit = takePts). Both are in ticks of syminfo.mintick, measured from the entry's fill price. Check that the symbol's tick equals MetaTrader's _Point; on some symbols it does not.

What is the Pine equivalent of checking ResultRetcode?

There is none, because simulated orders are not rejected. To react to a fill, compare strategy.position_size with its previous value, or count strategy.opentrades and strategy.closedtrades between bars.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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