How to Close Half of a Position in MQL5

 

Hello everyone,

I am developing a trading bot in MQL5 and I'm facing an issue with partially closing a position.
My goal is to close half of a position when a certain profit threshold is reached,
and to update the position's comment to reflect this partial closure.
Here are the key parts of my code:

Partial Closure Logic:
void OnTrade()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        string pos_symbol = PositionGetSymbol(i);
        if (pos_symbol == symbol)
        {
            double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
            double current_price = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK);
            double profit_pips = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? (current_price - entry_price) / _Point : (entry_price - current_price) / _Point;
            double lot_size = PositionGetDouble(POSITION_VOLUME);

            if (profit_pips >= 4700 && PositionGetString(POSITION_COMMENT) != "Partial Closed")
            {
                double close_lot = lot_size / 2;
                double min_lot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
                double lot_step = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
                close_lot = MathMax(close_lot, min_lot);
                close_lot = MathFloor(close_lot / lot_step) * lot_step;

                MqlTradeRequest request;
                MqlTradeResult result;
                ZeroMemory(request);
                ZeroMemory(result);

                request.action = TRADE_ACTION_DEAL;
                request.symbol = symbol;
                request.volume = close_lot;
                request.type = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
                request.price = (request.type == ORDER_TYPE_SELL) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK);
                request.type_filling = ORDER_FILLING_IOC;

                if (OrderSend(request, result))
                {
                    Print("Successfully closed half of the position for ", symbol);
                    // How to properly update the position comment or manage this partial closure?
                }
                else
                {
                    Print("Error closing half of the position for ", symbol, ": ", GetLastError());
                }
            }
        }
    }
}

I am looking for guidance on the best practices to:

  1. Close half of an existing position.
  2. Update the position's comment to indicate that it has been partially closed.

Any help or suggestions on improving this part of the code would be greatly appreciated. Thank you!




Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
  • www.mql5.com
Execution of trade operations results in the opening of a position, changing of its volume and/or direction, or its disappearance. Trade operations...
 
Total closure or partial closure of a position by applying opposite order is only possible with non-hedge accounts.
In case you are using a hedge account you may use PositionClosePartial method from Trade.mqh.
Also note that you are not allowed to update comment of position.
Can I ask why you are doing it in OnTrade event handler? Are you aware about the specific usage of this handler?
 
Yashar Seyyedin #:
Total closure or partial closure of a position by applying opposite order is only possible with non-hedge accounts.
In case you are using a hedge account you may use PositionClosePartial method from Trade.mqh.
Also note that you are not allowed to update comment of position.
Can I ask why you are doing it in OnTrade event handler? Are you aware about the specific usage of this handler?
i am really not too familiar with the ontrade and ontick but i do think that ontrade is for modifying opened trades isnt it?
 
Yashar Seyyedin #:
Total closure or partial closure of a position by applying opposite order is only possible with non-hedge accounts.
In case you are using a hedge account you may use PositionClosePartial method from Trade.mqh.
Also note that you are not allowed to update comment of position.
Can I ask why you are doing it in OnTrade event handler? Are you aware about the specific usage of this handler?
Anonymous Prime #:
i am really not too familiar with the ontrade and ontick but i do think that ontrade is for modifying opened trades isnt it?
what would recommend using
i am really lost and i am trying to learn how to do that
i am not really good at coding
 
Anonymous Prime #:
i am really not too familiar with the ontrade and ontick but i do think that ontrade is for modifying opened trades isnt it?

OnTrade event handler is invoked every time a trade event occurs. OnTick is used when you want to monitor market per tick and take actions accordingly. OnTick suits your purpose.

Check documentation for partial closure. 

 
Yashar Seyyedin #:

OnTrade event handler is invoked every time a trade event occurs. OnTick is used when you want to monitor market per tick and take actions accordingly. OnTick suits your purpose.

Check documentation for partial closure. 

thank you so much 
 
Anonymous Prime:

I am looking for guidance on the best practices to:

  1. Close half of an existing position.
  2. Update the position's comment to indicate that it has been partially closed.

Any help or suggestions on improving this part of the code would be greatly appreciated. Thank you!

#include <MT4Orders.mqh> // https://www.mql5.com/en/code/16006

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

void OnStart()
{
  const ulong Ticket = OrderSend(_Symbol, OP_BUY, 3.6, Ask, 0, 0, 0, "FullPosition");
  
  if (OrderSelect(Ticket, SELECT_BY_TICKET))
    OrderClose(OrderTicket(), 1.8, OrderClosePrice(), 0, clrNONE, "HalfPosition");
}
 
William Roeder #:
Don't post your MT4 code on this MT5 forum.

Please learn to see cross-platform code.