MA-EA-TSTOPS

Author: Copyright(c) 2010 Masaru Sasaki
MA-EA-TSTOPS

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

  1. 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.
  2. 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.
  3. 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.
Orders Execution
It can change open orders parameters, due to possible stepping strategyChecks for the total of open orders
5 Views
0 Downloads
0 Favorites
MA-EA-TSTOPS
//+------------------------------------------------------------------+
//|                                                 MA-EA-TSTOPS.mq4 |
//|                                  Copyright(c) 2010 Masaru Sasaki |
//|                                      http://youtarou.blogzine.jp |
//+------------------------------------------------------------------+
// < MetaTrader4 FX(ŠO‘ˆ×‘֏؋’‹àŽæˆø)Ž©“®ƒgƒŒƒCƒŠƒ“ƒOƒVƒXƒeƒ€EA >
// uƒ\[ƒXƒR[ƒhŒöŠJ——Rv
//  *ˆê”Ê“I‚ȌlƒgƒŒ[ƒ_[‚̈êl‚Æ‚µ‚āAƒvƒƒOƒ‰ƒ€‚É•sе‚ê‚È•û‚Ö‚Ì
//   ŽQl‚Æ‚µ‚ÄŒöŠJ‚·‚鎖‚É‚µ‚Ü‚µ‚½B
//   Ž©•ª‚͍K‚¢‚É‚àƒvƒƒOƒ‰ƒ~ƒ“ƒO‚ðŽï–¡‚Æ‚µ‚Ä—ˆ‚½ƒTƒ“ƒf[ƒvƒƒOƒ‰ƒ}[
//   ‚Å‚ ‚鎖‚©‚çAƒVƒXƒeƒ€ƒvƒƒOƒ‰ƒ~ƒ“ƒO(EA)‚ª‚Å‚«‚Ü‚µ‚½B
//   ƒvƒƒOƒ‰ƒ~ƒ“ƒO‚͏K‚¤‚æ‚èAе‚ê‚낾‚ÆŽv‚¢‚Ü‚·B
//
// u‹ÖŽ~Ž–€v
//  *‚±‚̃vƒƒOƒ‰ƒ€ƒ\[ƒXƒR[ƒh‚ð‚»‚Ì‚Ü‚Ü—¬—p‚µ‚½ƒ\ƒtƒg‚̔̔„“™‚ð
//   ˆêØ‹ÖŽ~’v‚µ‚Ü‚·B
// 
// u–Ɛӎ–€v
//  *‚±‚̃vƒƒOƒ‰ƒ€‚ÉŠî‚­sˆ×‚ÌŒ‹‰Ê”­¶‚µ‚½áŠQA‘¹Ž¸‚Ȃǂɂ‚¢‚Ä
//    ’˜ìŽÒ‚ÍˆêØ‚̐ӔC‚𕉂¢‚Ü‚¹‚ñB
//
// uà–¾v
//  *Ù—ʃgƒŒ[ƒh‚ɂăGƒ“ƒgƒŠ[‚µ‚½Œã‚̃gƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒv‚ðŽ©“®‰»‚·‚é
//   EA‚Å‚·B(Ž©“®”„”ƒ‚Í‚µ‚Ü‚¹‚ñB)
//   ‘}“ü‚µ‚½ƒ`ƒƒ[ƒg‚̒ʉ݂ŁA1ƒI[ƒ_[‚̂ݑΉž‚µ‚Ü‚·B
//   •¡”ƒI[ƒ_[‚ɂ͑Ήž‚µ‚Ä‚¢‚Ü‚¹‚ñB
//   Žg—p•û–@‚Æ‚µ‚ẮAÙ—ʃgƒŒ[ƒh‚ɂăGƒ“ƒgƒŠ[‚µ‚½Œã‚ÉEA‰Ò“®‚ð‹–‰Â
//   ‚Æ‚·‚邾‚¯‚Å‚·B
//   –”AƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒv•û–@‚ðˆê’蕝(pips’PˆÊ)‚©ˆê’蕝‚Å–³‚¢
//   (Žw’è”͈͂̍‚’lˆÀ’l)‚©‚ð‘I‘ð‚Å‚«‚Ü‚·B
//   ˆê’蕝‚Ípips’PˆÊ‚Őݒè‚Å‚«‚Ü‚·B
//
//   (’ˆÓFƒI[ƒ_[‚̃}ƒWƒbƒN”ԍ†‚ðŒ©‚Ä‚¢‚Ü‚¹‚ñ‚̂ŁA‘¼‚ÌEA‚Å“¯‚¶’ʉÝ
//          ‚Ƃ͋¤‘¶‚Å‚«‚Ü‚¹‚ñB
//
// ŽQl‘ÐFFXƒƒ^ƒgƒŒ[ƒ_[“ü–å (PanRolling)
//           FXƒƒ^ƒgƒŒ[ƒ_[ŽÀ‘HƒvƒƒOƒ‰ƒ~ƒ“ƒO (PanRolling)
//
#property copyright "Copyright(c) 2010 Masaru Sasaki"
#property link      "http://youtarou.blogzine.jp"

// ˆê’蕝‚Å–³‚¢ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒv‚̃o[‚ðŒ©‚é”
extern int HL_period = 20;

// ˆê’蕝ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒv‚ð‘I‘ð‚µ‚½Žž‚̃TƒCƒY(pips)
extern int sp_size = 5;

// ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒv•û–@‚Ì‘I‘ð(•W€‚͈ê’蕝‚Å–³‚¢•ûŽ®)
extern int TrailingStop_select = 1;

// ƒfƒoƒbƒO on/off ƒtƒ‰ƒO
bool debug = false;

// ˆê’蕝‚Å–³‚¢ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒvŠÖ”(Žw’肵‚½ƒo[”‚̍‚’lAˆÀ’l)
bool TrailingStopHL(int HL_period, double ask, double bid, int ticket, int type)
{
   // ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒvŒvŽZ
   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);
}

// ˆê’蕝‚̃gƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒvŠÖ”(pips’PˆÊ)
bool TrailingStopSetsize(int setsize, double point, double ask, double bid, int ticket, int type)
{
   // ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒvŒvŽZ
   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[‚ÌŽn’l‚ŃgƒŒ[ƒh‰Â”\‚©ƒ`ƒFƒbƒN
   if( Volume[0] > 1 || IsTradeAllowed() == false )
      return(0);
   // ƒI[ƒ_[—L–³‚̃`ƒFƒbƒN   
   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 )
   {
      // ˆê’蕝‚Å–³‚¢ƒgƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒvŠÖ”ŒÄ‚яo‚µ
      ret = TrailingStopHL(HL_period, Ask, Bid, ticket, type);
   }
   else
   {
      // ˆê’蕝‚̃gƒŒƒCƒŠƒ“ƒOƒXƒgƒbƒvŠÖ”ŒÄ‚яo‚µ
      ret = TrailingStopSetsize(sp_size, Point, Ask, Bid, ticket, type);
   }
   // ƒfƒoƒbƒO•\ަ
   if( debug == true )
   {
      Print("Open :", Open[1], "Close :", Close[1]);
      Print("Trailing stop :", ret); 
   }
   return(0);
   
  }
//+------------------------------------------------------------------+

Comments