strategy.close in MQL5: PositionClose by entry id

Short answer

Use CTrade::PositionClose(ticket) on the position whose comment carries the entry id, filtered by this EA's symbol and magic number. A qty or qty_percent smaller than the whole trade is CTrade::PositionClosePartial.

strategy.close(id) exits the trade that strategy.entry(id, ...) opened, at the next bar's open, and strategy.close_all() exits every open trade. The MQL5 equivalent is CTrade::PositionClose(ticket) on the position whose comment carries the id, filtered to this EA's symbol and magic number; a qty_percent or qty smaller than the whole trade is CTrade::PositionClosePartial.

What strategy.close computes

The call generates a market order in the opposite direction for the trade's remaining size, or for qty contracts or qty_percent percent of it when given, and the order fills at the open of the next bar (the signal bar's close with process_orders_on_close = true). It matches on the entry id only: with pyramiding above one, several trades can share the id "L" and strategy.close("L") closes all of them. A close for an id with no open trade does nothing; it does not cancel a resting strategy.entry with that id, which is strategy.cancel's job. comment labels the exit in the trade list. The P&L of the closed part moves from strategy.openprofit to strategy.netprofit and the trade moves from strategy.opentrades to strategy.closedtrades.

The MQL5 equivalent

//@version=6
strategy("Close demo", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 2)
rsi = ta.rsi(close, 14)
if ta.crossover(rsi, 30)
    strategy.entry("L", strategy.long)
if ta.crossunder(rsi, 70)
    strategy.entry("S", strategy.short)
// take half off when RSI crosses 50
if ta.crossover(rsi, 50)
    strategy.close("L", qty_percent = 50, comment = "half")
// flatten everything at the end of the week
if dayofweek == 6 and hour >= 20
    strategy.close_all(comment = "weekend")

In the EA, Close(id, qtyPercent) walks the position pool backwards (closing renumbers it), keeps only positions that belong to this EA and carry the id, and either closes whole or computes the partial volume rounded down to the lot step. CloseAll is the same walk with an empty id.

#include <Trade/Trade.mqh>
input double InpLots  = 0.20;
input long   InpMagic = 60014;
CTrade trade;
int hRsi = INVALID_HANDLE;

int OnInit()
  {
   hRsi = iRSI(_Symbol, _Period, 14, PRICE_CLOSE);
   if(hRsi == 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;
  }

// true when position i belongs to this EA on this symbol and, if id is
// not empty, was opened under that Pine entry id (the comment)
bool IsOwn(const int i, const string id)
  {
   if(PositionGetTicket(i) == 0)
      return false;
   if(PositionGetString(POSITION_SYMBOL) != _Symbol
      || PositionGetInteger(POSITION_MAGIC) != InpMagic)
      return false;
   return id == "" || PositionGetString(POSITION_COMMENT) == id;
  }

// strategy.close(id, qty_percent): close that share of every position
// opened under id. 100 closes it whole. Walks backwards because closing
// renumbers the pool.
void Close(const string id, const double qtyPercent = 100.0)
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      if(!IsOwn(i, id))
         continue;
      const ulong  ticket = PositionGetTicket(i);
      const double vol    = PositionGetDouble(POSITION_VOLUME);
      if(qtyPercent >= 100.0)
        {
         trade.PositionClose(ticket);
         continue;
        }
      const double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
      const double part = MathFloor(vol * qtyPercent / 100.0 / step) * step;
      if(part >= SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
         trade.PositionClosePartial(ticket, part);
     }
  }

// strategy.close_all(): every position of this EA on this symbol
void CloseAll()
  {
   Close("");
  }

void OnTick()
  {
   if(!IsNewBar())
      return;
   double r[2];
   if(CopyBuffer(hRsi, 0, 1, 2, r) != 2)
      return;
   if(r[0] <= 30 && r[1] > 30)
      trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
   if(r[0] >= 70 && r[1] < 70)
      trade.Sell(InpLots, _Symbol, 0.0, 0.0, 0.0, "S");
   if(r[0] <= 50 && r[1] > 50)
      Close("L", 50.0);                // strategy.close("L", qty_percent = 50)
   MqlDateTime dt;
   TimeToStruct(iTime(_Symbol, _Period, 1), dt);
   if(dt.day_of_week == 5 && dt.hour >= 20)
      CloseAll();                      // strategy.close_all()
  }

On a hedging account every entry is its own position and the loop closes each one; on a netting account there is at most one position per symbol, and a partial close shrinks it. The comment argument of strategy.close has no equivalent: an MT5 closing deal gets its own comment from the terminal and you cannot set it through PositionClose.

Where the two differ

TopicPineMQL5
What is closedtrades with this entry idpositions you select; the id is in POSITION_COMMENT
Fillnext bar's openbid (long) or ask (short) on the tick you send it
Partial closeqty or qty_percentPositionClosePartial(ticket, volume); volume must be a multiple of SYMBOL_VOLUME_STEP and at least SYMBOL_VOLUME_MIN
Ownershiponly the strategy's trades existfilter by POSITION_MAGIC, or you close manual trades too
Netting accountn/aone position holds the merged size; closing by id closes the whole merged position
Resting entriesuntoucheduntouched; OrderDelete is a separate call
Failurecannot failPositionClose returns false (requotes, market closed); check ResultRetcode()

What the Stratlate converter emits

The converter emits strategy.close("L") as the runtime call pine_close_id("L"), which collects the tickets of every open position on the symbol whose POSITION_COMMENT equals the id and closes each with CTrade::PositionClose; strategy.close_all() is pine_close_all(), the same walk with an empty id. Both are treated as exact. The qty, qty_percent and comment arguments are not carried: the position is closed whole, so the qty_percent = 50 in the script above becomes a full close in the EA. The runtime filters by symbol and comment, not by magic number, so run the EA on its own account or symbol when other positions with the same comment could exist. Compile and backtest the output before trading it.

Pitfalls

  • Walking the position pool forwards while closing. Symptom: every second position survives, because closing index 0 shifts the rest down.
  • Passing an unrounded partial volume. Symptom: retcode 10014 "Invalid volume" and the position stays open.
  • Closing by symbol only. Symptom: the EA flattens a manual trade or another EA's position on the same chart.
  • Expecting strategy.close to remove a pending entry with the same id. Symptom: the breakout order fills after the strategy was meant to be flat; call OrderDelete as well.
  • Relying on the comment to survive. Symptom: some brokers rewrite or strip comments; keep your own map from id to ticket if the broker does.

FAQ

Is strategy.close_all the same as closing all positions in MT5?

Only for this strategy's trades. In MT5 the equivalent loop should still filter by symbol and magic number, otherwise it closes every position in the account, including manual ones.

How do I close half a position in MQL5?

Compute half of POSITION_VOLUME, round it down to SYMBOL_VOLUME_STEP, make sure it is at least SYMBOL_VOLUME_MIN, and call trade.PositionClosePartial(ticket, volume). On a hedging account the remainder keeps the same ticket.

Why does the MT5 exit price differ from TradingView's?

TradingView closes at the next bar's open price; MT5 closes a long at the bid and a short at the ask of the current tick, so the exit is one spread worse on a long and shows the broker's actual quote.

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