Can you assist how to use OHLC to create signals for Harami candlestick pattern - page 2

 
Vladimir Karputov #:

If you are looking for a condition only at the moment of the birth of a new bar, why are you doing this AT EVERY TICK?

i had removed  EVERY TICK on the current script before i sent the code. The EA is working properly Vladimir.

Thanks very mush to you i would not have done this alone. I am also grateful for your support. 

 

Hi Vladimir

I have been doing a number of tests on a number of instruments that i want it to trade.

I have created a separate script which the EA should open sell trades, changed Ask to Bid, changed/ reversed the condition signals, used InpOrderSize and SellTP/SellSL.

if((iOpen(m_symbol.Name(), PERIOD_M15, 1) - iClose(m_symbol.Name(), PERIOD_M15, 1)) > 0)     //1st candle must be bearish
 if((iOpen(m_symbol.Name(), PERIOD_M15, 2) - iClose(m_symbol.Name(), PERIOD_M15, 2)) < 0)    //2nd candle must be bullish        
      
m_trade.Sell(InpOrderSize,m_symbol.Name(),m_symbol.Bid(),SellSL,SellTP);

I do not understand why the EA keeps on executing Buy trades only with the same lot size, same TakeProfit and same StopLoss but on different instruments. 

Every parameter that i have changed to suit each instrument remains the same. 

What could be the problem on the script?

Files:
 

OnInit must return a predefined variable:

//---
   return(INIT_SUCCEEDED);
  }

ID

Description

INIT_SUCCEEDED

Initialization successful, EA test can be continued.

This code means the same as the zero value – the EA initialization in the tester is successful.

INIT_FAILED

Initialization failed. There is no point in continuing the test due to unavoidable errors. For example, it is impossible to create an indicator necessary for the EA operation.

The return of this value means the same as returning the value different from zero – EA initialization in the tester failed.

INIT_PARAMETERS_INCORRECT

Designed to denote an incorrect set of input parameters by a programmer. In the general optimization table, the result string with this return code is highlighted in red.

A test for such a set of EA inputs is not performed. The agent is ready to receive a new task.

When this value is received, the strategy tester does not pass this task to other agents for repeated execution.

INIT_AGENT_NOT_SUITABLE

No program execution errors during initialization. However, for some reasons, the agent is not suitable for conducting a test. For example, there is not enough RAM, no OpenCL support, etc.

After returning this code, the agent no longer receives tasks until the very end of this optimization.

Documentation on MQL5: Working with OpenCL
Documentation on MQL5: Working with OpenCL
  • www.mql5.com
Working with OpenCL - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

If you work only at the time of the birth of a new bar, WHY DO YOU NOT LISTEN AND ASK FOR INFORMATION

   double Ask=NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_ASK),Digits());  // calculate the Ask price
   double Bid=NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_BID),Digits());  // calculate the Bid price
   string signal  ="";                                                        // Create a string for the signal
   int    digits  =(int)SymbolInfoInteger(Symbol(),SYMBOL_DIGITS);             // number of decimal places  
   double point   =SymbolInfoDouble(Symbol(),SYMBOL_POINT);                    // point
   double SellSL  =Bid-InpStopLossPts*point;                                  // unnormalized SL value
          SellSL  =NormalizeDouble(SellSL,digits);                            // normalizing Stop Loss 
   double SellTP  =Bid+InpTakeProfitPts*point;                                // unnormalized TP value
          SellTP  =NormalizeDouble(SellTP,digits);                            // normalizing Take Profit 
   double BuySL   =Ask-InpStopLossPts*point;                                  // unnormalized SL value
          BuySL   =NormalizeDouble(BuySL,digits);                             // normalizing Stop Loss 
   double BuyTP   =Ask+InpTakeProfitPts*point;                                // unnormalized TP value
          BuyTP   =NormalizeDouble(BuyTP,digits);                              // normalizing Take Profit

on every tick ???

 
Vladimir Karputov #:

If you work only at the time of the birth of a new bar, WHY DO YOU NOT LISTEN AND ASK FOR INFORMATION

on every tick ???

I seem to get lost. By working only at the time of the birth of a new bar, i wanted the EA to open trade on open of BAR[0] as soon as the conditions are met. 

 

Corrected code:

//+------------------------------------------------------------------+
//|                                               Harami Boy 1  .mq5 |
//|                                       Copyright 2021, Brian Jaka |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, Brian Jaka"
#property link      "https://www.mql5.com"
#property version   "1.10"
/*
 This EA trades a Harami setup at open of Bar[0]
 BUY - One bearish and one bullish bar formation
 SELL- One bullish and one bearish bar formation
*/
#include<Trade\SymbolInfo.mqh>
#include<Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class for receiving symbol settings
CTrade         m_trade;                      // object of CTrade class for performing trade operations
CPositionInfo  m_position;                   // object of CPositionInfo class for receiving position settings
CAccountInfo   m_account;                    // object of CAccountInfo class for receiving account settings
//--- input parameters
input group             "Trading settings"
input uint                 InpStopLoss             = 150;            // Stop Loss
input uint                 InpTakeProfit           = 460;            // Take Profit
input group             "Position size management (lot calculation)"
input double               InpLots                 = 0.01;           // Lots\
input group             "Additional features"
input bool                 InpPrintLog             = true;           // Print log
input ulong                InpDeviation            = 10;             // Deviation, in Points (1.00045-1.00055=10 points)
input ulong                InpMagic                = 12345;          // Magic number
//---
double   m_stop_loss                = 0.0;      // Stop Loss                  -> double
double   m_take_profit              = 0.0;      // Take Profit                -> double
datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- set the name for the appropriate symbol
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);            //--- set magicNumber for your orders identification
   m_trade.SetMarginMode();                           //--- set margin mode for your orders
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());   //--- set order filling mode allowed by the server
   m_trade.SetDeviationInPoints(InpDeviation);        //--- set available slippage in points when buying/selling
//---
   m_stop_loss                = InpStopLoss                 * m_symbol.Point();
   m_take_profit              = InpTakeProfit               * m_symbol.Point();
//--- receive current rates and display
   Print(m_symbol.Name()," (",m_symbol.Description(),")","  Bid=",m_symbol.Bid(),"   Ask=",m_symbol.Ask());
//--- receive minimum freeze levels for trade operations
   Print("StopsLevel=",m_symbol.StopsLevel()," points, FreezeLevel=",m_symbol.FreezeLevel()," points");
//--- receive the number of decimal places and point size
   Print("Digits=",m_symbol.Digits(),", Point=",DoubleToString(m_symbol.Point(),m_symbol.Digits()));
//--- spread info
   Print("SpreadFloat=",m_symbol.SpreadFloat(),", Spread(current)=",m_symbol.Spread()," points");
//--- request order execution type for limitations
   Print("Limitations for trade operations: ",EnumToString(m_symbol.TradeMode())," (",m_symbol.TradeModeDescription(),")");
//--- clarifying trades execution mode
   Print("Trades execution mode: ",EnumToString(m_symbol.TradeExecution())," (",m_symbol.TradeExecutionDescription(),")");
//--- clarifying contracts price calculation method
   Print("Contract price calculation: ",EnumToString(m_symbol.TradeCalcMode())," (",m_symbol.TradeCalcModeDescription(),")");
//--- sizes of contracts
   Print("Standard contract size: ",m_symbol.ContractSize()," (",m_symbol.CurrencyBase(),")");
//--- minimum and maximum volumes in trade operations
   Print("Volume info: LotsMin=",m_symbol.LotsMin(),"  LotsMax=",m_symbol.LotsMax(),"  LotsStep=",m_symbol.LotsStep());
//---
   Print(__FUNCTION__,"  completed");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
   if(!RefreshRates())
     {
      m_prev_bars=0;
      return;
     }
//---
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=6;
   if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)
     {
      m_prev_bars=0;
      return;
     }
//--- Condition for opening BUY position
   if(rates[1].open-rates[1].close<0.0)
      if(rates[2].open-rates[2].close>0.0)
        {
         //--- check volume before OrderSend to avoid "not enough money" error (CTrade)
         double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),
                                  ORDER_TYPE_BUY,
                                  InpLots,
                                  m_symbol.Bid());
         double margin_check=m_account.MarginCheck(m_symbol.Name(),
                             ORDER_TYPE_BUY,
                             InpLots,
                             m_symbol.Bid());
         if(free_margin_check>margin_check)
           {
            double sl=(m_stop_loss==0.0)?0.0:m_symbol.Bid()+m_stop_loss;
            double tp=(m_take_profit==0.0)?0.0:m_symbol.Bid()-m_take_profit;
            //---
            if(InpPrintLog)
               Print(__FILE__," ",__FUNCTION__,", OK: ","Signal SELL");
            m_trade.Sell(InpLots,m_symbol.Name(),m_symbol.Bid(),sl,tp);
           }
        }
//---
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+

Result:

Files:
 
Vladimir Karputov #:

Corrected code:

Result:

Right on point. Ooooh now i get it

 
Vladimir Karputov #:

Corrected code:

Result:

I have noticed the EA is showing me invalid stops on other instruments when backtesting on the strategy tester. 
I had normalized the previous script according to my understanding but now that you have corrected, may you assist normalizing the values on this corrected script..
Some of the instruments use 3 digits and some 4 digits hence i think failure to adjust results in invalid stops.

May you assist on that one.
 
Brian Jaka # :
I have noticed the EA is showing me invalid stops on other instruments when backtesting on the strategy tester. 
I had normalized the previous script according to my understanding but now that you have corrected, may you assist normalizing the values on this corrected script..
Some of the instruments use 3 digits and some 4 digits hence i think failure to adjust results in invalid stops.

May you assist on that one.

You must use normalized prices for Stop Loss and Take Profit. Use CSymbolInfo :: NormalizePrice method

An example is in the code iMACD Two Open , in the function 'OpenBuy'

//+------------------------------------------------------------------+
//| Open Buy position                                                |
//+------------------------------------------------------------------+
void OpenBuy(const int index,double sl,double tp)
  {
   sl=m_symbol.NormalizePrice(sl);
   tp=m_symbol.NormalizePrice(tp);
   double long_lot=0.0;
Documentation on MQL5: Standard Library / Trade Classes / CSymbolInfo / NormalizePrice
Documentation on MQL5: Standard Library / Trade Classes / CSymbolInfo / NormalizePrice
  • www.mql5.com
NormalizePrice(double) - CSymbolInfo - Trade Classes - Standard Library - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

So do i have to create another void function with a new normalized lot, sl and tp like this one in the example?

void OpenBuy(const int index,double sl,double tp)

Or i simply have to do it like this?

//--- Condition for opening BUY position
   if(rates[1].open-rates[1].close>0.0)
      if(rates[2].open-rates[2].close<0.0)
        {
         //--- check volume before OrderSend to avoid "not enough money" error (CTrade)
         double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),
                                  ORDER_TYPE_BUY,
                                  InpLots,
                                  m_symbol.Ask());
         double margin_check=m_account.MarginCheck(m_symbol.Name(),
                             ORDER_TYPE_BUY,
                             InpLots,
                             m_symbol.Ask());
         if(free_margin_check>margin_check)
           {
            double sl=(m_stop_loss==0.0)?0.0:m_symbol.Ask()+m_stop_loss;
                   sl=m_symbol.NormalizePrice(sl);
            double tp=(m_take_profit==0.0)?0.0:m_symbol.Ask()-m_take_profit;
                   tp=m_symbol.NormalizePrice(tp);
            //---
            if(InpPrintLog)
               Print(__FILE__," ",__FUNCTION__,", OK: ","Signal BUY");
            m_trade.Buy(InpLots,m_symbol.Name(),m_symbol.Ask(),sl,tp);
           }
        }
//---

Its still giving me invalid stops. The last EA i tried to code this is where i got stuck.

I have gone through iMACD Two Open and i have used CSymbolInfo. 

Where exactly do i place the code to make this work.

Do we also not need to Normalize Bid and Ask?

Reason: