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.

What Is Look-Ahead Bias – Amibroker Tutorial

4 min read

Look-ahead bias in Amibroker usually comes from one line: BuyPrice = Close; on the same bar where the signal is calculated from that close. The backtest assumes you bought at a price you could only know after the bar finished. The fix is to delay the trade by one bar and enter at the next bar’s open, either with Ref() and ValueWhen() as shown below or with SetTradeDelays().

Key Takeaways

  • If a signal depends on the close of a bar, the earliest realistic fill is the next bar’s open.
  • Buy = Ref(BuySignal, -1) plus BuyPrice = Open (or ValueWhen(Buy, Open)) removes the bias.
  • SetTradeDelays(1, 1, 1, 1) with BuyPrice = Open does the same job in one line and overrides the Settings window.
  • Compare the trade list of both versions: biased backtests show entries at the exact crossover close.

When you backtest a trading strategy, it’s tempting to use the closing price to make decisions.
But doing that can make your results look unrealistically good. That mistake is called look-ahead bias.

Let’s understand it in plain English – and then fix it with a simple AmiBroker example.

OpenAlgo Desktop: algo trading on your own computer

WINDOWS, MAC AND LINUX

OpenAlgo Desktop: algo trading on your own computer

Install, sign in, connect your broker and trade. No server to set up and no Python to install.

  • Same API and screens as OpenAlgo web
  • Strategy module, charting and scalping terminals
  • Keys stay encrypted on your machine

What Is Look-Ahead Bias?

Look-ahead bias happens when your trading strategy uses future information that wouldn’t have been available at the time of trading.

Example:

“Buy when the candle closes above the 20 EMA.”

The problem?
You don’t know where the candle will close until the bar is finished.
So, if your code triggers a buy at that same close, it’s cheating – because it’s using data from the future.


Why It’s a Problem

Look-ahead bias makes your backtest look like a genius – high profits, perfect entries, and zero lag.
But when you trade live, those same signals can’t be executed in real time.

That’s why your live performance never matches your backtest – because the backtest had an unfair advantage.

On a daily chart the gap between the signal close and the next open can be large, especially after overnight global news. On intraday charts the difference per trade is smaller, but with hundreds of trades a year the bias adds up and can turn a losing system into a winning one on paper.


The Correct Way: Use the Next Bar’s Open

The fix is simple:

Wait for the candle to close, confirm your signal, and take action at the next bar’s open.

This is how real trading works – you only act after the previous bar has completed.


Amibroker Example: 10–20 EMA Crossover Strategy

Below are two versions of the same strategy, the first one wrong, the second one correct using ValueWhen().


Wrong Version (Look-Ahead Bias Present)

// --- Wrong: Uses same bar's Close ---
ema10 = EMA(Close, 10);
ema20 = EMA(Close, 20);

Buy  = Cross(ema10, ema20);
Sell = Cross(ema20, ema10);

BuyPrice  = Close;   // ❌ Close not known in real time
SellPrice = Close;

Plot(Close, "Close", colorDefault, styleCandle);
Plot(ema10, "EMA10", colorBlue);
Plot(ema20, "EMA20", colorRed);
Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, Low, -15);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, High, -15);

This version assumes you could somehow know the closing price and act instantly at that same close, which is impossible.


Correct Version (Bias-Free, Uses Next Bar’s Open)

// --- Correct: Entry at next bar's open ---
ema10 = EMA(Close, 10);
ema20 = EMA(Close, 20);

BuySignal  = Cross(ema10, ema20);
SellSignal = Cross(ema20, ema10);

// Trigger confirmed only after bar closes
Buy  = Ref(BuySignal, -1);
Sell = Ref(SellSignal, -1);

// Use ValueWhen() to capture next bar's open after signal
BuyPrice  = ValueWhen(Buy, Open);
SellPrice = ValueWhen(Sell, Open);

Plot(Close, "Close", colorDefault, styleCandle);
Plot(ema10, "EMA10", colorBlue);
Plot(ema20, "EMA20", colorRed);
Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, Low, -15);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, High, -15);

Here’s what happens:

  • The crossover signal (BuySignal) is confirmed after the bar closes.
  • The actual trade executes at the next bar’s open.
  • ValueWhen() ensures the correct open price is recorded for that signal.

Because Buy is already true on the entry bar, ValueWhen(Buy, Open) on that bar simply returns that bar’s open, so writing BuyPrice = Open; gives the same result. ValueWhen() is useful when you want to carry the entry price forward, for example to calculate a stop or target from it.

Alternative: Use SetTradeDelays()

Amibroker also has a built-in way to delay execution. SetTradeDelays(buy, sell, short, cover) shifts each trade by the number of bars you specify, and a value set in code overrides the delays in the Analysis Settings window (Trades tab). With a delay of one bar, the trade is executed on the bar after the signal, so Open becomes the next bar’s open:

// --- Correct: same logic using SetTradeDelays ---
SetTradeDelays(1, 1, 1, 1);   // execute every trade one bar after the signal

ema10 = EMA(Close, 10);
ema20 = EMA(Close, 20);

Buy  = Cross(ema10, ema20);
Sell = Cross(ema20, ema10);

BuyPrice  = Open;   // with a 1-bar delay this is the next bar's open
SellPrice = Open;

Buy  = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);

Use one method or the other, not both. If you combine Ref(BuySignal, -1) with SetTradeDelays(1, 1, 1, 1), the entry is delayed by two bars. Note also that the arrows on the chart are plotted on the signal bar when you use SetTradeDelays(), while the backtest fills on the following bar.


Quick Comparison

VersionEntry Based OnTrade PriceLook-Ahead Bias
WrongSame bar closeCloseYes
CorrectPrevious bar closeOpen (next bar)No
Correct (SetTradeDelays)Previous bar closeOpen with 1-bar delayNo

How to Check Your Amibroker Backtest for Look-Ahead Bias

  1. Run the backtest and open the trade list. For a few trades, compare the entry price with the chart. If the entry equals the close of the crossover bar, the code is biased.
  2. Search your AFL for Ref(..., 1) or any positive offset. A positive offset in Ref() reads future bars and should never appear in signal logic.
  3. Check functions that look forward, such as Zig(), Peak() and Trough(). They change their past values as new bars arrive and are not suitable for backtesting signals.
  4. If you use TimeFrameSet() or TimeFrameExpand() for higher-timeframe data, make sure you are using the completed previous higher-timeframe bar, not the one still forming.
  5. Compare results with and without a one-bar delay. A strategy whose profits disappear with a one-bar delay was relying on the bias.

If you are building machine learning models in Python, the same problem shows up as data leakage; I explain it with a walk-forward example in look-ahead bias in trading strategies. For a full Amibroker backtesting workflow, see introduction to backtesting a trading system using Amibroker and walk forward testing explained in simple terms.

Final Takeaway

Look-ahead bias is the silent killer of backtests.
It gives you a false sense of accuracy and destroys your confidence when live results don’t match.

The golden rule:

If your signal depends on the candle close, trade at the next bar’s open.

So next time you’re backtesting in AmiBroker (or any platform), remember:
real traders wait for confirmation, not prediction.

Frequently Asked Questions

What is look-ahead bias in Amibroker?

It is when a backtest uses information that was not available at the time of the trade, most often by buying at the close of the same bar whose close generated the signal, or by using functions and offsets that read future bars.

How do I use SetTradeDelays in Amibroker?

Add SetTradeDelays(1, 1, 1, 1); at the top of your AFL and set BuyPrice, SellPrice, ShortPrice and CoverPrice to Open. Each trade is then executed at the open of the bar after the signal.

Is buying at the close always look-ahead bias?

Not always. If your system calculates the signal a few minutes before the close and places a market-on-close style order, a close fill can be realistic, but you should add slippage. For most retail systems, next-bar open is the safer assumption.

Does Zig() cause look-ahead bias in Amibroker?

Yes. Zig(), Peak() and Trough() are recalculated as new bars arrive, so historical turning points look perfect in a backtest but could not have been known in real time.

Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

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.

Leave a Reply

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