This script is a specialized utility designed for the MetaTrader 4 platform to automate the management of "Trailing Stops." A trailing stop is a dynamic order modification tool that moves a stop-loss price automatically as the market moves in favor of the trade, helping to lock in profits while allowing room for further price fluctuations.
The logic follows a structured approach to monitor active trades and adjust them based on two distinct methodologies:
Core Execution Logic
- Environment Check: Before performing any actions, the script verifies that the trading environment is active and ensures it does not interfere with other automated trading systems (EAs) already running on the account.
- Order Identification: The script scans your currently open positions to find a trade matching the current currency pair. Once identified, it proceeds to apply the chosen trailing logic.
- Mode Selection: The user can choose between two different "styles" of moving the stop-loss: High/Low calculation or Fixed Pips.
Trailing Method 1: High/Low Period Calculation
This method is designed for traders who prefer a more reactive approach based on recent price history.
- Logic: It looks back at a specific number of previous candles (defined by the user).
- Buy Trades: It identifies the lowest price reached during that period. If that low point is higher than your current stop-loss, it moves the stop-loss up to that level.
- Sell Trades: It identifies the highest price reached during that period. If that high point is lower than your current stop-loss (or if no stop-loss exists), it moves the stop-loss down to that level.
- Result: This effectively "trails" the price based on recent market結構 (structure).
Trailing Method 2: Fixed Pip Size
This method provides a more rigid, mathematical approach to profit protection.
- Logic: It calculates a specific distance in pips from the current market price.
- Execution: The script constantly checks if the trade has moved into enough profit to accommodate a "safety buffer." If the profit exceeds the defined pip amount, it moves the stop-loss forward by exactly that many pips.
- Result: This ensures that once a certain profit milestone is hit, your stop-loss follows at a constant, fixed distance behind the current price.
Key User Parameters
To control this behavior, the script provides several adjustable inputs:
- HL Period: Determines how many past candles to look at when using the High/Low method.
- SP Size: Sets the specific number of pips used for the fixed-distance trailing method.
- Trailing Stop Select: A simple toggle to switch between the two different tracking styles.
//+------------------------------------------------------------------+
//| MA-EA-TSTOPS.mq4 |
//| Copyright(c) 2010 Masaru Sasaki |
//| http://youtarou.blogzine.jp |
//+------------------------------------------------------------------+
// < MetaTrader4 FX(O×ÖØàæø)©®gCOVXeEA >
// u\[XR[höJRv
// *êÊIÈÂlg[_[ÌêlƵÄAvOÉsµêÈûÖÌ
// QlƵÄöJ·éɵܵ½B
// ©ªÍK¢ÉàvO~Oðï¡ÆµÄ½Tf[vO}[
// Å é©çAVXevO~O(EA)ªÅ«Üµ½B
// vO~OÍK¤æèAµêë¾Æv¢Ü·B
//
// uÖ~v
// *±ÌvO\[XR[hð»ÌÜܬpµ½\tgÌÌð
// êØÖ~vµÜ·B
//
// uÆÓv
// *±ÌvOÉîÃs×Ìʶµ½áQA¹¸ÈÇÉ¢Ä
// ìÒÍêØÌÓCð¢Ü¹ñB
//
// uà¾v
// *ÙÊg[hÉÄGg[µ½ãÌgCOXgbvð©®»·é
// EAÅ·B(©®ÍµÜ¹ñB)
// }üµ½`[gÌÊÝÅA1I[_[ÌÝεܷB
// ¡I[_[ÉÍεĢܹñB
// gpû@ƵÄÍAÙÊg[hÉÄGg[µ½ãÉEAÒ®ðÂ
// Ʒ龯ŷB
// AgCOXgbvû@ðêè(pipsPÊ)©êèų¢
// (wèÍÍÌlÀl)©ðIðūܷB
// êèÍpipsPÊÅÝèūܷB
//
// (ÓFI[_[Ì}WbNÔð©Ä¢Ü¹ñÌÅA¼ÌEAů¶ÊÝ
// ÆÍ¤¶Å«Ü¹ñB
//
// QlÐFFX^g[_[üå (PanRolling)
// FX^g[_[ÀHvO~O (PanRolling)
//
#property copyright "Copyright(c) 2010 Masaru Sasaki"
#property link "http://youtarou.blogzine.jp"
// êèų¢gCOXgbvÌo[ð©é
extern int HL_period = 20;
// êègCOXgbvðIðµ½ÌTCY(pips)
extern int sp_size = 5;
// gCOXgbvû@ÌIð(WÍêèų¢û®)
extern int TrailingStop_select = 1;
// fobO on/off tO
bool debug = false;
// êèų¢gCOXgbvÖ(wèµ½o[ÌlAÀl)
bool TrailingStopHL(int HL_period, double ask, double bid, int ticket, int type)
{
// gCOXgbvvZ
double spread = ask-bid;
double HH = High[iHighest(NULL, 0, MODE_HIGH, HL_period, 1)] + spread;
double LL = Low[iLowest(NULL, 0, MODE_LOW, HL_period, 1)];
bool ret = false;
OrderSelect(ticket, SELECT_BY_TICKET);
if( type == OP_BUY )
{
if( LL > OrderStopLoss() )
ret = OrderModify( ticket, OrderOpenPrice(), LL, OrderTakeProfit(), 0, Blue);
}
if( type == OP_SELL )
{
if( HH < OrderStopLoss() || OrderStopLoss() == 0 )
ret = OrderModify( ticket, OrderOpenPrice(), HH, OrderTakeProfit(), 0, Blue);
}
return(ret);
}
// êèÌgCOXgbvÖ(pipsPÊ)
bool TrailingStopSetsize(int setsize, double point, double ask, double bid, int ticket, int type)
{
// gCOXgbvvZ
bool ret = false;
double profit = 0.0;
double set_size = setsize * point;
double spread = ask - bid;
int i = 1000;
OrderSelect(ticket, SELECT_BY_TICKET);
while( i > 0 )
{
if( type == OP_BUY )
{
profit = ask - OrderOpenPrice() - (set_size * i + spread);
if( profit > 0 )
{
ret = OrderModify(ticket, OrderOpenPrice(), OrderStopLoss() + set_size, OrderTakeProfit(), 0, Blue);
return(ret);
}
}
if( type == OP_SELL )
{
profit = OrderOpenPrice() - bid - (set_size * i + spread);
if( profit > 0 )
{
ret = OrderModify(ticket, OrderOpenPrice(), OrderStopLoss() - set_size, OrderTakeProfit(), 0, Blue);
return(ret);
}
}
i--;
}
return(false);
}
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
// o[ÌnlÅg[hÂ\©`FbN
if( Volume[0] > 1 || IsTradeAllowed() == false )
return(0);
// I[_[L³Ì`FbN
int ticket = 0; bool ret = false;
for(int i = 0; i < OrdersTotal(); i++ )
{
if(OrderSelect(i, SELECT_BY_POS) == false) break;
if(OrderSymbol() != Symbol()) continue;
int type = OrderType();
if(type == OP_BUY || type == OP_SELL)
{
ticket = OrderTicket();
break;
}
}
if(ticket == 0) return(0);
if( TrailingStop_select == 1 )
{
// êèų¢gCOXgbvÖÄÑoµ
ret = TrailingStopHL(HL_period, Ask, Bid, ticket, type);
}
else
{
// êèÌgCOXgbvÖÄÑoµ
ret = TrailingStopSetsize(sp_size, Point, Ask, Bid, ticket, type);
}
// fobO\¦
if( debug == true )
{
Print("Open :", Open[1], "Close :", Close[1]);
Print("Trailing stop :", ret);
}
return(0);
}
//+------------------------------------------------------------------+
Comments