wrong buffer value retrieved from mql5 indicator using iCustom - mql4

I just moved from mql4 to mql5 and now i am trying to read buffers values from an indicator , but it only shows me 0 instead of the actual buffer values
Here is my code :
#property version "1.00"
int handle1 = 0;
double valu1,valu2,valu3,valu4;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create timer
EventSetTimer(60);
handle1 = iCustom(NULL, NULL, "LTD by KDMfx");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
IndicatorRelease(handle1);
}
//+------------------------------------------------------------------+
//| Get indicator value |
//+------------------------------------------------------------------+
double GetIndicator(int handle, int buffer_num, int index)
{
double arr[];
if(CopyBuffer(handle, buffer_num, 0, index+1, arr) <= 0)
{
Sleep(200);
for(int i=0; i<100; i++)
{
if(BarsCalculated(handle) > 0)
break;
Sleep(50);
}
int copied = CopyBuffer(handle, buffer_num, 0, index+1, arr);
if(copied <= 0)
{
Print("CopyBuffer failed. Maybe history has not download yet? Error = ", GetLastError());
return -1;
}
else
return (arr[index]);
}
return 0;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTick()
{
//---
valu1 = GetIndicator(handle1,0,4);
valu2 = GetIndicator(handle1,1,4);
valu3 = GetIndicator(handle1,2,4);
valu4 = GetIndicator(handle1,3,4);
Comment("b1: ", valu1,
"\nb2: ", valu2,
"\nb3: ", valu3,
"\nb4: ", valu4
);
}
what am i doing wrong here ?
the indicator does not appear on the current or the last closed candle , it appears on the current+4 candle , meaning on the 5th candle in past . so i am using "4" as the candle id but still no use , no matter what i try i can get it to work

Try simplifying things a bit. I don't have a copy of the indicator you are trying to read, but the following code should work
#property version "1.10"
#property strict
int handle;
//+------------------------------------------------------------------+
//| Initialization function of the expert |
//+------------------------------------------------------------------+
int OnInit()
{
handle=iCustom(_Symbol, 0, "LTD by KDMfx");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialization function of the expert |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
IndicatorRelease(handle);
}
//+------------------------------------------------------------------+
//| "Tick" event handler function |
//+------------------------------------------------------------------+
void OnTick()
{
double LTDindicator[];
ArraySetAsSeries(LTDindicator, true);
CopyBuffer(handle, 0, 0, 25, LTDindicator);
Comment(LTDindicator[0]);
return;
}

Related

problem With repeating Orders and let the Limited order move with the price in MQL5

am Trying To Code an EA has This Jobs dealing with Boom 1000 index
Set Limited Order (Buy \ Sell)
and The Orders moving with the price in that way:
if the price goes down the buy stop will follow each candle for waiting for the bullish candle, and the same thing for the sell order
I have this problem:
the orders repeating if I close the EA or I changed the frame
"I have a problem with deinitialization"
I have no idea how can I let the order move with each candle
"adjust the order
the code I have used:
//+------------------------------------------------------------------+
//| EABoom1000Scalper.mq5 |
//| Copyright 2022, OshGroup ltd. |
//| https://oshgrp.com/ar |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, OshGroup ltd."
#property link "https://oshgrp.com/ar"
#property version "1.01"
#property description "Note:The EA Work with Buy and Sell\n"
#property description "If You Dont Need TP Or SL just let it 0 "
#property description "Try Version N10 Will destroy after 7 days"
//+-----------------Include--------------------------------+
#include <Trade/Trade.mqh>
#include <Expert\Expert.mqh>
#include <Expert\Signal\SignalMA.mqh>
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
#include <Expert\Money\MoneySizeOptimized.mqh>
//+-----------------------Enumoration------------------------------+
enum TradeAutoOption{
Yes=0,
No=1
};
enum Trade_Type{
BUY=0, SELL=1
}
;
enum SYMBOL_ASK_O{
Boom_Index_1000=0, Crash_Index_1000=1, Boom_Index_500=2, Crash_Index_500=3
};
//+--------------------input parameters-----------------------+
input group "Setting"
input string Inp_Expert_Title ="ScalperExpert";
input group "Trade Type"
input Trade_Type Ordder_Type =BUY;
input group "Order_Details"
input double LOT_SIZE =1.00;
input double Buy_AT =00000.0000;
input double Sell_AT =00000.0000;
input double Tralling_InPoint =2000;
input double Take_Profit_At =0.0;
input double Stop_LOSE =0.0;
input group "Auto Trading"
input TradeAutoOption Trade_Auto =No;
input SYMBOL_ASK_O SYMBOL =Boom_Index_1000;
//--- input parameters
//+------------------------------------------------------------------+
//| Global expert object |
//+------------------------------------------------------------------+
CExpert ExtExpert;
CTrade Trade;
//+------------------------------------------------------------------+
//| Global expert object |
//+------------------------------------------------------------------+
//+-----------------------Function-----------------------------------+
void Start_Buy(double LOT_SIZE1 ,double Buy_From1 ,double Stop_LOSE1, double Take_Profit_At2){
double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK),_Digits);
if(Ask < Buy_From1){
Trade.BuyStop(LOT_SIZE1 ,Buy_From1,_Symbol,Stop_LOSE1,Take_Profit_At,ORDER_TIME_GTC, NULL , "Buying Started...\n ");
}
else if (Ask > Buy_From1)
{
Trade.BuyLimit(LOT_SIZE1 ,Buy_From1,_Symbol,Stop_LOSE1,Take_Profit_At,ORDER_TIME_GTC, NULL , "Buying Started...\n ");
}
else
{
string comment=StringFormat("\n\nError %d Is the Current Price" , Buy_From1 );
ChartSetString(0,CHART_COMMENT,comment);
}
};//function
void Start_Sell(double LOT_SIZE2 , double Sell_From2 , double Stop_LOSE2 , double Take_Profit_At2)
{
double Bid= NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
if(Bid > Sell_From2 )
{
Trade.SellStop(LOT_SIZE2 , Sell_From2 ,_Symbol,Stop_LOSE2 , Take_Profit_At2 , ORDER_TIME_GTC , "SEll Started...\n");
}
else if (Bid < Sell_From2)
{
Trade.SellLimit(LOT_SIZE2 , Sell_From2 ,_Symbol,Stop_LOSE2 , Take_Profit_At2 , ORDER_TIME_GTC , "SEll Started...\n");
}
else
{
string comment=StringFormat("\n\nError %d Is the Current Price" , Sell_From2 );
ChartSetString(0,CHART_COMMENT,comment);
}
};
void Chek_Typ(int Ordder_Type){
if(Ordder_Type == BUY)
{
Start_Buy(LOT_SIZE ,Buy_AT , Stop_LOSE , Take_Profit_At);
}
else
{
Start_Sell(LOT_SIZE , Sell_AT , Stop_LOSE , Take_Profit_At);
}
};
void SetVAlueOneTheChart(){
double ID = 1;
string comment=StringFormat("The Expert Working... %d" , ID );
ChartSetString(0,CHART_COMMENT,comment);
};
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
//-----------------------Initializing expert--------------------------------
//SetVAlueOneTheChart();
Comment("The Expert Working....");
Chek_Typ(Ordder_Type);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Function-event handler "tick" |
//+------------------------------------------------------------------+
void OnTick(void)
{
}
//+------------------------------------------------------------------+
//| Function-event handler "trade" |
//+------------------------------------------------------------------+
void OnTrade(void)
{
}
//+------------------------------------------------------------------+
//| Deinitialization function of the expert |
//+------------------------------------------------------------------+
void OnDeinit(const int reason )
{
if()
Trade_Type Ordder_Type =BUY;
double LOT_SIZE =1.00;
double Buy_AT =00000.0000;
double Sell_AT =00000.0000;
double Tralling_InPoint =2000;
double Take_Profit_At =0.0;
double Stop_LOSE =0.0;
ExtExpert.Deinit();
Print("The deinitialization occured_Error Number Is" , reason);
}

Excel mql4 mismatch

This is an indicator I am working on. The problem I am having is it doesn't match the same output as my excel file, and I am pretty sure my excel file is correct. If you would like to help me solve this issue just email me at thetfordjw#gmail.com Subject: Excel mql4 please and I will send you the excel file. Otherwise if you have something to add on this web page as to something I am doing wrong would be happy to hear from you. Thanks !
//+------------------------------------------------------------------+
//| JT-Statistics Close GT LT Terminated.mq4 |
//| Copyright 2021,Jon W. Thetford |
//| Email: thetfordjw#gmail.com |
//+------------------------------------------------------------------+
#property version "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int i;
float a,b,c,d,e,f,g,h,j,k;
float aa,bb,cc,dd,ee,ff,gg,hh,jj,kk,ll,mm,nn,oo;
//input float BarsBack = "1000";
input bool FrequencyNumber = True;
input bool FrequencyPercentage = False;
input bool CumulativePercentageOfAllBars = False;
//input bool PercentageOfCustomBarsBack = False;
int OnInit()
{
//--- indicator buffers mapping
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
for(i=0;i<Bars; i++)
{
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]<Close[i+4])
{
a=a+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]<Close[i+5])
{
b=b+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]<Close[i+6])
{
c=c+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]<Close[i+7])
{
d=d+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]<Close[i+8])
{
e=e+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]<Close[i+9])
{
f=f+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]<Close[i+10])
{
g=g+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]<Close[i+11])
{
h=h+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]>Close[i+11]&&Close[i+11]<Close[i+12])
{
j=j+1;
}
if(Close[i+1]<Close[i+2]&&Close[i+2]>Close[i+3]&&Close[i+3]>Close[i+4]&&Close[i+4]>Close[i+5]&&Close[i+5]>Close[i+6]&&Close[i+6]>Close[i+7]&&Close[i+7]>Close[i+8]&&Close[i+8]>Close[i+9]&&Close[i+9]>Close[i+10]&&Close[i+10]>Close[i+11]&&Close[i+11]>Close[i+12]&&Close[i+12]<Close[i+13])
{
k=k+1;
}
//LESS THAN Close[1]<Close[2]
//1
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]>Close[i+4])
{
aa=aa+1;
}
//2
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]>Close[i+5])
{
bb=bb+1;
}
//3
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]>Close[i+6])
{
cc=cc+1;
}
//4
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]>Close[i+7])
{
dd=dd+1;
}
//5
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]>Close[i+8])
{
ee=ee+1;
}
//6
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]>Close[i+9])
{
ff=ff+1;
}
//7
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]>Close[i+10])
{
gg=gg+1;
}
//8
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]>Close[i+11])
{
hh=hh+1;
}
//9
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]>Close[i+12])
{
jj=jj+1;
}
//10
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]>Close[i+13])
{
kk=kk+1;
}
//11
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]>Close[i+14])
{
ll=ll+1;
}
//12
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]<Close[i+14]&&Close[i+14]>Close[i+15])
{
mm=mm+1;
}
//13
if(Close[i+1]>Close[i+2]&&Close[i+2]<Close[i+3]&&Close[i+3]<Close[i+4]&&Close[i+4]<Close[i+5]&&Close[i+5]<Close[i+6]&&Close[i+6]<Close[i+7]&&Close[i+7]<Close[i+8]&&Close[i+8]<Close[i+9]&&Close[i+9]<Close[i+10]&&Close[i+10]<Close[i+11]&&Close[i+11]<Close[i+12]&&Close[i+12]<Close[i+13]&&Close[i+13]<Close[i+14]&&Close[i+14]<Close[i+15]&&Close[i+15]>Close[i+16])
{
nn=nn+1;
}
//=
if(Close[i+1]==Close[i+2])
{
oo=oo+1;
}
//OUTPUT > <
//Frequency NUMBER of consecutive closes greater than and less than the previous.
if(FrequencyNumber) Comment("FrequencyNumber\n# Close[1]>Close[2]\n\n1: "+a+"\n2: "+b+"\n3: "+c+"\n4: "+d+"\n5: "+e+"\n6: "+f+"\n7: "+g+"\n8: "+h+"\n9: "+j+"\n10: "+k
+"\n\n# Close[1]<Close[2]\n\n1: "+aa+"\n2: "+bb+"\n3: "+cc+"\n4: "+dd+"\n5: "+ee+"\n6: "+ff+"\n7: "+gg+"\n8: "+hh+"\n9: "+jj+"\n10: "+kk+"\n11: "+ll+"\n12: "+mm+"\n13: "+nn+"\n==: "+oo+"\n\n Total bars: "+Bars);
}

Messagebox is closing trades regardless of "Yes" or "No" button clicked

This has genuinely got to be one of the must ludicrous, most ridiculous situation I have even been in with this coding language.
Is there any reason as to why my trades are closing, regardless as to the button pressed on the prompted Messagebox- despite the fact my EA is only supposed to close trade when the IDYES button is selected?
I click the IDYES button, my trade liquidates, I click the IDNO button, my trade liquidates.
Why is me EA doing things I have not told it to do? The word "fuming" cannot express enough how I'm feeling.
Here is the snippet below:
//+------------------------------------------------------------------+
//| initialization_test.mq4 |
//| Copyright 2020, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
datetime LastActiontime;
bool totalOrders = OrdersTotal();
double currencyConversion;
double tradeSpread;
int ordersTotal;
int OnInit()
{
//---
LastActiontime=Time[0];
if (totalOrders == 0){
totalOrders = true;
}
//---
return(INIT_SUCCEEDED);
}
void OnTick()
{
//---
int LotSize = 1;
int RewardFactor = 3;
int stopLossPoints = 200;
double entryPriceBid = MarketInfo(Symbol(),MODE_BID);
double spread = MarketInfo(Symbol(), MODE_SPREAD);
double tickvalue = MarketInfo(Symbol(), MODE_TICKVALUE);
color sellcolor = clrGreen;
bool Newbar = true;
currencyConversion = 100000/(tickvalue * 100000);
tradeSpread = (spread * tickvalue)*LotSize;
if(LastActiontime!=Time[0])
if(OrdersTotal() == 0)
if(totalOrders == true){
bool OpenShort = OrderSend(Symbol(),OP_BUY,LotSize,MarketInfo(Symbol(),MODE_BID),100,((entryPriceBid/Point)-(stopLossPoints))*Point,((entryPriceBid/Point)+(stopLossPoints*RewardFactor))*Point,"Spread Charge £"+DoubleToStr((spread * tickvalue)*LotSize,2),Period(),0,sellcolor);
LastActiontime=Time[0];
if (OpenShort == true){
bool msgBox = MessageBox("Please confirm the risk on this trade with the margin at the bottom of the terminal. Would you liketo close this trade?"+
"\n"+
"\n£"+DoubleToStr(((tickvalue * LotSize)*stopLossPoints)+ tradeSpread,2),"Information", MB_YESNO|MB_ICONQUESTION|MB_TOPMOST);
if (msgBox = IDYES){
ordersTotal = OrdersTotal();
for(int b=ordersTotal-1;b>=0;b--){
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES)==true){
bool closeOrder = OrderClose(OrderTicket(),LotSize,MarketInfo(Symbol(),MODE_BID),300,clrAqua);
}
}
}
if (msgBox = IDNO){
return;
}
Print("The tick value used for this EA is £ "+DoubleToStr(tickvalue , 5)+" and the conversion is "+DoubleToStr(currencyConversion,5));
SendMail("You have opened a position","You have opened a position");
}
}
}
//+------------------------------------------------------------------+
You have defined the return value from your MessageBox as Boolean, however it should be of type int.
int MessageBox(string text, string caption=NULL, int flags=0);
Change your code to
int msgBox = MessageBox("Please confirm the risk on this trade with the margin at the bottom of the terminal. Would you liketo close this trade?"+
"\n"+
"\n£"+DoubleToStr(((tickvalue * LotSize)*stopLossPoints)+ tradeSpread,2),"Information", MB_YESNO|MB_ICONQUESTION|MB_TOPMOST);

Mql4 How to set toggle button ON OFF state?

I'm making a line of on-chart buttons that will launch specific functions and indicators. So far so good the buttons load an indicator when pressed and delete it when the button is unpressed.
But I would like to add two more functions to the button but I'm doing something wrong and it doesn't work properly and I need some help.
1st - I would like the button do be able to detect indicator on chart an automatically set the button to "ON" state in case I will drag and drop the indicator from indicator list.
2nd - when I press the button it will launch an indicator popup window and we have 2 options;
1 - "OK" which will launch the indicator on the chart and the button will stay in "ON" state.
2 - "CANCEL" which will abort lunching the indicator but it will leave the button in "ON" state. I would like the button to go back to the "OFF" state just after I press "CANCEL".
Here is a peace of the code for testing.
#property indicator_chart_window
string sButtonName1 ="B1";
string sButtonName2 ="B2";
const string IndiName1 ="X";
const string IndiName2 ="Y";
//--------------------------------------------------------------
color UnloadedColor=clrGray;
color LoadedColor=clrBlue;
color currentColor;
//--------------------------------------------------------------
#import "user32.dll"
void keybd_event(int bVk,int bScan,int dwFlags,int dwExtraInfo);
#define VK_L 0x4C
#define VK_M 0x4D
#define VK_MENU 0x12
#define KEYEVENTF_KEYUP 0x0002
#import
//+------------------------------------------------------------------+
int OnInit()
{
int buttonwindow=ObjectFind(sButtonName1);
int buttonwindow1=ObjectFind(sButtonName2);
{
if(buttonwindow<0)
CreateButton1(sButtonName1,UnloadedColor,"Arial",0);
if(buttonwindow1<0)
CreateButton2(sButtonName2,UnloadedColor,"Arial",0);
}
return(INIT_SUCCEEDED);
}
//+----------------------------------------------------------------------------------+
//|------------------------CreateButton 1--------------------------------------------|
//+----------------------------------------------------------------------------------+
void CreateButton1(string sName1,color sColor,string sFont="Arial",string sText="")
{
ObjectCreate(0,sName1,OBJ_BUTTON,0,0,0);
ObjectSetInteger(0,sName1,OBJPROP_XDISTANCE,725);
ObjectSetInteger(0,sName1,OBJPROP_YDISTANCE,0);
ObjectSetInteger(0,sName1,OBJPROP_XSIZE,50);
ObjectSetInteger(0,sName1,OBJPROP_YSIZE,50);
ObjectSetInteger(0,sName1,OBJPROP_CORNER,4);
ObjectSetString(0,sName1,OBJPROP_TEXT,"X");
ObjectSetInteger(0,sName1,OBJPROP_COLOR,sColor);
ObjectSetString(0,sName1,OBJPROP_FONT,sFont);
ObjectSetInteger(0,sName1,OBJPROP_FONTSIZE,26);
ObjectSetInteger(0,sName1,OBJPROP_STATE,false);
}
//+----------------------------------------------------------------------------------+
//|------------------------CreateButton 2--------------------------------------------|
//+----------------------------------------------------------------------------------+
void CreateButton2(string sName2,color sColor,string sFont="Arial",string sText="")
{
ObjectCreate(0,sName2,OBJ_BUTTON,0,0,0);
ObjectSetInteger(0,sName2,OBJPROP_XDISTANCE,775);
ObjectSetInteger(0,sName2,OBJPROP_YDISTANCE,0);
ObjectSetInteger(0,sName2,OBJPROP_XSIZE,50);
ObjectSetInteger(0,sName2,OBJPROP_YSIZE,50);
ObjectSetInteger(0,sName2,OBJPROP_CORNER,4);
ObjectSetString(0,sName2,OBJPROP_TEXT,"Y");
ObjectSetInteger(0,sName2,OBJPROP_COLOR,sColor);
ObjectSetString(0,sName2,OBJPROP_FONT,sFont);
ObjectSetInteger(0,sName2,OBJPROP_FONTSIZE,26);
ObjectSetInteger(0,sName2,OBJPROP_STATE,false);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//+----------------------------------------------------------------------------------+
//+--------------------------------------- BUTTON 1 ---------------------------------+
//+----------------------------------------------------------------------------------+
{
{
if(id==CHARTEVENT_OBJECT_CLICK && sparam==sButtonName1)
{
currentColor=ObjectGetInteger(0,sButtonName1,OBJPROP_COLOR);
if(currentColor==UnloadedColor)
{
keybd_event(VK_MENU,0,0,0);
keybd_event(VK_L,0,0,0);
keybd_event(VK_L,0,KEYEVENTF_KEYUP,0);
keybd_event(VK_MENU,0,KEYEVENTF_KEYUP,0);
ObjectSetInteger(0,sButtonName1,OBJPROP_COLOR,LoadedColor);
return;
}
else
if(currentColor==LoadedColor)
{
ChartIndicatorDelete(0,0,IndiName1);
ObjectSetInteger(0,sButtonName1,OBJPROP_COLOR,UnloadedColor);
}
}
}
//+----------------------------------------------------------------------------------+
//+---------------------------------------BUTTON 2-----------------------------------+
//+----------------------------------------------------------------------------------+
{
if(id==CHARTEVENT_OBJECT_CLICK && sparam==sButtonName2)
{
currentColor=ObjectGetInteger(0,sButtonName2,OBJPROP_COLOR);
if(currentColor==UnloadedColor)
{
keybd_event(VK_MENU,0,0,0);
keybd_event(VK_M,0,0,0);
keybd_event(VK_M,0,KEYEVENTF_KEYUP,0);
keybd_event(VK_MENU,0,KEYEVENTF_KEYUP,0);
ObjectSetInteger(0,sButtonName2,OBJPROP_COLOR,LoadedColor);
return;
}
else
if(currentColor==LoadedColor)
{
ChartIndicatorDelete(0,0,IndiName2);
ObjectSetInteger(0,sButtonName2,OBJPROP_COLOR,UnloadedColor);
}
}
}
}
/*
//+-------------------------------------NOT WORKING-----------------------------------+
//------------------------------ DETECT INDICATOR ON THE CHART-------------------------------
{
int indicators_total = ChartIndicatorsTotal(0,0);
for(int i = 0; indicators_total > i; i++)
//+------------------------- INDICATOR 1 DETECTED -----------------------------------
{
if(ChartIndicatorName(0,0,i)==IndiName1)
{
currentColor=ObjectGetInteger(0,sButtonName1,OBJPROP_COLOR);
if(currentColor==UnloadedColor)
{
ObjectSetInteger(0,sButtonName1,OBJPROP_STATE,true);
ObjectSetInteger(0,sButtonName1,OBJPROP_COLOR,LoadedColor);
}
}
//+------------------------- INDICATOR 1 NOT DETECTED -----------------------------------
if(!(ChartIndicatorName(0,0,i)==IndiName1))
{
currentColor=ObjectGetInteger(0,sButtonName1,OBJPROP_COLOR);
if(currentColor==LoadedColor)
{
ObjectSetInteger(0,sButtonName1,OBJPROP_STATE,false);
ObjectSetInteger(0,sButtonName1,OBJPROP_COLOR,UnloadedColor);
}
}
//+------------------------- INDICATOR 2 DETECTED-----------------------------------
if(ChartIndicatorName(0,0,i)==IndiName2)
{
currentColor=ObjectGetInteger(0,sButtonName2,OBJPROP_COLOR);
if(currentColor==UnloadedColor)
{
ObjectSetInteger(0,sButtonName2,OBJPROP_STATE,true);
ObjectSetInteger(0,sButtonName2,OBJPROP_COLOR,LoadedColor);
}
}
//+------------------------- INDICATOR 2 NOT DETECTED -----------------------------------
if(!(ChartIndicatorName(0,0,i)==IndiName2))
{
currentColor=ObjectGetInteger(0,sButtonName2,OBJPROP_COLOR);
if(currentColor==LoadedColor)
{
ObjectSetInteger(0,sButtonName2,OBJPROP_STATE,false);
ObjectSetInteger(0,sButtonName2,OBJPROP_COLOR,UnloadedColor);
}
}
}
}
//+-------------------------------------------------------------------------------------
*/
}
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
return(rates_total);
}
//+------------------------------------------------------------------+

MetaTrader Terminal 4: debugging an expert advisor on historical data

I have a MetaTrader Terminal 4 logged into a demo account.
I have written and compiled my first Expert Advisor.
I am able to debug it on a live chart, so working fine. I would like to debug it though on historical data. In the MetaEditor the Debug>Start on history data is grey out though.
Also when running the strategy tester my break points never get hit, I put the break point on the first line in the OnTick() function, so it should get hit in my understanding.
Is this because I have a demo account? If not how can I debug my script on historical data?
update code below
#property strict
//+------------------------------------------------------------------+
//| Includes and object initialization |
//+------------------------------------------------------------------+
#include <book_examples\Trade.mqh>
CTrade Trade;
CCount Count;
#include <book_examples\Timer.mqh>
CTimer Timer;
CNewBar NewBar; // keeps track of timestamp of current bar & allows us to
determine when a new bar has opened so prevents orders being opened intrabar
#include <book_examples\TrailingStop.mqh>
#include <book_examples\MoneyManagement.mqh>
#include <book_examples\Indicators.mqh>
//+------------------------------------------------------------------+
//| Input variables |
//+------------------------------------------------------------------+
// left out to keep the post short
//+------------------------------------------------------------------+
//| Enum |
//+------------------------------------------------------------------+
enum trade_action
{
NO_ACTION = 0,
LONG = 1,
SHORT = 2,
EXIT_TRADE = 3
};
//+------------------------------------------------------------------+
//| Global variable and indicators |
//+------------------------------------------------------------------+
int gBuyTicket, gSellTicket;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Set magic number
Trade.SetMagicNumber(101);
Trade.SetSlippage(10);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check for bar open
bool newBar = true; // I put a breakpoint on this line
int barShift = 0;
if(TradeOnBarOpen == true)
{
newBar = NewBar.CheckNewBar(_Symbol,_Period);
barShift = 1;
}
// Trading
if(newBar == true)
{
// Money management
double lotSize = FixedLotSize;
if(UseMoneyManagement == true)
{
lotSize = MoneyManagement(_Symbol,FixedLotSize,RiskPercent,StopLoss);
}
trade_action action = calculate_signal();
// Open buy order
if(action == LONG)
{
// close sell orders
Trade.CloseAllSellOrders();
// check if we already have an open buy trade
int open_buy = Count.Buy();
if(open_buy == 0)
{
// no current existing buy position so enter
gBuyTicket = Trade.OpenBuyOrder(_Symbol,lotSize);
ModifyStopsByPoints(gBuyTicket,StopLoss,TakeProfit);
}
}
// Open sell order
else if(action == SHORT)
{
Trade.CloseAllBuyOrders();
// check if we already have an open sell trade
int open_sell = Count.Sell();
if(open_sell == 0)
{
// no current existing sell position so enter
gSellTicket = Trade.OpenSellOrder(_Symbol,lotSize);
ModifyStopsByPoints(gSellTicket,StopLoss,TakeProfit);
}
}
}
}
trade_action calculate_signal()
{
trade_action action = NO_ACTION;
// now calculate trade logic
if (some_value > some_threshold)
{
action = LONG;
}
else if (some_value < some_threshold)
{
// enter short position
action = SHORT;
}
return action;
}
Q : "Is this because I have a demo account?"
No.
Q : "If not how can I debug my script on historical data?"
In the MT4 (as-is-2020/06) you still can implement, if in a need to have such, your own "debugging"-Inspector/Monitor-agent tool to get executed during the StrategyTester-mode of the run of the MQL4 compiled-EA.
The MT4's StrategyTester is a BackTesting tool, not an (emulated)live-market Simulator-and-Debugger, it only operates the EA in synthetic(accelerated|slowed-down)-time, using a controlled-flow of synthetic-QUOTE-message(s), emulated for a given trading instrument and TimeFrame.

Resources