Author: Copyright © 2017, Vladimir Karputov
This script, named "AutoSLTP," is designed to automatically manage the Stop Loss (SL) and Take Profit (TP) levels for your open trades in the MetaTrader platform. Think of it as a tool that helps you protect your profits and limit your losses.

Here's how it works:

1.  **Configuration File:** The script relies on a text file ("AutoSLTP.txt") located in a specific folder. This file contains the instructions for how the Stop Loss and Take Profit should be set for different trading instruments (like EURUSD, GBPJPY, etc.).

2.  **File Format:** The text file needs to be formatted in a specific way. Each line in the file represents a rule for a particular currency pair. The script expects each line to follow this format:

    `currency_pair*trade_type*stop_loss*take_profit`

    *   `currency_pair`: The trading instrument, e.g., "EURUSD".
    *   `trade_type`:  The type of trade: "POSITION\_TYPE\_BUY" for buy orders or "POSITION\_TYPE\_SELL" for sell orders.
    *   `stop_loss`: The desired Stop Loss level in *pips*. Pips are a standard unit of measurement in forex trading.
    *   `take_profit`: The desired Take Profit level in *pips*.

    For example, a line like `EURUSD*POSITION_TYPE_BUY*50*100` would tell the script to set the Stop Loss for any open EURUSD buy orders to 50 pips and the Take Profit to 100 pips.

3.  **Initialization:** When the script starts, it reads the "AutoSLTP.txt" file, line by line.  It parses each line, breaking it down into the four parts mentioned above (currency pair, trade type, Stop Loss, Take Profit). It stores these settings in its memory for later use. If the file cannot be opened, or any of the parameters are wrong, then the script will fail to load.

4.  **Tick-by-Tick Monitoring:**  The script then continuously monitors the market price movement (every "tick"). It checks if any open trades exist. It ignores any price updates that occur within 10 miliseconds of the previous one.

5.  **Position Evaluation:** For each open trade, the script does the following:

    *   It identifies the currency pair and the type of trade (buy or sell).

    *   It searches its stored settings (from the "AutoSLTP.txt" file) to see if there's a matching rule for this currency pair and trade type.

    *   If a matching rule is found, it retrieves the Stop Loss and Take Profit values (in pips) from that rule.

    *   If the rule isn't found, the script moves on to the next open trade and ignores the current trade.

6.  **Trailing Stop Logic:** For the trades where a matching rule is found, the script calculates the new Stop Loss and Take Profit prices based on the *current* market price and the pip values specified in the rules. It then attempts to *modify* the trade.
    *   For buy orders, it checks if the calculated stop loss is lower than the current price, and sets it if it is. Also it will set the take profit at the appropriate level if it has increased.
    *   For sell orders, it checks if the calculated stop loss is higher than the current price, and sets it if it is. It also sets the take profit at the appropriate level if it has decreased.

7.  **Trade Modification:** The script sends a request to the trading platform to modify the open trade, setting the Stop Loss and Take Profit to the calculated prices. The script also prints any errors or successes.

8.  **Looping:** This entire process (monitoring, position evaluation, trailing stop) repeats continuously, ensuring that the Stop Loss and Take Profit levels are automatically adjusted based on the rules defined in the "AutoSLTP.txt" file.

In essence, this script automates the process of setting and adjusting Stop Loss and Take Profit levels for your trades according to predefined rules, helping you to manage risk and secure profits more efficiently.
Price Data Components
Series array that contains close prices for each bar
8 Views
4 Downloads
0 Favorites
AutoSLTP
ÿþ//+------------------------------------------------------------------+

//|                                                     AutoSLTP.mq5 |

//|                              Copyright © 2017, Vladimir Karputov |

//|                                           http://wmua.ru/slesar/ |

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

#property copyright "Copyright © 2017, Vladimir Karputov"

#property link      "http://wmua.ru/slesar/"

#property version   "1.000"

#property description "Management of stop loss and take profit levels. The settings are taken from the file"

#property description "File format:"

#property description "name_symbol*position_type*sl*tp"

#property description "Example:"

#property description "AUDCAD*POSITION_TYPE_BUY*50*96"

#property description "AUDCAD*POSITION_TYPE_SELL*40*46"

#property description "USDJPY*POSITION_TYPE_SELL*80*38"

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Files\FileTxt.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

CFileTxt       m_file_txt;                   // file txt object

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

//| Struct SLTP                                                      |

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

struct STRUCT_SLTP

  {

   string            symbol_name;   // symbol name

   ENUM_POSITION_TYPE pos_type;     // position type

   ushort            stop_loss;     // stop loss (in pips)

   ushort            take_profit;   // take profit(in pips)

  };

STRUCT_SLTP arr_struct_sltp[];

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//--- It frees up a buffer of any dynamic array and sets the size of the zero dimension to 0.

   ArrayFree(arr_struct_sltp);

//---

   if(!m_file_txt.Open("AutoSLTP//AutoSLTP.txt",FILE_READ))

     {

      Print("Error open \"AutoSLTP//AutoSLTP.txt\" #",GetLastError());

      return(INIT_FAILED);

     }

   Print("Tell: ",m_file_txt.Tell());



   string sep="*";                // A separator as a character 

   ushort u_sep;                  // The code of the separator character 



//--- Get the separator code 

   u_sep=StringGetCharacter(sep,0);

   while(!m_file_txt.IsEnding())

     {

      //--- read and print the string 

      string to_split=m_file_txt.ReadString();

      Print(to_split);



      string result[];               // An array to get strings 

      //--- Split the string to substrings 

      int k=StringSplit(to_split,u_sep,result);

      if(k!=4)

        {

         Print("Error: Wrong number of parameters");

         return(INIT_FAILED);

        }

      //--- Show a comment  

      PrintFormat("Strings obtained: %d. Used separator '%s' with the code %d",k,sep,u_sep);

      //--- Now output all obtained strings 

      if(k>0)

        {

         for(int i=0;i<k;i++)

           {

            PrintFormat("result[%d]=\"%s\"",i,result[i]);

           }

        }

      string temp_symbol_name=result[0];

      if(!m_symbol.Name(temp_symbol_name)) // sets symbol name

        {

         Print("Error: Wrong parameter \"Symbol Name\"");

         return(INIT_FAILED);

        }



      ENUM_POSITION_TYPE   temp_pos_type=-1;

      string txt=result[1];

      if(txt=="POSITION_TYPE_BUY")

         temp_pos_type=POSITION_TYPE_BUY;

      else if(txt=="POSITION_TYPE_SELL")

         temp_pos_type=POSITION_TYPE_SELL;

      else

        {

         Print("Error: Wrong parameter \"Position Type\"");

         return(INIT_FAILED);

        }



      ushort temp_stop_loss=0;

      long sl_long=StringToInteger(result[2]);

      if(sl_long<0 || sl_long==0)

        {

         Print("Error: Wrong parameter \"Stop Loss\"");

         return(INIT_FAILED);

        }

      temp_stop_loss=(ushort)sl_long;



      ushort temp_take_profit=0;

      long tp_long=StringToInteger(result[3]);



      if(tp_long<0 || tp_long==0)

        {

         Print("Error: Wrong parameter \"Take Profit\"");

         return(INIT_FAILED);

        }

      temp_take_profit=(ushort)tp_long;

      //---

      int size=ArraySize(arr_struct_sltp);

      ArrayResize(arr_struct_sltp,size+1);

      arr_struct_sltp[size].symbol_name=temp_symbol_name;

      arr_struct_sltp[size].pos_type=temp_pos_type;

      arr_struct_sltp[size].stop_loss=temp_stop_loss;

      arr_struct_sltp[size].take_profit=temp_take_profit;

     }

   m_file_txt.Close();

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

   m_file_txt.Close();

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//---

   static datetime prev_time=0;

   datetime time_current=TimeCurrent();

   if(time_current-prev_time<10)

      return;

   prev_time=time_current;

//---

   for(int i=PositionsTotal()-1;i>=0;i--)

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

        {

         string               symbol_name=m_position.Symbol();

         ENUM_POSITION_TYPE   pos_type=m_position.PositionType();

         ushort               stop_loss=0;      // stop loss (in pips)

         ushort               take_profit=0;    // take profit(in pips)



         bool search=false;

         for(int j=0;j<ArraySize(arr_struct_sltp);j++)

           {

            if(symbol_name==arr_struct_sltp[j].symbol_name)

              {

               stop_loss   =arr_struct_sltp[j].stop_loss;

               take_profit =arr_struct_sltp[j].take_profit;



               search=true;

               break;

              }

           }

         if(!search)

            continue;



         if(m_position.PositionType()==POSITION_TYPE_BUY)

            Trailing(symbol_name,stop_loss,take_profit);



         if(m_position.PositionType()==POSITION_TYPE_SELL)

            Trailing(symbol_name,stop_loss,take_profit);

        }

  }

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

//| Trailing                                                         |

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

void Trailing(const string symbol,const ushort sl,const ushort tp)

  {

   double m_adjusted_point;   // point value adjusted for 3 or 5 points

   if(!m_symbol.Name(symbol)) // sets symbol name

      return;

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)

      digits_adjust=10;

   m_adjusted_point=m_symbol.Point()*digits_adjust;



   double ExtStopLoss   =sl*m_adjusted_point;

   double ExtTakeProfit =tp*m_adjusted_point;



   if(m_position.PositionType()==POSITION_TYPE_BUY)

     {

      double new_sl=m_position.StopLoss();

      double new_tp=m_position.TakeProfit();

      if(m_position.StopLoss()<m_position.PriceCurrent()-ExtStopLoss)

         new_sl=m_symbol.NormalizePrice(m_position.PriceCurrent()-ExtStopLoss);

      if(m_position.TakeProfit()<m_position.PriceCurrent()+ExtTakeProfit)

         new_tp=m_symbol.NormalizePrice(m_position.PriceCurrent()+ExtTakeProfit);



      if(!m_trade.PositionModify(m_position.Ticket(),new_sl,new_tp))

         Print("Modify ",m_position.Ticket(),

               " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),

               ", description of result: ",m_trade.ResultRetcodeDescription());

     }

   else

     {

      double new_sl=m_position.StopLoss();

      double new_tp=m_position.TakeProfit();

      if(m_position.StopLoss()>m_position.PriceCurrent()+ExtStopLoss || m_position.StopLoss()==0)

         new_sl=m_symbol.NormalizePrice(m_position.PriceCurrent()+ExtStopLoss);

      if(m_position.TakeProfit()>m_position.PriceCurrent()-ExtTakeProfit)

         new_tp=m_symbol.NormalizePrice(m_position.PriceCurrent()-ExtTakeProfit);



      if(!m_trade.PositionModify(m_position.Ticket(),new_sl,new_tp))

         Print("Modify ",m_position.Ticket(),

               " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),

               ", description of result: ",m_trade.ResultRetcodeDescription());

     }

  }

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

Comments