[HELP][MQL5] How to limit number of pending order & Close Parital Volume & Trailing SL, TP

 

I have an EA as below.

I want:

- limit the number of ending order = 20 (EA place ~200 order)

- When there is a profit of 200 points (20 pips), shift the SL and TP by 20 pips (using CheckAndAdjustProfitableOrders() and ModifyPosition())

- At the same time, close half the volume of active position.  (using CloseHalfPosition())

But it seems these functions don't work.

No order can be closed at half volume.

No SL TP moved (still 500 & 300)


Help me please!


Thank so muchhhh!!!!!!!




//+------------------------------------------------------------------+
//|                                                       TuNBH_EA.mq5 |
//|                        Copyright 2024, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property strict
#include <Trade\Trade.mqh>

#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class

// Input parameters
input double Lots = 0.1;             // Trading volume
input int StopLoss = 500;            // Stop loss (SL) in pips
input int TakeProfit = 350;          // Take profit (TP) in pips
input int MaxPointDifference = 1500; // Maximum point difference to delete limit orders
...
};

// Global variables


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
	...
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   	...
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
	...
  }


// Function to check if the order is a limit order
bool IsLimitOrder(const string symbol, const int ticket) {
    if (OrderSelect(ticket)) {
        long orderType = OrderGetInteger(ORDER_TYPE);
        if (orderType == ORDER_TYPE_BUY_LIMIT || orderType == ORDER_TYPE_SELL_LIMIT) {
            return true;
        }
    }
    return false;
}

// Function to check and delete limit orders if the current price difference is greater than 1500 points
void CheckAndDeleteLimitOrders() {
    	...
}

// Function to check and adjust orders when there is a profit of 200 pips
void CheckAndAdjustProfitableOrders() {
    int totalPositions = PositionsTotal();
    for (int i = 0; i < totalPositions; i++) {
        if (m_position.SelectByIndex(i)) {
            double entryPrice = m_position.PriceOpen();
            double currentPrice = m_position.PriceCurrent();
            double profitInPips = (currentPrice - entryPrice) / _Point; // Convert to pips
            if ((m_position.PositionType() == POSITION_TYPE_BUY && profitInPips >= 200) ||
                (m_position.PositionType() == POSITION_TYPE_SELL && profitInPips <= -200)) { // Condition for minimum profit of 200 pips
                // Adjust SL and TP by shifting 200 pips
                ModifyPosition(m_position.Ticket(), 200);
                // Close half of the position after adjustment
                CloseHalfPosition(m_position.Ticket());
            }
        }
    }
}

// Function to adjust SL and TP of the position
void ModifyPosition(ulong ticket, int pipOffset) {
    MqlTradeRequest request;
    MqlTradeResult result;
    ZeroMemory(request);
    ZeroMemory(result);

    request.action = TRADE_ACTION_SLTP;
    request.symbol = Symbol();
    request.position = ticket;
    
    // Get current position information
    if (!m_position.Select(ticket)) {
        Print("Failed to select position ", ticket, ". Error: ", GetLastError());
        return;
    }

    double entryPrice = m_position.PriceOpen();
    int orderType = m_position.PositionType();

    // Calculate new SL and TP
    if (orderType == POSITION_TYPE_BUY) {
        request.sl = entryPrice + 200 * _Point;
        request.tp = entryPrice + (200 + TakeProfit) * _Point;
    } else if (orderType == POSITION_TYPE_SELL) {
        request.sl = entryPrice - 200 * _Point;
        request.tp = entryPrice - (200 + TakeProfit) * _Point;
    }

    request.magic = 0;
    request.comment = "Adjust SL and TP";

    if (!OrderSend(request, result)) {
        Print("Failed to modify SL and TP for order ", ticket, ". Error: ", GetLastError());
    }
}

// Function to close half of the position
void CloseHalfPosition(ulong ticket) {
    double posVolume = m_position.Volume();
    double newVolume = NormalizeDouble(posVolume / 2.0, 2);

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

    request.action = TRADE_ACTION_DEAL;
    request.symbol = Symbol();
    request.volume = newVolume;
    request.position = ticket;
    request.deviation = 5;
    request.magic = 0;
    request.comment = "Close Half Position";
    request.type_filling = ORDER_FILLING_FOK;

    double currentPrice = SymbolInfoDouble(Symbol(), (m_position.PositionType() == POSITION_TYPE_BUY) ? SYMBOL_BID : SYMBOL_ASK);

    if (OrderSend(request, result)) {
        Print("Closed half position for order ", ticket);
    } else {
        Print("Failed to close half position for order ", ticket, ". Error: ", GetLastError());
    }
}
Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2024.07.18
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions