TrailingStop_v1

Download script
Author: Jo�o Barbosa
TrailingStop_v1

This script is designed to automate the management of open trades by dynamically adjusting "Stop Loss" levels as the market moves in your favor. Its primary objective is to protect your profits by ensuring that once a trade enters a winning state, the exit point follows the price movement at a consistent distance.

How it Works

The tool constantly scans all currently active trades in your portfolio. For every open position, it evaluates three specific conditions before taking action:

  1. Profitability Check: The script only activates when a trade is already in a profit state.
  2. Distance Threshold: It checks if the current price has moved far enough away from your original Stop Loss. If the distance between the current price and your Stop Loss exceeds the predefined "Trailing Stop" value (measured in pips), the script triggers an update.
  3. Market Compliance: It automatically ensures that the requested movement follows the broker's minimum rules, preventing the script from attempting to place a stop level that is too close to the current market price.

The Execution Process

When the conditions above are met, the script performs the following actions:

  • Dynamic Adjustment: If you are in a Buy position, it moves your Stop Loss upward to stay a set distance behind the rising price. If you are in a Sell position, it moves the Stop Loss downward to follow the falling price.
  • Persistence: The logic includes a "retry" mechanism. If the broker's server is busy or rejects an initial modification request, the script will attempt to re-send the update multiple times (up to 10 tries) with short pauses between attempts to ensure the protection is successfully placed.
  • Performance Tracking: The script keeps an internal tally of how many times it has successfully moved a stop loss into a profitable zone, providing you with a metric of how many "guaranteed pips" have been secured during the session.

Summary for the User

Essentially, this tool acts as a safety net that "locks in" your gains. As the market moves in your favor, the script automatically drags your exit point along with it. This ensures that if the market suddenly reverses, you capture as much of the profit as possible rather than letting a winning trade turn into a loss.

Price Data Components
Series array that contains open time of each bar
Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategy
16 Views
0 Downloads
0 Favorites
TrailingStop_v1
//+------------------------------------------------------------------+
//|                                      Universal Trailing Stop.mq4 |
//|                                                     Joao Barbosa |
//|                                        obarbosa2001@yahoo.com.br |
//+------------------------------------------------------------------+
#property copyright "João Barbosa"
#property link      "obarbosa2001@yahoo.com.br"

extern int TrailingStop = 20; // Valor do Trailing Stop
       int Tentativas = 10; // número de tentativas para executar a ordem
       int B=0; // Contagem de acionamentos = +- quantidade de pips garantidos
       // isso indica o quanto esse EA rendeu em pips em cada seçao para quem usa

int init()
  {Print("Garante Lucro Universal iniciado (",TimeToStr(CurTime(),TIME_DATE)," - ",TimeToStr(CurTime(),TIME_SECONDS),") ");
   start();return(0);}
int deinit()
  {Print("Garante Lucro Universal finalizado (",TimeToStr(CurTime(),TIME_DATE)," - ",TimeToStr(CurTime(),TIME_SECONDS),") ");return(0);}
int start()
  {Comment("Universal Trailing Stop(",TimeToStr(CurTime(),TIME_DATE)," - ",TimeToStr(CurTime(),TIME_SECONDS),") ");
   for(int J = OrdersTotal()-1; J >= 0; J--)
    {OrderSelect(J, SELECT_BY_POS, MODE_TRADES);
     double OrderPoint=MarketInfo(OrderSymbol(),MODE_POINT);
     double SLMin=MarketInfo(OrderSymbol(),MODE_STOPLEVEL);
     int TS=TrailingStop;
     int Mudou=Tentativas;
     if (TrailingStop<SLMin) TS=SLMin; 
     if ( (TrailingStop>0) && (OrderProfit()>0.0) && 
          (MathAbs(OrderStopLoss()-OrderClosePrice())/OrderPoint>TS) )
             { if (OrderType()==OP_SELL)
                { Print("Modificando ordem ",OrderSymbol()," SL: ", OrderClosePrice()+TS*OrderPoint);
                  while (Mudou>0)
                    { Mudou=Mudou-1;
                      if (OrderModify(OrderTicket(),OrderOpenPrice(),OrderClosePrice()+TS*OrderPoint,OrderTakeProfit(),0,Red)==0) Mudou=0;
                      else Sleep(1000);
                    }
                  B=B+1;}
               else if (OrderType()==OP_BUY)
                { Print("Modificando ordem ",OrderSymbol()," SL: ", OrderClosePrice()-TS*OrderPoint);
                  while (Mudou>0)
                    { Mudou=Mudou-1;
                      if (OrderModify(OrderTicket(),OrderOpenPrice(),OrderClosePrice()-TS*OrderPoint,OrderTakeProfit(),0,Red)==0) Mudou=0;
                      else Sleep(1000);
                    }
                  B=B+1;}
             }
    }
   return(0);
  }

Comments