TrailingUdavka

Download script
Author: I_D
TrailingUdavka

This script is designed to manage trade risk by automatically adjusting the "Stop Loss" price of an open position based on how much profit the trade has accumulated. Unlike a standard trailing stop that moves at a fixed distance, this logic uses a dynamic "staircase" approach.

Core Logic Overview

The script monitors a specific trade and adjusts the safety net (Stop Loss) more aggressively as the price moves in your favor. It operates on three distinct profit zones:

  • Zone 1 (Initial): When the trade is in its early stages, it maintains a wide trailing distance.
  • Zone 2 (Intermediate): Once the trade reaches a specific profit level, the script "tightens" the safety net, reducing the distance between the current price and the Stop Loss.
  • Zone 3 (Advanced): When the trade reaches an even higher profit milestone, the script applies its tightest trailing distance to lock in the majority of the gains.

How it Works Step-by-Step

1. Input Parameters The user defines three key sets of data:

  • Distance Levels: Three different distances (how many "points" away from the price the Stop Loss should stay).
  • Profit Thresholds: Two specific profit targets that trigger the move from one distance to the next.

2. Validation Before performing any actions, the script checks to ensure that the inputs provided are mathematically logical (e.g., ensuring that the profit levels are higher than the distances and that the trade actually exists). If the settings are incorrect, the script will alert the user and stop execution.

3. Trade Monitoring The script constantly calculates the current profit of the trade relative to your entry price. Depending on where the price currently sits:

  • If the profit is low, it selects Distance 1.
  • If profit has passed the first threshold but not the second, it selects Distance 2.
  • If profit has exceeded the second threshold, it selects Distance 3.

4. Automated Execution The script then calculates where the new Stop Loss should be placed based on the selected distance. It includes logic to handle both "Buy" (Long) and "Sell" (Short) positions:

  • For Buy Positions: It ensures the Stop Loss stays below the current price.
  • For Sell Positions: It ensures the Stop Loss stays above the current price.

5. Safety & Modification The script will only modify the trade if the new calculated Stop Loss is better than the existing one (i.e., it moves the stop in a way that protects more profit). It also checks against "Stop Levels" (minimum distance requirements set by the broker) to ensure the order modification isn't rejected by the server.

Summary for the User

Think of this as an automated "profit locker." As your trade becomes more successful, the script automatically moves your Stop Loss closer to the current price in stages. This helps protect your gains from sudden market reversals while giving the trade enough "breathing room" during its initial phases.

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

extern   int      iTicket;             // óíèêàëüíûé íîìåð (òèêåò) îòêðûòîé ïîçèöèè
extern   int      iTrl_dist_1 = 30;    // èñõîäíîå ðàññòîÿíèå òðåéëèíãà (ïóíêòîâ) (íå ìåíüøå MarketInfo(Symbol(),MODE_STOPLEVEL), áîëüøå trl_dist_2 è trl_dist_3);
extern   int      iLevel_1 = 50;       // óðîâåíü ïðîôèòà (ïóíêòîâ), ïðè äîñòèæåíèè êîòîðîãî äèñòàíöèÿ òðåéëèíãà áóäåò ñîêðàùåíà ñ trl_dist_1 äî trl_dist_2 (ìåíüøå level_2; áîëüøå trl_dist_1);
extern   int      iTrl_dist_2 = 20;    // ðàññòîÿíèå òðåéëèíãà (ïóíêòîâ) ïîñëå äîñòèæåíèÿ êóðñîì óðîâíÿ ïðîôèòà â level_1 ïóíêòîâ (íå ìåíüøå MarketInfo(Symbol(),MODE_STOPLEVEL));
extern   int      iLevel_2 = 70;       // óðîâåíü ïðîôèòà (ïóíêòîâ), ïðè äîñòèæåíèè êîòîðîãî äèñòàíöèÿ òðåéëèíãà áóäåò ñîêðàùåíà ñ trl_dist_2 äî trl_dist_3 ïóíêòîâ (áîëüøå trl_dist_1 è áîëüøå level_1);
extern   int      iTrl_dist_3 = 10;    // ðàññòîÿíèå òðåéëèíãà (ïóíêòîâ) ïîñëå äîñòèæåíèÿ êóðñîì óðîâíÿ ïðîôèòà â level_2 ïóíêòîâ (íå ìåíüøå MarketInfo(Symbol(),MODE_STOPLEVEL)).

//+------------------------------------------------------------------+
//| ÒÐÅÉËÈÍà ÑÒÀÍÄÀÐÒÍÛÉ-ÇÀÒßÃÈÂÀÞÙÈÉÑß ("ÓÄÀÂÊÀ")                   |
//| Ýêñïåðòó ïåðåäà¸òñÿ òèêåò ïîçèöèè, èñõîäíûé òðåéëèíã (ïóíêòîâ) è |
//| 2 "óðîâíÿ" (çíà÷åíèÿ ïðîôèòà, ïóíêòîâ), ïðè êîòîðûõ òðåéëèíã     |
//| ñîêðàùàåì, è ñîîòâåòñòâóþùèå çíà÷åíèÿ òðåéëèíãà (ïóíêòîâ)        |
//| Ïðèìåð: èñõîäíûé òðåéëèíã 30 ï., ïðè +50 - 20 ï., +80 è áîëüøå - |
//| íà ðàññòîÿíèè â 10 ïóíêòîâ.                                      |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {    
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   TrailingUdavka(iTicket,iTrl_dist_1,iLevel_1,iTrl_dist_2,iLevel_2,iTrl_dist_3);
   return(0);
  }
//+------------------------------------------------------------------+

void TrailingUdavka(int ticket,int trl_dist_1,int level_1,int trl_dist_2,int level_2,int trl_dist_3)
   {  
   
   double newstop = 0; // íîâûé ñòîïëîññ
   double trldist; // ðàññòîÿíèå òðåéëèíãà (â çàâèñèìîñòè îò "ïðîéäåííîãî" ìîæåò = trl_dist_1, trl_dist_2 èëè trl_dist_3)

   // ïðîâåðÿåì ïåðåäàííûå çíà÷åíèÿ
   if ((trl_dist_1<MarketInfo(Symbol(),MODE_STOPLEVEL)) || (trl_dist_2<MarketInfo(Symbol(),MODE_STOPLEVEL)) || (trl_dist_3<MarketInfo(Symbol(),MODE_STOPLEVEL)) || 
   (level_1<=trl_dist_1) || (level_2<=trl_dist_1) || (level_2<=level_1) || (ticket==0) || (!OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)))
      {
      Print("Òðåéëèíã ôóíêöèåé TrailingUdavka() íåâîçìîæåí èç-çà íåêîððåêòíîñòè çíà÷åíèé ïåðåäàííûõ åé àðãóìåíòîâ.");
      return(0);
      } 
   
   // åñëè äëèííàÿ ïîçèöèÿ (OP_BUY)
   if (OrderType()==OP_BUY)
      {
      // åñëè ïðîôèò <=trl_dist_1, òî trldist=trl_dist_1, åñëè ïðîôèò>trl_dist_1 && ïðîôèò<=level_1*Point ...
      if ((Bid-OrderOpenPrice())<=level_1*Point) trldist = trl_dist_1;
      if (((Bid-OrderOpenPrice())>level_1*Point) && ((Bid-OrderOpenPrice())<=level_2*Point)) trldist = trl_dist_2;
      if ((Bid-OrderOpenPrice())>level_2*Point) trldist = trl_dist_3; 
            
      // åñëè ñòîïëîññ = 0 èëè ìåíüøå êóðñà îòêðûòèÿ, òî åñëè òåê.öåíà (Bid) áîëüøå/ðàâíà äèñòàíöèè êóðñ_îòêðûòèÿ+ðàññò.òðåéëèíãà
      if ((OrderStopLoss()==0) || (OrderStopLoss()<OrderOpenPrice()))
         {
         if (Bid>(OrderOpenPrice() + trldist*Point))
         newstop = Bid -  trldist*Point;
         }

      // èíà÷å: åñëè òåêóùàÿ öåíà (Bid) áîëüøå/ðàâíà äèñòàíöèè òåêóùèé_ñòîïëîññ+ðàññòîÿíèå òðåéëèíãà, 
      else
         {
         if (Bid>(OrderStopLoss() + trldist*Point))
         newstop = Bid -  trldist*Point;
         }
      
      // ìîäèôèöèðóåì ñòîïëîññ
      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)
      { 
      // åñëè ïðîôèò <=trl_dist_1, òî trldist=trl_dist_1, åñëè ïðîôèò>trl_dist_1 && ïðîôèò<=level_1*Point ...
      if ((OrderOpenPrice()-(Ask + MarketInfo(Symbol(),MODE_SPREAD)*Point))<=level_1*Point) trldist = trl_dist_1;
      if (((OrderOpenPrice()-(Ask + MarketInfo(Symbol(),MODE_SPREAD)*Point))>level_1*Point) && ((OrderOpenPrice()-(Ask + MarketInfo(Symbol(),MODE_SPREAD)*Point))<=level_2*Point)) trldist = trl_dist_2;
      if ((OrderOpenPrice()-(Ask + MarketInfo(Symbol(),MODE_SPREAD)*Point))>level_2*Point) trldist = trl_dist_3; 
            
      // åñëè ñòîïëîññ = 0 èëè ìåíüøå êóðñà îòêðûòèÿ, òî åñëè òåê.öåíà (Ask) áîëüøå/ðàâíà äèñòàíöèè êóðñ_îòêðûòèÿ+ðàññò.òðåéëèíãà
      if ((OrderStopLoss()==0) || (OrderStopLoss()>OrderOpenPrice()))
         {
         if (Ask<(OrderOpenPrice() - (trldist + MarketInfo(Symbol(),MODE_SPREAD))*Point))
         newstop = Ask + trldist*Point;
         }

      // èíà÷å: åñëè òåêóùàÿ öåíà (Bid) áîëüøå/ðàâíà äèñòàíöèè òåêóùèé_ñòîïëîññ+ðàññòîÿíèå òðåéëèíãà, 
      else
         {
         if (Ask<(OrderStopLoss() - (trldist + MarketInfo(Symbol(),MODE_SPREAD))*Point))
         newstop = Ask +  trldist*Point;
         }
            
       // ìîäèôèöèðóåì ñòîïëîññ
      if (newstop>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