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 bearishif((iOpen(m_symbol.Name(), PERIOD_M15, 2) - iClose(m_symbol.Name(), PERIOD_M15, 2)) < 0) //2nd candle must be bullish
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.
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, noOpenCL support, etc.
After returning this code, the agent no longer receives tasks until the very end ofthis optimization.
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 pricedouble Bid=NormalizeDouble(SymbolInfoDouble(Symbol(),SYMBOL_BID),Digits()); // calculate the Bid pricestring signal =""; // Create a string for the signalint digits =(int)SymbolInfoInteger(Symbol(),SYMBOL_DIGITS); // number of decimal places double point =SymbolInfoDouble(Symbol(),SYMBOL_POINT); // pointdouble 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
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.
//+------------------------------------------------------------------+//| 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 parametersinput group "Trading settings"inputuint InpStopLoss = 150; // Stop Lossinputuint InpTakeProfit = 460; // Take Profitinput group "Position size management (lot calculation)"inputdouble InpLots = 0.01; // Lots\input group "Additional features"inputbool InpPrintLog = true; // Print loginputulong InpDeviation = 10; // Deviation, in Points (1.00045-1.00055=10 points)inputulong InpMagic = 12345; // Magic number//---double m_stop_loss = 0.0; // Stop Loss -> doubledouble m_take_profit = 0.0; // Take Profit -> doubledatetime m_prev_bars = 0; // "0" -> D'1970.01.01 00:00';//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
//--- set the name for the appropriate symbolResetLastError();
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 displayPrint(m_symbol.Name()," (",m_symbol.Description(),")"," Bid=",m_symbol.Bid()," Ask=",m_symbol.Ask());
//--- receive minimum freeze levels for trade operationsPrint("StopsLevel=",m_symbol.StopsLevel()," points, FreezeLevel=",m_symbol.FreezeLevel()," points");
//--- receive the number of decimal places and point sizePrint("Digits=",m_symbol.Digits(),", Point=",DoubleToString(m_symbol.Point(),m_symbol.Digits()));
//--- spread infoPrint("SpreadFloat=",m_symbol.SpreadFloat(),", Spread(current)=",m_symbol.Spread()," points");
//--- request order execution type for limitationsPrint("Limitations for trade operations: ",EnumToString(m_symbol.TradeMode())," (",m_symbol.TradeModeDescription(),")");
//--- clarifying trades execution modePrint("Trades execution mode: ",EnumToString(m_symbol.TradeExecution())," (",m_symbol.TradeExecutionDescription(),")");
//--- clarifying contracts price calculation methodPrint("Contract price calculation: ",EnumToString(m_symbol.TradeCalcMode())," (",m_symbol.TradeCalcModeDescription(),")");
//--- sizes of contractsPrint("Standard contract size: ",m_symbol.ContractSize()," (",m_symbol.CurrencyBase(),")");
//--- minimum and maximum volumes in trade operationsPrint("Volume info: LotsMin=",m_symbol.LotsMin()," LotsMax=",m_symbol.LotsMax()," LotsStep=",m_symbol.LotsStep());
//---Print(__FUNCTION__," completed");
//---return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
//---
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+voidOnTick()
{
//--- work only at the time of the birth of new bardatetime 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 positionif(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 ratesif(!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);
}
//+------------------------------------------------------------------+
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.
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(constint index,double sl,double tp)
{
sl=m_symbol.NormalizePrice(sl);
tp=m_symbol.NormalizePrice(tp);
double long_lot=0.0;
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
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.
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?
OnInit must return a predefined variable:
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.
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 ???
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:
Result:
Corrected code:
Result:
Right on point. Ooooh now i get it
Corrected code:
Result:
I have noticed the EA is showing me invalid stops on other instruments when backtesting on the strategy tester.
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'
So do i have to create another void function with a new normalized lot, sl and tp like this one in the example?
Or i simply have to do it like this?
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?