Introduction to Parabolic SAR in MQL5
What is Parabolic SAR?
The Parabolic Stop and Reverse (SAR) is a technical indicator used to identify potential reversal points in the price direction of an asset. It is displayed as a series of dots either above or below the price bars, indicating bearish or bullish trends, respectively. Unlike many other indicators, Parabolic SAR is primarily designed to act as a trailing stop-loss, hence the name. It helps traders determine where to place stop-loss orders that dynamically adjust as the price moves in their favor.
Purpose and Applications in Trading
The primary purpose of Parabolic SAR is to identify potential trend reversals and to provide dynamic stop-loss levels. It is widely used in trading to:
- Determine entry and exit points: Crossovers of the SAR dots above or below the price can signal potential buying or selling opportunities.
- Set trailing stop-loss orders: The SAR value acts as a dynamic stop-loss, helping to lock in profits as the trend progresses.
- Confirm trend direction: When the SAR is below the price, it suggests an upward trend; when it is above, it suggests a downward trend.
- Filter out sideways movement: Parabolic SAR works best in trending markets and can provide false signals during choppy, sideways price action.
Implementing Parabolic SAR in MQL5: A Brief Overview
Implementing Parabolic SAR in MQL5 involves understanding its formula and parameters and then translating that understanding into code. MQL5 provides a built-in function, iSAR(), which greatly simplifies the process. However, understanding the underlying calculations allows for more sophisticated customizations and strategies. This article will explore both the raw calculation and the use of iSAR() for indicator creation and strategy implementation.
Understanding the Parabolic SAR Formula and Parameters
Detailed Explanation of the Formula
The Parabolic SAR is calculated using the following formula:
SARt = SARt-1 + AF * (EP – SARt-1)
Where:
- SARt is the Parabolic SAR value for the current period.
- SARt-1 is the Parabolic SAR value for the previous period.
- AF is the Acceleration Factor.
- EP is the Extreme Point, which is the highest high in an uptrend or the lowest low in a downtrend since the last SAR reversal.
The initial SAR value is usually set to the previous high or low, depending on the initial trend direction. In an uptrend, the initial SAR is the previous low; in a downtrend, it’s the previous high.
Acceleration Factor (AF): How it Works
The Acceleration Factor (AF) increases with each new high (in an uptrend) or new low (in a downtrend) and determines the sensitivity of the SAR. A higher AF causes the SAR to move closer to the price. Typically, the AF starts at 0.02 and increases by 0.02 with each new extreme point.
Maximum AF: Setting the Limit
To prevent the SAR from becoming overly sensitive and generating false signals, a maximum value is set for the AF (typically 0.20). Once the AF reaches this maximum, it remains constant until the trend reverses.
Impact of AF and Maximum AF on the Indicator’s Sensitivity
The AF and Maximum AF parameters directly impact the indicator’s sensitivity. A higher AF makes the SAR more reactive to price changes, resulting in tighter stop-loss levels and potentially more frequent signals. Conversely, a lower AF makes the SAR less sensitive, leading to wider stop-loss levels and fewer signals. The Maximum AF prevents over-optimization and helps maintain a balance between sensitivity and reliability.
Implementing Parabolic SAR in MQL5: Code Examples
Basic MQL5 Code for Calculating Parabolic SAR
While the iSAR() function is readily available, understanding the underlying calculation is beneficial. Here’s a simplified example illustrating the SAR calculation logic:
double CalculateSAR(double previousSAR, double AF, double EP) {
return previousSAR + AF * (EP - previousSAR);
}
This function takes the previous SAR value, the acceleration factor, and the extreme point as inputs and returns the calculated SAR value for the current period. This is a basic building block; a complete implementation would require managing trend direction, initial SAR values, and AF adjustments.
Creating a Custom Indicator with iSAR()
The easiest way to implement Parabolic SAR in MQL5 is by using the built-in iSAR() function. Here’s how to create a custom indicator:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
input double InpStep = 0.02; // Acceleration Step
input double InpMaximum = 0.2; // Acceleration Maximum
double SarBuffer[];
int OnInit() {
SetIndexBuffer(0, SarBuffer, INDICATOR_DATA);
IndicatorSetInteger(INDICATOR_ARROWCODES_TRUE, 233); // Up Arrow
IndicatorSetInteger(INDICATOR_ARROWCODES_FALSE, 234); // Down Arrow
return(INIT_SUCCEEDED);
}
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[]) {
int start = prev_calculated - 1;
if(start < 0) start = 1;
for(int i = start; i < rates_total; i++) {
SarBuffer[i] = iSAR(NULL, 0, InpStep, InpMaximum, i);
}
return(rates_total);
}
This code defines a custom indicator that plots the Parabolic SAR values on a separate window. The iSAR() function retrieves the SAR value for each bar.
Customizing Parameters: AF and Maximum AF Input
The example above uses input variables InpStep and InpMaximum to allow users to adjust the AF and Maximum AF through the indicator’s settings. This is crucial for optimizing the indicator for different market conditions and trading styles.
Plotting Parabolic SAR on the Chart
The #property directives in the code specify how the indicator is plotted on the chart. In this case, it’s plotted as arrows in a separate window. You can modify these properties to plot the SAR dots directly on the price chart or use different drawing styles.
Using Parabolic SAR in MQL5 Trading Strategies
Generating Buy/Sell Signals Based on SAR
Buy signals are generated when the price crosses above the SAR dots, indicating a potential uptrend. Sell signals are generated when the price crosses below the SAR dots, indicating a potential downtrend. In MQL5, this can be implemented as follows:
if (close[i] > SarBuffer[i] && close[i-1] <= SarBuffer[i-1]) {
// Buy signal
Print("Buy Signal");
}
if (close[i] < SarBuffer[i] && close[i-1] >= SarBuffer[i-1]) {
// Sell signal
Print("Sell Signal");
}
Implementing Stop-Loss and Take-Profit Orders with SAR
The SAR value itself can be used as a dynamic stop-loss level. As the trend progresses, the SAR value adjusts, and the stop-loss order can be moved accordingly to lock in profits. Take-profit orders can be set based on a multiple of the initial risk or by identifying potential resistance/support levels.
Combining Parabolic SAR with Other Indicators (e.g., Moving Averages, RSI)
Parabolic SAR works best when combined with other indicators to filter out false signals. For example:
- Moving Averages: Use a moving average to confirm the overall trend direction. Only take buy signals when the price is above the moving average and sell signals when the price is below.
- RSI: Use the Relative Strength Index (RSI) to identify overbought or oversold conditions. Avoid taking buy signals when the RSI is overbought and sell signals when the RSI is oversold.
Backtesting and Optimization of SAR-Based Strategies in MQL5
MQL5 provides a powerful backtesting environment for evaluating the performance of trading strategies. Use the Strategy Tester to optimize the AF and Maximum AF parameters for different currency pairs and timeframes. Experiment with different combinations of indicators to find the most profitable strategy.
Advanced MQL5 Techniques with Parabolic SAR
Dynamic Adjustment of AF Based on Market Volatility
The AF can be dynamically adjusted based on market volatility using indicators like Average True Range (ATR). When volatility is high, decrease the AF to reduce sensitivity. When volatility is low, increase the AF to increase sensitivity.
double atr = iATR(NULL, 0, 14, i);
double dynamicAF = InpStep * (1 + atr / Average(atr, 100)); // Example
Multi-Timeframe Analysis using iSAR()
You can use the iSAR() function to analyze the SAR values on different timeframes. This can provide a more comprehensive view of the market and help identify potential trading opportunities.
double sarH1 = iSAR(NULL, PERIOD_H1, InpStep, InpMaximum, i); // SAR on H1
Creating Expert Advisors (EAs) with Automated SAR Trading Logic
Expert Advisors (EAs) can be created to automate SAR-based trading strategies. The EA can monitor the price and SAR values, generate buy/sell signals, and place orders automatically. This requires careful consideration of risk management and order execution logic.
Debugging and Troubleshooting MQL5 Code for Parabolic SAR
Debugging is crucial for ensuring the accuracy and reliability of MQL5 code. Use the MetaEditor’s debugging tools to step through the code, inspect variables, and identify potential errors. Common errors include incorrect parameter values, logical errors in the trading logic, and issues with order placement.