Trailing_StopLoss_for All_orders_and_symbols
Download scriptThis automated script is designed to act as a dynamic risk management tool for your trading account. Its primary purpose is to automatically "trail" or move your Stop Loss levels in real-time, helping to lock in profits as the market moves in your favor while providing a safety net against sudden price reversals.
How the Logic Works
The script operates continuously, scanning every open position in your portfolio—regardless of the currency pair or symbol—and applies the following logic:
1. Profit Validation The tool first checks if a trade is currently in a profitable state. It will only begin moving the Stop Loss once the trade has moved into positive territory. This ensures that your initial risk management remains untouched until the market starts working in your direction.
2. Dynamic Distance Monitoring The script uses two specific user-defined measurements to determine how to move your safety net:
- Trail Start: This defines the minimum distance from your entry price required before the script begins its adjustments.
- Trail Stop: This determines the specific "buffer" or gap the script maintains between the current market price and your new Stop Loss level.
3. Intelligent Price Adjustment The logic behaves differently depending on whether you are in a "Buy" or "Sell" position:
- For Buy Orders: As the price rises, the script calculates a new, higher Stop Loss level. It ensures that the new stop is never lower than your previous one, effectively "climbing" up with the market to protect your gains.
- For Sell Orders: As the price drops, the script calculates a new, lower Stop Loss level. Similarly, it ensures the stop only moves downward, capturing profit as the price falls.
4. Automatic Execution The script performs these calculations instantly on every "tick" (every time the market price updates). If it detects that the current market conditions allow for a better (safer) Stop Loss position than the one currently set, it automatically sends a command to your broker to update the order.
Key Benefits for the User
- Hands-Free Management: You do not need to manually monitor charts to move your stop losses; the script does this automatically.
- Universal Application: Because it scans all open orders, it works across your entire portfolio simultaneously.
- Loss Limitation: By constantly moving the Stop Loss into profit territory, the tool helps minimize the risk of a winning trade turning into a losing one due to market volatility.
//+------------------------------------------------------------------+
//| Trailing_StopLoss_for All_orders_and_symbols.mq4 |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|This script will trail the stop loss of all open buy and sell orders.
//|Adjust the TrailStart and TrailStop parameters to your preferred levels.
//|This is a basic example and can be further optimized and customized
//|based on your specific requirements.
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.01"
#property description "persinaru@gmail.com"
#property description "IP 2024 - free open source"
#property description "Trailing_StopLoss_for All_orders_and_symbols"
#property description ""
#property description "WARNING: Use this software at your own risk."
#property description "The creator of this script cannot be held responsible for any damage or loss."
#property description ""
#property strict
#property show_inputs
#property script_show_inputs
// Input parameters
extern int TrailStart = 20; // Trailing start level in pips
extern int TrailStop = 10; // Trailing stop level in pips
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
TrailingStop();
}
//+------------------------------------------------------------------+
//| Trailing stop function |
//+------------------------------------------------------------------+
void TrailingStop()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() <= OP_SELL)
{
double currentProfit = OrderProfit();
double currentStopLoss = OrderStopLoss();
double currentPrice = OrderOpenPrice();
if(currentProfit > 0) // Only trailing if the trade is in profit
{
double trailPrice = 0;
// Calculate the trailing stop price
if(OrderType() == OP_BUY)
{
trailPrice = currentPrice + TrailStart * Point;
trailPrice = MathMax(trailPrice, currentStopLoss + TrailStop * Point);
}
else if(OrderType() == OP_SELL)
{
trailPrice = currentPrice - TrailStart * Point;
trailPrice = MathMin(trailPrice, currentStopLoss - TrailStop * Point);
}
// Update stop loss if the new price is better
if(trailPrice != currentStopLoss)
{
bool res = OrderModify(OrderTicket(), OrderOpenPrice(), trailPrice, OrderTakeProfit(), 0, clrNONE);
if(res)
{
Print("Trailing stop for order ", OrderTicket(), " updated successfully.");
}
else
{
Print("Failed to update trailing stop for order ", OrderTicket());
}
}
}
}
}
}
}
Comments