TrailingByPriceChannel
Download scriptThis script is designed to automate the management of an active trading position by dynamically adjusting its "Stop Loss" (the price at which a trade automatically closes to prevent further loss) based on recent market price action. Instead of using a fixed numerical value, it uses a "Price Channel" logic to follow the trend of the market.
Core Logic Overview
The script monitors a specific open trade and calculates a boundary based on the highest and lowest prices reached over a user-defined number of past candles (bars). By analyzing this recent range, the script creates a ceiling and a floor, allowing the Stop Loss to "trail" behind the price as the market moves in your favor.
How it Works
The tool operates based on three primary inputs:
- Ticket Number: The unique identifier of the specific trade you want the script to manage.
- Lookback Period: The number of recent candles the script should scan to determine the current price range.
- Buffer Distance (Indent): A small safety margin added to the boundaries to ensure the Stop Loss isn't placed too close to the exact high or low of the price action.
Operational Behavior
The script behaves differently depending on whether you are in a "Buy" or "Sell" position:
-
For Buy Positions (Long): The script looks for the lowest price reached within your specified timeframe. It calculates a "floor" based on that low point plus your chosen buffer. If your current Stop Loss is lower than this new floor, the script automatically moves your Stop Loss upward. This effectively "locks in" profits as the price climbs higher.
-
For Sell Positions (Short): The script looks for the highest price reached within your specified timeframe. It calculates a "ceiling" based on that high point minus your chosen buffer. If your current Stop Loss is higher than this new ceiling (or if no Stop Loss is set), the script moves the Stop Loss downward. This protects your gains as the market price drops.
Safety Mechanisms
To ensure smooth execution, the logic includes several built-in checks:
- Validation: It verifies that the trade ticket exists and that the settings provided are mathematically valid before attempting any actions.
- Broker Constraints: The script checks the "Stop Level" (the minimum distance required by your broker between the current price and an order). This prevents the script from trying to place a Stop Loss too close to the market price, which would normally cause the trade command to be rejected.
- Error Reporting: If the script fails to move the Stop Loss due to external reasons (such as a disconnected server or insufficient margin), it will output a notification in the system log to alert you.
//+------------------------------------------------------------------+
//| TrailingByPriceChannel.mq4 |
//| I_D |
//| http://www.mymmk.com/ |
//+------------------------------------------------------------------+
#property copyright "I_D"
#property link "http://www.mymmk.com/ Ñîôò äëÿ óïðàâëåíèÿ êàïèòàëîì"
extern int iTicket; // óíèêàëüíûé íîìåð (òèêåò) îòêðûòîé ïîçèöèè
extern int iBars_n = 20; // êîë-âî áàðîâ òåêóùåãî ãðàôèêà, ïî êîòîðûì ñòðîèòñÿ öåíîâîé êàíàë
extern int iIndent = 3; // îòñòóï îò òåíè áàðà, íà êîòîðîì ðàçìåùàåòñÿ ñòîïëîññ
//+------------------------------------------------------------------+
//| ÒÐÅÉËÈÍÃ ÏÎ ÖÅÍÂÎÌÓ ÊÀÍÀËÓ |
//| Ïðè çàïóñêå ýêñïåðòà åìó íåîáõîäèìî óêàçàòü óíèêàëüíûé íîìåð |
//| (òèêåò) îòêðûòîé ïîçèöèè, à òàêæå îïðåäåëèòü ïàðàìåòðû òðåéëèíãà:|
//| êîë-âî áàðîâ, ñðåäè êîòîðûõ (êàê ïðè òðåéëèíãå ïî òåíÿì) îïðåäå- |
//| ëÿåòñÿ íàèáîëåå óäàë¸ííûé (ëîó äëÿ íèæíåé ãðàíèöû, õàé - äëÿ |
//| âåðõíåé), à òàêæå îòñòóï â ïóíêòàõ îò ãðàíèöû ïðè ðàçìåùåíèè |
//| ñòîïëîññà. |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
TrailingByPriceChannel(iTicket,iBars_n,iIndent);
return(0);
}
//+------------------------------------------------------------------+
void TrailingByPriceChannel(int iTicket,int iBars_n,int iIndent)
{
// ïðîâåðÿåì ïåðåäàííûå çíà÷åíèÿ
if ((iBars_n<1) || (iIndent<0) || (iTicket==0) || (!OrderSelect(iTicket,SELECT_BY_TICKET)))
{
Print("Òðåéëèíã ôóíêöèåé TrailingByPriceChannel() íåâîçìîæåí èç-çà íåêîððåêòíîñòè çíà÷åíèé ïåðåäàííûõ åé àðãóìåíòîâ.");
return(0);
}
double dChnl_max; // âåðõíÿÿ ãðàíèöà êàíàëà
double dChnl_min; // íèæíÿÿ ãðàíèöà êàíàëà
// îïðåäåëÿåì ìàêñ.õàé è ìèí.ëîó çà iBars_n áàðîâ íà÷èíàÿ ñ [1] (= âåðõíÿÿ è íèæíÿÿ ãðàíèöû öåíîâîãî êàíàëà)
dChnl_max = High[iHighest(Symbol(),0,2,iBars_n,1)] + (iIndent+MarketInfo(Symbol(),MODE_SPREAD))*Point;
dChnl_min = Low[iLowest(Symbol(),0,1,iBars_n,1)] - iIndent*Point;
// åñëè äëèííàÿ ïîçèöèÿ, è å¸ ñòîïëîññ õóæå (íèæå íèæíåé ãðàíèöû êàíàëà ëèáî íå îïðåäåëåí, ==0), ìîäèôèöèðóåì åãî
if (OrderType()==OP_BUY)
{
if ((OrderStopLoss()<dChnl_min) && (dChnl_min<Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
{
if (!OrderModify(iTicket,OrderOpenPrice(),dChnl_min,OrderTakeProfit(),OrderExpiration()))
Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
}
}
// åñëè ïîçèöèÿ - êîðîòêàÿ, è å¸ ñòîïëîññ õóæå (âûøå âåðõíåé ãðàíèöû êàíàëà èëè íå îïðåäåë¸í, ==0), ìîäèôèöèðóåì åãî
if (OrderType()==OP_SELL)
{
if (((OrderStopLoss()==0) || (OrderStopLoss()>dChnl_max)) && (dChnl_min>Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
{
if (!OrderModify(iTicket,OrderOpenPrice(),dChnl_max,OrderTakeProfit(),OrderExpiration()))
Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
}
}
}
//+------------------------------------------------------------------+
Comments