SetFixedSLandTP_v1-0

Download script
Author: Luca Spinello - mql4tradingautomation.com
SetFixedSLandTP_v1-0

This script is designed to streamline trade management by automatically applying consistent risk parameters—specifically Stop Loss and Take Profit levels—to all your active trades on a specific currency pair or asset. Instead of manually adjusting every open position one by one, this tool allows you to set global rules that the software applies across your entire portfolio instantly.

How the Logic Works

1. Filtering Your Trades The script doesn't necessarily change every trade you have open. It includes several "filters" to ensure it only touches the specific orders you want to modify. You can choose to:

  • Apply changes only to the current instrument shown on your chart.
  • Target only trades associated with a specific "Magic Number" (a unique ID often used by automated robots).
  • Target only trades that contain a specific written comment.

2. Price Calculation & Precision To ensure accuracy across different types of assets (like Forex, Gold, or Indices), the script automatically detects the correct decimal precision. It calculates the target prices based on the distance you define in "pips." For example, if you are in a "Buy" position, it places the Take Profit above your entry price and the Stop Loss below it; for a "Sell" position, it does the exact opposite.

3. Execution Process Once started, the script performs the following steps:

  • Scanning: It scans through all currently open positions in your account.
  • Verification: It checks each trade against your chosen filters (Symbol, Magic Number, and Comment).
  • Updating: For every trade that matches your criteria, it sends a command to the server to update the Stop Loss and Take Profit levels simultaneously.
  • Safety & Stability: To prevent overwhelming the trading platform or the broker's server, you can set a "Delay" between each modification. This ensures the script processes orders smoothly one after another.

4. Reporting After the process is complete, the script provides a summary in the terminal log, telling you exactly how many orders were successfully updated and providing error messages if any specific trade could not be modified for technical reasons.

Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategy
9 Views
0 Downloads
0 Favorites
SetFixedSLandTP_v1-0
//+------------------------------------------------------------------+
//|                                         SetFixedSLandTP_v1-0.mq4 |
//|                                                    Luca Spinello |
//|                                https://mql4tradingautomation.com |
//+------------------------------------------------------------------+


#property copyright     "Luca Spinello - mql4tradingautomation.com"
#property link          "https://mql4tradingautomation.com"
#property version       "1.00"
#property strict
#property description   "This script sets a stop loss and if required a take profit to all the open orders in the "
#property description   "instrument of the chart"
#property description   " "
#property description   "DISCLAIMER: This script comes with no guarantee, you can use it at your own risk"
#property description   "We recommend to test it first on a Demo Account"

#property show_inputs

//Configure the external variables
extern int TakeProfit=40;              //Take Profit in pips
extern int StopLoss=20;                //Stop Loss in pips
extern bool OnlyMagicNumber=false;     //Modify only orders matching the magic number
extern int MagicNumber=0;              //Matching magic number
extern bool OnlyWithComment=false;     //Modify only orders with the following comment
extern string MatchingComment="";      //Matching comment
extern double Slippage=2;              //Slippage
extern int Delay=0;                    //Delay to wait between modifying orders (in milliseconds)

//Function to normalize the digits
double CalculateNormalizedDigits()
{
   if(Digits<=3){
      return(0.01);
   }
   else if(Digits>=4){
      return(0.0001);
   }
   else return(0);
}

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   //Counter for orders modified
   int TotalModified=0;
   
   //Normalization of the digits
   if(Digits==3 || Digits==5){
      Slippage=Slippage*10;
   }
   double nDigits=CalculateNormalizedDigits();
   
   //Scan the open orders backwards
   for(int i=OrdersTotal()-1; i>=0; i--){
   
      //Select the order, if not selected print the error and continue with the next index
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) == false ) {
         Print("ERROR - Unable to select the order - ",GetLastError());
         continue;
      } 
      
      //Check if the order can be modified matching the criteria, if criteria not matched skip to the next
      if(OrderSymbol()!=Symbol()) continue;
      if(OnlyMagicNumber && OrderMagicNumber()!=MagicNumber) continue;
      if(OnlyWithComment && StringCompare(OrderComment(),MatchingComment)!=0) continue;
      
      //Prepare the prices
      double TakeProfitPrice=0;
      double StopLossPrice=0;
      double OpenPrice=OrderOpenPrice();
      RefreshRates();
      if(OrderType()==OP_BUY){
         TakeProfitPrice=NormalizeDouble(OpenPrice+TakeProfit*nDigits,Digits);
         StopLossPrice=NormalizeDouble(OpenPrice-StopLoss*nDigits,Digits);
      } 
      if(OrderType()==OP_SELL){
         TakeProfitPrice=NormalizeDouble(OpenPrice-TakeProfit*nDigits,Digits);
         StopLossPrice=NormalizeDouble(OpenPrice+StopLoss*nDigits,Digits);      
      }
         
      //Try to modify the order
      if(OrderModify(OrderTicket(),OpenPrice,StopLossPrice,TakeProfitPrice,0,clrNONE)){
         TotalModified++;
      }
      else{
         Print("Order failed to update with error - ",GetLastError());
      }      
      
      //Wait a delay
      Sleep(Delay);
   
   }
   
   //Print the total of orders modified
   Print("Total orders modified = ",TotalModified);
   
  }
//+------------------------------------------------------------------+

Comments