Exp_XPeriodCandle_X2

Download script
Author: Copyright © 2018, Nikolay Kositsin

This trading script is designed to automate the process of opening and closing trades based on specific price trends. It uses a multi-layered logic system that monitors different timeframes to ensure the strategy aligns with both short-term movements and long-term market direction.

Core Logic Overview

1. Dual Timeframe Monitoring The script doesn't just look at one chart; it simultaneously monitors two different timeframes (a primary timeframe and a secondary "High Time Frame"). By looking at multiple views, the system tries to verify that a trend is valid before taking action. This helps in filtering out "noise" or temporary price spikes that might lead to false signals.

2. Trend Detection & Smoothing To determine the market direction, the script employs specialized smoothing algorithms (such as JJMA). Instead of reacting to every tiny wiggle in price, it uses these mathematical models to identify a clear "Trend."

  • It assigns specific numerical values to represent the trend: one value indicates an upward move, while another indicates a downward move.
  • The system tracks these changes and only triggers actions when the smoothed data confirms a definitive shift in momentum.

3. Trade Execution Logic The script follows a structured set of rules for entering and exiting positions:

  • Entry: It looks for specific "Signal Bars." When the smoothed trend data hits a target value on a new candle, it identifies a signal to open either a Buy or a Sell position.
  • Exit & Reversal: The script is programmed to automatically close existing positions if the trend reverses (e.g., closing a Buy if the trend turns bearish). It also has specific settings to allow for "forced" closures based on the appearance of opposing signals.

4. Risk Management Every trade executed by the script is governed by several safety parameters:

  • Money Management: You can choose how the script calculates your position size, whether it's based on your total balance, free margin, or a fixed lot size.
  • Safety Nets: It includes "Stop Loss" and "Take Profit" levels. These ensure that every trade has a pre-defined limit to protect your capital from significant losses while securing profits at specific targets.
  • Deviations: The script handles slight price differences (slippage) to ensure that trades are executed accurately even in fast-moving markets.

5. Dynamic Synchronization Because the script looks at different timeframes, it includes a "Time Shift" calculation. This ensures that the signals from a higher timeframe are correctly synchronized with the current time on your primary chart, preventing the system from reacting to "old" data.

8 Views
0 Downloads
0 Favorites
Exp_XPeriodCandle_X2
ÿþ//+------------------------------------------------------------------+

//|                                         Exp_XPeriodCandle_X2.mq5 |

//|                               Copyright © 2018, Nikolay Kositsin | 

//|                              Khabarovsk,   farria@mail.redcom.ru | 

//+------------------------------------------------------------------+

#property copyright "Copyright © 2018, Nikolay Kositsin"

#property link      "farria@mail.redcom.ru"

#property version   "1.00"

//+-------------------------------------------------+

//|  ?8A0=85 :;0AA0 CXMA                           |

//+-------------------------------------------------+

#include <SmoothAlgorithms.mqh> 

//+-------------------------------------------------+

//  ">@3>2K5 0;3>@8B<K                              | 

//+-------------------------------------------------+

#include <TradeAlgorithms.mqh>

//+-------------------------------------------------+

//|  5@5G8A;5=85 4;O 20@80=B>2 @0AGQB0 ;>B0        |

//+-------------------------------------------------+

/*enum MarginMode  - ?5@5G8A;5=85 >1JO2;5=> 2 D09;5 TradeAlgorithms.mqh

  {

   FREEMARGIN=0,     //MM >B A2>1>4=KE A@54AB2 =0 AGQB5

   BALANCE,          //MM >B 10;0=A0 A@54AB2 =0 AGQB5

   LOSSFREEMARGIN,   //MM ?> C1KB:0< >B A2>1>4=KE A@54AB2 =0 AGQB5

   LOSSBALANCE,      //MM ?> C1KB:0< >B 10;0=A0 A@54AB2 =0 AGQB5

   LOT               //>B 157 87<5=5=8O

  }; */

//+-------------------------------------------------+

//|  >1JO2;5=85 ?5@5G8A;5=89                        |

//+-------------------------------------------------+

/*enum Smooth_Method - ?5@5G8A;5=85 >1JO2;5=> 2 D09;5 SmoothAlgorithms.mqh

  {

   MODE_SMA_,  // SMA

   MODE_EMA_,  // EMA

   MODE_SMMA_, // SMMA

   MODE_LWMA_, // LWMA

   MODE_JJMA,  // JJMA

   MODE_JurX,  // JurX

   MODE_ParMA, // ParMA

   MODE_T3,    // T3

   MODE_VIDYA, // VIDYA

   MODE_AMA    // AMA

  }; */

//+-------------------------------------------------+

//| E>4=K5 ?0@0<5B@K 8=48:0B>@0 M:A?5@B0           |

//+-------------------------------------------------+

sinput string Trade="#?@02;5=85 B>@3>2;59";    //+============== #  "  ==============+  

input double MM=0.1;               //>;O D8=0=A>2KE @5AC@A>2 >B 45?>78B0 2 A45;:5

input MarginMode MMMode=LOT;      //A?>A>1 >?@545;5=8O @07<5@0 ;>B0

input uint    StopLoss_=1000;      //AB>?;>AA 2 ?C=:B0E

input uint    TakeProfit_=2000;    //B59:?@>D8B 2 ?C=:B0E

sinput string MustTrade=" 07@5H5=8O B>@3>2;8";    //+==============   (/ "  ==============+  

input int    Deviation_=10;       //<0:A. >B:;>=5=85 F5=K 2 ?C=:B0E

input bool   BuyPosOpen=true;     // 07@5H5=85 4;O 2E>40 2 ;>=3

input bool   SellPosOpen=true;    // 07@5H5=85 4;O 2E>40 2 H>@B

//+-------------------------------------------------+

//| E>4=K5 ?0@0<5B@K 8=48:0B>@0 D8;LB@0            |

//+-------------------------------------------------+

sinput string Filter=" " +  " ";            //+==============  " + "  ==============+  

input ENUM_TIMEFRAMES TimeFrame=PERIOD_H6;                     //1 5@8>4 3@0D8:0 4;O B@5=40

input uint Cperiod=5;                                          // 5@8>4 @0AGQB0 A25G59

input Smooth_Method MA_SMethod=MODE_JJMA;                      // 5B>4 CA@54=5=8O

input int MA_Length=3;                                         // 3;C18=0 A3;06820=8O                    

input int MA_Phase=100;                                        // ?0@0<5B@ A3;06820=8O,

//---- 4;O JJMA 87<5=ONI89AO 2 ?@545;0E -100 ... +100, 2;8O5B =0 :0G5AB2> ?5@5E>4=>3> ?@>F5AA0;

//---- ;O VIDIA MB> ?5@8>4 CMO, 4;O AMA MB> ?5@8>4 <54;5==>9 A:>;L7OI59

input uint SignalBar=1;                                        // =><5@ 10@0 4;O ?>;CG5=8O A83=0;0 2E>40

input bool   BuyPosClose=true;                                 //  07@5H5=85 4;O 2KE>40 87 ;>=3>2 ?> B@5=4C

input bool   SellPosClose=true;                                //  07@5H5=85 4;O 2KE>40 87 H>@B>2 ?> B@5=4C

//+-------------------------------------------------+

//| E>4=K5 ?0@0<5B@K 8=48:0B>@0 2E>40              |

//+-------------------------------------------------+

sinput string Input=" " + %";                         //+===============  " + % ===============+  

input ENUM_TIMEFRAMES TimeFrame_=PERIOD_M30;                   //2 5@8>4 3@0D8:0 4;O 2E>40 

input uint Cperiod_=5;                                         // 5@8>4 @0AGQB0 A25G59

input Smooth_Method MA_SMethod_=MODE_JJMA;                     // 5B>4 CA@54=5=8O

input int MA_Length_=3;                                        // 3;C18=0 A3;06820=8O                    

input int MA_Phase_=100;                                       // ?0@0<5B@ A3;06820=8O,

//---- 4;O JJMA 87<5=ONI89AO 2 ?@545;0E -100 ... +100, 2;8O5B =0 :0G5AB2> ?5@5E>4=>3> ?@>F5AA0;

//---- ;O VIDIA MB> ?5@8>4 CMO, 4;O AMA MB> ?5@8>4 <54;5==>9 A:>;L7OI59

input uint SignalBar_=1;                                       // =><5@ 10@0 4;O ?>;CG5=8O A83=0;0 2E>40

input bool   BuyPosClose_=false;                               //  07@5H5=85 4;O 2KE>40 87 ;>=3>2 ?> A83=0;C

input bool   SellPosClose_=false;                              //  07@5H5=85 4;O 2KE>40 87 H>@B>2 ?> A83=0;C

//+-------------------------------------------------+

int TimeShiftSec,TimeShiftSec_;

//---- 1JO2;5=85 F5;KE ?5@5<5==KE 4;O E5=4;>2 8=48:0B>@>2

int InpInd_Handle,InpInd_Handle_;

//---- >1JO2;5=85 F5;KE ?5@5<5==KE =0G0;0 >BAG5B0 40==KE

int min_rates_total,min_rates_total_;

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//---- ?>;CG5=85 E5=4;0 8=48:0B>@0 XPeriodCandle

   InpInd_Handle=iCustom(Symbol(),TimeFrame,"XPeriodCandle",Cperiod,MA_SMethod,MA_Length,MA_Phase);

   if(InpInd_Handle==INVALID_HANDLE)

     {

      Print(" 5 C40;>AL ?>;CG8BL E5=4; 8=48:0B>@0 XPeriodCandle");

      return(INIT_FAILED);

     }



//---- ?>;CG5=85 E5=4;0 8=48:0B>@0 XPeriodCandled _

   InpInd_Handle_=iCustom(Symbol(),TimeFrame_,"XPeriodCandle",Cperiod_,MA_SMethod_,MA_Length_,MA_Phase_);

   if(InpInd_Handle_==INVALID_HANDLE)

     {

      Print(" 5 C40;>AL ?>;CG8BL E5=4; 8=48:0B>@0 XPeriodCandle _");

      return(INIT_FAILED);

     }



   if(MQLInfoInteger(MQL_VISUAL_MODE))

     {

      //---- ?>;CG5=85 E5=4;0 8=48:0B>@0 XPeriodCandle_HTF

      int Ind_Handle=iCustom(Symbol(),Period(),"XPeriodCandle_HTF",TimeFrame,Cperiod,MA_SMethod,MA_Length,MA_Phase);

      if(Ind_Handle==INVALID_HANDLE)

        {

         Print(" 5 C40;>AL ?>;CG8BL E5=4; 8=48:0B>@0 XPeriodCandle_HTF");

         return(INIT_FAILED);

        }

      //---- ?>;CG5=85 E5=4;0 8=48:0B>@0 XPeriodCandle_HTF

      Ind_Handle=iCustom(Symbol(),Period(),"XPeriodCandle_HTF",TimeFrame_,Cperiod_,MA_SMethod_,MA_Length_,MA_Phase_);

      if(Ind_Handle==INVALID_HANDLE)

        {

         Print(" 5 C40;>AL ?>;CG8BL E5=4; 8=48:0B>@0 XPeriodCandle_HTF _");

         return(INIT_FAILED);

        }



     }



//---- 8=8F80;870F8O ?5@5<5==>9 4;O E@0=5=8O ?5@8>40 3@0D8:0 2 A5:C=40E  

   TimeShiftSec=PeriodSeconds(TimeFrame);

   TimeShiftSec_=PeriodSeconds(TimeFrame_);



//---- 8=8F80;870F8O ?5@5<5==KE =0G0;0 >BAGQB0 40==KE

   int min_rates_1=GetStartBars(MA_SMethod,MA_Length,MA_Phase);

   min_rates_total=min_rates_1+int(Cperiod_)+1;

   min_rates_total+=int(2+SignalBar);

//---- 8=8F80;870F8O ?5@5<5==KE =0G0;0 >BAGQB0 40==KE   

   min_rates_1=GetStartBars(MA_SMethod_,MA_Length_,MA_Phase_);

   min_rates_total=min_rates_1+int(Cperiod_)+1;

   min_rates_total_+=int(3+SignalBar_);

//--- 7025@H5=85 8=8F80;870F88

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//----

   GlobalVariableDel_(Symbol());

//----

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

//---- ?>43@C7:0 8AB>@88 4;O =>@<0;L=>9 @01>BK DC=:F89 IsNewBar() 8 SeriesInfoInteger()  

   LoadHistory(TimeCurrent()-PeriodSeconds(TimeFrame)-1,Symbol(),TimeFrame);

   LoadHistory(TimeCurrent()-PeriodSeconds(TimeFrame_)-1,Symbol(),TimeFrame_);

//---- ?@>25@:0 :>;8G5AB20 10@>2 =0 4>AB0B>G=>ABL 4;O @0AGQB0

   int barscal=BarsCalculated(InpInd_Handle);

   int barscal_=BarsCalculated(InpInd_Handle_);

   if(barscal<min_rates_total || barscal_<min_rates_total_) return;



//---- 1JO2;5=85 AB0B8G5A:8E ?5@5<5==KE

   static bool Recount=true,Recount_=true;

   static bool BUY_Open=false,BUY_Close=false;

   static bool SELL_Open=false,SELL_Close=false;

   static bool ReBUY_Open=false,ReSELL_Open=false;

   static datetime UpSignalTime,DnSignalTime;

   static CIsNewBar NB,NB_;

   static int Trend=0;  //=0?@02;5=85 B@5=40 4;O D8;LB@0 A45;>:



//---- >?@545;O5< B5:CI89 B@5=4 =0 ?>A;54=5< 70:@KB>< 10@5

   if(NB.IsNewBar(Symbol(),TimeFrame) || Recount) // ?@>25@:0 =0 ?>O2;5=85 =>2>3> 10@0

     {

      Recount=false;

      Trend=0;

      //---- 1JO2;5=85 ;>:0;L=KE ?5@5<5==KE

      double Value[1];

      //---- :>?8@C5< 2=>2L ?>O282H85AO 40==K5 2 <0AA82

      if(CopyBuffer(InpInd_Handle,4,SignalBar,1,Value)<=0) {Recount=true; return;}

      //---- >?@545;O5< B@5=4

      if(Value[0]==2) Trend=-1;

      if(Value[0]==0) Trend=+1;

     }



//---- >?@545;O5< A83=0; 4;O A45;:8 =0 ?>A;54=5< 70:@KB>< 10@5

   if(NB_.IsNewBar(Symbol(),TimeFrame_) || Recount_) // ?@>25@:0 =0 ?>O2;5=85 =>2>3> 10@0

     {

      //---- >1=C;8< B>@3>2K5 A83=0;K

      BUY_Open=false;

      SELL_Open=false;

      BUY_Close=false;

      SELL_Close=false;

      ReBUY_Open=false;

      ReSELL_Open=false;

      Recount_=false;

      UpSignalTime=datetime(SeriesInfoInteger(Symbol(),TimeFrame_,SERIES_LASTBAR_DATE))+TimeShiftSec_;

      DnSignalTime=datetime(SeriesInfoInteger(Symbol(),TimeFrame_,SERIES_LASTBAR_DATE))+TimeShiftSec_;



      //---- 1JO2;5=85 ;>:0;L=KE ?5@5<5==KE

      double Value[2];



      //---- :>?8@C5< 2=>2L ?>O282H85AO 40==K5 2 <0AA82K

      if(CopyBuffer(InpInd_Handle_,4,SignalBar,2,Value)<=0) {Recount_=true; return;}



      //---- >?@545;O5< A83=0;K 4;O A45;>:

      if(BuyPosClose_ && Value[1]==2) BUY_Close=true;

      if(SellPosClose_ && Value[1]==0) SELL_Close=true;

      if(Trend<0)

        {

         if(BuyPosClose) BUY_Close=true;

         if(SellPosOpen && Value[0]<2 && Value[1]==2) SELL_Open=true;

        }

      if(Trend>0)

        {

         if(SellPosClose) SELL_Close=true;

         if(BuyPosOpen && Value[0]>0 && Value[1]==0) BUY_Open=true;

        }

     }

//+-------------------------------------------------+

//| !>25@H5=85 A45;>:                               |

//+-------------------------------------------------+

//---- 0:@K205< ;>=3

   BuyPositionClose(BUY_Close,Symbol(),Deviation_);



//---- 0:@K205< H>@B   

   SellPositionClose(SELL_Close,Symbol(),Deviation_);



//---- B:@K205< ;>=3

   BuyPositionOpen(BUY_Open,Symbol(),UpSignalTime,MM,MMMode,Deviation_,StopLoss_,TakeProfit_);



//---- B:@K205< H>@B

   SellPositionOpen(SELL_Open,Symbol(),DnSignalTime,MM,MMMode,Deviation_,StopLoss_,TakeProfit_);

//----

  }

//+------------------------------------------------------------------+

Comments