Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Autocorrelation Heatmap – TASC 2025.02 Indicator – Amibroker AFL using ChatGPT O3-Mini Model

4 min read

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 spot patterns, cycles, and trends in the market. This post presents an Amibroker AFL code that creates an Autocorrelation Heatmap, originally inspired by the TradingView PineScript version from Pinecoders

The AFL code for this indicator was generated with the assistance of the OpenAI o3-mini model, which is good at STEM reasoning tasks.

This indicator calculates autocorrelation over a configurable lookback period (called Length) and uses a smoothing filter called 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.

Build desktop apps with Claude Code
LIVE COURSE · DEC 2026

Build desktop apps with Claude Code

Plan, build, package and distribute desktop apps for Windows, macOS and Linux, with Claude Code as your development partner.

  • 5 live sessions, 10 hours, starts 7 December 2026
  • CRM, algo trading and NSE Bhavcopy projects
  • Installers for Windows, macOS and Linux
Join the course →by Marketcalls

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 reliable. 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]+c2​us[i−1]+c3​us[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 using ParamField, 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 turns a statistical measure into a visual format that is easy to read. With smoothing and autocorrelation across many lags, it shows how price behaves at different lags and can help with strategy development and risk management. The code was written with the help of the OpenAI o3-mini model. Use it to look for patterns in your data and test whether they help your trading.

Feel free to customize and extend the code to suit your individual trading style. Happy trading!

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

One Reply to “Autocorrelation Heatmap – TASC 2025.02 Indicator – Amibroker AFL…”

  1. HI,
    This indicator coded in amibroker is repainting badly,The pinescript version doesnt repaint.Can u please correct the AFL code to remove repainting,Thanks.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More