e-Smart_Trailing

Download script

This script is a specialized automated trading tool designed for the MetaTrader 5 platform. Its primary purpose is to manage "Stop Loss" orders dynamically as the market moves in your favor, a technique commonly known as a Smart Trailing Stop.

Instead of leaving your risk fixed, this script constantly monitors your open positions and adjusts your protection levels to lock in profits while allowing for continued growth. Here is a breakdown of how the logic works:

Core Functionality

1. Real-Time Market Monitoring The script runs continuously in the background. Every time the price updates (on every "tick"), it scans all currently open trading positions. It specifically looks for trades that match the current currency symbol you are viewing on your chart.

2. Intelligent Profit Filtering To ensure it only manages active, live opportunities, the script checks the status of your trade. If a position is already in a loss, the script ignores it to avoid interfering with manual risk management or other strategies. It focuses specifically on trades that have the potential to secure gains.

3. Precision Price Calculation The logic includes an automatic "adjustment" feature. Trading platforms use different decimal precisions (for example, some pairs show three decimals while others show five). The script detects this automatically so that the trailing movement is mathematically accurate regardless of which currency pair you are trading.

Trailing Logic for Buy and Sell Positions

The script treats Buy and Sell orders with specific logic to ensure the "Trailing Stop" always moves in the correct direction:

  • For Buy Positions: It looks at the current market price. If the price climbs high enough, the script calculates a new Stop Loss level based on your predefined distance (TrailingStop). It then checks if this new level is higher than your current Stop Loss. If it is, the script automatically updates your order to "trail" behind the rising price.
  • For Sell Positions: The logic mirrors this for downward moves. It monitors the falling market price and calculates a new Stop Loss level based on your predefined distance. If the price drops significantly enough, it moves your protection lower (closer to the current price) to lock in profits as the trade goes into the green.

Key User Controls

The behavior of the script is governed by two main settings:

  • Trailing Stop: This defines the "buffer" or the distance from the current price where your safety net sits.
  • Trailing Step: This acts as a sensitivity filter. It ensures the script doesn't try to modify the order every single second; instead, it waits for the price to move by a specific amount before triggering a new update.

Summary of Benefits

By using this logic, you automate the "lock-in" process. As the market trends in your favor, the script moves your Stop Loss forward automatically. This helps protect your capital from sudden market reversals while removing the emotional stress of deciding exactly when to move your protective orders manually.

12 Views
1 Downloads
0 Favorites
e-Smart_Trailing
ÿþ//+------------------------------------------------------------------+

//|                    e-Smart_Trailing(barabashkakvn's edition).mq5 |

//+------------------------------------------------------------------+

#property version   "1.00"

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

//---

input    ushort   TrailingStop = 30;         // TrailingStop

input    ushort   TrailingStep = 5;          // TrailingStep

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//---



  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions

      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties

         if(m_position.Symbol()==Symbol())

           {

            if(m_position.Profit()<0.0)

               break;

            //---

            long digits=SymbolInfoInteger(m_position.Symbol(),SYMBOL_DIGITS);

            double point=SymbolInfoDouble(m_position.Symbol(),SYMBOL_POINT);

            //--- tuning for 3 or 5 digits

            int digits_adjust=1;

            if(digits==3 || digits==5)

               digits_adjust=10;

            double m_adjusted_point=point*digits_adjust;

            //---

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(m_position.PriceCurrent()-(TrailingStop+TrailingStep)*m_adjusted_point>m_position.StopLoss())

                 {

                  //--- save Magic Number for the position

                  m_trade.SetExpertMagicNumber(m_position.Magic());

                  m_trade.PositionModify(m_position.Ticket(),

                                         m_position.PriceCurrent()-TrailingStop*m_adjusted_point,

                                         m_position.TakeProfit());

                 }

              }



            if(m_position.PositionType()==POSITION_TYPE_SELL)

              {

               double sl=0.0;

               if(m_position.StopLoss()>0)

                 {

                  if(m_position.PriceCurrent()+(TrailingStop+TrailingStep)*m_adjusted_point<m_position.StopLoss())

                    {

                     sl=m_position.PriceCurrent()+TrailingStop*m_adjusted_point;

                     //--- save Magic Number for the position

                     m_trade.SetExpertMagicNumber(m_position.Magic());

                     m_trade.PositionModify(m_position.Ticket(),sl,m_position.TakeProfit());

                    }

                 }

               else

                 {

                  sl=m_position.PriceCurrent()+TrailingStop*m_adjusted_point;

                  //--- save Magic Number for the position

                  m_trade.SetExpertMagicNumber(m_position.Magic());

                  m_trade.PositionModify(m_position.Ticket(),sl,m_position.TakeProfit());

                 }

              }

           }

  }

//+------------------------------------------------------------------+

Comments