AI Trading Tutorial - MQL5 Average True Range with Trailing Stops

Published: 01 January 1970
on channel: MQL5 Tutorial
220
4

https://mql5tutorial.com/?s=iatr

In this video, we are going to create an Expert Advisor using the Average True Range (ATR) indicator along with trailing stops. Let's see how we can do that.
We begin by starting Metaeditor, which can be accessed by clicking on the little icon or by pressing F4. Within Metaeditor, we first include the CTrade class from the standard library. This class provides simplified trading methods such as PositionOpen and PositionModify, which are essential for managing trade operations including position management. We instantiate a CTrade object with default parameters, which will handle all the trade operations for us.
Next, we define the strategy configuration parameters, which are adjustable in the Expert Advisor properties. These parameters include LookbackBars, which is the historical range for highs and lows and can vary between 1 and 1000 candles. MinCandlesBack is the minimum age for a valid high or low, ranging from 5 to 50 candles. TrailingOffset is the safety margin for the trailing stop, measured in points and can be set between 1 and 20. ATRPeriod is the period for the Average True Range, with a default value of 14. ATRThreshold is the threshold for signal generation, set at 0.0002, which helps in determining significant volatility for trade entries.
For global variables and handles, we store states between ticks and indicator data. We define an atrHandle to hold the ATR indicator handle, atrBuffer as an array to store ATR values, and priceData as an array for OHLC price data.
The Expert Initialization Function, OnInit, is executed once when the Expert Advisor starts and is responsible for setting up the indicator. We create an ATR indicator handle for the current symbol on the H1 timeframe using the iATR function. The atrBuffer and priceData arrays are configured as time series, meaning the newest data will be at index 0. The function returns a success code to indicate successful initialization.
The position opening functions are responsible for executing market orders with a specified lot size. In OpenBuyPosition, we retrieve the current ask price using SymbolInfoDouble with SYMBOL ASK. We then open a buy position with the financial instrument specified by Symbol, setting the order type to ORDER TYPE BUY. The position size is set to 0.10, which means 10 micro lots. The entry price is set at the current ask price, with both the initial stop loss and take profit disabled. A comment, "ATR Position," is added for reference.
Similarly, in OpenSellPosition, we retrieve the current bid price using SymbolInfoDouble with SYMBOL BID. We open a sell position with the financial instrument specified by Symbol, setting the order type to ORDER TYPE SELL. The position size is again 0.10, with the entry price at the current bid price, and both the initial stop loss and take profit disabled. The same comment, "ATR Position," is used.
The main price update function, OnTick, is executed on every tick and contains the core strategy logic. We first retrieve historical price data for analysis by copying H1 candle data for the lookback period using CopyRates. We also copy ATR indicator values into the atrBuffer array using CopyBuffer to facilitate volatility analysis.
We check the position status to determine if open positions exist and their type. We initialize a boolean variable, hasOpenPosition, to false and set the currentPositionType to POSITION TYPE BUY by default. We then iterate backwards through all open positions to find relevant ones. For each position, we get the unique ticket number using PositionGetTicket and check if the position belongs to the current symbol using PositionSelectByTicket and PositionGetString with POSITION SYMBOL. If a matching position is found, we mark hasOpenPosition as true, store the position type using PositionGetInteger with POSITION TYPE, and exit the loop.


Watch video AI Trading Tutorial - MQL5 Average True Range with Trailing Stops online without registration, duration hours minute second in high quality. This video was added by user MQL5 Tutorial 01 January 1970, don't forget to share it with your friends and acquaintances, it has been viewed on our site 220 once and liked it 4 people.