will the following ea trail the price after tp :


//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
#property copyright ""
#property link ""
#property version "1.17" // Updated version
#property strict

#include <Trade\Trade.mqh>

class CGUI
{
public:
    void AddLabel(string name, string text, int x, int y, color clr)
    {
        ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
        ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
        ObjectSetString(0, name, OBJPROP_TEXT, text);
        ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
    }
    void UpdateLabel(string name, string text, color clr)
    {
        ObjectSetString(0, name, OBJPROP_TEXT, text);
        ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
    }
};

// Inputs
input double Lots = 0.01;
input int PointsThreshold = 30;
input int CheckInterval = 10;
input int TrailingStopPoints = 10;
input int EAStartHour = 2;
input int EAStopHour = 20;
input ENUM_TIMEFRAMES PriceTF = PERIOD_M1;
input int TradesPerSignal = 1;
input int InitialStopLossPoints = 0;
input int InitialTakeProfitPoints = 140;
input bool UseMAForClosing = false;
input bool CloseTradesAtSpecificHour = true;
input int HourToCloseTrades = 20;
input int ADXPeriod = 14;
input double ADXThreshold = 20.0;

// Global variables
datetime lastCheckTime = 0;
double priceAtLastCheck = 0.0;
int adxHandle = INVALID_HANDLE;
bool isNewTradingSession = true;
datetime tradingSessionStartTime = 0;
int tradingDelayMinutes = 30;
string priceMoveLineName = "PriceMoveLine";
string priceMoveTextName = "PriceMoveText";
string maxPosMoveTextName = "MaxPosMoveText";
string maxNegMoveTextName = "MaxNegMoveText";
string breakoutArrowNameBuy = "BreakoutBuy";
string breakoutArrowNameSell = "BreakoutSell";
double maxPosPointsMoved = 0.0;
double maxPosRatePointsPerSec = 0.0;
double maxNegPointsMoved = 0.0;
double maxNegRatePointsPerSec = 0.0;
int prevPositionsCount = 0;
datetime lastTradeCloseTime = 0;
CGUI gui;
CTrade trade;

// Struct to track position info for trailing stop
struct PosInfo
{
    ulong ticket;
    bool trailing_started;
    double open_price;
    ENUM_POSITION_TYPE type;
};

PosInfo posInfos[];

// Function prototypes
int GetPosInfoIndex(ulong ticket);
void AddPosInfo(ulong ticket, double open_price, ENUM_POSITION_TYPE type);
void RemovePosInfo(ulong ticket);
void ManageTrailingStop();
bool ModifyPositionSL(ulong ticket, double new_sl);

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
    PrintFormat("EA started with InitialStopLossPoints=%d, TrailingStopPoints=%d, ADXPeriod=%d, ADXThreshold=%.1f, UseMAForClosing=%s",
        InitialStopLossPoints, TrailingStopPoints, ADXPeriod, ADXThreshold, UseMAForClosing ? "true" : "false");
    if(UseMAForClosing)
    {
        Print("Warning: UseMAForClosing is set to true, but MA logic has been removed. Trade closing will not use MA.");
    }
    priceAtLastCheck = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    lastCheckTime = TimeCurrent();
    adxHandle = iADX(_Symbol, PriceTF, ADXPeriod);
    if(adxHandle == INVALID_HANDLE)
    {
        Print("Failed to create ADX handle");
        return INIT_FAILED;
    }
    else
    {
        PrintFormat("ADX indicator created successfully (Period: %d).", ADXPeriod);
    }
    prevPositionsCount = 0;
    isNewTradingSession = true;
    gui.AddLabel("spreadLabel", "Spread: 0", 5, 255 + 35, clrYellow);
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    CleanOldObjects();
    if(adxHandle != INVALID_HANDLE)
    {
        IndicatorRelease(adxHandle);
        adxHandle = INVALID_HANDLE;
    }
}

//+------------------------------------------------------------------+
//| Check if current time is inside operation window |
//+------------------------------------------------------------------+
bool IsWithinTradingTime()
{
    datetime now = TimeCurrent();
    MqlDateTime tm;
    TimeToStruct(now, tm);
    return(tm.hour >= EAStartHour && tm.hour < EAStopHour);
}

//+------------------------------------------------------------------+
//| Check if EA has any open positions on current symbol |
//+------------------------------------------------------------------+
bool HasOpenPositions()
{
    for(int i = 0; i < PositionsTotal(); i++)
    {
        ulong ticket = PositionGetTicket(i);
        if(PositionSelectByTicket(ticket))
        {
            if(PositionGetInteger(POSITION_MAGIC) == ExpertHandle() &&
               PositionGetString(POSITION_SYMBOL) == _Symbol)
                return true;
        }
    }
    return false;
}

//+------------------------------------------------------------------+
//| Place buy order without initial take profit |
//+------------------------------------------------------------------+
bool PlaceBuy()
{
    double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double sl_price = (InitialStopLossPoints > 0) ? NormalizeDouble(price - InitialStopLossPoints * _Point, _Digits) : 0.0;
    bool res = trade.Buy(Lots, _Symbol, price, sl_price, 0, "Buy no TP, manual trailing");
    if(!res)
    {
        PrintFormat("Buy order failed: %s", trade.ResultRetcodeDescription());
        return false;
    }
    PrintFormat("Buy order placed at price %.5f with SL at %.5f (no TP)", price, sl_price);
    ulong ticket = trade.ResultOrder();
    AddPosInfo(ticket, price, POSITION_TYPE_BUY);
    return true;
}

//+------------------------------------------------------------------+
//| Place sell order without initial take profit |
//+------------------------------------------------------------------+
bool PlaceSell()
{
    double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double sl_price = (InitialStopLossPoints > 0) ? NormalizeDouble(price + InitialStopLossPoints * _Point, _Digits) : 0.0;
    bool res = trade.Sell(Lots, _Symbol, price, sl_price, 0, "Sell no TP, manual trailing");
    if(!res)
    {
        PrintFormat("Sell order failed: %s", trade.ResultRetcodeDescription());
        return false;
    }
    PrintFormat("Sell order placed at price %.5f with SL at %.5f (no TP)", price, sl_price);
    ulong ticket = trade.ResultOrder();
    AddPosInfo(ticket, price, POSITION_TYPE_SELL);
    return true;
}

//+------------------------------------------------------------------+
//| Helper functions for PosInfo tracking |
//+------------------------------------------------------------------+
int GetPosInfoIndex(ulong ticket)
{
    for(int i = 0; i < ArraySize(posInfos); i++)
    {
        if(posInfos[i].ticket == ticket)
        {
            return i;
        }
    }
    return -1;
}

void AddPosInfo(ulong ticket, double open_price, ENUM_POSITION_TYPE type)
{
    PosInfo p;
    p.ticket = ticket;
    p.open_price = open_price;
    p.type = type;
    p.trailing_started = false;
    int resize = ArraySize(posInfos) + 1;
    ArrayResize(posInfos, resize);
    posInfos[ArraySize(posInfos) - 1] = p;
}

void RemovePosInfo(ulong ticket)
{
    int index = GetPosInfoIndex(ticket);
    if(index != -1)
    {
        for(int i = index; i < ArraySize(posInfos) - 1; i++)
        {
            posInfos[i] = posInfos[i + 1];
        }
        ArrayResize(posInfos, ArraySize(posInfos) - 1);
    }
}

//+------------------------------------------------------------------+
//| Implement trailing stop for each position |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
    if(TrailingStopPoints <= 0) return;

    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if(!PositionSelectByTicket(ticket)) continue;
        if(PositionGetInteger(POSITION_MAGIC) != ExpertHandle()) continue;
        if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;

        ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
        double current_price = (type == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double position_sl = PositionGetDouble(POSITION_SL);
        double position_open_price = PositionGetDouble(POSITION_PRICE_OPEN);

        int index = GetPosInfoIndex(ticket);
        if(index == -1)
        {
            AddPosInfo(ticket, position_open_price, type);
            index = GetPosInfoIndex(ticket);
        }

        PosInfo p = posInfos[index];
        double profit_points = (type == POSITION_TYPE_BUY) ? (current_price - position_open_price) / _Point : (position_open_price - current_price) / _Point;

        if(!p.trailing_started)
        {
            if(profit_points >= InitialTakeProfitPoints && InitialTakeProfitPoints > 0)
            {
                p.trailing_started = true;
                posInfos[index] = p;
                PrintFormat("Position %I64u reached manual TP (%.1f pts). Starting trailing stop.", ticket, profit_points);
                double new_sl = (type == POSITION_TYPE_BUY) ? current_price - TrailingStopPoints * _Point : current_price + TrailingStopPoints * _Point;
                new_sl = NormalizeDouble(new_sl, _Digits);
                if((type == POSITION_TYPE_BUY && (position_sl == 0 || position_sl < new_sl)) ||
                   (type == POSITION_TYPE_SELL && (position_sl == 0 || position_sl > new_sl)))
                {
                    if(ModifyPositionSL(ticket, new_sl))
                        PrintFormat("Initial trailing SL set at %.5f", new_sl);
                    else
                        Print("Failed to set initial trailing SL.");
                }
            }
        }
        else
        {
            double new_sl = (type == POSITION_TYPE_BUY) ? current_price - TrailingStopPoints * _Point : current_price + TrailingStopPoints * _Point;
            new_sl = NormalizeDouble(new_sl, _Digits);
            if((type == POSITION_TYPE_BUY && new_sl > position_sl) || (type == POSITION_TYPE_SELL && new_sl < position_sl))
            {
                if(ModifyPositionSL(ticket, new_sl))
                    PrintFormat("Trailing SL moved to %.5f for position %I64u", new_sl, ticket);
                else
                    Print("Failed to move trailing SL.");
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Modify position SL |
//+------------------------------------------------------------------+
bool ModifyPositionSL(ulong ticket, double new_sl)
{
    MqlTradeRequest request = {};
    MqlTradeResult result = {};
    request.action = TRADE_ACTION_SLTP;
    request.position = ticket;
    request.sl = new_sl;
    request.tp = 0;
    if(!OrderSend(request, result))
    {
        PrintFormat("Modify SL failed: %d - %s", result.retcode, result.comment);
        return false;
    }
    return true;
}

//+------------------------------------------------------------------+
//| Remove old chart objects to keep the chart clean |
//+------------------------------------------------------------------+
void CleanOldObjects()
{
    string names[] = {priceMoveLineName, priceMoveTextName, maxPosMoveTextName, maxNegMoveTextName, breakoutArrowNameBuy, breakoutArrowNameSell};
    for(int i = 0; i < ArraySize(names); i++)
    {
        if(ObjectFind(0, names[i]) != -1)
            ObjectDelete(0, names[i]);
    }
}

//+------------------------------------------------------------------+
//| Draw price movement visualization |
//+------------------------------------------------------------------+
void DrawPriceMoveLine(datetime time1, double price1, datetime time2, double price2)
{
    if(ObjectFind(0, priceMoveLineName) == -1)
        ObjectCreate(0, priceMoveLineName, OBJ_TREND, 0, time1, price1, time2, price2);
    else
    {
        ObjectMove(0, priceMoveLineName, 0, time1, price1);
        ObjectMove(0, priceMoveLineName, 1, time2, price2);
    }
    ObjectSetInteger(0, priceMoveLineName, OBJPROP_COLOR, clrDodgerBlue);
    ObjectSetInteger(0, priceMoveLineName, OBJPROP_WIDTH, 2);
    ObjectSetInteger(0, priceMoveLineName, OBJPROP_RAY_RIGHT, false);
}

//+------------------------------------------------------------------+
//| Draw current move statistics |
//+------------------------------------------------------------------+
void DrawSpeedText(double pointsMoved, int secondsPassed)
{
    string text = StringFormat("Move: %.1f pts\nTime: %d sec\nRate: %.2f pts/sec", pointsMoved, secondsPassed, pointsMoved / secondsPassed);
    if(ObjectFind(0, priceMoveTextName) == -1)
    {
        ObjectCreate(0, priceMoveTextName, OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, priceMoveTextName, OBJPROP_CORNER, 0);
        ObjectSetInteger(0, priceMoveTextName, OBJPROP_XDISTANCE, 10);
        ObjectSetInteger(0, priceMoveTextName, OBJPROP_YDISTANCE, 20);
        ObjectSetInteger(0, priceMoveTextName, OBJPROP_FONTSIZE, 12);
        ObjectSetInteger(0, priceMoveTextName, OBJPROP_COLOR, clrWhite);
        ObjectSetInteger(0, priceMoveTextName, OBJPROP_BACK, true);
    }
    ObjectSetString(0, priceMoveTextName, OBJPROP_TEXT, text);
}

//+------------------------------------------------------------------+
//| Draw maximum positive move statistics |
//+------------------------------------------------------------------+
void DrawMaxPosMoveText()
{
    string text = StringFormat("Max +move: %.1f pts\nMax +rate: %.2f pts/sec", maxPosPointsMoved, maxPosRatePointsPerSec);
    if(ObjectFind(0, maxPosMoveTextName) == -1)
    {
        ObjectCreate(0, maxPosMoveTextName, OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, maxPosMoveTextName, OBJPROP_CORNER, 0);
        ObjectSetInteger(0, maxPosMoveTextName, OBJPROP_XDISTANCE, 10);
        ObjectSetInteger(0, maxPosMoveTextName, OBJPROP_YDISTANCE, 40);
        ObjectSetInteger(0, maxPosMoveTextName, OBJPROP_FONTSIZE, 12);
        ObjectSetInteger(0, maxPosMoveTextName, OBJPROP_COLOR, clrGreen);
        ObjectSetInteger(0, maxPosMoveTextName, OBJPROP_BACK, true);
    }
    ObjectSetString(0, maxPosMoveTextName, OBJPROP_TEXT, text);
}

//+------------------------------------------------------------------+
//| Draw maximum negative move statistics |
//+------------------------------------------------------------------+
void DrawMaxNegMoveText()
{
    string text = StringFormat("Max -move: %.1f pts\nMax -rate: %.2f pts/sec", maxNegPointsMoved, maxNegRatePointsPerSec);
    if(ObjectFind(0, maxNegMoveTextName) == -1)
    {
        ObjectCreate(0, maxNegMoveTextName, OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, maxNegMoveTextName, OBJPROP_CORNER, 0);
        ObjectSetInteger(0, maxNegMoveTextName, OBJPROP_XDISTANCE, 10);
        ObjectSetInteger(0, maxNegMoveTextName, OBJPROP_YDISTANCE, 60);
        ObjectSetInteger(0, maxNegMoveTextName, OBJPROP_FONTSIZE, 12);
        ObjectSetInteger(0, maxNegMoveTextName, OBJPROP_COLOR, clrRed);
        ObjectSetInteger(0, maxNegMoveTextName, OBJPROP_BACK, true);
    }
    ObjectSetString(0, maxNegMoveTextName, OBJPROP_TEXT, text);
}

//+------------------------------------------------------------------+
//| Draw breakout arrow on chart |
//+------------------------------------------------------------------+
void DrawBreakoutArrow(bool isBuy, datetime time_, double price_)
{
    string name = isBuy ? breakoutArrowNameBuy : breakoutArrowNameSell;
    int arrowCode = isBuy ? 233 : 234;
    color clrArrow = isBuy ? clrLime : clrRed;
    if(ObjectFind(0, name) != -1)
        ObjectDelete(0, name);
    ObjectCreate(0, name, OBJ_ARROW, 0, time_, price_);
    ObjectSetInteger(0, name, OBJPROP_ARROWCODE, arrowCode);
    ObjectSetInteger(0, name, OBJPROP_COLOR, clrArrow);
    ObjectSetInteger(0, name, OBJPROP_WIDTH, 3);
}

//+------------------------------------------------------------------+
//| Get trend direction using ADX: 1 = Bullish, -1 = Bearish, 0 = No Clear Trend |
//+------------------------------------------------------------------+
int GetTrendDirection()
{
    if(adxHandle == INVALID_HANDLE)
    {
        Print("GetTrendDirection: ADX handle is invalid.");
        return 0;
    }
    double adxMainBuffer[], adxPlusBuffer[], adxMinusBuffer[];
    if(CopyBuffer(adxHandle, 0, 0, 1, adxMainBuffer) <= 0 ||
       CopyBuffer(adxHandle, 1, 0, 1, adxPlusBuffer) <= 0 ||
       CopyBuffer(adxHandle, 2, 0, 1, adxMinusBuffer) <= 0)
    {
        Print("GetTrendDirection: Failed to copy ADX buffer data");
        return 0;
    }
    double adxMain = adxMainBuffer[0];
    double adxPlus = adxPlusBuffer[0];
    double adxMinus = adxMinusBuffer[0];
    if(adxMain > ADXThreshold)
    {
        if(adxPlus > adxMinus) return 1;
        else if(adxMinus > adxPlus) return -1;
    }
    return 0;
}

//+------------------------------------------------------------------+
//| Close position by ticket |
//+------------------------------------------------------------------+
bool ClosePosition(ulong ticket)
{
    if(!PositionSelectByTicket(ticket))
    {
        PrintFormat("Position %I64u not found for closing", ticket);
        return false;
    }
    double volume = PositionGetDouble(POSITION_VOLUME);
    string symbol = PositionGetString(POSITION_SYMBOL);
    ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
    MqlTradeRequest request;
    MqlTradeResult result;
    ZeroMemory(request);
    ZeroMemory(result);
    request.action = TRADE_ACTION_DEAL;
    request.position = ticket;
    request.symbol = symbol;
    request.volume = volume;
    request.type = (type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
    request.price = SymbolInfoDouble(symbol, (type == POSITION_TYPE_BUY) ? SYMBOL_BID : SYMBOL_ASK);
    request.deviation = 10;
    request.magic = ExpertHandle();
    if(!OrderSend(request, result))
    {
        PrintFormat("Failed to close position %I64u: %s", ticket, result.comment);
        return false;
    }
    PrintFormat("Position %I64u closed successfully", ticket);
    return true;
}

//+------------------------------------------------------------------+
//| Function to close all open trades |
//+------------------------------------------------------------------+
void CloseAllOpenTrades()
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if(PositionSelectByTicket(ticket))
        {
            if(PositionGetInteger(POSITION_MAGIC) == ExpertHandle() &&
               PositionGetString(POSITION_SYMBOL) == _Symbol)
            {
                ClosePosition(ticket);
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Check and close positions if price crosses MA with buffer |
//+------------------------------------------------------------------+
void CheckCloseByMA()
{
    if(!UseMAForClosing)
        return;
    Print("CheckCloseByMA called, but UseMAForClosing is false. No action taken.");
}

//+------------------------------------------------------------------+
//| Check price speed and trade accordingly |
//+------------------------------------------------------------------+
void CheckAndTrade()
{
    datetime now = TimeCurrent();
    if(lastTradeCloseTime != 0 && (now - lastTradeCloseTime) < 300)
        return;
    else if(lastTradeCloseTime != 0)
    {
        lastCheckTime = now;
        priceAtLastCheck = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        lastTradeCloseTime = 0;
        Print("Cooldown period ended. Reset price reference.");
    }
    if(HasOpenPositions())
        return;
    if(!IsWithinTradingTime())
        return;
    double current_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double points_moved = (current_price - priceAtLastCheck) / _Point;
    int time_diff = (int)(now - lastCheckTime);
    if(time_diff < CheckInterval)
        return;
    CleanOldObjects();
    DrawPriceMoveLine(lastCheckTime, priceAtLastCheck, now, current_price);
    DrawSpeedText(points_moved, time_diff);
    double absPointsMoved = MathAbs(points_moved);
    double rate = absPointsMoved / time_diff;
    if(points_moved > 0)
    {
        if(points_moved > maxPosPointsMoved) maxPosPointsMoved = points_moved;
        if(rate > maxPosRatePointsPerSec) maxPosRatePointsPerSec = rate;
    }
    else if(points_moved < 0)
    {
        double negMoveAbs = -points_moved;
        if(negMoveAbs > maxNegPointsMoved) maxNegPointsMoved = negMoveAbs;
        if(rate > maxNegRatePointsPerSec) maxNegRatePointsPerSec = rate;
    }
    DrawMaxPosMoveText();
    DrawMaxNegMoveText();
    int trend = GetTrendDirection();
    if(points_moved >= PointsThreshold)
    {
        PrintFormat("Bullish breakout detected: Moved up %.1f points in %d seconds", points_moved, time_diff);
        DrawBreakoutArrow(true, now, current_price);
        if(trend == 1)
        {
            double log_bid_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double log_ask_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            PrintFormat("!!! TRADE CONFIRMATION - BUY (ADX) !!!");
            PrintFormat("Current Bid Price: %.5f", log_bid_price);
            PrintFormat("Current Ask Price: %.5f (Price used for Buy order)", log_ask_price);
            PrintFormat("ADX Trend Check Result: %d (1=Bullish, -1=Bearish, 0=Neutral/No Trend)", trend);
            for(int i = 0; i < TradesPerSignal; i++)
                PlaceBuy();
        }
        else
        {
            PrintFormat("Bullish breakout detected but ADX trend is not bullish (Trend: %d). No buy trade taken.", trend);
        }
    }
    else if(points_moved <= -PointsThreshold)
    {
        PrintFormat("Bearish breakout detected: Moved down %.1f points in %d seconds", points_moved, time_diff);
        DrawBreakoutArrow(false, now, current_price);
        if(trend == -1)
        {
            double log_bid_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double log_ask_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            PrintFormat("!!! TRADE CONFIRMATION - SELL (ADX) !!!");
            PrintFormat("Current Bid Price: %.5f (Price used for Sell order)", log_bid_price);
            PrintFormat("Current Ask Price: %.5f", log_ask_price);
            PrintFormat("ADX Trend Check Result: %d (1=Bullish, -1=Bearish, 0=Neutral/No Trend)", trend);
            for(int i = 0; i < TradesPerSignal; i++)
                PlaceSell();
        }
        else
        {
            PrintFormat("Bearish breakout detected but ADX trend is not bearish (Trend: %d). No sell trade taken.", trend);
        }
    }
    lastCheckTime = now;
    priceAtLastCheck = current_price;
}

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
    ManageTrailingStop();
    CheckCloseByMA();
    datetime now = TimeCurrent();
    MqlDateTime tm;
    TimeToStruct(now, tm);
    if(CloseTradesAtSpecificHour && tm.hour == HourToCloseTrades && tm.min == 0)
    {
        Print("Closing all open trades to prevent swap fees.");
        CloseAllOpenTrades();
    }
    if(isNewTradingSession && tm.hour == EAStartHour && tm.min == 0)
    {
        priceAtLastCheck = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        lastCheckTime = now;
        tradingSessionStartTime = now;
        isNewTradingSession = false;
        Print("New trading session started. Reset initial price reference.");
    }
    if(now - tradingSessionStartTime < tradingDelayMinutes * 60)
        return;
    int currentPositionsCount = 0;
    for(int i = 0; i < PositionsTotal(); i++)
    {
        ulong ticket = PositionGetTicket(i);
        if(PositionSelectByTicket(ticket))
        {
            if(PositionGetInteger(POSITION_MAGIC) == ExpertHandle() &&
               PositionGetString(POSITION_SYMBOL) == _Symbol)
                currentPositionsCount++;
        }
    }
    if(prevPositionsCount > 0 && currentPositionsCount == 0)
    {
        lastTradeCloseTime = now;
        isNewTradingSession = true;
        PrintFormat("Trade closed at %s, cooldown start", TimeToString(lastTradeCloseTime, TIME_SECONDS));
    }
    prevPositionsCount = currentPositionsCount;
    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
    int spreadPoints = (int)round((ask - bid) / point);
    gui.UpdateLabel("spreadLabel", "Spread: " + IntegerToString(spreadPoints) + " pts", clrYellow);
    CheckAndTrade();
}

//+------------------------------------------------------------------+
//| Helper: return magic number |
//+------------------------------------------------------------------+
uint ExpertHandle()
{
    return 123456;
}




like the following does:

/*


    Does NOT set TP on the order when opened (so broker won't auto-close).
    Tracks price manually: once price moves up by TakeProfitPoints, it starts trailing stop.
    Trailing stop moves SL upwards by TrailingStopPoints behind current price.
    Closes position only when trailing SL is hit.
    This works properly in the strategy tester or live, simulating the requested "TP then trailing stop" behavior.
*/
//+------------------------------------------------------------------+
//|                                         TP-then-trail-adjusted.mq5|
//|      Opens Buy, waits until profit target in points reached, then|
//|        starts trailing stop instead of broker TP                 |
//+------------------------------------------------------------------+
#property copyright "ChatGPT"
#property link      "https://openai.com/"
#property version   "1.30"
#property strict

#include <Trade\Trade.mqh>

input int    TakeProfitPoints   = 140;    // Target profit in points before trailing start
input int    TrailingStopPoints = 3;     // Trailing stop distance in points
input ulong  MagicNumber        = 123456; // EA magic number
input double LotSize           = 0.01;    // Trade lot size

ulong ticket = 0;
bool  trailing_started = false;

CTrade trade;

//+------------------------------------------------------------------+
//| Expert initialization                                            |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
     {
      Print("Trading not allowed in this terminal!");
      return(INIT_FAILED);
     }
   Print("EA initialized. Waiting for market to open to place buy...");
   return(INIT_SUCCEEDED);
  }

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

//+------------------------------------------------------------------+
//| Expert tick                                                     |
//+------------------------------------------------------------------+
void OnTick()
  {
   // If no position, try open buy at first valid tick
   if(!PositionSelect(_Symbol))
     {
      double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      if(ask <= 0)
         return; // wait for valid price

      // Validate lot size per symbol rules
      double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
      double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
      double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
      double lot = LotSize;

      if(lot < min_lot) lot = min_lot;
      else lot = MathFloor(lot / lot_step) * lot_step;
      if(lot > max_lot) lot = max_lot;

      trade.SetExpertMagicNumber(MagicNumber);
      trade.SetDeviationInPoints(10);

      // ** NO TP set here to avoid broker auto closing **
      PrintFormat("Trying BUY order: volume=%.2f at price=%.5f (NO TP)", lot, ask);

      if(trade.Buy(lot, _Symbol, ask, 0, 0, "Buy no TP, manual trailing"))
        {
         ticket = trade.ResultOrder();
         trailing_started = false;
         PrintFormat("Buy order placed successfully. Ticket=%I64u", ticket);
        }
      else
        {
         PrintFormat("Buy order failed: %d - %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
        }
      return;
     }

   // We have a position; confirm it’s ours by magic & ticket
   ulong pos_ticket = PositionGetInteger(POSITION_TICKET);
   ulong pos_magic  = PositionGetInteger(POSITION_MAGIC);
   if(pos_magic != MagicNumber || pos_ticket != ticket)
     {
      // Not our position
      return;
     }

   double current_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   if(current_price <= 0)
      return;

   double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
   double current_sl = PositionGetDouble(POSITION_SL);
   double profit_points = (current_price - open_price) / _Point; // points gained for BUY position

   // If trailing not started yet, check if profit target reached
   if(!trailing_started)
     {
      if(profit_points >= TakeProfitPoints)
        {
         trailing_started = true;
         PrintFormat("Profit target reached: %.1f points. Starting trailing stop.", profit_points);

         // Set initial SL for trailing stop at current_price - TrailingStopPoints
         double new_sl = NormalizeDouble(current_price - TrailingStopPoints * _Point, _Digits);

         // Only set SL if > 0 and less than open_price (better safe)
         if(new_sl > 0 && (current_sl == 0 || new_sl > current_sl))
           {
            if(ModifyPositionSL(new_sl))
               PrintFormat("Initial trailing SL set at %.5f", new_sl);
            else
               Print("Failed to set initial trailing SL.");
           }
        }
     }
   else
     {
      // Trailing started: move SL up if price moved up enough
      double new_sl = NormalizeDouble(current_price - TrailingStopPoints * _Point, _Digits);

      if(new_sl > current_sl)
        {
         if(ModifyPositionSL(new_sl))
            PrintFormat("Trailing SL moved up to %.5f", new_sl);
         else
            Print("Failed to move trailing SL.");
        }
     }
  }

//+------------------------------------------------------------------+
//| Modify position SL                                               |
//+------------------------------------------------------------------+
bool ModifyPositionSL(double new_sl)
  {
   trade.SetExpertMagicNumber(MagicNumber);
   bool res = trade.PositionModify(ticket, new_sl, 0);
   if(!res)
     {
      PrintFormat("Modify SL failed: %d - %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
     }
   return res;
  }
//+------------------------------------------------------------------+

/*

What this EA does:

    Opens a buy order with NO TP.
    Tracks profit in points (profit_points).
    Once profit >= TakeProfitPoints, the EA:
        Starts trailing stop by setting SL at current price minus trailing distance.
    Moves SL upward as price moves up by trailing distance.
    Position closes automatically only if price breaks trailing stop (SL).
    All trade management by the EA, no broker TP involved.

*/