SetUpProfitAndLoss

Download script
Author: TheLiteShadow

This script is an automated management tool designed to oversee your open trades in MetaTrader, specifically focusing on the automatic placement and adjustment of safety nets (Stop Loss) and profit targets (Take Profit). It ensures that your trading positions are consistently protected according to pre-defined rules without requiring manual intervention for every single order.

Core Functionalities

1. Automatic Safety Net Application The primary role of this script is to scan all currently open trades on a specific currency pair. If it detects an open position that lacks a Take Profit (TP) or a Stop Loss (SL), it will automatically apply them based on the values you provide in the settings. This ensures that no trade is left "unguarded," reducing the risk of unexpected losses while securing potential gains.

2. Precision Handling for Different Market Types The script is smart enough to recognize different types of price displays (different decimal places). It automatically scales your input numbers so that the safety levels are placed at the correct distance from the current market price, regardless of whether the specific financial instrument uses four or five decimal places.

3. Intelligent Trailing Systems Beyond just setting initial targets, the script includes advanced "Trailing" logic to lock in profits as the market moves in your favor:

  • Standard Trailing Stop: If enabled with a positive value, the script follows the price movement. As the market moves toward your profit goal, it moves the safety net along with it, maintaining a constant distance. This helps protect the gains you have already accumulated.
  • Zero Trailing (Break-Even): If configured with a negative value, the script acts as a "break-even" guardian. It monitors the price and, once it reaches a certain level of profit, it moves your safety net to the entry point (or near it). This ensures that if the market suddenly reverses, you exit the trade at least at your original entry price rather than losing money.

4. Safety Checks and Validations To prevent errors caused by "too-tight" settings, the script performs a background check before making any changes. If you try to set a profit target or safety net that is closer than the market allows (based on the broker's minimum requirements), the script will display a warning message on your screen rather than allowing an invalid order to be placed.

Summary of User Benefits

  • Consistency: It applies the same risk management rules to every trade automatically.
  • Risk Mitigation: It ensures that "orphaned" trades (those without stop losses) are caught and protected immediately.
  • Dynamic Protection: It moves your protection levels in real-time, allowing you to ride profitable trends while minimizing the potential for a winning trade to turn into a losing one.
Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategy
14 Views
0 Downloads
0 Favorites
SetUpProfitAndLoss
//+------------------------------------------------------------------+
//|                                   Copyright © 2012,TheLiteShadow |
//+------------------------------------------------------------------+
#property copyright "TheLiteShadow"
extern double TakeProfit=20;
extern double StopLoss=20;
extern double TrailingStop=-10;//îòðèöàòåëüíûå çíà÷åíèÿ äëÿ ïåðåâîäà â îðäåðà ÁÓ ïî äîñòèæåíèè
extern bool   SetOnlyZeroValues=true; //Ïðèçíàê èçìåíåíèÿ òîëüêî íóëåâûõ çíà÷åíèé
extern color  BuyOrderColor=Green;
extern color  SellOrderColor=Red;
//+------------------------------------------------------------------+
int start()
  { int cnt, ticket, total=OrdersTotal(); double kd;
    if (Digits==5) kd=10; else kd=1;
    double TP=MathAbs(TakeProfit)*kd;
    double SL=MathAbs(StopLoss)*kd;
    double TS=TrailingStop*kd;
    if (TP<MarketInfo(Symbol(),MODE_STOPLEVEL) && TP!=0)
      { Comment("TakeProfit value too small, must be >= "+DoubleToStr(MarketInfo(Symbol(),MODE_STOPLEVEL)/kd,0));
       return(0);
      }
    if (SL<MarketInfo(Symbol(),MODE_STOPLEVEL) && SL!=0)
      { Comment("StopLoss value too small, must be >= "+DoubleToStr(MarketInfo(Symbol(),MODE_STOPLEVEL)/kd,0));
       return(0);
      }
 // Óñòàíîâêà îãðàíè÷åíèÿ ïðèáûëè è óáûòêà
   for(cnt=0;cnt<total;cnt++)
     { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        { if(OrderType()==OP_BUY)
           { if(((OrderTakeProfit()==0 && TP!=0) || (OrderStopLoss()==0 && SL!=0)) && !SetOnlyZeroValues)
              { OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-Point*SL,OrderOpenPrice()+Point*TP,0,BuyOrderColor);
               return(0);
              }
             if(OrderTakeProfit()==0 && SetOnlyZeroValues && TP!=0)
              { OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderOpenPrice()+Point*TP,0,BuyOrderColor);
               return(0);
              }
             if(OrderStopLoss()==0 && SetOnlyZeroValues && SL!=0)
              { OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-Point*SL,OrderTakeProfit(),0,BuyOrderColor);
               return(0);
              } 
           }
         else
           { if(((OrderTakeProfit()==0 && TP!=0) || (OrderStopLoss()==0 && SL!=0)) && !SetOnlyZeroValues)
              { OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+Point*SL,OrderOpenPrice()-Point*TP,0,SellOrderColor);
               return(0);
              }
             if(OrderTakeProfit()==0 && SetOnlyZeroValues && TP!=0)
              { OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderOpenPrice()-Point*TP,0,SellOrderColor);
               return(0);
              }
             if(OrderStopLoss()==0 && SetOnlyZeroValues && SL!=0)
              { OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+Point*SL,OrderTakeProfit(),0,SellOrderColor);
               return(0);
              }
           }
        }
     }
 if (MathAbs(TS)<MarketInfo(Symbol(),MODE_STOPLEVEL) && TS!=0)
   { Comment("Traling stop value too small, must be >= "+DoubleToStr(MarketInfo(Symbol(),MODE_STOPLEVEL)/kd,0));
    return(0);
   }
//Trailing
 if (TS>0) { 
   for(cnt=0;cnt<total;cnt++)
     { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        { if(OrderType()==OP_BUY)
          { if(Bid-OrderOpenPrice()>Point*TS && OrderStopLoss()<Bid-Point*TS)
            { OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TS,OrderTakeProfit(),0,BuyOrderColor);
              return(0);
            }
          }
         else
          { if(OrderOpenPrice()-Ask>Point*TS && OrderStopLoss()>Ask+Point*TS)
            { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TS,OrderTakeProfit(),0,SellOrderColor);
              return(0);
            }
          }
        }
     }}
//ZeroTrailing     
 if (TS<0) { 
   for(cnt=0;cnt<total;cnt++)
     { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        { if(OrderType()==OP_BUY)
          { if(Bid-OrderOpenPrice()>-Point*TS && OrderStopLoss()!=OrderOpenPrice() && OrderStopLoss()<Bid+Point*TS)
            { OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,BuyOrderColor);
              return(0);
            }
          }
         else
          { if(OrderOpenPrice()-Ask>-Point*TS && OrderStopLoss()!=OrderOpenPrice() && OrderStopLoss()>Ask-Point*TS)
            { OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,SellOrderColor);
              return(0);
            }
          }
        }
     }}
   return(0);
 }

Comments