GEX Gamma Grid v2
THE SOURCE FILE /code/gex-gamma.pine
Read the file, copy it, or download the exact bytes served at this address. No performance figure is claimed on this page.
//@version=6
// =============================================================================
// DAAVILE — GEX Gamma Grid v2
// -----------------------------------------------------------------------------
// GAMMA, IN FOREX WORDS
// Dealers who are long gamma buy dips and sell rallies, so they smooth a move.
// Dealers who are short gamma chase a move, so they amplify it. This chart has
// no options feed, so gamma is a candles-only proxy: where price closed inside
// its own bar (CLV) times relative volume, summed over a window.
// In v2 gamma is a SOFT overlay. It nudges grid spacing by at most 20%. It can
// never block, size or cancel an entry. The breakout stays the only boss.
//
// Core: previous completed bar high/low plus one tick, 20-21 exchange session,
// ATR(3) stop, N-leg fixed-risk grid, one shared exit at the average price,
// trail, backstop stop, adverse-close trigger, four prop risk stops.
//
// DAAVILE-owned code. NOT backtest-validated. No performance is claimed.
// =============================================================================
strategy("GEX Gamma Grid v2", overlay=true,
initial_capital = 100000,
commission_type = strategy.commission.percent,
commission_value = 0,
pyramiding = 4,
process_orders_on_close = false)
//--- Eight editable inputs — the entire trader-facing control panel -----------
allowBuys = input.bool(true, "Allow buys")
allowSells = input.bool(true, "Allow sells")
useGrid = input.bool(true, "Grid entries (pyramid)")
gridLevels = input.int(4, "Grid levels (1 = single entry)", minval=1, maxval=4)
addMode = input.string("Positive", "Add direction", options=["Positive", "Negative"])
riskPercent = input.float(5.0, "Max risk per trade, % of equity", minval=0.01, maxval=100.0)
trailStep = input.float(2.0, "Trail step, % from the extreme", minval=0.0)
entryTrigger = input.string("Immediately", "Entry trigger", options=["Immediately", "NextBar"])
//--- Direct-code values — visible here, but they take no settings slot --------
bufferPoints = 1.0 // edge in ticks, one tick stops same-price fills
atrLen = 3 // short ATR keeps the stop near the signal bar
sessionStart = 20 // exchange hour the window opens
sessionEnd = 21 // exchange hour the window closes, flat outside
stopAtr = 0.5 // stop distance in ATR, sizes the whole idea
targetAtr = 1.0 // fixed target in ATR, about 2:1 versus the stop
oneTradeDay = false // extra trade cap off, prop stops already cover days
//--- Gamma overlay constants — candles only, never an entry gate --------------
volLookback = 20 // bars in the average-volume baseline
gexWindow = 24 // bars summed into one gamma reading
volRatioCap = 3.0 // caps one volume spike so it cannot dominate
proxyThreshold = 0.35 // reading where gamma starts to lean on spacing
maxTilt = 0.20 // at most 20% spacing change, zero permission change
//--- Exit policy — active, one path, no dormant layer switch ------------------
trailActivateAtr = 1.0 // start trailing after 1 ATR of profit
basicSlAtr = 8.0 // disaster brake, far outside the working stop
closeMode = "Percent" // adverse-close unit, switchable in source
closeTrigger = 3.0 // give back 3% from the peak and leave
//--- Four prop risk stops — first is sizing, other three are daily halts ------
maxTotalRiskPct = 25.0 // cap on open stop loss across our own positions
profitToStopPct = 50.0 // daily profit that locks the book for the day
ddToStopPct = 20.0 // daily drawdown that locks the book for the day
//--- Helpers: floor only. An unaffordable grid is rejected, never rounded up --
floorLegQty(rawQty, levels, minQty) =>
levels > 0 and minQty > 0.0 and rawQty >= levels * minQty ? math.floor(rawQty / levels / minQty + 1e-9) * minQty : 0.0
// Adverse excursion from the peak. Points divide by tick size, percent by peak.
closeTriggerHit(extreme, current, isLong, mode, trigger, pointSize) =>
adverse = isLong ? extreme - current : current - extreme
distance = mode == "Percent" ? (extreme != 0.0 ? adverse / math.abs(extreme) * 100.0 : 0.0) : (pointSize > 0.0 ? adverse / pointSize : na)
not na(distance) and distance >= trigger
// Risk uses the real stop price we will send, not the configured risk input.
ownedRiskPct(posQty, averagePrice, stopPrice, pointValue, equity) =>
if posQty == 0.0
0.0
else if na(stopPrice) or stopPrice <= 0.0 or equity <= 0.0
maxTotalRiskPct + 1.0 // no owned stop means unbounded, not zero risk
else
stopDistance = posQty > 0.0 ? math.max(averagePrice - stopPrice, 0.0) : math.max(stopPrice - averagePrice, 0.0)
math.abs(posQty) * stopDistance * pointValue / equity * 100.0
inSession(h) =>
sessionStart < sessionEnd ? h >= sessionStart and h < sessionEnd : h >= sessionStart or h < sessionEnd
// A strategy owns only its synthetic position: close its own entry IDs only.
cancelLongEntries() =>
strategy.cancel("L1")
strategy.cancel("L2")
strategy.cancel("L3")
strategy.cancel("L4")
cancelShortEntries() =>
strategy.cancel("S1")
strategy.cancel("S2")
strategy.cancel("S3")
strategy.cancel("S4")
cancelAllEntries() =>
cancelLongEntries()
cancelShortEntries()
closeOwnedPosition() =>
if strategy.position_size > 0
strategy.close("L1", comment="Owned long exit")
strategy.close("L2", comment="Owned long exit")
strategy.close("L3", comment="Owned long exit")
strategy.close("L4", comment="Owned long exit")
else if strategy.position_size < 0
strategy.close("S1", comment="Owned short exit")
strategy.close("S2", comment="Owned short exit")
strategy.close("S3", comment="Owned short exit")
strategy.close("S4", comment="Owned short exit")
liquidateOwned() =>
cancelAllEntries()
closeOwnedPosition()
//--- Bookkeeping ---------------------------------------------------------------
dayKey = math.floor(time / 86400000) // one integer per calendar day
var float lastTradeDay = na
var float dayStartEquity = na
var float guardDay = na
var float avgPx = na
var bool dayHalted = false
var float trailPeak = na
var int buyStreak = 0
var int sellStreak = 0
atrVal = ta.atr(atrLen)
minDist = syminfo.mintick
buf = bufferPoints * minDist
stopDist = stopAtr * atrVal
tgtDist = targetAtr * atrVal
// The signal is the last CLOSED bar only, the forming bar is never used.
signalHigh = high[1]
signalLow = low[1]
buyStop = signalHigh + buf
sellStop = signalLow - buf
riskMoney = strategy.equity * riskPercent / 100.0 // whole idea, not per leg
qtyRaw = stopDist > 0.0 ? riskMoney / stopDist : 0.0
minQty = syminfo.mincontract
qtyBudget = minQty > 0.0 ? math.floor(qtyRaw / minQty + 1e-9) * minQty : 0.0
activeLvls = useGrid ? gridLevels : 1
perQty = floorLegQty(qtyBudget, activeLvls, minQty)
gridStep = activeLvls > 0 ? stopDist / activeLvls : 0.0
dirSign = addMode == "Negative" ? -1 : 1
//--- Gamma proxy: closed-bar CLV x capped relative volume, summed -------------
clv = high == low ? 0.0 : ((close - low) - (high - close)) / (high - low)
volSma = ta.sma(volume, volLookback)
volRatio = na(volSma) or volSma == 0.0 ? 1.0 : math.min(volume / volSma, volRatioCap)
netGex = math.sum(clv * volRatio, gexWindow)
gammaTilt = math.max(-1.0, math.min(1.0, netGex / (2.0 * proxyThreshold)))
// Positive gamma favors longs: tighter long adds, wider short adds. Never a gate.
longSpacingFactor = 1.0 - maxTilt * gammaTilt
shortSpacingFactor = 1.0 + maxTilt * gammaTilt
//--- Confirmed bars only -------------------------------------------------------
if barstate.isconfirmed
if na(dayStartEquity) or dayKey != guardDay
dayStartEquity := strategy.equity // prop-book floor resets each day
guardDay := dayKey
dayHalted := false
// Opposite-side-only OCO: same-side ladder legs survive a fill.
if strategy.position_size == 0
cancelAllEntries()
trailPeak := na
else if strategy.position_size > 0
cancelShortEntries()
else
cancelLongEntries()
if not inSession(hour(time))
liquidateOwned()
else
if strategy.position_size > 0
avgPx := strategy.position_avg_price
trailPeak := na(trailPeak) or high > trailPeak ? high : trailPeak
else if strategy.position_size < 0
avgPx := strategy.position_avg_price
trailPeak := na(trailPeak) or low < trailPeak ? low : trailPeak
float ownedStop = na
if strategy.position_size > 0
ownedStop := avgPx - stopDist
ownedStop := math.max(ownedStop, avgPx - basicSlAtr * atrVal) // disaster brake
if trailPeak - avgPx >= trailActivateAtr * atrVal
// Percent keeps the trail meaningful across symbols with different tick sizes.
trailStop = trailPeak * (1.0 - trailStep / 100.0)
ownedStop := math.max(ownedStop, trailStop)
else if strategy.position_size < 0
ownedStop := avgPx + stopDist
ownedStop := math.min(ownedStop, avgPx + basicSlAtr * atrVal)
if avgPx - trailPeak >= trailActivateAtr * atrVal
trailStop = trailPeak * (1.0 + trailStep / 100.0)
ownedStop := math.min(ownedStop, trailStop)
// One shared stop and target, applied to every leg at the average price.
if strategy.position_size > 0
llim = targetAtr > 0.0 ? avgPx + tgtDist : na
strategy.exit("LX1", "L1", stop=ownedStop, limit=llim)
if activeLvls >= 2
strategy.exit("LX2", "L2", stop=ownedStop, limit=llim)
if activeLvls >= 3
strategy.exit("LX3", "L3", stop=ownedStop, limit=llim)
if activeLvls >= 4
strategy.exit("LX4", "L4", stop=ownedStop, limit=llim)
if strategy.position_size < 0
slim = targetAtr > 0.0 ? avgPx - tgtDist : na
strategy.exit("SX1", "S1", stop=ownedStop, limit=slim)
if activeLvls >= 2
strategy.exit("SX2", "S2", stop=ownedStop, limit=slim)
if activeLvls >= 3
strategy.exit("SX3", "S3", stop=ownedStop, limit=slim)
if activeLvls >= 4
strategy.exit("SX4", "S4", stop=ownedStop, limit=slim)
dayPnlPct = dayStartEquity > 0.0 ? (strategy.equity - dayStartEquity) / dayStartEquity * 100.0 : 0.0
openRiskPct = ownedRiskPct(strategy.position_size, avgPx, ownedStop, syminfo.pointvalue, strategy.equity)
if dayPnlPct >= profitToStopPct or dayPnlPct <= -ddToStopPct or openRiskPct > maxTotalRiskPct
dayHalted := true // a halt is sticky until the next calendar day
if dayHalted
liquidateOwned()
// Adverse-close trigger runs only when a position exists.
if strategy.position_size > 0 and closeTriggerHit(trailPeak, close, true, closeMode, closeTrigger, minDist)
liquidateOwned()
if strategy.position_size < 0 and closeTriggerHit(trailPeak, close, false, closeMode, closeTrigger, minDist)
liquidateOwned()
dayIsFree = not oneTradeDay or na(lastTradeDay) or dayKey != lastTradeDay
distOk = not na(stopDist) and stopDist >= minDist and (targetAtr == 0.0 or tgtDist >= minDist)
if strategy.position_size == 0 and dayIsFree and distOk and perQty > 0.0 and not dayHalted
needBars = entryTrigger == "Immediately" ? 0 : 1
buySetup = buyStop > close + minDist and allowBuys
sellSetup = sellStop < close - minDist and allowSells
buyStreak := buySetup ? buyStreak + 1 : 0
sellStreak := sellSetup ? sellStreak + 1 : 0
// Gamma changes only WHERE adds sit, never IF the idea is allowed.
longStep = gridStep * longSpacingFactor
shortStep = gridStep * shortSpacingFactor
if buyStreak > needBars
strategy.entry("L1", strategy.long, qty=perQty, stop=buyStop)
if activeLvls >= 2
strategy.entry("L2", strategy.long, qty=perQty, stop=buyStop + dirSign * longStep)
if activeLvls >= 3
strategy.entry("L3", strategy.long, qty=perQty, stop=buyStop + dirSign * longStep * 2)
if activeLvls >= 4
strategy.entry("L4", strategy.long, qty=perQty, stop=buyStop + dirSign * longStep * 3)
lastTradeDay := dayKey
if sellStreak > needBars
strategy.entry("S1", strategy.short, qty=perQty, stop=sellStop)
if activeLvls >= 2
strategy.entry("S2", strategy.short, qty=perQty, stop=sellStop - dirSign * shortStep)
if activeLvls >= 3
strategy.entry("S3", strategy.short, qty=perQty, stop=sellStop - dirSign * shortStep * 2)
if activeLvls >= 4
strategy.entry("S4", strategy.short, qty=perQty, stop=sellStop - dirSign * shortStep * 3)
lastTradeDay := dayKey
//--- Visuals: gamma is shown for review but has no order authority -------------
plot(buyStop, "Buy stop", color=color.new(color.teal, 0), linewidth=1)
plot(sellStop, "Sell stop", color=color.new(color.red, 0), linewidth=1)
plot(netGex, "Gamma proxy", display=display.data_window)
plot(longSpacingFactor, "Long spacing factor", display=display.data_window)
plot(shortSpacingFactor, "Short spacing factor", display=display.data_window)
#THE CLAIM
No profit-factor, return or win-rate claim is made here.
#SOURCE
Pine v6 · 271 lines · /code/gex-gamma.pine · category Options & evaluation.
#NOTES FROM THE REPO
The **8 editable inputs and their defaults are unchanged** in meaning, except the trail-step label now states percent because that is the active unit. Grid 4, risk 5%, Positive adds, immediate entry, buys and sells allowed.
Scripts are provided for research; publication is not a performance claim. No backtest result is implied by this file. Not financial advice.
Source is provided for research, not as a performance claim. Paste into a Pine editor before use. Not financial advice.