TrailingByMA
Download scriptThis script is designed to automate the management of your open trades by dynamically adjusting the Stop Loss levels based on a moving average indicator. Instead of leaving your protection at a static price, this tool "trails" your stop loss to follow market trends automatically.
How It Works
The logic follows a specific sequence of steps to ensure your trades are managed safely and accurately:
1. Validation of Inputs Before performing any actions, the script checks that all user-provided settings are valid. It verifies that the trade ticket number is correct, that the timeframe is supported, and that the technical parameters (like moving average period and price types) fall within acceptable limits. If any information is incorrect, the script will notify you and stop execution to prevent errors.
2. Calculating the Moving Average The script calculates a specific Moving Average (MA) based on your custom settings. You can define:
- The time period for the average.
- The calculation method (e.g., Simple, Exponential, etc.).
- The price type used for the calculation (e.g., Close, Open, High, Low).
- A specific offset or shift relative to the current bar.
3. Intelligent Stop Loss Adjustment The core logic then applies different rules depending on whether you are in a "Buy" or "Sell" position:
- For Buy Positions: The script monitors the current market price. If your current Stop Loss is lower than the calculated Moving Average (minus a specific safety buffer you define), the script automatically moves your Stop Loss up to that higher level. This helps lock in profits as the price climbs.
- For Sell Positions: The script monitors if your Stop Loss is either non-existent or set too high. It ensures the Stop Loss stays below the Moving Average (plus a safety buffer that accounts for the market spread). This protects your position from losses if the market moves against you.
4. Safety Checks & Execution The script includes built-in safeguards to ensure it doesn't violate broker rules. Before moving a Stop Loss, it checks:
- Minimum Distance: It verifies that the new Stop Loss isn't too close to the current market price (based on your broker's "Stop Level" requirements).
- Error Reporting: If the script tries to move a Stop Loss and the broker rejects the request for any reason, it will print a specific error message in the log so you can diagnose what happened.
Summary for the User
In simple terms, this tool acts as an automated bodyguard. It watches your trade and constantly moves your "safety net" (Stop Loss) to stay tucked behind the Moving Average. This allows you to ride a profitable trend longer while automatically protecting your gains as the market fluctuates.
//+------------------------------------------------------------------+
//| TrailingByFractals.mq4 |
//| I_D |
//| http://www.mymmk.com/ |
//+------------------------------------------------------------------+
#property copyright "I_D"
#property link "http://www.mymmk.com/ Ñîôò äëÿ óïðàâëåíèÿ êàïèòàëîì"
extern int iTicket; // óíèêàëüíûé íîìåð (òèêåò) îòêðûòîé ïîçèöèè
extern int iTmfrm; // ïåðèîä ãðàôèêà, íà êîòîðîì ñòðîèòñÿ ÌÀ (1, 5, 15, 30, 60, 240, 1440, 10080, 43200)
extern int iMAPeriod = 21; // ïåðèîä ÌÀ (íå ìåíüøå 2)
extern int iMAShift = 0; // ñäâèã èíäèêàòîðà îòíîñèòåëüíî öåíîâîãî ãðàôèêà
extern int iMAMethod = 0; // ìåòîä óñðåäíåíèÿ (0 - MODE_SMA, 1 - MODE_EMA, 2 - MODE_SMMA, 3 - MODE_LWMA);
extern int iApplPrice = 0; // èñïîëüçóåìàÿ öåíà (0 - PRICE_CLOSE, 1 - PRICE_OPEN, 2 - PRICE_HIGH, 3 - PRICE_LOW, 4 - PRICE_MEDIAN, 5 - PRICE_TYPICAL, 6 - PRICE_WEIGHTED)
extern int iShift = 1; // èíäåêñ ïîëó÷àåìîãî çíà÷åíèÿ èç èíäèêàòîðíîãî áóôåðà (ñäâèã îòíîñèòåëüíî òåêóùåãî áàðà íà óêàçàííîå êîëè÷åñòâî ïåðèîäîâ íàçàä)
extern int iIndent = 3; // îòñòóï îò òåíè áàðà, íà êîòîðîì ðàçìåùàåòñÿ ñòîïëîññ
//+------------------------------------------------------------------+
//| ÒÐÅÉËÈÍÃ ÏÎ ÑÊÎËÜÇßÙÅÌÓ ÑÐÅÄÍÅÌÓ |
//| Ïðè çàïóñêå ýêñïåðòà åìó íåîáõîäèìî óêàçàòü óíèêàëüíûé íîìåð |
//| (òèêåò) îòêðûòîé ïîçèöèè, à òàêæå îïðåäåëèòü ïàðàìåòðû òðåéëèíãà:|
//| òàéìôðåéì, íà êîòîðîì ñòðîèòñÿ ñêîëüçÿùåå ñðåäíåå, åãî ïàðàìåòðû |
//| (ïåðèîä, ñäâèã îòíîñèòåëüíî ãðàôèêà, ìåòîä ïîñòðîåíèÿ, òèï öåíû, |
//| ïî êîòîðîé ñ÷èòàåòñÿ, íà êàêîì áàðå ñ÷èòûâàåì çíà÷åíèå), à òàêæå |
//| îòñòóï (ïóíêòîâ) îò ñðåäíåãî, íà êîòîðîì óñòàíàâëèâàåòñÿ ñòîïëîññ|
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
TrailingByMA(iTicket,iTmfrm,iMAPeriod,iMAShift,iMAMethod,iApplPrice,iShift,iIndent);
return(0);
}
//+------------------------------------------------------------------+
void TrailingByMA(int iTicket,int iTmFrme,int iMAPeriod,int iMAShift,int MAMethod,int iApplPrice,int iShift,int iIndent)
{
// ïðîâåðÿåì ïåðåäàííûå çíà÷åíèÿ
if ((iTicket==0) || (!OrderSelect(iTicket,SELECT_BY_TICKET)) || ((iTmFrme!=1) && (iTmFrme!=5) && (iTmFrme!=15) && (iTmFrme!=30) && (iTmFrme!=60) && (iTmFrme!=240) && (iTmFrme!=1440) && (iTmFrme!=10080) && (iTmFrme!=43200)) ||
(iMAPeriod<2) || (MAMethod<0) || (MAMethod>3) || (iApplPrice<0) || (iApplPrice>6) || (iShift<0) || (iIndent<0))
{
Print("Òðåéëèíã ôóíêöèåé TrailingByMA() íåâîçìîæåí èç-çà íåêîððåêòíîñòè çíà÷åíèé ïåðåäàííûõ åé àðãóìåíòîâ.");
return(0);
}
double dMA; // çíà÷åíèå ñêîëüçÿùåãî ñðåäíåãî ñ ïåðåäàííûìè ïàðàìåòðàìè
// îïðåäåëèì çíà÷åíèå ÌÀ ñ ïåðåäàííûìè ôóíêöèè ïàðàìåòðàìè
dMA = iMA(Symbol(),iTmFrme,iMAPeriod,iMAShift,MAMethod,iApplPrice,iShift);
// åñëè äëèííàÿ ïîçèöèÿ, è å¸ ñòîïëîññ õóæå çíà÷åíèÿ ñðåäíåãî ñ îòñòóïîì â iIndent ïóíêòîâ, ìîäèôèöèðóåì åãî
if (OrderType()==OP_BUY)
{
if ((OrderStopLoss()<dMA-iIndent*Point) && (dMA-iIndent*Point<Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
{
if (!OrderModify(iTicket,OrderOpenPrice(),dMA-iIndent*Point,OrderTakeProfit(),OrderExpiration()))
Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
}
}
// åñëè ïîçèöèÿ - êîðîòêàÿ, è å¸ ñòîïëîññ õóæå (âûøå âåðõíåé ãðàíèöû êàíàëà èëè íå îïðåäåë¸í, ==0), ìîäèôèöèðóåì åãî
if (OrderType()==OP_SELL)
{
if (((OrderStopLoss()==0) || (OrderStopLoss()>dMA+(MarketInfo(Symbol(),MODE_SPREAD)+iIndent)*Point)) && (dMA+(MarketInfo(Symbol(),MODE_SPREAD)+iIndent)*Point>Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point))
{
if (!OrderModify(iTicket,OrderOpenPrice(),dMA+(MarketInfo(Symbol(),MODE_SPREAD)+iIndent)*Point,OrderTakeProfit(),OrderExpiration()))
Print("Íå óäàëîñü ìîäèôèöèðîâàòü ñòîïëîññ îðäåðà ¹",OrderTicket(),". Îøèáêà: ",GetLastError());
}
}
}
//+------------------------------------------------------------------+
Comments