A cumulative delta line tells you how much more volume traded at the ask than at the bid, but it forgets where that happened. Absorption is a question about where: aggressive orders pile into one price, resting orders soak them up, and price refuses to move. This note builds delta by price level from NinjaTrader 8's own market data stream, marks the levels where one side's aggression stalled, and walks through a hypothetical session showing how a trader might read them. The example is educational and unvalidated.
NinjaTrader's licensed Order Flow+ tools already offer delta per price inside Volumetric bars. This strategy does not use them, so it runs on any NinjaTrader 8 installation with suitable data.
What the strategy computes
Every trade arrives in OnMarketData() as a Last event carrying its price, its volume and the best bid and ask at that moment. The strategy rounds the price to whole ticks and drops the volume into one of three buckets at that level:
- Buy: the trade printed at or above the ask, so a buyer crossed the spread.
- Sell: the trade printed at or below the bid, so a seller crossed the spread.
- Neutral: the trade printed inside the spread, or the quote was locked or crossed.
Level delta is Buy - Sell. Two profiles are kept side by side. The bar profile holds delta by price for the bar being built and is cleared after the bar closes. The session profile adds each completed bar into a running delta by price that resets on the first bar of each trading session. The session profile is the cumulative part: it shows, price by price, which side has been more aggressive since the open.
When a bar closes, the strategy looks at the top EdgeZoneTicks levels of the bar for buy absorption and the bottom levels for sell absorption. For buy absorption, a level qualifies when:
- at least
MinAggressorVolumetraded at the ask there, - its delta is at least
MinDeltaRatioof the level's volume, - the bar closed at least
CloseRejectTicksbelow it, and - the session's cumulative delta at that price is also positive.
The strongest qualifying level is drawn as a short line labelled BA with its delta. If the next ConfirmBars bars never trade BreachTicks above it, the level is confirmed with a diamond. If price does push through, the zone is dropped, because the buyers got their move after all. Sell absorption mirrors this at the bar's low with the label SA.
A session with the tool
Picture an index futures trader on a 2,000-tick chart, an hour into the regular session. The numbers below are made up to show how the marks read, not taken from a real chart.
Loading it. The strategy needs historical trades with their bid and ask, so the trader turns on "Show Tick Replay" in the Market data section of NinjaTrader's Options window, then ticks Tick Replay on the chart's data series and on the strategy, as the Help Guide's Tick Replay page describes. With Tick Replay, OnMarketData() runs on historical bars too, so the morning's profile is rebuilt when the strategy loads instead of starting empty. Renko and Line Break bars do not support Tick Replay, which is why a tick chart is used here. Enable Trading stays off, so the strategy only draws.
The first mark. Price has climbed for twenty minutes. A bar spikes into a new high and closes four ticks off it. At the close, a short orange line appears at the high's second-to-top tick with the label BA 640: about 900 contracts traded at the ask there against about 260 at the bid. The trader reads it in one breath. Buyers paid up hard at that price, the bar could not hold above it, and the session profile says this price has been net bought all morning. Somebody was selling into them.
Waiting for confirmation. The next bar drifts lower. The one after pokes up but stops a tick short of the level. When that second bar closes, a diamond lands on the line. The zone is confirmed: two bars of chances to trade through, and buyers did not take them. The trader now has a specific price where aggressive buying has twice failed to move the market, which is more useful than a vague feeling that the rally looks tired.
A mark that fails. Later, a bar flushes to the session low and leaves a blue SA 410 near the bottom. Sellers hit the bid hard and the bar closed back up. One bar later, price breaks two ticks under the level, and the zone disappears without a diamond. Sellers eventually moved price, so it was not absorption. Watching zones die is half the value: the trader learns which pushes stall and which simply pause.
Using the levels. With a confirmed BA zone overhead, the trader has a few options. One is to treat the level as a reference for a short, with a stop placed just beyond it, where the idea is plainly wrong if price trades there. Another is to hold off on new longs while price sits under it. A third is to watch the level on the next test: if the next push into it shows a large positive delta and price goes through, the earlier absorption has been used up. Turning on Enable Trading automates only the first option. On a confirmed BA zone it requests a short with a stop StopBufferTicks above the level and a fixed target of TargetTicks. A confirmed SA zone requests the mirror-image long.
Reading the numbers, not just the marks. The label's delta matters more than the shape on the chart. A BA 640 on a 2,000-tick bar says something very different from a BA 60, which is why MinAggressorVolume should be scaled to the instrument and bar size before any session. A level that keeps getting marked across several bars, with the session delta at that price growing each time, describes a seller who keeps reloading at one price.
NinjaScript strategy
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
namespace NinjaTrader.NinjaScript.Strategies.OranselIndustries
{
public class DeltaAbsorptionProfileStrategy : Strategy
{
private sealed class LevelFlow
{
public long Buy, Sell, Neutral;
public long Delta { get { return Buy - Sell; } }
public long Total { get { return Buy + Sell + Neutral; } }
}
private sealed class AbsorptionZone
{
public int PriceTicks;
public bool IsBuyAbsorption;
public int BarDetected;
public string Tag;
}
private const string LongSignal = "AbsorbLong";
private const string ShortSignal = "AbsorbShort";
private Dictionary<int, LevelFlow> _barProfile;
private Dictionary<int, long> _sessionDelta;
private List<AbsorptionZone> _zones;
private long _historicalLastEvents;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Marks bar-edge price levels where one-sided aggressive volume failed to move price.";
Name = "DeltaAbsorptionProfileStrategy";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 20;
IsInstantiatedOnEachOptimizationIteration = true;
EdgeZoneTicks = 2;
MinAggressorVolume = 300;
MinDeltaRatio = 0.6;
CloseRejectTicks = 2;
ConfirmBars = 2;
BreachTicks = 1;
EnableTrading = false;
StopBufferTicks = 4;
TargetTicks = 8;
}
else if (State == State.Configure)
{
SetProfitTarget(LongSignal, CalculationMode.Ticks, TargetTicks);
SetProfitTarget(ShortSignal, CalculationMode.Ticks, TargetTicks);
}
else if (State == State.DataLoaded)
{
_barProfile = new Dictionary<int, LevelFlow>();
_sessionDelta = new Dictionary<int, long>();
_zones = new List<AbsorptionZone>();
_historicalLastEvents = 0;
}
else if (State == State.Realtime && CurrentBar > 0 && _historicalLastEvents == 0)
{
Print(Name + ": no historical trades received; enable Tick Replay to build history.");
}
}
protected override void OnMarketData(MarketDataEventArgs e)
{
if (_barProfile == null || e.MarketDataType != MarketDataType.Last || e.Volume <= 0)
return;
if (State == State.Historical)
_historicalLastEvents++;
int key = ToTicks(e.Price);
LevelFlow flow;
if (!_barProfile.TryGetValue(key, out flow))
_barProfile[key] = flow = new LevelFlow();
bool quoteUsable = e.Ask > 0 && e.Bid > 0 && e.Ask > e.Bid;
if (quoteUsable && e.Price >= e.Ask)
flow.Buy += e.Volume;
else if (quoteUsable && e.Price <= e.Bid)
flow.Sell += e.Volume;
else
flow.Neutral += e.Volume;
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (Bars.IsFirstBarOfSession)
_sessionDelta.Clear();
// Session profile: cumulative delta by price since the session open.
foreach (KeyValuePair<int, LevelFlow> level in _barProfile)
{
long existing;
_sessionDelta.TryGetValue(level.Key, out existing);
_sessionDelta[level.Key] = existing + level.Value.Delta;
}
UpdateZones();
if (_barProfile.Count == 0)
return;
DetectAbsorption(true);
DetectAbsorption(false);
_barProfile.Clear();
}
private void DetectAbsorption(bool buySide)
{
int edgeTicks = ToTicks(buySide ? High[0] : Low[0]);
int bestKey = int.MinValue;
long bestDelta = 0;
foreach (KeyValuePair<int, LevelFlow> level in _barProfile)
{
bool inEdge = buySide ? level.Key > edgeTicks - EdgeZoneTicks : level.Key < edgeTicks + EdgeZoneTicks;
LevelFlow flow = level.Value;
long aggressorVolume = buySide ? flow.Buy : flow.Sell;
long signedDelta = buySide ? flow.Delta : -flow.Delta;
if (!inEdge || aggressorVolume < MinAggressorVolume || flow.Total <= 0
|| (double)signedDelta / flow.Total < MinDeltaRatio || signedDelta <= bestDelta)
continue;
bestDelta = signedDelta;
bestKey = level.Key;
}
if (bestKey == int.MinValue)
return;
int closeTicks = ToTicks(Close[0]);
bool rejected = buySide ? closeTicks <= bestKey - CloseRejectTicks : closeTicks >= bestKey + CloseRejectTicks;
long sessionDelta;
_sessionDelta.TryGetValue(bestKey, out sessionDelta);
bool sessionAgrees = buySide ? sessionDelta > 0 : sessionDelta < 0;
if (!rejected || !sessionAgrees)
return;
string tag = (buySide ? "BuyAbs" : "SellAbs") + CurrentBar;
double levelPrice = bestKey * TickSize;
Brush brush = buySide ? Brushes.OrangeRed : Brushes.DodgerBlue;
_zones.Add(new AbsorptionZone { PriceTicks = bestKey, IsBuyAbsorption = buySide, BarDetected = CurrentBar, Tag = tag });
Draw.Line(this, tag, Math.Min(CurrentBar, 3), levelPrice, 0, levelPrice, brush);
Draw.Text(this, tag + "Label", (buySide ? "BA " : "SA ") + bestDelta, 0,
levelPrice + (buySide ? 2 : -2) * TickSize, brush);
}
private void UpdateZones()
{
int highTicks = ToTicks(High[0]);
int lowTicks = ToTicks(Low[0]);
for (int i = _zones.Count - 1; i >= 0; i--)
{
AbsorptionZone zone = _zones[i];
if (zone.BarDetected >= CurrentBar)
continue;
bool breached = zone.IsBuyAbsorption
? highTicks >= zone.PriceTicks + BreachTicks
: lowTicks <= zone.PriceTicks - BreachTicks;
if (breached)
_zones.RemoveAt(i);
else if (CurrentBar - zone.BarDetected >= ConfirmBars)
{
OnZoneConfirmed(zone);
_zones.RemoveAt(i);
}
}
}
private void OnZoneConfirmed(AbsorptionZone zone)
{
double levelPrice = zone.PriceTicks * TickSize;
Draw.Diamond(this, zone.Tag + "Confirmed", false, 0, levelPrice,
zone.IsBuyAbsorption ? Brushes.OrangeRed : Brushes.DodgerBlue);
if (!EnableTrading || CurrentBar < BarsRequiredToTrade || Position.MarketPosition != MarketPosition.Flat)
return;
int quantity = Convert.ToInt32(DefaultQuantity);
if (zone.IsBuyAbsorption)
{
double stopPrice = levelPrice + StopBufferTicks * TickSize;
if (stopPrice <= Close[0])
return;
SetStopLoss(ShortSignal, CalculationMode.Price, stopPrice, false);
EnterShort(quantity, ShortSignal);
}
else
{
double stopPrice = levelPrice - StopBufferTicks * TickSize;
if (stopPrice >= Close[0])
return;
SetStopLoss(LongSignal, CalculationMode.Price, stopPrice, false);
EnterLong(quantity, LongSignal);
}
}
private int ToTicks(double price)
{
return (int)Math.Round(price / TickSize);
}
#region Properties
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Edge Zone (Ticks)", Description = "Levels at the bar's high or low searched for aggression", Order = 1, GroupName = "Absorption")]
public int EdgeZoneTicks { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Min Aggressor Volume", Description = "Minimum aggressive volume at the level", Order = 2, GroupName = "Absorption")]
public int MinAggressorVolume { get; set; }
[NinjaScriptProperty]
[Range(0.05, 1.0)]
[Display(Name = "Min Delta Ratio", Description = "Level delta divided by level volume", Order = 3, GroupName = "Absorption")]
public double MinDeltaRatio { get; set; }
[NinjaScriptProperty]
[Range(0, int.MaxValue)]
[Display(Name = "Close Reject (Ticks)", Description = "Minimum distance of the close from the level", Order = 4, GroupName = "Absorption")]
public int CloseRejectTicks { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Confirm Bars", Description = "Bars without a breach before a zone is confirmed", Order = 5, GroupName = "Absorption")]
public int ConfirmBars { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Breach (Ticks)", Description = "Ticks beyond the level that cancel the zone", Order = 6, GroupName = "Absorption")]
public int BreachTicks { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Trading", Description = "Submit orders on confirmed zones; off = chart marks only", Order = 1, GroupName = "Orders")]
public bool EnableTrading { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Stop Buffer (Ticks)", Description = "Stop distance beyond the absorbed level", Order = 2, GroupName = "Orders")]
public int StopBufferTicks { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Target (Ticks)", Description = "Profit target distance from the fill", Order = 3, GroupName = "Orders")]
public int TargetTicks { get; set; }
#endregion
}
}
Parameter ledger
| Parameter | Default | What it controls |
|---|---|---|
| Edge Zone | 2 ticks | How many levels at the bar's high (or low) are searched |
| Min Aggressor Volume | 300 | Volume at the ask (or bid) needed at one price |
| Min Delta Ratio | 0.6 | Level delta as a share of that level's volume |
| Close Reject | 2 ticks | How far the close must finish from the level |
| Confirm Bars | 2 | Bars the level must hold before the diamond appears |
| Breach | 1 tick | Trading this far beyond the level cancels the zone |
| Enable Trading | Off | Chart marks only until switched on |
| Stop Buffer | 4 ticks | Stop distance beyond the level |
| Target | 8 ticks | Fixed target from the fill |
| Calculate | On bar close | Profiles are read once per completed bar |
The volume threshold carries the most weight. On a busy index future, 300 contracts at one tick on a 2,000-tick bar is ordinary; on a thinner market it may be the whole bar. Set it from the instrument's typical per-level volume, then let the session profile's agreement test and the confirmation bars filter out the noise.
Taking it further
The per-price profile opens up more than the absorption marks. Plotting the session delta at the current price as a separate series would show, at a glance, whether price is trading into a level that buyers or sellers have been leaning on. Comparing the price of each confirmed BA zone with the session's highest-volume price could separate absorption at the edge of the day's range from absorption in the middle of it. Each of these is a small change to OnBarUpdate(), because the strategy already keeps every trade's volume by price.