TrailingByTime

Download script
Author: I_D
TrailingByTime

This script is designed to automate the management of an active trading position by dynamically adjusting your "Stop Loss" (the price at which a trade automatically closes to limit losses) based on the amount of time that has passed since the trade was opened.

Core Logic Overview

Unlike standard trailing stops that move based solely on price fluctuations, this tool uses time-based progression. It calculates how much time has elapsed and moves the Stop Loss forward at fixed intervals.

How it Works

To use this script, you identify a specific trade (via its unique ticket number) and set three primary parameters:

  1. Time Interval: The frequency (in minutes) at which the Stop Loss should move.
  2. Step Size: The amount of price movement (in points) by which the Stop Loss will shift during each interval.
  3. Loss Trailing Toggle: A setting to decide if the Stop Loss should follow your current profit/loss progress or remain anchored relative to your entry price.

Operational Behavior

For Buy Positions (Long): The script calculates how many time intervals have passed since you entered the trade. For every interval completed, it moves the Stop Loss higher:

  • If "Loss Trailing" is off, the stop moves up based on your original opening price.
  • If "Loss Trailing" is on, the script looks at your current Stop Loss and pushes it further up from that point.
  • It includes a safety check to ensure the new Stop Loss isn't set too close to the current market price, preventing the trade from closing instantly due to broker restrictions.

For Sell Positions (Short): The logic is inverted to accommodate downward price movements. The script moves the Stop Loss lower as time passes:

  • It calculates the downward shift based on the number of intervals passed.
  • It accounts for the "Spread" (the difference between the buy and sell price) to ensure the new stop level is valid and doesn't trigger an accidental closure.
  • It checks if the Stop Loss is currently unset or below your entry price before moving it down.

Summary of Execution

The script constantly monitors the specific trade you provided. Every time the "Time Interval" is met, it calculates the next logical price point for your Stop Loss based on your defined "Step Size." It then automatically updates the order on the platform, effectively "locking in" a progression as the trade stays open longer.

Price Data Components
Series array that contains open time of each bar
Orders Execution
It can change open orders parameters, due to possible stepping strategy
8 Views
0 Downloads
0 Favorites
TrailingByTime
//+------------------------------------------------------------------+
//|                                           TrailingFiftyFifty.mq4 |
//|                                                              I_D |
//|                                            http://www.mymmk.com/ |
//+------------------------------------------------------------------+
#property copyright "I_D"
#property link      "http://www.mymmk.com/ Ñîôò äëÿ óïðàâëåíèÿ êàïèòàëîì"

extern   int      iTicket;             // óíèêàëüíûé íîìåð (òèêåò) îòêðûòîé ïîçèöèè
extern   int      iInterval = 240;     // âðåìåííîé èíòåðâàë, ÷åðåç êîòîðûé (ïî âîçìîæíîñòè) ïåðåíîñèòñÿ ñòîïëîññ, ìèíóò
extern   int      iTrlstep = 20;       // øàã òðåéëèíãà, ïóíêòîâ
extern   bool     bTrlinloss = false;  // ñëåäóåò ëè òðàëèòü íà ó÷àñòêå ëîññîâ (ìåæäó êóðñîì ñòîïëîññà è îòêðûòèÿ)

//+------------------------------------------------------------------+
//| ÒÐÅÉËÈÍÃ ÏÎ ÂÐÅÌÅÍÈ                                              |
//| Ïðè çàïóñêå ýêñïåðòà åìó íåîáõîäèìî óêàçàòü óíèêàëüíûé íîìåð     |
//| (òèêåò) îòêðûòîé ïîçèöèè, à òàêæå îïðåäåëèòü ïàðàìåòðû òðåéëèíãà:|
//| âðåìåííîé èíòåðâàë (ìèíóò), ñ êîòîðûì ïðîèçâîäèòñÿ ïåðåìåùåíèå   |
//| ñòîïëîññà, øàã ñòîïëîññà (ïóíêòîâ), à òàêæå îïðåäåëèòü, ñëåäóåò  |
//| ëè òðåéëèíãîâàòü íà ó÷àñòêå ñòîïëîññîâ                           |
//+------------------------------------------------------------------+

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

void TrailingByTime(int ticket,int interval,int trlstep,bool trlinloss)
   {
      
   // ïðîâåðÿåì ïåðåäàííûå çíà÷åíèÿ
   if ((ticket==0) || (interval<1) || (trlstep<1) || !OrderSelect(ticket,SELECT_BY_TICKET))
      {
      Print("Òðåéëèíã ôóíêöèåé TrailingByTime() íåâîçìîæåí èç-çà íåêîððåêòíîñòè çíà÷åíèé ïåðåäàííûõ åé àðãóìåíòîâ.");
      return(0);
      }
      
   double minpast; // êîë-âî ïîëíûõ ìèíóò îò îòêðûòèÿ ïîçèöèè äî òåêóùåãî ìîìåíòà 
   double times2change; // êîë-âî èíòåðâàëîâ interval ñ ìîìåíòà îòêðûòèÿ ïîçèöèè (ò.å. ñêîëüêî ðàç äîëæåí áûë áûòü ïåðåìåùåí ñòîïëîññ) 
   double newstop; // íîâîå çíà÷åíèå ñòîïëîññà (ó÷èòûâàÿ êîë-âî ïåðåíîñîâ, êîòîðûå äîëæíû áûëè èìåòü ìåñòî)
   
   // îïðåäåëÿåì, ñêîëüêî âðåìåíè ïðîøëî ñ ìîìåíòà îòêðûòèÿ ïîçèöèè
   minpast = (TimeCurrent() - OrderOpenTime()) / 60;
      
   // ñêîëüêî ðàç íóæíî áûëî ïåðåäâèíóòü ñòîïëîññ
   times2change = MathFloor(minpast / interval);
         
   // åñëè äëèííàÿ ïîçèöèÿ (OP_BUY)
   if (OrderType()==OP_BUY)
      {
      // åñëè òðàëèì â óáûòêå, òî îòñòóïàåì îò ñòîïëîññà (åñëè îí íå 0, åñëè 0 - îò îòêðûòèÿ)
      if (trlinloss==true)
         {
         if (OrderStopLoss()==0) newstop = OrderOpenPrice() + times2change*(trlstep*Point);
         else newstop = OrderStopLoss() + times2change*(trlstep*Point); 
         }
      else
      // èíà÷å - îò êóðñà îòêðûòèÿ ïîçèöèè
      newstop = OrderOpenPrice() + times2change*(trlstep*Point); 
         
      if (times2change>0)
         {
         if ((newstop>OrderStopLoss()) && (newstop<Bid- MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
            {
            if (!OrderModify(ticket,OrderOpenPrice(),newstop,OrderTakeProfit(),OrderExpiration()))
            Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
            }
         }
      }
      
   // åñëè êîðîòêàÿ ïîçèöèÿ (OP_SELL)
   if (OrderType()==OP_SELL)
      {
      // åñëè òðàëèì â óáûòêå, òî îòñòóïàåì îò ñòîïëîññà (åñëè îí íå 0, åñëè 0 - îò îòêðûòèÿ)
      if (trlinloss==true)
         {
         if (OrderStopLoss()==0) newstop = OrderOpenPrice() - times2change*(trlstep*Point) - MarketInfo(Symbol(),MODE_SPREAD)*Point;
         else newstop = OrderStopLoss() - times2change*(trlstep*Point) - MarketInfo(Symbol(),MODE_SPREAD)*Point;
         }
      else
      newstop = OrderOpenPrice() - times2change*(trlstep*Point) - MarketInfo(Symbol(),MODE_SPREAD)*Point;
                
      if (times2change>0)
         {
         if (((OrderStopLoss()==0) || (OrderStopLoss()<OrderOpenPrice())) && (newstop>Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
            {
            if (!OrderModify(ticket,OrderOpenPrice(),newstop,OrderTakeProfit(),OrderExpiration()))
            Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
            }
         else
         if ((newstop<OrderStopLoss()) && (newstop>Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
            {
            if (!OrderModify(ticket,OrderOpenPrice(),newstop,OrderTakeProfit(),OrderExpiration()))
            Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
            }
         }
      }      
   }
//+------------------------------------------------------------------+

Comments