FX NOOKAI CODE LAB
Loading

MQL5 How to Close a Position: Code and Checks

By FXNook Lab team

To close one exact MQL5 position, include <Trade/Trade.mqh>, create a CTrade object, and call PositionClose(ticket). Check both the method’s Boolean return and ResultRetcode(), then select the ticket again to confirm the position is gone. A true return by itself does not prove that the trade server completed the close.

Close one position by ticket with CTrade

A ticket identifies one position. This is the clearest choice when the EA must close a particular trade, especially if several positions on the same symbol are open. The example below is a complete MQL5 Expert Advisor shell with a helper function you can call when your own exit condition is met.

#include <Trade/Trade.mqh>

CTrade trade;

int OnInit()
{
   trade.SetAsyncMode(false);
   return INIT_SUCCEEDED;
}

void OnTick()
{
   // Call ClosePositionByTicket(ticket) when your exit rule is met.
}

bool ClosePositionByTicket(const ulong ticket)
{
   if(!PositionSelectByTicket(ticket))
   {
      PrintFormat("Position ticket %I64u is not open or could not be selected.", ticket);
      return false;
   }

   string symbol = PositionGetString(POSITION_SYMBOL);

   ResetLastError();
   bool request_ok = trade.PositionClose(ticket);
   uint retcode = trade.ResultRetcode();
   int last_error = GetLastError();

   PrintFormat("Close request: ticket=%I64u symbol=%s method_return=%s retcode=%u (%s) last_error=%d",
               ticket, symbol, request_ok ? "true" : "false",
               retcode, trade.ResultRetcodeDescription(), last_error);

   if(!request_ok)
      return false;

   if(retcode != TRADE_RETCODE_DONE && retcode != TRADE_RETCODE_DONE_PARTIAL)
      return false;

   // Refresh the position data and verify that this ticket no longer exists.
   if(PositionSelectByTicket(ticket))
   {
      PrintFormat("Position %I64u still exists after the close request.", ticket);
      return false;
   }

   PrintFormat("Position %I64u on %s is no longer open.", ticket, symbol);
   return true;
}

Call the helper with a valid open ticket, for example one obtained from PositionGetTicket(index). It returns true only when the request reports an accepted execution result and a fresh selection cannot find the ticket. A partial close normally leaves the position open, so this helper returns false in that case: it is intended to report a full close, not merely a submitted request.

SetAsyncMode(false) makes the trade object use synchronous requests, which is useful when the next line of code checks the result. Even in synchronous mode, inspect the server retcode and refreshed position state. The Boolean from PositionClose() reports whether the method passed its basic request checks; it is not, on its own, confirmation that the server executed the trade.

Close by symbol or by ticket

trade.PositionClose(symbol) asks CTrade to close a position selected by symbol. trade.PositionClose(ticket) targets a specific position. Choose based on what your exit rule means, rather than using the symbol overload simply because the EA already has a symbol string.

MethodWhat it targetsWhen it fits
PositionClose(symbol)A position identified by symbol. In hedging mode, the symbol overload closes the position with the lowest ticket for that symbol.When the EA intends to close the symbol’s net position, or when its account mode and position selection make the target unambiguous.
PositionClose(ticket)The position with that exact ticket.When the EA must close one particular position, including one of several positions on the same symbol in a hedging account.

Ticket targeting avoids an easy-to-miss hedging bug. An EA may find a position by ticket, apply its exit rule to that trade, and then accidentally call PositionClose(symbol). If multiple positions share the symbol, the symbol overload may close a different position. Keep using the ticket that you selected and validated.

Find and close matching positions safely

Use PositionsTotal() to get the current number of open positions and PositionGetTicket(index) to retrieve a ticket by index. Iterate from the last index down to zero. Removing a position changes the list, so walking backward avoids skipping lower indexes as entries are removed.

The function below closes positions that match both a symbol and a magic number. It selects each ticket again before reading its properties, closes by ticket, logs the result, and counts only positions that are no longer present afterward.

int CloseMatchingPositions(const string target_symbol, const long target_magic)
{
   int closed_count = 0;

   for(int i = PositionsTotal() - 1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0)
         continue;

      if(!PositionSelectByTicket(ticket))
         continue;

      string symbol = PositionGetString(POSITION_SYMBOL);
      long magic = PositionGetInteger(POSITION_MAGIC);

      if(symbol != target_symbol || magic != target_magic)
         continue;

      ResetLastError();
      bool request_ok = trade.PositionClose(ticket);
      uint retcode = trade.ResultRetcode();
      int last_error = GetLastError();

      PrintFormat("Close attempt: ticket=%I64u symbol=%s magic=%I64d method_return=%s retcode=%u (%s) last_error=%d",
                  ticket, symbol, magic, request_ok ? "true" : "false",
                  retcode, trade.ResultRetcodeDescription(), last_error);

      if(request_ok && retcode == TRADE_RETCODE_DONE &&
         !PositionSelectByTicket(ticket))
      {
         ++closed_count;
      }
   }

   return closed_count;
}

The example counts full closes reported with TRADE_RETCODE_DONE. If the server reports TRADE_RETCODE_DONE_PARTIAL, the position may still be open with reduced volume, so it is not counted as a full close. Decide explicitly how your EA should handle partial execution instead of treating every successful request as a complete exit.

Filtering by symbol and magic number is useful, but understand what the magic number represents on your account. In hedging mode, positions are separate and the filter can help distinguish an EA’s trades. In netting mode, a symbol has one aggregate position; trades from different sources can contribute to that position, so its magic number should not be treated as a perfect record of ownership for every contributing deal.

Netting and hedging account differences

MQL5 supports two account position models. The model determines whether several positions can exist for one symbol and changes what a symbol-based close means. You can inspect the account’s margin mode with AccountInfoInteger(ACCOUNT_MARGIN_MODE).

Account modelPositions on one symbolEffect on closing
NettingOne aggregate position per symbol.A symbol-based close targets that symbol’s single net position. Use a ticket when your code already tracks the exact position, and remember that the position can reflect multiple deals.
HedgingMultiple separate positions can exist on the same symbol, including positions in opposite directions.A ticket specifies the exact position. The symbol overload may close only one matching position, not every position on that symbol.

For example, a hedging-account EA may have two EURUSD positions with different tickets. If its exit rule applies only to the first one, calling PositionClose("EURUSD") does not express that intent as clearly as closing the selected ticket. On a netting account, there is only one EURUSD position, but that position is the account’s combined exposure for that symbol.

Read the trade result and diagnose failures

After each trade method call, get trade.ResultRetcode() and trade.ResultRetcodeDescription(). The retcode describes the trade server’s result. Also log the ticket and symbol, and capture GetLastError() when useful; the terminal error number and the trade-server retcode are different diagnostic details.

A stale ticket is a common cause of a failed close: another part of the EA, a manual action, or another program may already have closed the position. Select the ticket immediately before using it, and handle the case where it no longer exists as a normal state change rather than assuming the terminal is broken.

Market hours and permissions are separate issues. A request can fail when the market is closed, algorithmic trading or account trading is disabled, or the broker refuses the request for another trading rule. The retcode description in the Experts log is a better starting point than repeatedly sending the same request without changing the cause.

When the method returns true but the position remains visible, look at both the retcode and the position’s current volume. A partial execution can leave a remainder, while a successful request check can still precede a server refusal. Refresh the position selection after the request; do not rely on values selected before the close call.

Close only part of a position

PositionClose() is for closing a position in full. For a partial close on a hedging account, CTrade provides PositionClosePartial(ticket, volume). It takes the position ticket and the volume to close, and it still requires the same result checks: inspect the method return, retcode, and updated position volume.

Partial volume must satisfy the instrument’s minimum volume and volume step, and it cannot exceed the open position volume. Read the symbol’s volume properties with SymbolInfoDouble(), including SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_STEP, and calculate a permitted volume rather than rounding blindly. A small remainder that is below the broker’s minimum can make the intended operation invalid.

PositionClosePartial() is intended for hedging accounts. A netting account has an aggregate position, so do not assume that a hedging-style partial-close call applies there. If you implement a partial reduction on a netting account using an opposite deal, calculate its direction and volume carefully so that the deal reduces the position rather than reversing it.

Test the close logic before using it live

  1. Compile in MetaEditor. Confirm that the file is MQL5, includes Trade/Trade.mqh, and uses the MQL5 position functions rather than MQL4 order functions.
  2. Test the exit condition in Strategy Tester. Use a test setup that creates the type of position your EA is designed to handle. Inspect the trade list and logs to see whether the expected ticket was closed.
  3. Exercise the account model. If the EA supports hedging, test more than one position on the same symbol. If it supports netting, test how it handles the aggregate position.
  4. Read the Experts and Journal logs. Compare the ticket, symbol, method return, retcode description, and position state. This helps separate a selection error from a server rejection or partial execution.
  5. Try the logic on a demo account. Confirm that the EA’s real terminal permissions and broker conditions allow the close request before relying on the behavior in a live environment.

A clean compile only shows that MetaEditor accepted the source; it does not show that your EA selected the intended position or handled every server response. Test the close path with the relevant position model and inspect the resulting logs. Past or tested results do not guarantee future results.

If the code does not compile, or the close path behaves differently from what the log suggests, the FXNook Lab MQL4/MQL5 error fixer can compile uploaded code, identify errors, and show what changed. Your practical next step is to run the ticket-based helper in Strategy Tester or on a demo account, then compare its logged retcode with the position list.

Questions

How do I close a position by ticket in MQL5?

Include <Trade/Trade.mqh>, create a CTrade object, and call trade.PositionClose(ticket) with the open position’s ticket. Inspect ResultRetcode() and then select the ticket again to verify that it is no longer open.

What is the difference between PositionClose by symbol and by ticket?

PositionClose(symbol) targets a position through its symbol, while PositionClose(ticket) specifies one exact position. In hedging mode, several positions can share a symbol, so a ticket is the clearer choice when only a particular trade should close.

Why does PositionClose return true but the position remain open?

The Boolean return indicates that the method’s basic request checks passed; it does not by itself confirm execution by the trade server. Read ResultRetcode() and its description, then refresh the position data because a refusal, partial execution, or remaining volume can leave a position open.