Manual SL TP Trend Lines Panel

Author: Copyright © 2019, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
0 Views
0 Downloads
0 Favorites
Manual SL TP Trend Lines Panel
ÿþ//+------------------------------------------------------------------+

//|                               Manual SL TP Trend Lines Panel.mq5 |

//|                              Copyright © 2019, Vladimir Karputov |

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

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

#property copyright "Copyright © 2019, Vladimir Karputov"

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

#property version   "1.000"

/*

   barabashkakvn Trading engine 3.101

*/

#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   InpSLLineName        = "SL Line";   // Stop Loss Line Name

input string   InpTPLineName        = "TP Line";   // Take Profit Line Name

input bool     InpPrintLog          = false;       // Print log

//---

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

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

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



string   m_prefix                = "Manual SL TP Trend Lines Panel ";

bool     m_sl                    = false;

bool     m_tp                    = false;

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

//| 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(10);

//--- create application dialog

   if(!ExtDialog.Create(0,"Manual SL TP Panel",0,40,90,209,160))

      return(INIT_FAILED);

//--- run application

   ExtDialog.Run();

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//--- destroy dialog

   ExtDialog.Destroy(reason);

//---

   ObjectsDeleteAll(0,m_prefix,0,-1);

  }

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

//| Expert chart event function                                      |

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

void OnChartEvent(const int id,         // event ID

                  const long& lparam,   // event parameter of the long type

                  const double& dparam, // event parameter of the double type

                  const string& sparam) // event parameter of the string type

  {

   ExtDialog.ChartEvent(id,lparam,dparam,sparam);

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//---



  }

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

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

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

//---

   return(true);

  }

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

//| Trailing                                                         |

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

void Trailing(const double stop_level, double sl=0.0, double tp=0.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_trade.SetExpertMagicNumber(m_position.Magic());

            //---

            double ask           = m_symbol.Ask();

            double bid           = m_symbol.Bid();

            double price_current = m_position.PriceCurrent();

            double price_open    = m_position.PriceOpen();

            double stop_loss     = m_position.StopLoss();

            bool new_sl          = false;

            if(sl!=0.0 && !CompareDoubles(sl,stop_loss,m_symbol.Digits()))

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                  if(bid-sl>=stop_level)

                    {

                     stop_loss=sl;

                     new_sl=true;

                    }

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                  if(sl-ask>=stop_level)

                    {

                     stop_loss=sl;

                     new_sl=true;

                    }

              }

            double take_profit   = m_position.TakeProfit();

            bool new_tp          = false;

            if(tp!=0.0 && !CompareDoubles(tp,take_profit,m_symbol.Digits()))

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                  if(tp-bid>=stop_level)

                    {

                     take_profit=tp;

                     new_tp=true;

                    }

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                  if(ask-tp>=stop_level)

                    {

                     take_profit=tp;

                     new_tp=true;

                    }

              }

            if(!new_sl && !new_tp)

               continue;

            //---

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

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

                                          m_symbol.NormalizePrice(stop_loss),

                                          m_symbol.NormalizePrice(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(!m_trade.PositionModify(m_position.Ticket(),

                                          m_symbol.NormalizePrice(stop_loss),

                                          m_symbol.NormalizePrice(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()));

  }

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

//| Search trading signals                                           |

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

bool SearchTradingSignals(void)

  {

//--- only OBJ_HLINE is allowed

   long object_sl=-1;

   long object_tp=-1;

   double price_sl=0.0;

   double price_tp=0.0;

   if(ObjectFind(0,InpSLLineName)==0)

     {

      object_sl=ObjectGetInteger(0,InpSLLineName,OBJPROP_TYPE,0);

      if(object_sl!=-1 && object_sl!=OBJ_HLINE)

         return(true);

      price_sl=ObjectGetDouble(0,InpSLLineName,OBJPROP_PRICE,0);

      if(price_sl==0.0)

         return(true);

     }

   if(ObjectFind(0,InpTPLineName)==0)

     {

      object_tp=ObjectGetInteger(0,InpTPLineName,OBJPROP_TYPE,0);

      if(object_tp!=-1 && object_tp!=OBJ_HLINE)

         return(true);

      price_tp=ObjectGetDouble(0,InpTPLineName,OBJPROP_PRICE,0);

      if(price_tp==0.0)

         return(true);

     }

//---

   if((object_sl!=-1 && object_sl!=OBJ_HLINE) || (object_tp!=-1 && object_tp!=OBJ_HLINE))

      return(true);

   if(object_sl!=-1 && object_tp==-1)

      return(true);

//---

   double level;

   if(FreezeStopsLevels(level))

      Trailing(level,price_sl,price_tp);

//---

   return(true);

  }

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

//| Compare doubles                                                  |

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

bool CompareDoubles(double number1,double number2,int digits)

  {

   digits--;

   if(digits<0)

      digits=0;

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

      return(true);

   else

      return(false);

  }

//---

#include <Controls\Dialog.mqh>

#include <Controls\Button.mqh>

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

//| defines                                                          |

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

//--- indents and gaps

#define INDENT_LEFT                         (11)      // indent from left (with allowance for border width)

#define INDENT_TOP                          (11)      // indent from top (with allowance for border width)

#define CONTROLS_GAP_X                      (5)       // gap by X coordinate

//--- for buttons

#define BUTTON_WIDTH                        (60)      // size by X coordinate

#define BUTTON_HEIGHT                       (20)      // size by Y coordinate

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

//| Class CControlsDialog                                            |

//| Usage: main dialog of the Controls application                   |

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

class CControlsDialog : public CAppDialog

  {

private:

   CButton           m_button_start;                  // the button object



public:

                     CControlsDialog(void);

                    ~CControlsDialog(void);

   //--- create

   virtual bool      Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);

   //--- chart event handler

   virtual bool      OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);



protected:

   //--- create dependent controls

   bool              CreateButtonStart(void);

   //--- handlers of the dependent controls events

   void              OnClickButtonStart(void);



  };

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

//| Event Handling                                                   |

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

EVENT_MAP_BEGIN(CControlsDialog)

ON_EVENT(ON_CLICK,m_button_start,OnClickButtonStart)

EVENT_MAP_END(CAppDialog)

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

//| Constructor                                                      |

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

CControlsDialog::CControlsDialog(void)

  {

  }

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

//| Destructor                                                       |

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

CControlsDialog::~CControlsDialog(void)

  {

  }

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

//| Create                                                           |

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

bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)

  {

   if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))

      return(false);

//--- create dependent controls

   if(!CreateButtonStart())

      return(false);

//--- succeed

   return(true);

  }

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

//| Create the "Pause" button                                         |

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

bool CControlsDialog::CreateButtonStart(void)

  {

//--- coordinates

   int x1=INDENT_LEFT;

   int y1=INDENT_TOP;

   int x2=x1+2*BUTTON_WIDTH;

   int y2=y1+BUTTON_HEIGHT;

//--- create

   if(!m_button_start.Create(m_chart_id,m_name+"Button Start",m_subwin,x1,y1,x2,y2))

      return(false);

   m_button_start.Pressed(true);

   if(!m_button_start.Text("Start"))

      return(false);

   if(!Add(m_button_start))

      return(false);

//--- succeed

   return(true);

  }

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

//| Event handler                                                    |

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

void CControlsDialog::OnClickButtonStart(void)

  {

   SearchTradingSignals();

//---

  }

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

//| Global Variables                                                 |

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

CControlsDialog ExtDialog;

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

Comments