Trend Line SL TP

Author: Copyright © 2019, Vladimir Karputov
Price Data Components
0 Views
0 Downloads
0 Favorites
Trend Line SL TP
ÿþ//+------------------------------------------------------------------+

//|                                             Trend Line SL TP.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.006

*/

#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 string   InpTrenLineSL     = "TrendLine SL"; // Trend Line SL name

input string   InpTrenLineTP     = "TrendLine TP"; // Trend Line TP name.

//---

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

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

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

      return(INIT_FAILED);

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(0);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(10);

//---

   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

   datetime time_0=iTime(m_symbol.Name(),Period(),0);

   if(time_0==ExtPrevBars)

      return;

   ExtPrevBars=time_0;

   if(!RefreshRates())

     {

      ExtPrevBars=0; return;

     }

   double level;

   if(FreezeStopsLevels(level))

      Trailing(level);

//---

  }

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

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

   freeze_level*=1.1;

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

   stop_level*=1.1;



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

      return(false);



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

//---

   return(true);

  }

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

//| Trailing                                                         |

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

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

void Trailing(const double stop_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

*/

   MqlRates rates[];

   ArraySetAsSeries(rates,true);

   int start_pos=0,count=3;

   if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

     {

      ExtPrevBars=0; return;

     }



   double price_trend_line_sl=ObjectGetValueByTime(0,InpTrenLineSL,rates[0].time);

   Print("price_trend_line_sl: ",DoubleToString(price_trend_line_sl,m_symbol.Digits()));

   double price_trend_line_tp=ObjectGetValueByTime(0,InpTrenLineTP,rates[0].time);

   Print("price_trend_line_tp: ",DoubleToString(price_trend_line_tp,m_symbol.Digits()));



   if(price_trend_line_sl==0.0 && price_trend_line_tp==0.0)

      return;



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

           {

            double new_sl=(price_trend_line_sl==0.0)?m_position.StopLoss():price_trend_line_sl;

            bool use_new_sl=(new_sl==0.0)?true:false;



            double new_tp=(price_trend_line_tp==0.0)?m_position.TakeProfit():price_trend_line_tp;

            bool use_new_tp=(new_tp==0.0)?true:false;

            //---

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(!use_new_sl)

                 {

                  if(!CompareDoubles(new_sl,m_position.StopLoss(),m_symbol.Digits()) && m_symbol.Bid()-new_sl>=stop_level)

                     use_new_sl=true;

                 }

               if(!use_new_tp)

                 {

                  if(!CompareDoubles(new_tp,m_position.TakeProfit(),m_symbol.Digits()) && new_tp-m_symbol.Bid()>=stop_level)

                     use_new_tp=true;

                 }

               if(!use_new_sl && !use_new_tp)

                 {

                  Print("New SL and New TP -> false");

                  continue;

                 }



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

                  m_symbol.NormalizePrice((use_new_sl)?new_sl:m_position.StopLoss()),

                  m_symbol.NormalizePrice((new_tp)?new_tp:m_position.TakeProfit())))

                  Print("Modify ",m_position.Ticket(),

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

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

              }

            else

              {

               if(!use_new_sl)

                 {

                  if(!CompareDoubles(new_sl,m_position.StopLoss(),m_symbol.Digits()) && new_sl-m_symbol.Ask()>=stop_level)

                     use_new_sl=true;

                 }

               if(!use_new_tp)

                 {

                  if(!CompareDoubles(new_tp,m_position.TakeProfit(),m_symbol.Digits()) && m_symbol.Ask()-new_tp>=stop_level)

                     use_new_tp=true;

                 }

               if(!use_new_sl && !use_new_tp)

                 {

                  Print("New SL and New TP -> false");

                  continue;

                 }



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

                  m_symbol.NormalizePrice((use_new_sl)?new_sl:m_position.StopLoss()),

                  m_symbol.NormalizePrice((new_tp)?new_tp:m_position.TakeProfit())))

                  Print("Modify ",m_position.Ticket(),

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

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

              }



           }

  }

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

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

  }

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

Comments