Author: Copyright © 2017, Vladimir Karputov
Price Data Components
0 Views
0 Downloads
0 Favorites
DojiTrader
ÿþ//+------------------------------------------------------------------+

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

//|                              Copyright © 2017, Vladimir Karputov |

//|                                           http://wmua.ru/slesar/ |

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

#property copyright "Copyright © 2017, Vladimir Karputov"

#property link      "http://wmua.ru/slesar/"

#property version   "1.002"

//---

#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

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

//| Enum hours                                                       |

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

enum ENUM_HOURS

  {

   hour_00  =0,   // 00

   hour_01  =1,   // 01

   hour_02  =2,   // 02

   hour_03  =3,   // 03

   hour_04  =4,   // 04

   hour_05  =5,   // 05

   hour_06  =6,   // 06

   hour_07  =7,   // 07

   hour_08  =8,   // 08

   hour_09  =9,   // 09

   hour_10  =10,  // 10

   hour_11  =11,  // 11

   hour_12  =12,  // 12

   hour_13  =13,  // 13

   hour_14  =14,  // 14

   hour_15  =15,  // 15

   hour_16  =16,  // 16

   hour_17  =17,  // 17

   hour_18  =18,  // 18

   hour_19  =19,  // 19

   hour_20  =20,  // 20

   hour_21  =21,  // 21

   hour_22  =22,  // 22

   hour_23  =23,  // 23

  };

//--- input parameters

input double      InpLots              = 0.1;      // Lots

input ushort      InpStopLoss          = 50;       // Stop Loss (in pips)

input ushort      InpTakeProfit        = 50;       // Take Profit (in pips)

input ENUM_HOURS  InpStartHour         = hour_08;  // Start hour

input ENUM_HOURS  InpEndHour           = hour_17;  // End hour

input int         InpMaximumDojiHeight = 1;        // Maximum Doji height

input ulong       m_magic              = 107802402;// magic number

//---

ulong             m_slippage=30;                   // slippage



double            ExtStopLoss=0.0;

double            ExtTakeProfit=0.0;

double            ExtMaximumDojiHeight=0.0;



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

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

   if(!m_symbol.Name(Symbol())) // sets symbol name

      return(INIT_FAILED);

   RefreshRates();



   string err_text="";

   if(!CheckVolumeValue(InpLots,err_text))

     {

      Print(err_text);

      return(INIT_PARAMETERS_INCORRECT);

     }

//---

   m_trade.SetExpertMagicNumber(m_magic);

//---

   if(IsFillingTypeAllowed(SYMBOL_FILLING_FOK))

      m_trade.SetTypeFilling(ORDER_FILLING_FOK);

   else if(IsFillingTypeAllowed(SYMBOL_FILLING_IOC))

      m_trade.SetTypeFilling(ORDER_FILLING_IOC);

   else

      m_trade.SetTypeFilling(ORDER_FILLING_RETURN);

//---

   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;



   ExtStopLoss=InpStopLoss*m_adjusted_point;

   ExtTakeProfit=InpTakeProfit*m_adjusted_point;

   ExtMaximumDojiHeight=InpMaximumDojiHeight*m_adjusted_point;

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//--- we work only at the time of the birth of new bar

   static datetime PrevBars=0;

   datetime time_0=iTime(0);

   if(time_0==PrevBars)

      return;

   PrevBars=time_0;

//--- trade EU and US sessions only

   MqlDateTime str1;

   TimeToStruct(PrevBars,str1);

   if(str1.hour<InpStartHour || str1.hour>=InpEndHour)

      return;

//---

   if(!RefreshRates())

     {

      PrevBars=iTime(1);

      return;

     }

//---

   double dOpen=0.0;

   double dHigh      = 0.0;

   double dLow       = 0.0;

   double dClose     = 0.0;

   int    eDirection = 0;

   int    dBar       = 0;

   double ePrice     = 0.0;

   MqlRates          rates_array[];                   // target array to copy 

   ArraySetAsSeries(rates_array,true);                // -> the rates_array[0] is on the chart to the right

   string            symbol_name = m_symbol.Name();   // symbol name 

   ENUM_TIMEFRAMES   timeframe   = Period();          // period 

   int               start_pos   = 0;                 // start position 

   int               count       = 4;                 // data count to copy 

   int copied=CopyRates(symbol_name,timeframe,start_pos,count,rates_array);

   if(copied!=count)

      return;

   for(int i=1; i<count; i++)

     {

      //--- if we got a dodji then save the high and low

      if(MathAbs(rates_array[i].open-rates_array[i].close)<=ExtMaximumDojiHeight)

        {

         dHigh=rates_array[i].high;

         dLow=rates_array[i].low;

         dBar=i;

         break;

        }

     }

//--- if we had a doji within the last 3 Bars

   if(dBar<count && dBar>1)

     {

      //--- if last candle closed higher than the doji high, long is our direction

      if(rates_array[1].close>dHigh)

        {

         eDirection=1;

         ePrice=rates_array[1].close;

        }

      else if(rates_array[1].close<dLow)

        {

         eDirection=-1;

         ePrice=rates_array[1].close;

        }

     }

   else

      eDirection=0;

//---

   for(int i=PositionsTotal()-1;i>=0;i--)

      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)

           {

            if(eDirection==1) // open buy

              {

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                 {

                  m_trade.PositionClose(m_position.Ticket());

                  double sl=(InpStopLoss==0.0)?0.0:m_symbol.Ask()-ExtStopLoss;

                  double tp=(InpTakeProfit==0.0)?0.0:m_symbol.Ask()+ExtTakeProfit;

                  OpenBuy(sl,tp);

                 }

              }

            else if(eDirection==1) // open sell

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                 {

                  m_trade.PositionClose(m_position.Ticket());

                  double sl=(InpStopLoss==0.0)?0.0:m_symbol.Bid()+ExtStopLoss;

                  double tp=(InpTakeProfit==0.0)?0.0:m_symbol.Bid()-ExtTakeProfit;

                  OpenSell(sl,tp);

                 }

              }

           }

//---

   int positions_total=0;



   for(int i=PositionsTotal()-1;i>=0;i--)

      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)

            positions_total++;



   if(positions_total>1) // in work there can always be only one position

     {

      CloseAllPositions();

      PrevBars=iTime(1);

      return;

     }

//--- check that we don't already have an position going

   if(positions_total==0)

     {

      if(eDirection==1) // open buy

        {

         double sl=(InpStopLoss==0.0)?0.0:m_symbol.Ask()-ExtStopLoss;

         double tp=(InpTakeProfit==0.0)?0.0:m_symbol.Ask()+ExtTakeProfit;

         OpenBuy(sl,tp);

        }

      else if(eDirection==-1) // open sell

        {

         double sl=(InpStopLoss==0.0)?0.0:m_symbol.Bid()+ExtStopLoss;

         double tp=(InpTakeProfit==0.0)?0.0:m_symbol.Bid()-ExtTakeProfit;

         OpenSell(sl,tp);

        }

     }

//---

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//---



  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates(void)

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      Print("RefreshRates error");

      return(false);

     }

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

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

      return(false);

//---

   return(true);

  }

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

//| Check the correctness of the order volume                        |

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

bool CheckVolumeValue(double volume,string &error_description)

  {

//--- minimal allowed volume for trade operations

// double min_volume=m_symbol.LotsMin();

   double min_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);

   if(volume<min_volume)

     {

      error_description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume);

      return(false);

     }



//--- maximal allowed volume of trade operations

// double max_volume=m_symbol.LotsMax();

   double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);

   if(volume>max_volume)

     {

      error_description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume);

      return(false);

     }



//--- get minimal step of volume changing

// double volume_step=m_symbol.LotsStep();

   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);



   int ratio=(int)MathRound(volume/volume_step);

   if(MathAbs(ratio*volume_step-volume)>0.0000001)

     {

      error_description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f",

                                     volume_step,ratio*volume_step);

      return(false);

     }

   error_description="Correct volume value";

   return(true);

  }

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

//| Checks if the specified filling mode is allowed                  | 

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

bool IsFillingTypeAllowed(int fill_type)

  {

//--- Obtain the value of the property that describes allowed filling modes 

   int filling=m_symbol.TradeFillFlags();

//--- Return true, if mode fill_type is allowed 

   return((filling & fill_type)==fill_type);

  }

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

//| Get Time for specified bar index                                 | 

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

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

  {

   if(symbol==NULL)

      symbol=m_symbol.Name();

   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);

  }

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

//| Open Buy position                                                |

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

void OpenBuy(double sl,double tp)

  {

   sl=m_symbol.NormalizePrice(sl);

   tp=m_symbol.NormalizePrice(tp);

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

   double check_volume_lot=m_trade.CheckVolume(m_symbol.Name(),InpLots,m_symbol.Ask(),ORDER_TYPE_BUY);



   if(check_volume_lot!=0.0)

      if(check_volume_lot>=InpLots)

        {

         if(m_trade.Buy(InpLots,NULL,m_symbol.Ask(),sl,tp))

           {

            if(m_trade.ResultDeal()==0)

              {

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

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

               PrintResult(m_trade,m_symbol);

              }

            else

              {

               Print("#2 Buy -> true. Result Retcode: ",m_trade.ResultRetcode(),

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

               PrintResult(m_trade,m_symbol);

              }

           }

         else

           {

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

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

            PrintResult(m_trade,m_symbol);

           }

        }

//---

  }

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

//| Open Sell position                                               |

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

void OpenSell(double sl,double tp)

  {

   sl=m_symbol.NormalizePrice(sl);

   tp=m_symbol.NormalizePrice(tp);

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

   double check_volume_lot=m_trade.CheckVolume(m_symbol.Name(),InpLots,m_symbol.Bid(),ORDER_TYPE_SELL);



   if(check_volume_lot!=0.0)

      if(check_volume_lot>=InpLots)

        {

         if(m_trade.Sell(InpLots,NULL,m_symbol.Bid(),sl,tp))

           {

            if(m_trade.ResultDeal()==0)

              {

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

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

               PrintResult(m_trade,m_symbol);

              }

            else

              {

               Print("#2 Sell -> true. Result Retcode: ",m_trade.ResultRetcode(),

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

               PrintResult(m_trade,m_symbol);

              }

           }

         else

           {

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

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

            PrintResult(m_trade,m_symbol);

           }

        }

//---

  }

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

//| Print CTrade result                                              |

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

void PrintResult(CTrade &trade,CSymbolInfo &symbol)

  {

   Print("Code of request result: "+IntegerToString(trade.ResultRetcode()));

   Print("code of request result: "+trade.ResultRetcodeDescription());

   Print("deal ticket: "+IntegerToString(trade.ResultDeal()));

   Print("order ticket: "+IntegerToString(trade.ResultOrder()));

   Print("volume of deal or order: "+DoubleToString(trade.ResultVolume(),2));

   Print("price, confirmed by broker: "+DoubleToString(trade.ResultPrice(),symbol.Digits()));

   Print("current bid price: "+DoubleToString(trade.ResultBid(),symbol.Digits()));

   Print("current ask price: "+DoubleToString(trade.ResultAsk(),symbol.Digits()));

   Print("broker comment: "+trade.ResultComment());

   DebugBreak();

  }

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

//| Close all positions                                              |

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

void CloseAllPositions()

  {

   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current 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)

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

  }

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

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 ---