Autocorrelation is a statistical tool that measures the degree to which current price movements are related to past movements. By visualizing autocorrelation across various lags, traders can uncover hidden patterns, cycles, and trends in the market. In this post, we present an Amibroker AFL code that creates an Autocorrelation Heatmap, originally inspired by the TradingView PineScript version from Pinecoders

Notably, the AFL code for this indicator was generated with the assistance of the OpenAI o3-mini model, renowned for its exceptional STEM reasoning capabilities and efficiency. This collaboration ensures that the code is not only robust and accurate but also optimized for rapid problem-solving in technical domains.
TradEdge 7.0 – Apr 2025 Edition
80+ hours of Live Online Mentorship Program on Market Profile, Orderflow Analytics, VSA
This indicator not only calculates autocorrelation over a configurable lookback period (called Length) but also uses an advanced smoothing filter—known as the UltimateSmoother—to reduce noise. Additionally, the code allows you to select a price field (defaulting to the closing price) and even use a test signal (a sine wave) for experimentation.
Autocorrelation Heatmap – Amibroker AFL
/*
TASC 2025.02 Autocorrelation Indicator (AFL Version)
Article: Drunkards Walk: Theory And Measurement By Autocorrelation.
Article By: John F. Elhers
Transcripted from : Tradingview Pinescript V6 Coded by Pinecoders
Transcripted by : Rajandran R (Creator - OpenAlgo)
Transcripted Assistance : O3-Mini-High Model
Date : 01-Feb-2025
This version avoids self–referencing series by using a for–loop to compute
the UltimateSmoother filter. The color for each bar is computed vector–wise so that
the plotted line changes color over time.
*/
_SECTION_BEGIN("Autocorrelation Heatmap");
// Ensure we have enough bars for the loop calculations.
SetBarsRequired(10000,10000);
// ---------- User Inputs ----------
Length = Param("Length", 20, 1, 100, 1);
iTest = ParamToggle("Use test signal", "No|Yes", 0);
rangeOption = ParamList("Lag Range", "0-32,33-65,66-98", 0);
// Map the chosen lag range to start and end lag values.
if( rangeOption == "0-32" )
{
startLag = 1;
endLag = 32;
}
else if( rangeOption == "33-65" )
{
startLag = 34;
endLag = 65;
}
else // "66-98"
{
startLag = 67;
endLag = 98;
}
// ---------- Source Price ----------
Src = ParamField("Source",3); // Source default used as Close
//----------------------------------------------------
// UltimateSmoother Calculation via For Loop
//
// The smoother is defined by the recursive formula:
// us[i] = (1-c1)*Src[i]
// + (2*c1-c2)*Src[i-1]
// - (c1+c3)*Src[i-2]
// + c2*us[i-1]
// + c3*us[i-2]
pi = 3.14159265;
a1 = exp( -1.414 * pi / Length );
c2 = 2 * a1 * cos( 1.414 * pi / Length );
c3 = - a1 * a1;
c1 = ( 1 + c2 - c3 ) / 4;
nBars = BarCount;
us = Src; // initialize us as a copy of Src
// Compute the recursive filter for bars starting from index 2.
for( i = 2; i < nBars; i++ )
{
us[i] = (1 - c1) * Src[i]
+ (2 * c1 - c2) * Src[i - 1]
- (c1 + c3) * Src[i - 2]
+ c2 * us[i - 1]
+ c3 * us[i - 2];
}
//---------- Select the Series to Analyze ----------
//
// If iTest is enabled, use a 30–bar sine wave as a test signal;
// otherwise, use the computed UltimateSmoother series.
if( iTest )
{
Filt = sin( 2 * pi * BarIndex() / 30 );
}
else
{
Filt = us;
}
//---------- Autocorrelation Heatmap Plotting ----------
//
// For each lag in the selected range, compute the Pearson correlation
// (over the past "Length" bars) between Filt and its lag–shifted version.
// (No LastValue() is used so that we retain a per–bar array of correlation values.)
SetChartOptions(0, chartShowArrows | chartShowDates);
for( lag = startLag; lag <= endLag; lag++ )
{
// Compute the correlation array for the entire series.
tempCorr = Correlation( Filt, Ref( Filt, lag ), Length );
// Compute color components as arrays using vectorized IIf:
red = IIf( tempCorr >= 0, 255 * (1 - tempCorr), 255 );
green = IIf( tempCorr >= 0, 255, 255 * (1 + tempCorr) );
blue = 0;
// ColorRGB() accepts arrays so that each bar is colored individually.
col = ColorRGB( red, green, blue );
// Set a constant y–value for this lag; it will be repeated for all bars.
yVal = lag + 1;
// Plot the horizontal line at y = yVal.
// Since the color (col) is an array, the line's color will change with each bar.
Plot( yVal, StrFormat("Lag %g", lag), col, styleLine, 0, 0, Null, 2 );
}
//---------- Indicator Title ----------
Title = "TASC 2025.02 Autocorrelation Heatmap" +
"\nSource = Close" +
"\nLength = " + WriteVal( Length, 1.0 ) +
"\nLag Range = " + rangeOption;
_SECTION_END();
Code Overview
1. User Inputs and Lag Range Selection
The first section of the code sets up user inputs:
- Length: Number of bars over which the Pearson correlation is computed.
- iTest: A toggle to choose between using a test sine wave signal or the computed smoother.
- rangeOption: A parameter to select which lag range to display (e.g., 0–32, 33–65, 66–98). The code maps this choice to start and end lag values.
2. Source Price Selection
Instead of hardcoding the source price, we now use ParamField("Source", 3)
. This function lets users choose a price field from the drop-down list in Amibroker (with “Close” as the default). This flexibility is important for traders who may wish to analyze other data series such as Open, High, or Low.
3. UltimateSmoother Calculation
The UltimateSmoother is a recursive filter that smooths out the price data to make autocorrelation analysis more robust. Its formula is given by:us[i]=(1−c1) Src[i]+(2c1−c2) Src[i−1]−(c1+c3) Src[i−2]+c2 us[i−1]+c3 us[i−2]us[i] = (1-c_1)\,\text{Src}[i] + (2c_1-c_2)\,\text{Src}[i-1] – (c_1+c_3)\,\text{Src}[i-2] + c_2\,us[i-1] + c_3\,us[i-2]us[i]=(1−c1)Src[i]+(2c1−c2)Src[i−1]−(c1+c3)Src[i−2]+c2us[i−1]+c3us[i−2]
Since Amibroker does not support self-referencing series natively, the code uses a for–loop to compute each value of the smoothed series (us
) bar-by-bar.
4. Series Selection
The indicator lets you choose between:
- A test signal (a 30–bar sine wave), useful for verifying the indicator’s behavior.
- The computed UltimateSmoother series, which is applied to the selected source price.
5. Autocorrelation Heatmap Plotting
For each lag in the specified range, the code computes the Pearson correlation between the filtered series and its lagged version. The key points are:
- Vectorized Color Computation:
The correlation array (tempCorr
) is used to determine color components. For positive correlations, the red channel diminishes as the correlation approaches 1, while the green channel stays at maximum. For negative correlations, the green channel is reduced. This mapping creates a dynamic heatmap where color intensity reflects the strength of the autocorrelation. - Dynamic Plotting:
A horizontal line is plotted for each lag value (with the y-value set to lag + 1). Although the y-value remains constant per lag, the color of the line changes over time (per bar) because the color is computed as an array. This produces a heatmap effect that evolves as new data arrives.
6. Indicator Title
The final section of the code sets a title for the indicator, including details on the source price, the length of the lookback period, and the selected lag range. This information helps you quickly verify the settings when the indicator is overlaid on a chart.
How Traders Can Use This Indicator
Visual Pattern Recognition
- Cycles and Seasonality:
The heatmap may reveal recurring patterns that hint at cyclical behavior. For example, periodic increases in autocorrelation could indicate seasonality or repeating market cycles. - Trend Confirmation:
High positive autocorrelation at short lags may confirm trending behavior, suggesting that a trend-following strategy could be effective. Conversely, strong negative autocorrelation might indicate overextended moves and potential reversals.
Risk Management and Strategy Timing
- Entry/Exit Signals:
When the autocorrelation heatmap shows significant shifts in color (indicating changes in correlation strength), it can be used as a supplementary signal for timing entries and exits. For instance, a sudden drop in autocorrelation might warn of an upcoming reversal. - Market Efficiency:
Consistently low autocorrelation might suggest an efficient market where past prices have little predictive power. In such cases, traders might focus on alternative strategies.
Customization and Experimentation
- Source Flexibility:
With the ability to choose the source price usingParamField
, traders can experiment with different data series to see which one best suits their strategy. - Test Signal Mode:
The built-in test signal mode (using a sine wave) allows traders to experiment with known periodic behavior, ensuring that the autocorrelation computations are working as expected before applying them to real market data.
Conclusion
The Autocorrelation Heatmap in Amibroker AFL is a powerful and flexible tool that transforms complex statistical measures into an intuitive visual format. By leveraging advanced smoothing techniques and dynamic autocorrelation analysis, this indicator provides traders with deep insights into market behavior, aiding in strategy development and risk management. With the help of the innovative OpenAI o3-mini model, the code behind this indicator is both robust and optimized for fast, accurate performance. Embrace this tool to uncover hidden patterns in your data and elevate your trading strategy to the next level.
Feel free to customize and extend the code to suit your individual trading style. Happy trading!