Student Question: How to add StopLoss and TakeProfit? - page 2

 

we have notices that when you remove StopLossLevel and TakeProfitLevel the error will go back to 

10021

TRADE_RETCODE_PRICE_OFF

There are no quotes to process the request


int HeraBuy(){
   Alert("Hera is Buying");
   
   
   //StopLoss & TakeProfit Setup
   double Bid;
   double Ask;

   double TakeProfit;
   double StopLoss;

   double TakeProfitLevel;
   double StopLossLevel;

   Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   
   TakeProfit = 60;
   StopLoss = 60;
   
   TakeProfitLevel = Ask + TakeProfit*Point();   //0.0001 // Take Profit value defined
   StopLossLevel = Ask - StopLoss*Point(); // Stop loss value defined
   
   /*
   //Code For 5-Digit Brokers
   //Here we are assuming that the TakeProfit and StopLoss are entered in Pips
   
   TakeProfitLevel = Bid + TakeProfit*Point*10;   //0.00001 * 10 = 0.0001
   StopLossLevel = Bid - StopLoss*Point*10;
   */
   
   
   
   if(!trade.Buy(0.1,"GBPUSD", Bid))
     {
      //--- failure message
      Print("Buy() method failed. Return code=",trade.ResultRetcode(),
            ". Code description: ",trade.ResultRetcodeDescription());
     }
   else
     {
      Print("Buy() method executed successfully. Return code=",trade.ResultRetcode(),
            " (",trade.ResultRetcodeDescription(),")");
     }
     
   return(0);
}


then when you finally remove "Bid" from the parameters the code will work and execute a buy order


int HeraBuy(){
   Alert("Hera is Buying");
   
   
   //StopLoss & TakeProfit Setup
   double Bid;
   double Ask;

   double TakeProfit;
   double StopLoss;

   double TakeProfitLevel;
   double StopLossLevel;

   Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   
   TakeProfit = 60;
   StopLoss = 60;
   
   TakeProfitLevel = Ask + TakeProfit*Point();   //0.0001 // Take Profit value defined
   StopLossLevel = Ask - StopLoss*Point(); // Stop loss value defined
   
   /*
   //Code For 5-Digit Brokers
   //Here we are assuming that the TakeProfit and StopLoss are entered in Pips
   
   TakeProfitLevel = Bid + TakeProfit*Point*10;   //0.00001 * 10 = 0.0001
   StopLossLevel = Bid - StopLoss*Point*10;
   */
   
   
   
   if(!trade.Buy(0.1,"GBPUSD"))
     {
      //--- failure message
      Print("Buy() method failed. Return code=",trade.ResultRetcode(),
            ". Code description: ",trade.ResultRetcodeDescription());
     }
   else
     {
      Print("Buy() method executed successfully. Return code=",trade.ResultRetcode(),
            " (",trade.ResultRetcodeDescription(),")");
     }
     
   return(0);
}


the only thing wrong with this is that there is obviously no stop loss, take profit or execution price where: 


bool Buy( double volume,  // position volume

       const string symbol=NULL,   // symbol double

               price=0.0,   // execution price

               double sl=0.0,  // stop loss price

       double tp=0.0,   // take profit price

const string comment=" " // comment ) 


my guess is that it does not like the variable bid, even though it works for other purposes and this is causing it to effect

the stop loss and take profit variable values which there causing the error 10016


10016

TRADE_RETCODE_INVALID_STOPS

Invalid stops in the request

 

WORKING NOW!

dont know how but its working now ?!!!


//+------------------------------------------------------------------+
//| Global Variables                                                 |
//+------------------------------------------------------------------+

#include <Trade\Trade.mqh>
CTrade trade;



//+------------------------------------------------------------------+
//| Execute Once                                                     |
//+------------------------------------------------------------------+


void OnInit()
  {
   
   //Test
   
   Alert("Expert Advisor has been launched");
   
   
   
 
   //Order Setup
   
   int MagicNumber=123456; //--- set MagicNumber for your orders identification
   trade.SetExpertMagicNumber(MagicNumber);

   int deviation=10; //--- set available slippage in points when buying/selling
   trade.SetDeviationInPoints(deviation);
 
   trade.SetTypeFilling(ORDER_FILLING_RETURN); //--- order filling mode, the mode allowed by the server should be used
 
   trade.LogLevel(1); //--- logging mode: it would be better not to declare this method at all, the class will set the best mode on its own
   
   trade.SetAsyncMode(true); //--- what function is to be used for trading: true - OrderSendAsync(), false - OrderSend()
   
   
   
   
   //Trading Critera 
 
   int x = 0;
   
   if (x == 1){
      HeraBuy();
   }
   
   else{
      HeraSell();
   }   
   
   
  }




//+------------------------------------------------------------------+
//| End                                                             |
//+------------------------------------------------------------------+


void OnDeinit(const int reason)
  {
      
      Alert("Expert Advisor terminated");
      
  }
  
  
  
 
//+------------------------------------------------------------------+
//| Main Loop                                                        |
//+------------------------------------------------------------------+  



void OnTick()
  {
      
      /*
      double Bid;
      Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
      Alert("Your new Bid price is: " + string(Bid)); //Display the bid price continuously
      */
   
  }
  
  
  
  
  
  
 
  
//+------------------------------------------------------------------+
//| External Functions                                               |
//+------------------------------------------------------------------+


int HeraSell(){
   Alert("Hera is Selling");
   
   
   //StopLoss & TakeProfit Setup
   double Bid;
   double Ask;

   double TakeProfit;
   double StopLoss;

   double TakeProfitLevel;
   double StopLossLevel;

   Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   
   TakeProfit = 60;
   StopLoss = 60;
   
   TakeProfitLevel = Bid - TakeProfit*Point();   //0.0001 // Take Profit value defined
   StopLossLevel = Bid + StopLoss*Point(); // Stop loss value defined
   
   /*
   //Code For 5-Digit Brokers
   //Here we are assuming that the TakeProfit and StopLoss are entered in Pips
   
   TakeProfitLevel = Bid + TakeProfit*Point*10;   //0.00001 * 10 = 0.0001
   StopLossLevel = Bid - StopLoss*Point*10;
   */
   
   
   
   if(!trade.Sell(0.1,_Symbol, Bid, StopLossLevel, TakeProfitLevel))
     {
      //--- failure message
      Print("Sell() method failed. Return code=",trade.ResultRetcode(),
            ". Code description: ",trade.ResultRetcodeDescription());
     }
   else
     {
      Print("Sell() method executed successfully. Return code=",trade.ResultRetcode(),
            " (",trade.ResultRetcodeDescription(),")");
     }

   return(0);
}



int HeraBuy(){
   Alert("Hera is Buying");
   
   
   //StopLoss & TakeProfit Setup
   double Bid;
   double Ask;

   double TakeProfit;
   double StopLoss;

   double TakeProfitLevel;
   double StopLossLevel;

   Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
   Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   
   TakeProfit = 60;
   StopLoss = 60;
   
   TakeProfitLevel = Ask + TakeProfit*Point();   //0.0001 // Take Profit value defined
   StopLossLevel = Ask - StopLoss*Point(); // Stop loss value defined
   
   /*
   //Code For 5-Digit Brokers
   //Here we are assuming that the TakeProfit and StopLoss are entered in Pips
   
   TakeProfitLevel = Bid + TakeProfit*Point*10;   //0.00001 * 10 = 0.0001
   StopLossLevel = Bid - StopLoss*Point*10;
   */
   
   
   
   if(!trade.Buy(0.1,_Symbol, Ask, StopLossLevel, TakeProfitLevel))
     {
      //--- failure message
      Print("Buy() method failed. Return code=",trade.ResultRetcode(),
            ". Code description: ",trade.ResultRetcodeDescription());
     }
   else
     {
      Print("Buy() method executed successfully. Return code=",trade.ResultRetcode(),
            " (",trade.ResultRetcodeDescription(),")");
     }
     
   return(0);
}
 

Corrected version:

//+------------------------------------------------------------------+
//|                                                         Test.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"
//---
#include <Trade\Trade.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input int   InpOpenPositions  = 0;           // Open position ("0" -> BUY, "1" -> SELL)
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- set MagicNumber for your POSITIONS identification
   m_trade.SetExpertMagicNumber(123456);
//--- margin mode
   m_trade.SetMarginMode();
//--- filling mode, the mode allowed by the server should be used
   m_trade.SetTypeFillingBySymbol(Symbol());
//--- set available slippage in points when buying/selling
   m_trade.SetDeviationInPoints(30);
//--- logging mode: it would be better not to declare this method at all, the class will set the best mode on its own
   m_trade.LogLevel(LOG_LEVEL_ALL);
//--- SetAsyncMode(true) can only be used by professionals
//trade.SetAsyncMode(true); //--- what function is to be used for trading: true - OrderSendAsync(), false - OrderSend()
//---
   if(InpOpenPositions==0)
     {
      HeraBuy();
     }
   if(InpOpenPositions==1)
     {
      HeraSell();
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {

//---
  }
//+------------------------------------------------------------------+
//| Open Buy                                                         |
//+------------------------------------------------------------------+
bool HeraBuy()
  {
   Alert("Hera is Buying");
   /*
   It is recommended to use SymbolInfoTick() if the function is used for getting information about the last tick.
   It may well be that not a single quote has appeared yet since the terminal is connected to a trading account.
   In such a case, the requested value will be indefinite.

   In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive
   the values of Ask, Bid, Last, Volume and the time of the last tick's arrival during a single call.
   */
   MqlTick tick;
   if(!SymbolInfoTick(Symbol(),tick))
     {
      Alert(__FUNCTION__,", ERROR SymbolInfoTick");
      return(false);
     }

   ushort TakeProfit=60;
   ushort StopLoss=60;

   double TakeProfitLevel=NormalizePrice(tick.ask+TakeProfit*Point());   // Take Profit value defined
   double StopLossLevel=NormalizePrice(tick.ask-StopLoss*Point()); // Stop loss value defined
   if(TakeProfitLevel==0.0 || StopLossLevel==0.0)
      return(false);

   if(!m_trade.Buy(0.1,Symbol(),tick.ask,StopLossLevel,TakeProfitLevel))
     {
      //--- failure message
      Print("Buy() method failed. Return code=",m_trade.ResultRetcode(),
            ". Code description: ",m_trade.ResultRetcodeDescription());
      return(false);
     }
   else
     {
      Print("Buy() method executed successfully. Return code=",m_trade.ResultRetcode(),
            " (",m_trade.ResultRetcodeDescription(),")");
      return(true);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Open Sell                                                        |
//+------------------------------------------------------------------+
bool HeraSell()
  {
   Alert("Hera is Selling");
   /*
   It is recommended to use SymbolInfoTick() if the function is used for getting information about the last tick.
   It may well be that not a single quote has appeared yet since the terminal is connected to a trading account.
   In such a case, the requested value will be indefinite.

   In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive
   the values of Ask, Bid, Last, Volume and the time of the last tick's arrival during a single call.
   */
   MqlTick tick;
   if(!SymbolInfoTick(Symbol(),tick))
     {
      Alert(__FUNCTION__,", ERROR SymbolInfoTick");
      return(false);
     }

   ushort TakeProfit=60;
   ushort StopLoss=60;

   double TakeProfitLevel=NormalizePrice(tick.bid-TakeProfit*Point());   // Take Profit value defined
   double StopLossLevel=NormalizePrice(tick.bid+StopLoss*Point()); // Stop loss value defined
   if(TakeProfitLevel==0.0 || StopLossLevel==0.0)
      return(false);

   if(!m_trade.Sell(0.1,Symbol(),tick.bid,StopLossLevel,TakeProfitLevel))
     {
      //--- failure message
      Print("Sell() method failed. Return code=",m_trade.ResultRetcode(),
            ". Code description: ",m_trade.ResultRetcodeDescription());
      return(false);
     }
   else
     {
      Print("Sell() method executed successfully. Return code=",m_trade.ResultRetcode(),
            " (",m_trade.ResultRetcodeDescription(),")");
      return(true);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Normalize price                                                  |
//+------------------------------------------------------------------+
double NormalizePrice(const double price)
  {
   double   m_tick_size=0.0;     // symbol tick size
   int      m_digits;            // symbol digits
//--- preparation
   long tmp=0;
//---
   if(!SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE,m_tick_size))
      return(0.0);
   if(!SymbolInfoInteger(Symbol(),SYMBOL_DIGITS,tmp))
      return(0.0);
   m_digits=(int)tmp;
//---
   if(m_tick_size!=0)
      return(NormalizeDouble(MathRound(price/m_tick_size)*m_tick_size,m_digits));
//---
   return(NormalizeDouble(price,m_digits));
  }
//+------------------------------------------------------------------+
Files:
Test.mq5  14 kb
Reason: