TrailingStairs

Download script
Author: I_D
TrailingStairs

This script is designed to automate the management of open trades by implementing a dynamic "staircase" trailing stop logic. Instead of simply moving a stop-loss at a fixed interval, this tool calculates specific price milestones to progressively secure profits as the market moves in your favor.

Core Functionality

The primary purpose of the script is to automatically adjust the Stop Loss (SL) of a specific trade (identified by its ticket number). It ensures that as the market price progresses, your "safety net" follows behind it in a structured, incremental fashion.

How the Logic Works

The script operates based on three main user-defined parameters:

  1. Target Distance: The minimum distance from the current price required before the trailing logic activates.
  2. Step Size: The specific increment by which the Stop Loss is moved forward.
  3. Trade Identifier: The specific position the script should monitor.

Operational Behavior

The logic adapts differently depending on whether you are in a "Buy" or "Sell" position:

For Buy Positions (Long):

  • Initial Activation: If there is no Stop Loss set, or if the current Stop Loss is below your entry price, the script calculates the first "staircase" level based on your entry price plus the defined distance.
  • Dynamic Movement: As the market price climbs, the script monitors for milestones. When the price hits a calculated threshold, it moves the Stop Loss forward by the "Step Size."
  • Safety Check: It ensures that the new Stop Loss is never placed too close to the current market price (respecting the broker's minimum requirements), preventing execution errors.

For Sell Positions (Short):

  • Initial Activation: Similarly, if no Stop Loss exists or it is above the entry price, the script establishes a baseline level relative to your entry price minus the defined distance and market spread.
  • Dynamic Movement: As the market price drops, the script identifies when the price has moved sufficiently to "step" the Stop Loss further down into profit.
  • Spread Awareness: The logic accounts for the market spread to ensure that stop-loss adjustments remain valid and executable in real-time trading conditions.

Summary of Benefits

By using a "staircase" approach rather than a standard continuous trailing stop, this script provides a more controlled way to lock in gains. It prevents the Stop Loss from moving too aggressively on minor price fluctuations while ensuring that significant market movements result in updated, secured profit levels automatically.

Orders Execution
It can change open orders parameters, due to possible stepping strategy
12 Views
0 Downloads
0 Favorites
TrailingStairs
//+------------------------------------------------------------------+
//|                                               TrailingStairs.mq4 |
//|                                                              I_D |
//|                                            http://www.mymmk.com/ |
//+------------------------------------------------------------------+
#property copyright "I_D"
#property link      "http://www.mymmk.com/ Ñîôò äëÿ óïðàâëåíèÿ êàïèòàëîì"

extern   int      iTicket;             // óíèêàëüíûé íîìåð (òèêåò) îòêðûòîé ïîçèöèè
extern   int      iTrldistance = 40;   // ðàññòîÿíèå îò òåêóùåãî êóðñà (ïóíêòîâ), íà êîòîðîì âêëþ÷àåòñÿ òðåéëèíã, ïóíêòîâ
extern   int      iTrlstep = 10;       // "øàã" èçìåíåíèÿ ñòîïëîññà (ïóíêòîâ) (íå ìåíüøå 1)

//+------------------------------------------------------------------+
//| ÒÐÅÉËÈÍà ÑÒÀÍÄÀÐÒÍÛÉ-ÑÒÓÏÅÍ×ÀÑÒÛÉ                                |
//| Ñîâåòíèêó ïåðåäà¸òñÿ òèêåò ïîçèöèè, ðàññòîÿíèå îò êóðñà îòêðûòèÿ,|
//| íà êîòîðîì òðåéëèíã çàïóñêàåòñÿ (ïóíêòîâ) è "øàã", ñ êîòîðûì îí  |
//| ïåðåíîñèòñÿ (ïóíêòîâ)                                            |
//| Ïðèìåð: ïðè +30 ñòîï íà +10, ïðè +40 - ñòîï íà +20 è ò.ä.        |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {    
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   TrailingStairs(iTicket,iTrldistance,iTrlstep);
   return(0);
  }
//+------------------------------------------------------------------+

void TrailingStairs(int ticket,int trldistance,int trlstep)
   { 
   
   double nextstair; // áëèæàéøåå çíà÷åíèå êóðñà, ïðè êîòîðîì áóäåì ìåíÿòü ñòîïëîññ

   // ïðîâåðÿåì ïåðåäàííûå çíà÷åíèÿ
   if ((trldistance<MarketInfo(Symbol(),MODE_STOPLEVEL)) || (trlstep<1) || (trldistance<trlstep) || (ticket==0) || (!OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)))
      {
      Print("Òðåéëèíã ôóíêöèåé TrailingStairs() íåâîçìîæåí èç-çà íåêîððåêòíîñòè çíà÷åíèé ïåðåäàííûõ åé àðãóìåíòîâ.");
      return(0);
      } 
   
   // åñëè äëèííàÿ ïîçèöèÿ (OP_BUY)
   if (OrderType()==OP_BUY)
      {
      // ðàñ÷èòûâàåì, ïðè êàêîì çíà÷åíèè êóðñà ñëåäóåò ñêîððåêòèðîâàòü ñòîïëîññ
      // åñëè ñòîïëîññ íèæå îòêðûòèÿ èëè ðàâåí 0 (íå âûñòàâëåí), òî áëèæàéøèé óðîâåíü = êóðñ îòêðûòèÿ + trldistance + ñïðýä
      if ((OrderStopLoss()==0) || (OrderStopLoss()<OrderOpenPrice()))
      nextstair = OrderOpenPrice() + trldistance*Point;
         
      // èíà÷å áëèæàéøèé óðîâåíü = òåêóùèé ñòîïëîññ + trldistance + trlstep + ñïðýä
      else
      nextstair = OrderStopLoss() + trldistance*Point;

      // åñëè òåêóùèé êóðñ (Bid) >= nextstair è íîâûé ñòîïëîññ òî÷íî ëó÷øå òåêóùåãî, êîððåêòèðóåì ïîñëåäíèé
      if (Bid>=nextstair)
         {
         if ((OrderStopLoss()==0) || (OrderStopLoss()<OrderOpenPrice()) && (OrderOpenPrice() + trlstep*Point<Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)) 
            {
            if (!OrderModify(ticket,OrderOpenPrice(),OrderOpenPrice() + trlstep*Point,OrderTakeProfit(),OrderExpiration()))
            Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
            }
         }
      else
         {
         if (!OrderModify(ticket,OrderOpenPrice(),OrderStopLoss() + trlstep*Point,OrderTakeProfit(),OrderExpiration()))
         Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
         }
      }
      
   // åñëè êîðîòêàÿ ïîçèöèÿ (OP_SELL)
   if (OrderType()==OP_SELL)
      { 
      // ðàñ÷èòûâàåì, ïðè êàêîì çíà÷åíèè êóðñà ñëåäóåò ñêîððåêòèðîâàòü ñòîïëîññ
      // åñëè ñòîïëîññ íèæå îòêðûòèÿ èëè ðàâåí 0 (íå âûñòàâëåí), òî áëèæàéøèé óðîâåíü = êóðñ îòêðûòèÿ + trldistance + ñïðýä
      if ((OrderStopLoss()==0) || (OrderStopLoss()>OrderOpenPrice()))
      nextstair = OrderOpenPrice() - (trldistance + MarketInfo(Symbol(),MODE_SPREAD))*Point;
      
      // èíà÷å áëèæàéøèé óðîâåíü = òåêóùèé ñòîïëîññ + trldistance + trlstep + ñïðýä
      else
      nextstair = OrderStopLoss() - (trldistance + MarketInfo(Symbol(),MODE_SPREAD))*Point;
       
      // åñëè òåêóùèé êóðñ (Àñê) >= nextstair è íîâûé ñòîïëîññ òî÷íî ëó÷øå òåêóùåãî, êîððåêòèðóåì ïîñëåäíèé
      if (Ask<=nextstair)
         {
         if ((OrderStopLoss()==0) || (OrderStopLoss()>OrderOpenPrice()) && (OrderOpenPrice() - (trlstep + MarketInfo(Symbol(),MODE_SPREAD))*Point>Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
            {
            if (!OrderModify(ticket,OrderOpenPrice(),OrderOpenPrice() - (trlstep + MarketInfo(Symbol(),MODE_SPREAD))*Point,OrderTakeProfit(),OrderExpiration()))
            Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
            }
         }
      else
         {
         if (!OrderModify(ticket,OrderOpenPrice(),OrderStopLoss()- (trlstep + MarketInfo(Symbol(),MODE_SPREAD))*Point,OrderTakeProfit(),OrderExpiration()))
         Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
         }
      }      
   }
//+------------------------------------------------------------------+

Comments