Stop loss Take profit

Author: Copyright © 2019, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
0 Views
0 Downloads
0 Favorites
Stop loss Take profit
ÿþ//+------------------------------------------------------------------+

//|                                        Stop loss Take profit.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"

#property description "barabashkakvn Trading engine 3.001"

/*

   barabashkakvn Trading engine 3.001

*/

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Trade\AccountInfo.mqh>

#include <Trade\DealInfo.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

//--- input parameters

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

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

input ushort   InpSignalsFrequency  = 10;          // Search signals, in seconds (< "10" -> only on a new bar)

//---

ulong  ExtSlippage=100;               // Slippage



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

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



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



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

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

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

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

      digits_adjust=10;

   ExtAdjustedPoint=m_symbol.Point()*digits_adjust;



   ExtStopLoss       = InpStopLoss        * ExtAdjustedPoint;

   ExtTakeProfit     = InpTakeProfit      * ExtAdjustedPoint;

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//---

   if(InpSignalsFrequency>=10) // search for trading signals no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastSignals>10)

        {

         //--- search for trading signals

         if(!RefreshRates())

           {

            ExtPrevBars=0;

            return;

           }

         if(!SearchTradingSignals())

           {

            ExtPrevBars=0;

            return;

           }

         ExtLastSignals=time_current;

        }

     }

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

     }

   if(InpSignalsFrequency<10) // search for trading signals only at the time of the birth of new bar

     {

      //--- search for trading signals

      if(!SearchTradingSignals())

        {

         ExtPrevBars=0;

         return;

        }

     }

//---

  }

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

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

  }

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

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

  }

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

//| Search trading signals                                           |

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

bool SearchTradingSignals(void)

  {

   double level;

   if(!FreezeStopsLevels(level))

      return(false);



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

           {

            if(m_position.StopLoss()!=0.0 && m_position.TakeProfit()!=0.0)

               continue;

/*

   Option 1:   (input)     Stop Loss 0

               (position)  Stop Loss 0

               (new)       Stop Loss 0

   Option 2:   (input)     Stop Loss 50

               (position)  Stop Loss 0

               (new)       Stop Loss =    (input)     Stop Loss 50

   Option 3:   (input)     Stop Loss 50

               (position)  Stop Loss 30

               (new)       Stop Loss =    (position)  Stop Loss 30

   Option 4:   (input)     Stop Loss 0

               (position)  Stop Loss 30

               (new)       Stop Loss =    (position)  Stop Loss 30

*/

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               double price=m_symbol.Ask();

               double sl_new=0.0,sl_old=m_position.StopLoss();

               if(sl_old!=0.0)

                 {

                  sl_new=sl_old;

                 }

               else

                 {

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

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

                     sl_new=price-level;

                 }

               double tp_new=0.0,tp_old=m_position.TakeProfit();

               if(tp_old!=0.0)

                 {

                  tp_new=tp_old;

                 }

               else

                 {

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

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

                     tp_new=price+level;

                 }

               if(CompareDoubles(sl_new,sl_old,m_symbol.Digits()) && CompareDoubles(tp_new,tp_old,m_symbol.Digits()))

                  continue;

               m_trade.SetExpertMagicNumber((ulong)m_position.Magic());

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

                  m_symbol.NormalizePrice(sl_new),

                  m_symbol.NormalizePrice(tp_new)))

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

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

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

               RefreshRates();

               m_position.SelectByIndex(i);

               PrintResultModify(m_trade,m_symbol,m_position);

               continue;

              }

            else

              {

               double price=m_symbol.Bid();

               double sl_new=0.0,sl_old=m_position.StopLoss();

               if(sl_old!=0.0)

                 {

                  sl_new=sl_old;

                 }

               else

                 {

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

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

                     sl_new=price+level;

                 }

               double tp_new=0.0,tp_old=m_position.TakeProfit();

               if(tp_old!=0.0)

                 {

                  tp_new=tp_old;

                 }

               else

                 {

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

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

                     tp_new=price-level;

                 }

               if(CompareDoubles(sl_new,sl_old,m_symbol.Digits()) && CompareDoubles(tp_new,tp_old,m_symbol.Digits()))

                  continue;

               m_trade.SetExpertMagicNumber((ulong)m_position.Magic());

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

                  m_symbol.NormalizePrice(sl_new),

                  m_symbol.NormalizePrice(tp_new)))

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

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

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

               RefreshRates();

               m_position.SelectByIndex(i);

               PrintResultModify(m_trade,m_symbol,m_position);

               continue;

              }

           }

//---

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

  }

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

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