New Bar Event in EA - MetaTrader 4 Expert | MT4 EA Download - MetaTrader 4 Resources
Many people want:
How to detect the presence of new rebar.
This is very simple, especially if you want to detect new bars in the current time frame,
blank start() { static date and time tmp; if (tmp!=time[ 0 ]) { tmp = time[ 0 ]; //Do your code here } }
But what about other timeframe events? It's not too difficult, but has some limitations:
MT4 does not support the onBar event, but you can put the rise count into an array and check the array count on each price move and if the correct time is reached, execute a new bar event.
This means that if you run e.g. a backtest on the M5 timeframe, you can capture M6 M7...D1 events.
Why can you only detect uptrends? The answer is a question: How to generate tick data through MetaTrader ? A1 , A2 , A3 ,...
Before the D1 timeframe it would be more difficult because the week starts on e.g.: Sunday at 20:45 (broker specific) and the start of the current month can start on the middle week... etc. I think this information is not too relevant so I won't post it...
So there is a thread for this problem but I think many people don't read articles and forums so I posted this code.
Some explanations:
In the init function, you fill the time array with the startup time:
curIndex = utils.periodToPeriodIndex( period ()); times[curIndex] = time[ 0 ]; for ( integer i = current index + 1 ; i < max; i++) Times[i] = times[curIndex] -math module (times[curIndex],utils.periodIndexToPeriod(i)* 60 );
In the startup function you check if enough time has passed by now and then execute the event
if (time[curIndex] != time[ 0 ]) { times[curIndex] = time[ 0 ]; bar( period ()); for ( integer i = current index + 1 ; i < max; i++) { Integer period = utils.periodIndexToPeriod(i), Seconds = period * 60 , time0 = times [curIndex] - math module (times [curIndex], seconds); if (time[i]!=time0){ times[i] = time 0; onBar(period); } } }
Write your code into
blank onTick() {
}and
blank bar( integer period) { }
This is everyone.
Update 1.1 : Thanks to WH Rod for the clear code
Attachment download
📎ea_symr_newBar.mq4 (2.61 KB)
Source: MQL5 #10370
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •