Author: Peter Byrom
Price Data Components
Series array that contains the lowest prices of each barSeries array that contains the highest prices of each bar
Indicators Used
Commodity channel indexMoving average indicatorLarry William percent range indicator
0 Views
0 Downloads
0 Favorites
Rabbit3
ÿþ//+------------------------------------------------------------------+

//|                             Rabbit3(barabashkakvn's edition).mq5 |

//|                                                     Peter  Byrom |

//|                                                  pete@byroms.net |

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

#property copyright "Peter  Byrom"

#property link      "pete@byroms.net"

#property version   "1.001"

//---

#define MODE_LOW 1

#define MODE_HIGH 2

//---

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

//--- input parameters

input int      cci_level_sell = 80;

input int      cci_level_buy  = -80;

input int      ma_period_cci  = 15;

input int      calc_period_wpr= 62;

input int      ma_period_fast = 17;

input int      ma_period_slow = 30;

input int      highest_count  = 24;

input int      max_positions  = 2;

input double   profit_level=4;           // profit level to increase the volume of positions (in money)

input double   InpLot=0.01;

input ulong    m_magic=444544;      // magic number

input ushort   m_slippage     = 30;

input ushort   stoploss       = 45;

input ushort   takeprofit     = 110;

//---

double         ExtLot=0.0;

int            handle_iCCI;                  // variable for storing the handle of the iCCI indicator 

int            handle_iMA_fast;              // variable for storing the handle of the iMA indicator 

int            handle_iMA_slow;              // variable for storing the handle of the iMA indicator 

int            handle_iWPR;                  // variable for storing the handle of the iWPR indicator 



ENUM_ACCOUNT_MARGIN_MODE m_margin_mode;

double         m_adjusted_point;             // point value adjusted for 3 or 5 points

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

   SetMarginMode();

   if(!IsHedging())

     {

      Print("Hedging only!");

      return(INIT_FAILED);

     }

//---

   m_symbol.Name(Symbol());                  // sets symbol name

   if(!RefreshRates())

     {

      Print("Error RefreshRates. Bid=",DoubleToString(m_symbol.Bid(),Digits()),

            ", Ask=",DoubleToString(m_symbol.Ask(),Digits()));

      return(INIT_FAILED);

     }

   m_symbol.Refresh();

//---

   m_trade.SetExpertMagicNumber(m_magic);

//---

   m_trade.SetDeviationInPoints(m_slippage);

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)

      digits_adjust=10;

   m_adjusted_point=m_symbol.Point()*digits_adjust;

   ExtLot=InpLot;

//--- create handle of the indicator iCCI

   handle_iCCI=iCCI(m_symbol.Name(),Period(),ma_period_cci,PRICE_CLOSE);

//--- if the handle is not created 

   if(handle_iCCI==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iCCI indicator for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//--- create handle of the indicator iMA

   handle_iMA_fast=iMA(m_symbol.Name(),Period(),ma_period_fast,0,MODE_EMA,PRICE_CLOSE);

//--- if the handle is not created 

   if(handle_iMA_fast==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//--- create handle of the indicator iMA

   handle_iMA_slow=iMA(m_symbol.Name(),Period(),ma_period_slow,0,MODE_EMA,PRICE_CLOSE);

//--- if the handle is not created 

   if(handle_iMA_slow==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//--- create handle of the indicator iWPR

   handle_iWPR=iWPR(m_symbol.Name(),Period(),calc_period_wpr);

//--- if the handle is not created 

   if(handle_iWPR==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iWPR indicator for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//--- trading will be started with first tick of new bar only

   static datetime PrevBars=0;

   datetime time_0=iTime(0);

   if(time_0==PrevBars)

      return;

   PrevBars=time_0;



   double CCI=iCCIGet(0);

   double ema_fast=iMAGet(handle_iMA_fast,0);

   double ema_slow=iMAGet(handle_iMA_slow,0);

   double will=iWPRGet(0);

   double will_lag=iWPRGet(1);

   if(will==0)

      will=-1;

   if(will_lag==0)

      will_lag=-1;



   int total=0;

   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions

      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==m_magic)

            total++;

//--- BUY 

   if(will<-80 && will_lag<-80 && max_positions>total && CCI<cci_level_buy)

     {

      if(!RefreshRates())

         return;

      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)

      double chek_volime_lot=m_trade.CheckVolume(m_symbol.Name(),ExtLot,m_symbol.Ask(),ORDER_TYPE_BUY);



      if(chek_volime_lot!=0.0)

         if(chek_volime_lot>=ExtLot)

           {

            if(m_trade.Buy(ExtLot,NULL,m_symbol.Ask(),

               m_symbol.NormalizePrice(m_symbol.Ask()-stoploss*m_adjusted_point),

               m_symbol.NormalizePrice(m_symbol.Ask()+takeprofit*m_adjusted_point)))

              {

               if(m_trade.ResultDeal()==0)

                 {

                  Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),

                        ", description of result: ",m_trade.ResultRetcodeDescription());

                 }

              }

            else

              {

               Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),

                     ", description of result: ",m_trade.ResultRetcodeDescription());

              }

           }

     }

//--- SELL

   if(will>-20 && will_lag>-20 && max_positions>total && CCI>cci_level_sell)

     {

      if(!RefreshRates())

         return;

      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)

      double chek_volime_lot=m_trade.CheckVolume(m_symbol.Name(),ExtLot,m_symbol.Ask(),ORDER_TYPE_SELL);



      if(chek_volime_lot!=0.0)

         if(chek_volime_lot>=ExtLot)

           {

            if(m_trade.Sell(ExtLot,NULL,m_symbol.Bid(),

               m_symbol.NormalizePrice(m_symbol.Bid()+stoploss*m_adjusted_point),

               m_symbol.NormalizePrice(m_symbol.Bid()-takeprofit*m_adjusted_point)))

              {

               if(m_trade.ResultDeal()==0)

                 {

                  Print("Sell -> false. Result Retcode: ",m_trade.ResultRetcode(),

                        ", description of result: ",m_trade.ResultRetcodeDescription());

                 }

              }

            else

              {

               Print("Sell -> false. Result Retcode: ",m_trade.ResultRetcode(),

                     ", description of result: ",m_trade.ResultRetcodeDescription());

              }

           }

     }

//---

   return;

  }

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

//| Close Positions                                                  |

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

void ClosePositions(ENUM_POSITION_TYPE pos_type)

  {

   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current orders

      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties

         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)

            if(m_position.PositionType()==pos_type) // gets the position type

               m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

   double res=0.0;

   int losses=0.0;

//--- get transaction type as enumeration value 

   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;

//--- if transaction is result of addition of the transaction in history

   if(type==TRADE_TRANSACTION_DEAL_ADD)

     {

      long     deal_entry        =0;

      double   deal_profit       =0.0;

      double   deal_volume       =0.0;

      string   deal_symbol       ="";

      long     deal_magic        =0;

      if(HistoryDealSelect(trans.deal))

        {

         deal_entry=HistoryDealGetInteger(trans.deal,DEAL_ENTRY);

         deal_profit=HistoryDealGetDouble(trans.deal,DEAL_PROFIT);

         deal_volume=HistoryDealGetDouble(trans.deal,DEAL_VOLUME);

         deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);

         deal_magic=HistoryDealGetInteger(trans.deal,DEAL_MAGIC);

        }

      else

         return;

      if(deal_symbol==Symbol() && deal_magic==m_magic)

         if(deal_entry==DEAL_ENTRY_OUT)

           {

            if(deal_profit>profit_level)

              {

               double lots=InpLot*1.6;

               ExtLot=LotCheck(lots);

              }

            else

              {

               ExtLot=InpLot;

              }

           }

     }

  }

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

//| Lot Check                                                        |

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

double LotCheck(double lots)

  {

//--- calculate maximum volume

   double volume=NormalizeDouble(lots,2);

   double stepvol=m_symbol.LotsStep();

   if(stepvol>0.0)

      volume=stepvol*MathFloor(volume/stepvol);

//---

   double minvol=m_symbol.LotsMin();

   if(volume<minvol)

      volume=0.0;

//---

   double maxvol=m_symbol.LotsMax();

   if(volume>maxvol)

      volume=maxvol;

   return(volume);

  }

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

//|                                                                  |

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

void SetMarginMode(void)

  {

   m_margin_mode=(ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE);

  }

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

//|                                                                  |

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

bool IsHedging(void)

  {

   return(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);

  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

      return(false);

//--- protection against the return value of "zero"

   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)

      return(false);

//---

   return(true);

  }

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

//|                                                                  |

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

int iLowest(string symbol,

            ENUM_TIMEFRAMES timeframe,

            int type,

            int count=WHOLE_ARRAY,

            int start=0)

  {

   if(start<0)

      return(-1);

   if(count<=0)

      count=Bars(symbol,timeframe);

   if(type==MODE_LOW)

     {

      double Low[];

      ArraySetAsSeries(Low,true);

      CopyLow(symbol,timeframe,start,count,Low);

      return(ArrayMinimum(Low,0,count)+start);

     }

//---

   return(0);

  }

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

//| Get Low for specified bar index                                  | 

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

double iLow(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)

  {

   if(symbol==NULL)

      symbol=Symbol();

   if(timeframe==0)

      timeframe=Period();

   double Low[1];

   double low=0;

   int copied=CopyLow(symbol,timeframe,index,1,Low);

   if(copied>0) low=Low[0];

   return(low);

  }

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

//|                                                                  |

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

int iHighest(string symbol,

             ENUM_TIMEFRAMES timeframe,

             int type,

             int count=WHOLE_ARRAY,

             int start=0)

  {

   if(start<0)

      return(-1);

   if(count<=0)

      count=Bars(symbol,timeframe);

   if(type==MODE_HIGH)

     {

      double High[];

      ArraySetAsSeries(High,true);

      CopyHigh(symbol,timeframe,start,count,High);

      return(ArrayMaximum(High,0,count)+start);

     }

//---

   return(0);

  }

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

//| Get the High for specified bar index                             | 

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

double iHigh(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)

  {

   if(symbol==NULL)

      symbol=Symbol();

   if(timeframe==0)

      timeframe=Period();

   double High[1];

   double high=0;

   int copied=CopyHigh(symbol,timeframe,index,1,High);

   if(copied>0) high=High[0];

   return(high);

  }

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

//| Get value of buffers for the iCCI                                |

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

double iCCIGet(const int index)

  {

   double CCI[1];

//--- reset error code 

   ResetLastError();

//--- fill a part of the iCCIBuffer array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iCCI,0,index,1,CCI)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iCCI indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(CCI[0]);

  }

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

//| Get value of buffers for the iMA                                 |

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

double iMAGet(int handle_iMA,const int index)

  {

   double MA[1];

//--- reset error code 

   ResetLastError();

//--- fill a part of the iMABuffer array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iMA,0,index,1,MA)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iMA indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(MA[0]);

  }

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

//| Get value of buffers for the iWPR                                |

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

double iWPRGet(const int index)

  {

   double WPR[];

   ArraySetAsSeries(WPR,true);

//--- reset error code 

   ResetLastError();

//--- fill a part of the iWPRBuffer array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iWPR,0,0,index+1,WPR)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iWPR indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(WPR[index]);

  }

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

//| Get Time for specified bar index                                 | 

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

datetime iTime(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)

  {

   if(symbol==NULL)

      symbol=Symbol();

   if(timeframe==0)

      timeframe=Period();

   datetime Time[1];

   datetime time=0;

   int copied=CopyTime(symbol,timeframe,index,1,Time);

   if(copied>0) time=Time[0];

   return(time);

  }

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

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---