Manual Three rectangles

Author: Copyright © 2020, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
0 Views
0 Downloads
0 Favorites
Manual Three rectangles
ÿþ//+------------------------------------------------------------------+

//|                                    Manual Three rectangles 2.mq5 |

//|                              Copyright © 2020, Vladimir Karputov |

//|                     https://www.mql5.com/ru/market/product/43516 |

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

#property copyright "Copyright © 2020, Vladimir Karputov"

#property link      "https://www.mql5.com/ru/market/product/43516"

#property version   "1.005"

/*

   barabashkakvn Trading engine 3.117

*/

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>

#include <Trade\AccountInfo.mqh>

//---

CPositionInfo  m_position;                   // object of CPositionInfo class

CTrade         m_trade;                      // object of CTrade class

CSymbolInfo    m_symbol;                     // object of CSymbolInfo class

CAccountInfo   m_account;                    // object of CAccountInfo class

//--- input parameters

input string   InpRectangleUpName      = "Rectangle Up";       // "Rectangle Up" Name

input string   InpRectangleMiddleName  = "Rectangle Middle";   // "Rectangle Middle" Name

input string   InpRectangleDownName    = "Rectangle Down";     // "Rectangle Down" Name

input ulong    InpDeviation            = 10;                   // Deviation, in points (1.00045-1.00055=10 points)

input bool     InpPrintLog             = false;                // Print log

//---

datetime m_last_signal                 = 0;                    // "0" -> D'1970.01.01 00:00';

string   m_prefix                      = "rpl_";

//---

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

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

     {

      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");

      return(INIT_FAILED);

     }

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(0);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(InpDeviation);

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

   for(int i=0; i<7; i++)

      ArrowRightPriceDelete(0,m_prefix+IntegerToString(i));

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//--- search for trading signals no more than once every 10 seconds

   datetime time_current=TimeCurrent();

   if(time_current-m_last_signal>10)

     {

      if(ObjectFind(0,InpRectangleUpName)<0 || ObjectFind(0,InpRectangleMiddleName)<0 || ObjectFind(0,InpRectangleDownName)<0)

         m_last_signal=time_current;



      double temp_price_up=0.0,temp_price_down=0.0;

      double rect_up_price_up=0.0,rect_up_price_down=0.0;

      double rect_middle_price_up=0.0,rect_middle_price_down=0.0;

      double rect_down_price_up=0.0,rect_down_price_down=0.0;



      temp_price_up=ObjectGetDouble(0,InpRectangleUpName,OBJPROP_PRICE,0);

      temp_price_down=ObjectGetDouble(0,InpRectangleUpName,OBJPROP_PRICE,1);

      if(temp_price_up==0.0 || temp_price_down==0.0)

        {

         m_last_signal=time_current;

         return;

        }

      if(temp_price_up<temp_price_down)

        {

         rect_up_price_up=temp_price_down;

         rect_up_price_down=temp_price_up;

        }

      else

        {

         rect_up_price_up=temp_price_up;

         rect_up_price_down=temp_price_down;

        }



      temp_price_up=ObjectGetDouble(0,InpRectangleMiddleName,OBJPROP_PRICE,0);

      temp_price_down=ObjectGetDouble(0,InpRectangleMiddleName,OBJPROP_PRICE,1);

      if(temp_price_up==0.0 || temp_price_down==0.0)

        {

         m_last_signal=time_current;

         return;

        }

      if(temp_price_up<temp_price_down)

        {

         rect_middle_price_up=temp_price_down;

         rect_middle_price_down=temp_price_up;

        }

      else

        {

         rect_middle_price_up=temp_price_up;

         rect_middle_price_down=temp_price_down;

        }



      temp_price_up=ObjectGetDouble(0,InpRectangleDownName,OBJPROP_PRICE,0);

      temp_price_down=ObjectGetDouble(0,InpRectangleDownName,OBJPROP_PRICE,1);

      if(temp_price_up==0.0 || temp_price_down==0.0)

        {

         m_last_signal=time_current;

         return;

        }

      if(temp_price_up<temp_price_down)

        {

         rect_down_price_up=temp_price_down;

         rect_down_price_down=temp_price_up;

        }

      else

        {

         rect_down_price_up=temp_price_up;

         rect_down_price_down=temp_price_down;

        }



      double temp_arr_prices[6],arr_prices[];

      temp_arr_prices[0]=rect_up_price_up;

      temp_arr_prices[1]=rect_up_price_down;

      temp_arr_prices[2]=rect_middle_price_up;

      temp_arr_prices[3]=rect_middle_price_down;

      temp_arr_prices[4]=rect_down_price_up;

      temp_arr_prices[5]=rect_down_price_down;



      ArraySort(temp_arr_prices); // [0] -> min price

      ArrayResize(arr_prices,4);

      arr_prices[0]=temp_arr_prices[0];

      arr_prices[1]=NormalizeDouble((temp_arr_prices[1]+temp_arr_prices[2])/2.0,Digits());

      arr_prices[2]=NormalizeDouble((temp_arr_prices[3]+temp_arr_prices[4])/2.0,Digits());

      arr_prices[3]=temp_arr_prices[5];



      double rlp_price[];

      ArrayResize(rlp_price,7);

      rlp_price[0]=arr_prices[0];

      rlp_price[1]=(arr_prices[0]+arr_prices[1])/2.0;

      rlp_price[2]=arr_prices[1];

      rlp_price[3]=(arr_prices[1]+arr_prices[2])/2.0;

      rlp_price[4]=arr_prices[2];

      rlp_price[5]=(arr_prices[2]+arr_prices[3])/2.0;

      rlp_price[6]=arr_prices[3];



      for(int i=0; i<7; i++)

        {

         string name=m_prefix+IntegerToString(i);

         if(ObjectFind(0,name)<0)

            ArrowRightPriceCreate(0,name,0,time_current,rlp_price[i]);

         else

            ArrowRightPriceMove(0,name,time_current,rlp_price[i]);

        }



      double level;

      if(FreezeStopsLevels(level))

         Trailing(level,arr_prices);

      else

         return;

      m_last_signal=time_current;

     }

//---

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//---



  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");

      return(false);

     }

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

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

     {

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");

      return(false);

     }

//---

   return(true);

  }

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

//| Check Freeze and Stops levels                                    |

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

bool FreezeStopsLevels(double &level)

  {

//--- check Freeze and Stops levels

   /*

      Type of order/position  |  Activation price  |  Check

      ------------------------|--------------------|--------------------------------------------

      Buy Limit order         |  Ask               |  Ask-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

      Buy Stop order          |  Ask               |  OpenPrice-Ask  >= SYMBOL_TRADE_FREEZE_LEVEL

      Sell Limit order        |  Bid               |  OpenPrice-Bid  >= SYMBOL_TRADE_FREEZE_LEVEL

      Sell Stop order         |  Bid               |  Bid-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

      Buy position            |  Bid               |  TakeProfit-Bid >= SYMBOL_TRADE_FREEZE_LEVEL

                              |                    |  Bid-StopLoss   >= SYMBOL_TRADE_FREEZE_LEVEL

      Sell position           |  Ask               |  Ask-TakeProfit >= SYMBOL_TRADE_FREEZE_LEVEL

                              |                    |  StopLoss-Ask   >= SYMBOL_TRADE_FREEZE_LEVEL



      Buying is done at the Ask price                 |  Selling is done at the Bid price

      ------------------------------------------------|----------------------------------

      TakeProfit        >= Bid                        |  TakeProfit        <= Ask

      StopLoss          <= Bid                        |  StopLoss          >= Ask

      TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL

      Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL

   */

   if(!RefreshRates() || !m_symbol.Refresh())

      return(false);

//--- FreezeLevel -> for pending order and modification

   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();

   if(freeze_level==0.0)

      freeze_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;

//--- StopsLevel -> for TakeProfit and StopLoss

   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();

   if(stop_level==0.0)

      stop_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;



   if(freeze_level<=0.0 || stop_level<=0.0)

      return(false);



   level=(freeze_level>stop_level)?freeze_level:stop_level;



   double spread=m_symbol.Spread()*m_symbol.Point()*3.0;

   level=(level>spread)?level:spread;

//---

   return(true);

  }

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

//| Trailing                                                         |

//|   InpTrailingStop: min distance from price to Stop Loss          |

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

void Trailing(const double stop_level,double &arr_prices[])

  {

   int d=0;

   /*

      Buying is done at the Ask price                 |  Selling is done at the Bid price

      ------------------------------------------------|----------------------------------

      TakeProfit        >= Bid                        |  TakeProfit        <= Ask

      StopLoss          <= Bid                        |  StopLoss          >= Ask

      TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL

      Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL

   */

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

      if(m_position.SelectByIndex(i))

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

           {

            double price_current = m_position.PriceCurrent();

            double price_open    = m_position.PriceOpen();

            double stop_loss     = m_position.StopLoss();

            double take_profit   = m_position.TakeProfit();

            double ask           = m_symbol.Ask();

            double bid           = m_symbol.Bid();

            //---

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(price_current>price_open)

                 {

                  double new_sl=0.0;

                  if(price_current>arr_prices[3])

                     continue;

                  else

                     if(price_current>(arr_prices[2]+arr_prices[3])/2.0)

                        new_sl=arr_prices[2];

                     else

                        if(price_current>arr_prices[2])

                           new_sl=(arr_prices[1]+arr_prices[2])/2.0;

                        else

                           if(price_current>(arr_prices[1]+arr_prices[2])/2.0)

                              new_sl=arr_prices[1];

                           else

                              if(price_current>arr_prices[1])

                                 new_sl=(arr_prices[0]+arr_prices[1])/2.0;

                              else

                                 if(price_current>(arr_prices[0]+arr_prices[1])/2.0)

                                    new_sl=arr_prices[0];

                                 else

                                    continue;

                  if(new_sl==0.0)

                     continue;

                  if(stop_loss<new_sl && !CompareDoubles(stop_loss,new_sl))

                     if(new_sl-stop_loss>=stop_level && (take_profit-bid>=stop_level || take_profit==0.0))

                       {

                        if(!m_trade.PositionModify(m_position.Ticket(),

                                                   m_symbol.NormalizePrice(new_sl),

                                                   take_profit))

                           if(InpPrintLog)

                              Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify BUY ",m_position.Ticket(),

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

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

                        if(InpPrintLog)

                          {

                           RefreshRates();

                           m_position.SelectByIndex(i);

                           PrintResultModify(m_trade,m_symbol,m_position);

                          }

                        continue;

                       }

                 }

              }

            else

              {

               if(price_current<price_open)

                 {

                  double new_sl=0.0;

                  if(price_current<arr_prices[0])

                     continue;

                  else

                     if(price_current<(arr_prices[0]+arr_prices[1])/2.0)

                        new_sl=arr_prices[1];

                     else

                        if(price_current<arr_prices[1])

                           new_sl=(arr_prices[1]+arr_prices[2])/2.0;

                        else

                           if(price_current<(arr_prices[1]+arr_prices[2])/2.0)

                              new_sl=arr_prices[2];

                           else

                              if(price_current<arr_prices[2])

                                 new_sl=(arr_prices[2]+arr_prices[3])/2.0;

                              else

                                 if(price_current<(arr_prices[2]+arr_prices[3])/2.0)

                                    new_sl=arr_prices[3];

                                 else

                                    continue;

                  if(new_sl==0.0)

                     continue;

                  if((stop_loss>new_sl && !CompareDoubles(stop_loss,new_sl)) || stop_loss==0.0)

                     if((stop_loss-new_sl>=stop_level || stop_loss==0) && ask-take_profit>=stop_level)

                       {

                        if(!m_trade.PositionModify(m_position.Ticket(),

                                                   m_symbol.NormalizePrice(new_sl),

                                                   take_profit))

                           if(InpPrintLog)

                              Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify SELL ",m_position.Ticket(),

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

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

                        if(InpPrintLog)

                          {

                           RefreshRates();

                           m_position.SelectByIndex(i);

                           PrintResultModify(m_trade,m_symbol,m_position);

                          }

                       }

                 }

              }

           }

  }

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

//| Print CTrade result                                              |

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

void PrintResultModify(CTrade &trade,CSymbolInfo &symbol,CPositionInfo &position)

  {

   Print("File: ",__FILE__,", symbol: ",symbol.Name());

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

   Print("code of request result as a string: "+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(symbol.Bid(),symbol.Digits())+" (the requote): "+DoubleToString(trade.ResultBid(),symbol.Digits()));

   Print("Current ask price: "+DoubleToString(symbol.Ask(),symbol.Digits())+" (the requote): "+DoubleToString(trade.ResultAsk(),symbol.Digits()));

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

   Print("Freeze Level: "+DoubleToString(symbol.FreezeLevel(),0),", Stops Level: "+DoubleToString(symbol.StopsLevel(),0));

   Print("Price of position opening: "+DoubleToString(position.PriceOpen(),symbol.Digits()));

   Print("Price of position's Stop Loss: "+DoubleToString(position.StopLoss(),symbol.Digits()));

   Print("Price of position's Take Profit: "+DoubleToString(position.TakeProfit(),symbol.Digits()));

   Print("Current price by position: "+DoubleToString(position.PriceCurrent(),symbol.Digits()));

  }

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

//| Compare doubles                                                  |

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

bool CompareDoubles(double number1,double number2)

  {

   if(NormalizeDouble(number1-number2,8)==0)

      return(true);

   else

      return(false);

  }

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

//| Create the right price label                                     |

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

bool ArrowRightPriceCreate(const long              chart_ID=0,          // chart's ID

                           const string            name="RightPrice",   // price label name

                           const int               sub_window=0,        // subwindow index

                           datetime                time=0,              // anchor point time

                           double                  price=0,             // anchor point price

                           const color             clr=DodgerBlue,      // price label color

                           const ENUM_LINE_STYLE   style=STYLE_SOLID,   // border line style

                           const int               width=1,             // price label size

                           const bool              back=false,          // in the background

                           const bool              selection=false,     // highlight to move

                           const bool              hidden=true,         // hidden in the object list

                           const long              z_order=0)           // priority for mouse click

  {

//--- set anchor point coordinates if they are not set

   ChangeArrowEmptyPoint(time,price);

//--- reset the error value

   ResetLastError();

//--- create a price label

   if(!ObjectCreate(chart_ID,name,OBJ_ARROW_RIGHT_PRICE,sub_window,time,price))

     {

      Print(__FUNCTION__,

            ": failed to create the right price label! Error code = ",GetLastError());

      return(false);

     }

//--- set the label color

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- set the border line style

   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);

//--- set the label size

   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);

//--- display in the foreground (false) or background (true)

   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);

//--- enable (true) or disable (false) the mode of moving the label by mouse

//--- when creating a graphical object using ObjectCreate function, the object cannot be

//--- highlighted and moved by default. Inside this method, selection parameter

//--- is true by default making it possible to highlight and move the object

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);

//--- hide (true) or display (false) graphical object name in the object list

   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

//--- set the priority for receiving the event of a mouse click in the chart

   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);

//--- successful execution

   return(true);

  }

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

//| Move the anchor point                                            |

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

bool ArrowRightPriceMove(const long   chart_ID=0,        // chart's ID

                         const string name="RightPrice", // label name

                         datetime     time=0,            // anchor point time coordinate

                         double       price=0)           // anchor point price coordinate

  {

//--- if point position is not set, move it to the current bar having Bid price

   if(!time)

      time=TimeCurrent();

   if(!price)

      price=SymbolInfoDouble(Symbol(),SYMBOL_BID);

//--- reset the error value

   ResetLastError();

//--- move the anchor point

   if(!ObjectMove(chart_ID,name,0,time,price))

     {

      Print(__FUNCTION__,

            ": failed to move the anchor point! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Delete the right price label from the chart                      |

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

bool ArrowRightPriceDelete(const long   chart_ID=0,        // chart's ID

                           const string name="RightPrice") // label name

  {

//--- reset the error value

   ResetLastError();

//--- delete the label

   if(!ObjectDelete(chart_ID,name))

     {

      Print(__FUNCTION__,

            ": failed to delete the right price label! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Check anchor point values and set default values                 |

//| for empty ones                                                   |

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

void ChangeArrowEmptyPoint(datetime &time,double &price)

  {

//--- if the point's time is not set, it will be on the current bar

   if(!time)

      time=TimeCurrent();

//--- if the point's price is not set, it will have Bid value

   if(!price)

      price=SymbolInfoDouble(Symbol(),SYMBOL_BID);

  }

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

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

Comments