本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Order Flow Control Regime [Jireh]", shorttitle = "Flow Control", overlay = true, max_labels_count = 50)
// =====================================================================
// Order Flow Control Regime [Jireh]
// Colors candles by who is in control: buyers, sellers, or contested.
// Built from aggressive volume (delta), whether price is actually responding
// to that aggression, and a decaying memory of recent absorption.
// Filtered with hysteresis + confirmation so candles don't flip every bar.
// =====================================================================
// ---------- Data ----------
grpData = "Data"
srcMode = input.string("Auto", "Delta source", options = ["Auto", "Footprint", "Approximate"], group = grpData, tooltip = "Footprint = real bid/ask volume (Premium/Ultimate). Approximate = estimated from where each candle closes in its range (works on any plan). Auto = footprint when available, otherwise approximate.")
fpTicks = input.int(100, "Footprint ticks per row", minval = 1, group = grpData, tooltip = "Only bar totals are used, so a large value keeps it light. Doesn't change the result.")
// ---------- Engine ----------
grpEng = "Control engine"
len = input.int(14, "Lookback (bars)", minval = 2, group = grpEng, tooltip = "Window for aggression balance and price response.")
aggFull = input.float(0.15, "Delta ratio for full credit", minval = 0.01, step = 0.01, group = grpEng, tooltip = "Net delta / total volume over the lookback. 0.15 = buyers outpacing sellers by 15% of volume counts as full control.")
atrLen = input.int(14, "ATR length", minval = 1, group = grpEng)
moveFull = input.float(1.5, "Price move for full credit (x ATR)", minval = 0.1, step = 0.1, group = grpEng, tooltip = "Is price actually going where the aggression is pushing? Aggression without price response cancels out, which is how absorption shows up.")
smoothLen = input.int(3, "Score smoothing", minval = 1, group = grpEng)
// ---------- Absorption memory ----------
grpAbs = "Absorption memory"
absMult = input.float(2.0, "Big delta (x average)", minval = 1.0, step = 0.1, group = grpAbs, tooltip = "A bar's delta must be this many times the recent average to count as a big push.")
absLen = input.int(50, "Average delta length", minval = 5, group = grpAbs)
absDecay = input.float(0.90, "Memory decay per bar", minval = 0.5, maxval = 0.99, step = 0.01, group = grpAbs, tooltip = "How long absorption keeps influencing control. 0.90 fades over roughly 10-20 bars.")
showAbs = input.bool(true, "Show absorption dots", group = grpAbs)
// ---------- Weights ----------
grpW = "Weights"
wAgg = input.float(1.0, "Aggression (delta)", minval = 0, step = 0.1, group = grpW)
wMove = input.float(1.0, "Price response", minval = 0, step = 0.1, group = grpW)
wAbs = input.float(0.7, "Absorption memory", minval = 0, step = 0.1, group = grpW)
// ---------- Regime filter ----------
grpR = "Regime filter"
enterThr = input.int(30, "Enter control at score", minval = 1, maxval = 100, group = grpR, tooltip = "Score must reach +this for buyers or -this for sellers to take control.")
exitThr = input.int(10, "Lose control below score", minval = 0, maxval = 100, group = grpR, tooltip = "Once in control, the side keeps it until the score falls under this. The gap between enter and exit stops color flicker.")
confBars = input.int(2, "Confirmation bars", minval = 1, group = grpR, tooltip = "A change must hold this many bars before the color switches.")
// ---------- Display ----------
grpD = "Display"
candleMode = input.string("Full candle", "Candle coloring", options = ["Full candle", "Bodies only", "Off"], group = grpD, tooltip = "If full candles only show on hover, use the indicator menu: Visual order > Bring to front.")
showLabel = input.bool(true, "Show right-edge label", group = grpD)
showScore = input.bool(true, "Show score in label", group = grpD)
lblOffset = input.int(6, "Label offset (bars)", minval = 0, group = grpD)
lblSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = grpD)
// ---------- Colors ----------
grpC = "Colors"
buyCol = input.color(#00E600, "Buyers in control", group = grpC)
sellCol = input.color(#F928F5, "Sellers in control", group = grpC)
neutCol = input.color(#B2B5BE, "Contested", group = grpC)
absBuyCol = input.color(#FF9800, "Absorbed buying (dot)", group = grpC)
absSellCol = input.color(#00E5FF, "Absorbed selling (dot)", group = grpC)
lblTxtCol = input.color(color.black, "Label text", group = grpC)
// =====================================================================
// Helpers
// =====================================================================
clip(float x) =>
math.max(-1.0, math.min(1.0, x))
// =====================================================================
// Delta
// =====================================================================
fp = request.footprint(fpTicks)
fpDelta = na(fp) ? na : fp.delta()
fpVol = na(fp) ? na : fp.buy_volume() + fp.sell_volume()
rng = high - low
apxDelta = rng > 0 ? volume * (2 * close - high - low) / rng : 0.0
useFP = srcMode == "Footprint" or (srcMode == "Auto" and not na(fpDelta))
d = nz(useFP ? fpDelta : apxDelta)
v = nz(useFP ? fpVol : volume)
// =====================================================================
// Engine
// =====================================================================
// 1) Aggression balance
sumD = math.sum(d, len)
sumV = math.sum(v, len)
aggRatio = sumV > 0 ? sumD / sumV : 0.0
aggScore = clip(aggRatio / aggFull)
// 2) Price response
atr = ta.atr(atrLen)
moveScore = atr > 0 ? clip((close - close[len]) / (atr * moveFull)) : 0.0
// 3) Absorption memory
absThr = ta.sma(math.abs(d), absLen) * absMult
pos = rng > 0 ? (close - low) / rng : 0.5
buyAbs = d >= absThr and close <= open and pos < 0.5 // big buying, candle failed to rise: bearish
sellAbs = -d >= absThr and close >= open and pos > 0.5 // big selling, candle failed to fall: bullish
var float absBias = 0.0
absBias := absBias * absDecay + (sellAbs ? 1.0 : 0.0) - (buyAbs ? 1.0 : 0.0)
absScore = clip(absBias)
// Combined score (-100 sellers ... +100 buyers)
wSum = math.max(wAgg + wMove + wAbs, 0.0001)
raw = 100 * (wAgg * aggScore + wMove * moveScore + wAbs * absScore) / wSum
score = ta.ema(raw, smoothLen)
// =====================================================================
// Regime filter (hysteresis + confirmation)
// state: 1 buyers, -1 sellers, 0 contested
// =====================================================================
var int st = 0
var int cand = 0
var int cnt = 0
int target = st
if st == 1
target := score < exitThr ? (score <= -enterThr ? -1 : 0) : 1
else if st == -1
target := score > -exitThr ? (score >= enterThr ? 1 : 0) : -1
else
target := score >= enterThr ? 1 : score <= -enterThr ? -1 : 0
if target != st
if target == cand
cnt += 1
else
cand := target
cnt := 1
if cnt >= confBars
st := target
cnt := 0
else
cand := st
cnt := 0
col = st == 1 ? buyCol : st == -1 ? sellCol : neutCol
// =====================================================================
// Plots
// =====================================================================
barcolor(candleMode == "Bodies only" ? col : na, title = "Control candles (bodies)")
fullOn = candleMode == "Full candle"
plotcandle(fullOn ? open : na, fullOn ? high : na, fullOn ? low : na, fullOn ? close : na, title = "Control candles (full)", color = col, wickcolor = col, bordercolor = col)
plotshape(showAbs and buyAbs, "Absorbed buying", shape.circle, location.abovebar, absBuyCol, size = size.tiny)
plotshape(showAbs and sellAbs, "Absorbed selling", shape.circle, location.belowbar, absSellCol, size = size.tiny)
// Label
stateName = st == 1 ? "BUYERS" : st == -1 ? "SELLERS" : "CONTESTED"
lblSz = lblSize == "Tiny" ? size.tiny : lblSize == "Normal" ? size.normal : size.small
var label lbl = na
if barstate.islast
label.delete(lbl)
if showLabel
txt = stateName + (showScore ? " " + str.tostring(math.round(score)) : "")
tip = "Control: " + stateName +
"\nScore: " + str.tostring(math.round(score)) + " (-100 sellers / +100 buyers)" +
"\nDelta ratio (" + str.tostring(len) + " bars): " + str.tostring(aggRatio * 100, "#.#") + "%" +
"\nPrice response: " + str.tostring(moveScore * 100, "#") +
"\nAbsorption bias: " + str.tostring(absScore * 100, "#") +
"\nData: " + (useFP ? "footprint" : "approximate")
lbl := label.new(bar_index + lblOffset, close, txt, style = label.style_label_left, color = col, textcolor = lblTxtCol, size = lblSz, tooltip = tip)
// =====================================================================
// Alerts (set to "Once per bar close")
// =====================================================================
alertcondition(st == 1 and st[1] != 1, "Buyers take control", "Flow Control: BUYERS in control on {{ticker}} {{interval}}")
alertcondition(st == -1 and st[1] != -1, "Sellers take control", "Flow Control: SELLERS in control on {{ticker}} {{interval}}")
alertcondition(st == 0 and st[1] != 0, "Contested", "Flow Control: CONTESTED on {{ticker}} {{interval}}")
alertcondition(buyAbs, "Absorbed buying", "Flow Control: big buying absorbed on {{ticker}} {{interval}}")
alertcondition(sellAbs, "Absorbed selling", "Flow Control: big selling absorbed on {{ticker}} {{interval}}")