Author: Copyright © 2018, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Bummer
ÿþ//+------------------------------------------------------------------+

//|                                                       Bummer.mq5 |

//|                              Copyright © 2018, Vladimir Karputov |

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

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

#property copyright "Copyright © 2018, Vladimir Karputov"

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

#property version   "1.000"

//---

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Trade\AccountInfo.mqh>

#include <Trade\DealInfo.mqh>

#include <Trade\OrderInfo.mqh>

#include <Expert\Money\MoneyFixedMargin.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

CAccountInfo   m_account;                    // account info wrapper

CDealInfo      m_deal;                       // deals object

COrderInfo     m_order;                      // pending orders object

CMoneyFixedMargin *m_money;

//--- input parameters

input ushort   InpStopLoss       = 50;       // Stop Loss, in pips (1.00045-1.00055=1 pips)

input ushort   InpTakeProfit     = 140;      // Take Profit, in pips (1.00045-1.00055=1 pips)

input ushort   InpTrailingStop   = 15;       // Trailing Stop (min distance from price to Stop Loss, in pips

input ushort   InpTrailingStep   = 5;        // Trailing Step, in pips (1.00045-1.00055=1 pips)

input bool     InpPrintLog       = true;     // Print log

//---

ulong  m_slippage=10;                        // slippage

double ExtStopLoss      = 0.0;               // Stop Loss      -> double

double ExtTakeProfit    = 0.0;               // Take Profit    -> double

double ExtTrailingStop  = 0.0;               // Trailing Stop  -> double

double ExtTrailingStep  = 0.0;               // Trailing Stop  -> double

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

   if(InpTrailingStop!=0 && InpTrailingStep==0)

     {

      string err_text=(TerminalInfoString(TERMINAL_LANGUAGE)=="Russian")?

                      ""@59;8=3 =52>7<>65=: ?0@0<5B@ \"Trailing Step\" @025= =C;N!":

                      "Trailing is not possible: parameter \"Trailing Step\" is zero!";

      //--- when testing, we will only output to the log about incorrect input parameters

      if(MQLInfoInteger(MQL_TESTER))

        {

         Print(__FUNCTION__,", ERROR: ",err_text);

         return(INIT_FAILED);

        }

      else // if the Expert Advisor is run on the chart, tell the user about the error

        {

         Alert(__FUNCTION__,", ERROR: ",err_text);

         return(INIT_PARAMETERS_INCORRECT);

        }

     }

//---

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

      return(INIT_FAILED);

   RefreshRates(m_symbol);

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

   if(m_money!=NULL)

      delete m_money;

  }

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

//| 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(m_symbol.Name(),Period(),0);

   if(time_0==PrevBars)

      return;

   PrevBars=time_0;



   Trailing();

//--- 

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//--- 



  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates(CSymbolInfo &symbol)

  {

//--- refresh rates

   if(!symbol.RefreshRates())

     {

      Print("RefreshRates error");

      return(false);

     }

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

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

      return(false);

//---

   return(true);

  }

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

//| Check Freeze and Stops levels                                    |

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

bool FreezeStopsLevels(CSymbolInfo &symbol,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(symbol) || !symbol.Refresh())

      return(false);

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

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

   if(freeze_level==0.0)

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

   freeze_level*=1.1;

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

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

   if(stop_level==0.0)

      stop_level=(symbol.Ask()-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(void)

  {

/*

     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(InpTrailingStop==0)

      return;

   if(InpStopLoss==0 && InpTakeProfit==0)

      return;

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

      if(m_position.SelectByIndex(i))

        {

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

            continue;



         double level;

         if(!FreezeStopsLevels(m_symbol,level))

            continue;

         //--- tuning for 3 or 5 digits

         int digits_adjust=1;

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

            digits_adjust=10;

         double m_adjusted_point=m_symbol.Point()*digits_adjust;



         ExtStopLoss       = InpStopLoss        * m_adjusted_point;

         ExtTakeProfit     = InpTakeProfit      * m_adjusted_point;

         ExtTrailingStop   = InpTrailingStop    * m_adjusted_point;

         ExtTrailingStep   = InpTrailingStep    * m_adjusted_point;



         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            double price=m_symbol.Ask();



            double sl=(InpStopLoss==0)?0.0:price-ExtStopLoss;

            if(sl!=0.0 && ExtStopLoss<level) // check sl

               sl=price-level;



            double tp=(InpTakeProfit==0)?0.0:price+ExtTakeProfit;

            if(tp!=0.0 && ExtTakeProfit<level) // check price

               tp=price+level;



            if((sl!=0.0 && m_position.StopLoss()==0.0) || (tp!=0.0 && m_position.TakeProfit()==0.0))

              {

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

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



               PositionModify(new_sl,new_tp);



               continue;

              }



            if(m_position.PriceCurrent()-m_position.PriceOpen()>ExtTrailingStop+ExtTrailingStep)

               if(m_position.StopLoss()<m_position.PriceCurrent()-(ExtTrailingStop+ExtTrailingStep))

                  if(ExtTrailingStop>=level)

                    {

                     PositionModify(m_position.PriceCurrent()-ExtTrailingStop,m_position.TakeProfit());

                     continue;

                    }

           }

         else

           {

            double price=m_symbol.Bid();



            double sl=(InpStopLoss==0)?0.0:price+ExtStopLoss;

            if(sl!=0.0 && ExtStopLoss<level) // check sl

               sl=price+level;



            double tp=(InpTakeProfit==0)?0.0:price-ExtTakeProfit;

            if(tp!=0.0 && ExtTakeProfit<level) // check tp

               tp=price-level;



            if((sl!=0.0 && m_position.StopLoss()==0.0) || (tp!=0.0 && m_position.TakeProfit()==0.0))

              {

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

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



               PositionModify(new_sl,new_tp);



               continue;

              }



            if(m_position.PriceOpen()-m_position.PriceCurrent()>ExtTrailingStop+ExtTrailingStep)

               if((m_position.StopLoss()>(m_position.PriceCurrent()+(ExtTrailingStop+ExtTrailingStep))) || 

                  (m_position.StopLoss()==0))

                  if(ExtTrailingStop>=level)

                    {

                     PositionModify(m_position.PriceCurrent()-ExtTrailingStop,m_position.TakeProfit());

                     continue;

                    }

           }



        }

  }

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

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

   int d=0;

  }

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

//|                                                                  |

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

void PositionModify(const double sl,const double tp)

  {

   m_trade.SetExpertMagicNumber(m_position.Magic());

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(m_slippage);



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

      m_symbol.NormalizePrice(sl),

      m_symbol.NormalizePrice(tp)))

      if(InpPrintLog)

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

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

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

//---

  }

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

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