In this tutorial, we are going to create an Expert Advisor for MetaTrader 4 that dynamically places an arrow on the chart. This arrow will be positioned at the medium price of the current candle and will change its appearance with each tick. Let’s see how we can do that.
To start, open the MetaEditor by clicking on its icon or pressing F4 on your keyboard.
The OnTick Function
The function we are focusing on is
OnTick. This function is triggered every time a new tick, or price update, is received for the symbol the Expert Advisor is attached to.
Retrieving Current Prices
We first retrieve the current Ask and Bid prices. The function
SymbolInfoDouble fetches the required price, and
NormalizeDouble ensures the price has the correct number of decimal places based on the symbol’s properties.
Calculating the Medium Price
The medium price is the average of the Ask and Bid prices. This will be the position where our arrow will be placed on the chart.
Random Arrow Appearance
To give our arrow a unique appearance, we initialize the random number generator using
MathSrand. The seed for this generator is the current tick count. Using the
MathRand function, we generate a random number between 0 and 99.
Arrow Creation and Customization
We create an arrow object named My Object on the chart. This arrow is of type OBJ ARROW. Its initial position is set to the current time and the calculated medium price. We then customize the arrow’s appearance by setting a random arrow code and adjusting its width. Finally, the arrow is positioned correctly using
Displaying Information on the Chart
Comment function displays the Ask, Bid, and Medium prices directly on the chart. This provides a quick reference for the trader.
After writing the code, press F7 to compile it. If this was too fast for you or if you don’t understand what all the code is doing, you might want to check out the Premium course on our website or watch one of the basic videos first.
Once compiled, return to MetaTrader by pressing F4 or clicking on the icon. In MetaTrader, press Control and R to start the strategy tester. Pick the Expert Advisor we have just created, enable the visual mode, and start a strategy test. You should then see the Expert Advisor on the chart.
If you’re already a Premium course member and have an idea for a video like this one, feel free to send us an email.
And that was it!
In this tutorial, we’ve learned how to create an Expert Advisor for MetaTrader 4 that places a dynamic arrow on the chart. With just a few lines of MQL4 code, you’ve coded this Expert Advisor yourself. Thanks for watching, and I’ll see you in the next video!