aggressor_flow_lib

gmoneybtc · library · 1222 行 · 点赞 7 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
 
// @description Aggressor Flow engine. Turns one chart bar of order flow into
// a fixed set of named signals, tracks the price zones those signals create,
// and scores every signal against what price actually did next. Built for
// the Aggressor Volume Delta indicator and for any script that wants the
// same engine.
//
// Contents:
//   - two engines that fill one BarFlow object (footprint, sub-bar tick rule)
//   - classify(): named bar signals; a zone book for zone events
//   - a triple-barrier scorecard that tests every signal against a baseline
//   - per-row arrays on BarFlow (rowDn / rowBuy / rowSell), filled by both
//     engines, so a caller can read the footprint at ANY price
//   - LEVEL HOOKS: levelRead() -- the footprint at a level the CALLER owns
//     (a range high, an opening-range edge, a session level...), and
//     LevelWatch -- a stateful tracker of touches, holds, breaks and
//     retests of one level
//   - TRADE-MANAGEMENT HOOKS: stopBehind(), opposingStack()
//   - EVENT MASKS: signalMask() / levelMask() pack events into one number a
//     plot can carry to another script through input.source()
//
// The hooks are CONFLUENCE inputs, not signals: a script that already has a
// reason to trade at a level asks the footprint a specific question there.
// Test any use of them in your own backtest before relying on it.
//
// HOW THE FOOTPRINT IS CLASSIFIED. request.footprint() splits volume into
// buy and sell by comparing each intrabar's close with its open (a tick
// rule on tick intrabars, coarser intrabars further back in history). That
// is an approximation of the aggressor side, not an exchange flag. It reads
// the CHART symbol only, and older bars are rebuilt from coarser intrabars,
// so a bar's live and historical footprints can differ.
//
// ============================================================================
// TWO ENGINES, ONE SHAPE
// ============================================================================
// Both engines fill the same BarFlow object, so every signal, zone and score
// downstream is computed by identical code no matter where the data came from.
//
//   fromFootprint()  The platform's volume footprint: buy/sell volume per
//                    price row, per bar. Needs a plan with footprint access.
//   fromSubBars()    A pseudo-footprint for everyone else: 1-second sub-bars
//                    classified by the tick rule, then binned into rows by
//                    each sub-bar's CLOSE. A 1s bar that traded at several
//                    prices has all its volume booked to its last one, so this
//                    is coarser than a real footprint, and the imbalance flags
//                    it produces are this library's own, not the platform's.
//
// THIS LIBRARY NEVER CALLS request.footprint() ITSELF, deliberately. The
// consumer makes the call and passes the object in. Two reasons:
//   1. Pine allows ONE request.footprint() per script. A library that made
//      the call would take that slot from every strategy that imports it.
//   2. The call needs a plan with footprint access. Keeping it in the
//      consumer keeps it in one visible place, so a script without that
//      access can import this library and
//      use the sub-bar path without ever touching the gated function.
//
// No inputs in here either -- Pine forbids input.*() in libraries. Every
// threshold lives in Config, which the consumer builds from its own inputs.
//
// ============================================================================
// THE SIGNALS -- what each one CLAIMS, and the rule that tests the claim
// ============================================================================
// Bullish and bearish alternate by construction, so signalDir(id) is simply
// +1 for even ids and -1 for odd. Names say who did what, because "absorption
// sellers" can be read either way round: here "sellers absorbed" means sell
// aggression was soaked up by passive buyers, which is BULLISH.
//
// Shared per-bar measures:
//   dz    bar delta as a z-score against its own recent history
//   rvol  bar volume / its moving average
//   clv   close location in the bar's range, 0 = at the low, 1 = at the high
//   edge  the bottom (or top) `edgeRows` footprint rows of the bar
//
//  0 SELLERS ABSORBED (bull)  One side made the effort; the other side
//      soaked it up. Effort without result, measured directly:
//        effort  bar delta as a z-score, at least absMinEffortZ in size
//        normal  the move this much delta usually buys ON THIS instrument,
//                recently: a rolling least-squares fit of (close - open) on
//                delta over zLen bars, beta = cov / var, and the fitted
//                prediction  expected = mean move + beta x (delta - mean)
//        result  rho = (close - open) / expected, the fraction of that
//                normal move that actually happened
//      Absorbed when rho <= absMaxResult. Negative rho means price moved
//      AGAINST the aggressor. Skipped where beta <= 0 (the normal
//      relationship has broken down) or where the fit does not expect the
//      aggressor's move at all -- effort cannot be "absorbed" if it was
//      never expected to work.
//      Where in the bar it happened is NOT a condition -- a passive order
//      can sit anywhere. The footprint supplies location instead: the zone
//      is drawn on the row where the absorbed side's volume was heaviest,
//      i.e. the price that did the absorbing. Why it was absorbed (iceberg,
//      resting limit, market maker) is unknowable from the tape and the
//      engine does not guess. The bullish arrow is a HYPOTHESIS about what
//      comes next -- passive buyers held -- and the scorecard tests it; it
//      is not part of the definition.
//  1 BUYERS ABSORBED (bear)   Mirror: buy effort soaked up by passive sellers.
//
//  2 SELLERS EXHAUSTED (bull) A new swing low printed on thin selling.
//      New `swingLen` low, the lowest row traded <= exhThinRow x the average
//      row, and bar delta is less negative than exhFade x the most negative
//      delta of the previous exhFadeBars. Distinct from absorption: here
//      price DID extend, but the aggression behind it dried up.
//  3 BUYERS EXHAUSTED (bear)  Mirror at a new swing high.
//
//  4 BUYER CONTINUATION (bull) Initiative buying that is making progress.
//      Stacked buy imbalances >= minStack rows, dz >= contMinDz, clv >=
//      contMinClv, close above the prior bar's high, rvol >= contMinRvol.
//  5 SELLER CONTINUATION (bear) Mirror.
//
//  6 SELLERS TRAPPED (bull)   Aggressive sellers made a new low, and the very
//      next bar closed back above that bar's high -- they are now offside.
//  7 BUYERS TRAPPED (bear)    Mirror.
//
//  8 DELTA FLIP UP (bull)     Buyers took back over: a positive bar with
//      dz >= flipMinDz after `flipRun` straight negative bars.
//  9 DELTA FLIP DOWN (bear)   Mirror.
//
// ZONE EVENTS. Signals 0, 1 and stacked imbalances create zones; so does a
// single row trading heavyRowMult x the bar's average row ("heavy level").
// A zone is demand (+1) or supply (-1). Every bar, zones are tested BEFORE
// the bar's own new zones are added -- a zone cannot be defended by the bar
// that created it.
//
// 10/11 DEFENDED     Price traded into the zone and closed back out on its
//                    own side, with bar delta agreeing (or an absorption
//                    signal on that side).
// 12/13 RECLAIMED    A zone breached within `reclaimBars` is closed back
//                    through by its own side. The sweep-and-reclaim.
// 14/15 BREACHED     Closed through the far edge with delta agreeing. 14 is
//                    buyers breaking supply (bull); 15 sellers breaking
//                    demand (bear). A breach not reclaimed in time flips the
//                    zone's polarity -- broken demand becomes supply.
// 16/17 HEAVY LEVEL HELD  A heavy-level zone defended for the 2nd+ time.
//
// ON "ICEBERGS", plainly: an iceberg is defined by the ORDER BOOK -- displayed
// size refreshing at a price while trades execute against it. Pine has no
// order book and no order IDs, so no Pine script can see an iceberg. What a
// footprint DOES show is the traded side of one: a price that absorbs
// outsized volume again and again without giving way. Signals 16/17 are that,
// and nothing more. They are equally consistent with a stack of ordinary
// resting orders or a market maker leaning on a level -- the tape cannot tell
// those apart, and neither can this.
//
// repeatPrints() is the one tool here that could say more: fed trade-by-trade
// data it finds identical sizes printing at one price, the signature of an
// algo slicing a parent order. It needs tick-level input, and whether tick
// data is served through request.security_lower_tf(..., "1T") is
// UNVERIFIED -- it compiles, which proves nothing about runtime.
//
// ============================================================================
// SCORING -- how "fires when it should" gets measured instead of asserted
// ============================================================================
// Scorecard puts a triple barrier on every fired signal: from the signal
// bar's close, does price reach +barrierAtr x ATR in the signal's direction
// before -barrierAtr x ATR against it, within `horizon` bars? Timeouts count
// as misses. Evaluation starts on the NEXT bar -- the signal is only known at
// its own close. A bar that touches both barriers counts as a MISS -- the
// stop is assumed to have been hit first.
//
// Every bar is also scored as if it had fired both ways. That baseline is
// the number every hit rate has to beat: a signal at 55% against a 54%
// baseline has told you nothing. Results split into the early and late half
// of the loaded history, so a threshold tuned by eye on one half can be
// checked on the other.
//
// Contract for callers: call classify() and step() on EVERY bar. classify()
// holds ta.* state that silently corrupts if any bar is skipped.
library("aggressor_flow_lib")
 
// ============================================================================
// Types
// ============================================================================
 
// @type One chart bar's order flow, in a shape both engines fill.
// @field ok True only when the bar actually has flow data behind it.
// @field source 1 = footprint, 2 = sub-bar tick rule.
// @field samples Sub-bars read (sub-bar engine only; 0 for footprint).
export type BarFlow
    bool  ok = false
    int   source = 0
    int   samples = 0
    float buy = 0.0
    float sell = 0.0
    float delta = 0.0
    float total = 0.0
    int   rows = 0
    float rowSize = na
    float lowEdgeBuy = 0.0
    float lowEdgeSell = 0.0
    float highEdgeBuy = 0.0
    float highEdgeSell = 0.0
    float lowRowVol = 0.0
    float highRowVol = 0.0
    float avgRowVol = 0.0
    bool  unfinishedLow = false
    bool  unfinishedHigh = false
    float poc = na
    float vah = na
    float val = na
    int   stackBuy = 0
    float stackBuyTop = na
    float stackBuyBot = na
    int   stackSell = 0
    float stackSellTop = na
    float stackSellBot = na
    float maxRowVol = 0.0
    float maxRowPrice = na
    float maxRowDelta = 0.0
    float maxBuyRowVol = 0.0
    float maxBuyRowPrice = na
    float maxSellRowVol = 0.0
    float maxSellRowPrice = na
    array<float> rowDn
    array<float> rowBuy
    array<float> rowSell
 
// @type Every threshold the engine uses. Defaults are the starting tune; see
// the header for what each one means.
export type Config
    int   zLen = 50
    int   volLen = 50
    int   swingLen = 20
    int   edgeRows = 2
    float absMinRvol = 1.0
    float absMinEffortZ = 1.0
    float absMaxResult = 0.25
    float exhThinRow = 0.5
    float exhFade = 0.5
    int   exhFadeBars = 3
    int   minStack = 3
    float contMinDz = 1.0
    float contMinClv = 0.6
    float contMinRvol = 1.0
    float trapDz = 1.5
    int   flipRun = 3
    float flipMinDz = 0.5
    float heavyRowMult = 3.0
    float heavyMinRvol = 1.5
    float maxZoneAtr = 1.5
    float strictPct = 0.0
    int   strictMemory = 200
 
// @type The engine's verdict on one bar. `fire` and `score` are indexed by
// signal id 0-9 for generic consumers; the named fields are the same values.
export type Signals
    bool  ok = false
    bool  sellersAbsorbed = false
    bool  buyersAbsorbed = false
    bool  sellersExhausted = false
    bool  buyersExhausted = false
    bool  buyerContinuation = false
    bool  sellerContinuation = false
    bool  sellersTrapped = false
    bool  buyersTrapped = false
    bool  flipUp = false
    bool  flipDown = false
    bool  heavyLevel = false
    bool  newLow = false
    bool  newHigh = false
    float dz = na
    float rvol = na
    float clv = na
    float atr = na
    float rho = na
    array<bool>  fire
    array<float> score
 
// @type A price zone created by an order-flow event.
// @field side +1 demand (buyers' zone), -1 supply.
// @field kind 1 absorption, 2 stacked imbalance, 3 heavy level.
// @field state 0 active, 1 breached and awaiting reclaim.
export type Zone
    float top
    float bot
    int   side
    int   kind
    int   born
    int   state = 0
    int   breachBar = na
    int   touches = 0
    float vol = 0.0
 
export type ZoneBook
    array<Zone> zones
    int maxZones = 30
    int life = 300
    int reclaimBars = 5
 
// @type What happened to zones on one bar. top/bot are the last zone that
// produced an event, for labelling.
export type ZoneEvents
    bool  defendedBull = false
    bool  defendedBear = false
    bool  reclaimedBull = false
    bool  reclaimedBear = false
    bool  breachedBull = false
    bool  breachedBear = false
    bool  heavyHeldBull = false
    bool  heavyHeldBear = false
    float top = na
    float bot = na
 
// @type One open triple-barrier test. id < 0 marks a baseline probe.
export type Probe
    int   id
    int   dir
    float up
    float dn
    int   bar
    int   half
 
export type Scorecard
    int   nIds
    int   horizon
    float barrierAtr
    array<Probe> live
    array<int> win
    array<int> tot
    array<int> baseWin
    array<int> baseTot
    array<int> bars
 
// Not exported: a wrapper so each signal can keep its own score history.
// Pine has no array<array<float>>.
type ScoreHist
    array<float> v
 
// ============================================================================
// Signal catalogue
// ============================================================================
 
// @function Number of scored signal ids (0-9 bar signals, 10-17 zone events).
export signalCount() =>
    18
 
// @function Direction of a signal id: +1 bullish, -1 bearish.
export signalDir(int id) =>
    id % 2 == 0 ? 1 : -1
 
// @function Short display name for a signal id.
export signalName(int id) =>
    switch id
        0  => "sellers absorbed"
        1  => "buyers absorbed"
        2  => "sellers exhausted"
        3  => "buyers exhausted"
        4  => "buyer continuation"
        5  => "seller continuation"
        6  => "sellers trapped"
        7  => "buyers trapped"
        8  => "delta flip up"
        9  => "delta flip down"
        10 => "zone defended"
        11 => "zone defended"
        12 => "zone reclaimed"
        13 => "zone reclaimed"
        14 => "supply breached"
        15 => "demand breached"
        16 => "heavy level held"
        17 => "heavy level held"
        => "?"
 
// ============================================================================
// Internal helpers
// ============================================================================
 
// Longest run of true values; returns [length, firstIndex, lastIndex].
f_bestRun(array<bool> fl) =>
    int best = 0
    int bestEnd = -1
    int run = 0
    int n = array.size(fl)
    if n > 0
        for i = 0 to n - 1
            if array.get(fl, i)
                run += 1
                if run > best
                    best := run
                    bestEnd := i
            else
                run := 0
    [best, bestEnd - best + 1, bestEnd]
 
// Value area by expanding outward from the POC row toward whichever
// neighbour row carries more volume. Returns [lowRow, highRow].
f_valueArea(array<float> vols, int pocIdx, float pct) =>
    int n = array.size(vols)
    float target = array.sum(vols) * pct / 100.0
    int lo = pocIdx
    int hi = pocIdx
    float acc = array.get(vols, pocIdx)
    while acc < target and (lo > 0 or hi < n - 1)
        float vDn = lo > 0 ? array.get(vols, lo - 1) : -1.0
        float vUp = hi < n - 1 ? array.get(vols, hi + 1) : -1.0
        if vUp >= vDn
            hi += 1
            acc += vUp
        else
            lo -= 1
            acc += vDn
    [lo, hi]
 
f_initHist(int n) =>
    array<ScoreHist> h = array.new<ScoreHist>()
    for i = 0 to n - 1
        array.push(h, ScoreHist.new(array.new<float>()))
    h
 
f_safeDiv(float a, float b) =>
    b != 0 and not na(b) and not na(a) ? a / b : 0.0
 
// ============================================================================
// Engine 1: footprint
// ============================================================================
 
// @function Reads a volume footprint into a BarFlow.
// @param fp The object from the CONSUMER's request.footprint() call, or na.
// @param edgeRows How many rows at each end of the bar count as "the edge".
export fromFootprint(footprint fp, int edgeRows) =>
    BarFlow f = BarFlow.new()
    if not na(fp)
        array<volume_row> rows = footprint.rows(fp)
        int n = array.size(rows)
        if n > 0
            f.ok := true
            f.source := 1
            f.buy := footprint.buy_volume(fp)
            f.sell := footprint.sell_volume(fp)
            f.delta := footprint.delta(fp)
            f.total := footprint.total_volume(fp)
            f.rows := n
            volume_row r0 = array.get(rows, 0)
            f.rowSize := volume_row.up_price(r0) - volume_row.down_price(r0)
            int e = math.min(edgeRows, n)
            array<bool> bImb = array.new<bool>(n, false)
            array<bool> sImb = array.new<bool>(n, false)
            f.rowDn := array.new<float>()
            f.rowBuy := array.new<float>()
            f.rowSell := array.new<float>()
            for i = 0 to n - 1
                volume_row r = array.get(rows, i)
                float rb = volume_row.buy_volume(r)
                float rsl = volume_row.sell_volume(r)
                float rt = rb + rsl
                array.push(f.rowDn, volume_row.down_price(r))
                array.push(f.rowBuy, rb)
                array.push(f.rowSell, rsl)
                if i < e
                    f.lowEdgeBuy += rb
                    f.lowEdgeSell += rsl
                if i >= n - e
                    f.highEdgeBuy += rb
                    f.highEdgeSell += rsl
                float mid = (volume_row.up_price(r) + volume_row.down_price(r)) / 2.0
                if rt > f.maxRowVol
                    f.maxRowVol := rt
                    f.maxRowPrice := mid
                    f.maxRowDelta := rb - rsl
                if rb > f.maxBuyRowVol
                    f.maxBuyRowVol := rb
                    f.maxBuyRowPrice := mid
                if rsl > f.maxSellRowVol
                    f.maxSellRowVol := rsl
                    f.maxSellRowPrice := mid
                array.set(bImb, i, volume_row.has_buy_imbalance(r))
                array.set(sImb, i, volume_row.has_sell_imbalance(r))
            volume_row rl = array.get(rows, 0)
            volume_row rh = array.get(rows, n - 1)
            f.lowRowVol := volume_row.total_volume(rl)
            f.highRowVol := volume_row.total_volume(rh)
            // Unfinished auction: both sides still trading at the extreme row.
            f.unfinishedLow := volume_row.buy_volume(rl) > 0 and volume_row.sell_volume(rl) > 0
            f.unfinishedHigh := volume_row.buy_volume(rh) > 0 and volume_row.sell_volume(rh) > 0
            f.avgRowVol := f.total / n
            volume_row pr = footprint.poc(fp)
            f.poc := (volume_row.up_price(pr) + volume_row.down_price(pr)) / 2.0
            f.vah := volume_row.up_price(footprint.vah(fp))
            f.val := volume_row.down_price(footprint.val(fp))
            [bl, bs, be] = f_bestRun(bImb)
            f.stackBuy := bl
            if bl > 0
                f.stackBuyBot := volume_row.down_price(array.get(rows, bs))
                f.stackBuyTop := volume_row.up_price(array.get(rows, be))
            [sl, ss, se] = f_bestRun(sImb)
            f.stackSell := sl
            if sl > 0
                f.stackSellBot := volume_row.down_price(array.get(rows, ss))
                f.stackSellTop := volume_row.up_price(array.get(rows, se))
    f
 
// ============================================================================
// Engine 2: sub-bar tick rule (pseudo-footprint)
// ============================================================================
 
// @function Builds a pseudo-footprint from lower-timeframe sub-bars.
// @param closes Sub-bar closes from request.security_lower_tf().
// @param vols Sub-bar volumes, same call.
// @param seed The prior chart bar's close, to classify the first sub-bar.
// @param rowSize Row height in price (ticksPerRow x syminfo.mintick).
// @param imbPct Diagonal imbalance threshold, percent (300 = 3x).
// @param vaPct Value-area percentage.
// @param edgeRows Rows at each end that count as the edge.
export fromSubBars(array<float> closes, array<float> vols, float seed, float rowSize, float imbPct, float vaPct, int edgeRows) =>
    BarFlow f = BarFlow.new()
    // `and` short-circuits in Pine v6, so array.size() is never reached on an
    // na array -- which is a runtime error, not a zero.
    if not na(closes) and not na(vols) and array.size(closes) > 0 and rowSize > 0
        float rng = high - low
        // Cap the row count. A bar hundreds of rows tall is a bar whose rows
        // are too thin to mean anything, and the loops below scale with it.
        int n = math.min(300, int(math.floor(rng / rowSize)) + 1)
        float rs = n >= 300 ? rng / 299.0 : rowSize
        array<float> bRow = array.new<float>(n, 0.0)
        array<float> sRow = array.new<float>(n, 0.0)
        float prevC = seed
        bool lastUp = true
        int used = 0
        int m = array.size(closes)
        for i = 0 to m - 1
            float cc = array.get(closes, i)
            float vv = array.get(vols, i)
            if not na(cc) and not na(vv)
                used += 1
                bool isBuy = cc > prevC ? true : cc < prevC ? false : lastUp
                lastUp := isBuy
                prevC := cc
                int idx = math.max(0, math.min(n - 1, int(math.floor((cc - low) / rs))))
                if isBuy
                    array.set(bRow, idx, array.get(bRow, idx) + vv)
                else
                    array.set(sRow, idx, array.get(sRow, idx) + vv)
        if used > 0
            f.ok := true
            f.source := 2
            f.samples := used
            f.rows := n
            f.rowSize := rs
            f.rowBuy := bRow
            f.rowSell := sRow
            f.rowDn := array.new<float>(n, 0.0)
            for i = 0 to n - 1
                array.set(f.rowDn, i, low + i * rs)
            f.buy := array.sum(bRow)
            f.sell := array.sum(sRow)
            f.delta := f.buy - f.sell
            f.total := f.buy + f.sell
            f.avgRowVol := f.total / n
            int e = math.min(edgeRows, n)
            array<float> tRow = array.new<float>(n, 0.0)
            int pocIdx = 0
            for i = 0 to n - 1
                float rb = array.get(bRow, i)
                float rsl = array.get(sRow, i)
                float rt = rb + rsl
                array.set(tRow, i, rt)
                if i < e
                    f.lowEdgeBuy += rb
                    f.lowEdgeSell += rsl
                if i >= n - e
                    f.highEdgeBuy += rb
                    f.highEdgeSell += rsl
                float mid = low + (i + 0.5) * rs
                if rt > f.maxRowVol
                    f.maxRowVol := rt
                    f.maxRowPrice := mid
                    f.maxRowDelta := rb - rsl
                    pocIdx := i
                if rb > f.maxBuyRowVol
                    f.maxBuyRowVol := rb
                    f.maxBuyRowPrice := mid
                if rsl > f.maxSellRowVol
                    f.maxSellRowVol := rsl
                    f.maxSellRowPrice := mid
            f.lowRowVol := array.get(tRow, 0)
            f.highRowVol := array.get(tRow, n - 1)
            f.unfinishedLow := array.get(bRow, 0) > 0 and array.get(sRow, 0) > 0
            f.unfinishedHigh := array.get(bRow, n - 1) > 0 and array.get(sRow, n - 1) > 0
            f.poc := f.maxRowPrice
            [vl, vh] = f_valueArea(tRow, pocIdx, vaPct)
            f.val := low + vl * rs
            f.vah := low + (vh + 1) * rs
            // Diagonal imbalances, the footprint convention: a row's buying
            // against the row BELOW's selling, and a row's selling against
            // the row ABOVE's buying. The floor at a quarter of the average
            // row stops a 2-lot over a 0-lot counting as a 300% imbalance.
            float floorV = 0.25 * f.avgRowVol
            array<bool> bImb = array.new<bool>(n, false)
            array<bool> sImb = array.new<bool>(n, false)
            for i = 0 to n - 1
                float rb = array.get(bRow, i)
                float rsl = array.get(sRow, i)
                if i > 0 and rb >= floorV and rb >= array.get(sRow, i - 1) * imbPct / 100.0
                    array.set(bImb, i, true)
                if i < n - 1 and rsl >= floorV and rsl >= array.get(bRow, i + 1) * imbPct / 100.0
                    array.set(sImb, i, true)
            [bl, bs, be] = f_bestRun(bImb)
            f.stackBuy := bl
            if bl > 0
                f.stackBuyBot := low + bs * rs
                f.stackBuyTop := low + (be + 1) * rs
            [sl, ss, se] = f_bestRun(sImb)
            f.stackSell := sl
            if sl > 0
                f.stackSellBot := low + ss * rs
                f.stackSellTop := low + (se + 1) * rs
    f
 
// ============================================================================
// Classification
// ============================================================================
 
// @function Classifies one bar. Call on EVERY bar: the ta.* state inside
// silently corrupts if any bar is skipped, and none of those calls sit
// behind a condition for exactly that reason.
// @param atrLen A separate argument, not a Config field, because ta.atr()
//   needs a compile-time `simple int` and every UDT field is `series`. Pass
//   an input.int() straight through.
export classify(BarFlow f, Config c, simple int atrLen) =>
    Signals s = Signals.new()
    s.ok := f.ok
    // na, not zero, on bars without data, so the rolling statistics warm up
    // honestly instead of averaging in a run of fake zeros.
    float d = f.ok ? f.delta : na
    float v = f.ok ? f.total : na
    float dm = ta.sma(d, c.zLen)
    float dsd = ta.stdev(d, c.zLen)
    float vm = ta.sma(v, c.volLen)
    float atr = ta.atr(atrLen)
    float priorLow = ta.lowest(low, c.swingLen)[1]
    float priorHigh = ta.highest(high, c.swingLen)[1]
    float priorMinD = ta.lowest(nz(d), c.exhFadeBars)[1]
    float priorMaxD = ta.highest(nz(d), c.exhFadeBars)[1]
    float negRun = math.sum(nz(d) < 0 ? 1.0 : 0.0, c.flipRun)[1]
    float posRun = math.sum(nz(d) > 0 ? 1.0 : 0.0, c.flipRun)[1]
    float dz = dsd > 0 ? (d - dm) / dsd : na
    // Effort vs result. dp is the bar's own price result; beta is how far
    // price normally moves per unit of delta here, recently. Population
    // covariance over population variance -- ta.stdev defaults to the
    // population form, so the two use the same normalisation. na on data
    // holes, so the fit warms up honestly after a gap.
    float dp = f.ok ? close - open : na
    float mP = ta.sma(dp, c.zLen)
    float mDP = ta.sma(d * dp, c.zLen)
    float beta = dsd > 0 ? (mDP - dm * mP) / (dsd * dsd) : na
    // The fitted line's own prediction, intercept included: the mean move
    // plus beta times how far this bar's delta sits from the mean delta.
    // Dropping the intercept (beta x delta alone) would skew "normal" on any
    // trending stretch, where price drifts with no net delta behind it.
    float expMove = na(beta) ? na : mP + beta * (d - dm)
    float rho = not na(beta) and beta > 0 and not na(expMove) and expMove != 0 ? dp / expMove : na
    float rvol = vm > 0 ? v / vm : na
    float rng = high - low
    float clv = rng > 0 ? (close - low) / rng : 0.5
    bool newLow = low < priorLow
    bool newHigh = high > priorHigh
    float dz1 = dz[1]
    bool newLow1 = newLow[1]
    bool newHigh1 = newHigh[1]
 
    bool okz = f.ok and not na(dz) and not na(rvol)
    bool thinLow = f.ok and f.avgRowVol > 0 and f.lowRowVol <= c.exhThinRow * f.avgRowVol
    bool thinHigh = f.ok and f.avgRowVol > 0 and f.highRowVol <= c.exhThinRow * f.avgRowVol
 
    bool absFit = okz and not na(rho) and rvol >= c.absMinRvol
    // expMove must point the aggressor's way. On a strong trend the intercept
    // can make the fit predict an UP move even for a heavily sold bar, and
    // "the effort was absorbed" means nothing if the effort was never
    // expected to work in the first place.
    bool r0 = absFit and d < 0 and expMove < 0 and dz <= -c.absMinEffortZ and rho <= c.absMaxResult
    bool r1 = absFit and d > 0 and expMove > 0 and dz >= c.absMinEffortZ and rho <= c.absMaxResult
    bool r2 = okz and newLow and thinLow and priorMinD < 0 and d > c.exhFade * priorMinD
    bool r3 = okz and newHigh and thinHigh and priorMaxD > 0 and d < c.exhFade * priorMaxD
    bool r4 = okz and f.stackBuy >= c.minStack and dz >= c.contMinDz and clv >= c.contMinClv and close > high[1] and rvol >= c.contMinRvol
    bool r5 = okz and f.stackSell >= c.minStack and dz <= -c.contMinDz and clv <= 1.0 - c.contMinClv and close < low[1] and rvol >= c.contMinRvol
    bool r6 = okz and newLow1 and not na(dz1) and dz1 <= -c.trapDz and close > high[1]
    bool r7 = okz and newHigh1 and not na(dz1) and dz1 >= c.trapDz and close < low[1]
    bool r8 = okz and d > 0 and dz >= c.flipMinDz and negRun >= c.flipRun
    bool r9 = okz and d < 0 and dz <= -c.flipMinDz and posRun >= c.flipRun
 
    // Strength per signal. Only compared against the same signal's own past
    // values, so the units need to be consistent per signal, not across them.
    float thinL = f.avgRowVol > 0 ? 1.0 - math.min(1.0, f.lowRowVol / f.avgRowVol) : 0.0
    float thinH = f.avgRowVol > 0 ? 1.0 - math.min(1.0, f.highRowVol / f.avgRowVol) : 0.0
    float fadeL = priorMinD < 0 ? math.max(0.0, 1.0 - nz(d) / priorMinD) : 0.0
    float fadeH = priorMaxD > 0 ? math.max(0.0, 1.0 - nz(d) / priorMaxD) : 0.0
    float adz = math.abs(nz(dz))
    float rv = nz(rvol)
    array<bool> raw = array.from(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9)
    float missing = na(rho) ? 0.0 : math.min(3.0, math.max(0.0, 1.0 - rho))
    array<float> sc = array.from(adz * missing, adz * missing, thinL + fadeL, thinH + fadeH, adz * f.stackBuy * rv, adz * f.stackSell * rv, math.abs(nz(dz1)) * f_safeDiv(close - high[1], atr), math.abs(nz(dz1)) * f_safeDiv(low[1] - close, atr), adz, adz)
 
    // Strictness gate: fire only when this instance is in the top
    // (100 - strictPct)% of the signal's own recent qualifying instances.
    // Off at 0. Needs 20 prior instances before it gates anything.
    var array<ScoreHist> hist = f_initHist(10)
    array<bool> fire = array.new<bool>(10, false)
    for i = 0 to 9
        bool r = array.get(raw, i)
        float scv = array.get(sc, i)
        bool pass = r
        array<float> h = array.get(hist, i).v
        if r and c.strictPct > 0 and array.size(h) >= 20
            pass := scv >= array.percentile_nearest_rank(h, c.strictPct)
        if r and barstate.isconfirmed
            array.push(h, scv)
            if array.size(h) > c.strictMemory
                array.shift(h)
        array.set(fire, i, pass)
 
    s.sellersAbsorbed := array.get(fire, 0)
    s.buyersAbsorbed := array.get(fire, 1)
    s.sellersExhausted := array.get(fire, 2)
    s.buyersExhausted := array.get(fire, 3)
    s.buyerContinuation := array.get(fire, 4)
    s.sellerContinuation := array.get(fire, 5)
    s.sellersTrapped := array.get(fire, 6)
    s.buyersTrapped := array.get(fire, 7)
    s.flipUp := array.get(fire, 8)
    s.flipDown := array.get(fire, 9)
    s.heavyLevel := okz and f.rows >= 3 and f.maxRowVol >= c.heavyRowMult * f.avgRowVol and rv >= c.heavyMinRvol
    s.rho := rho
    s.newLow := newLow
    s.newHigh := newHigh
    s.dz := dz
    s.rvol := rvol
    s.clv := clv
    s.atr := atr
    s.fire := fire
    s.score := sc
    s
 
// ============================================================================
// Zones
// ============================================================================
 
// @function Creates an empty zone book.
export newZoneBook(int maxZones, int life, int reclaimBars) =>
    ZoneBook.new(array.new<Zone>(), maxZones, life, reclaimBars)
 
// Adds a zone, merging into an overlapping active zone of the same side
// rather than stacking duplicates -- unless the merge would grow the zone
// taller than maxZoneAtr x ATR, at which point it is a different level.
f_addZone(ZoneBook b, float top, float bot, int side, int kind, float vol, float maxH) =>
    bool merged = false
    int n = array.size(b.zones)
    if n > 0 and not na(top) and not na(bot)
        for i = 0 to n - 1
            Zone z = array.get(b.zones, i)
            if not merged and z.state == 0 and z.side == side and top >= z.bot and bot <= z.top
                float nt = math.max(z.top, top)
                float nb = math.min(z.bot, bot)
                if na(maxH) or nt - nb <= maxH
                    z.top := nt
                    z.bot := nb
                    z.vol += vol
                    z.kind := math.max(z.kind, kind)
                    z.born := bar_index
                    merged := true
    if not merged and not na(top) and not na(bot) and top > bot
        array.push(b.zones, Zone.new(top, bot, side, kind, bar_index, 0, na, 0, vol))
        if array.size(b.zones) > b.maxZones
            array.shift(b.zones)
 
// @function Advances every zone by one bar, then adds the zones this bar
// created. Returns what happened. Call on every bar with data.
export method update(ZoneBook b, BarFlow f, Signals s, Config c) =>
    ZoneEvents ev = ZoneEvents.new()
    if f.ok
        int n = array.size(b.zones)
        if n > 0
            // Backwards, so removing a zone does not skip the next one.
            for j = 0 to n - 1
                int i = n - 1 - j
                Zone z = array.get(b.zones, i)
                if bar_index - z.born > b.life
                    array.remove(b.zones, i)
                    continue
                bool touched = low <= z.top and high >= z.bot
                if z.state == 0
                    if z.side == 1
                        if close < z.bot and f.delta < 0
                            z.state := 1
                            z.breachBar := bar_index
                            ev.breachedBear := true
                            ev.top := z.top
                            ev.bot := z.bot
                        else if touched and close > z.top and (f.delta > 0 or s.sellersAbsorbed)
                            z.touches += 1
                            z.vol += f.total
                            ev.defendedBull := true
                            ev.top := z.top
                            ev.bot := z.bot
                            if z.kind == 3 and z.touches >= 2
                                ev.heavyHeldBull := true
                    else
                        if close > z.top and f.delta > 0
                            z.state := 1
                            z.breachBar := bar_index
                            ev.breachedBull := true
                            ev.top := z.top
                            ev.bot := z.bot
                        else if touched and close < z.bot and (f.delta < 0 or s.buyersAbsorbed)
                            z.touches += 1
                            z.vol += f.total
                            ev.defendedBear := true
                            ev.top := z.top
                            ev.bot := z.bot
                            if z.kind == 3 and z.touches >= 2
                                ev.heavyHeldBear := true
                else
                    int since = bar_index - z.breachBar
                    if z.side == 1 and since <= b.reclaimBars and close > z.top and f.delta > 0
                        z.state := 0
                        ev.reclaimedBull := true
                        ev.top := z.top
                        ev.bot := z.bot
                    else if z.side == -1 and since <= b.reclaimBars and close < z.bot and f.delta < 0
                        z.state := 0
                        ev.reclaimedBear := true
                        ev.top := z.top
                        ev.bot := z.bot
                    else if since > b.reclaimBars
                        // Not reclaimed in time: polarity flip. Broken demand
                        // becomes supply and vice versa -- the classic
                        // support-turned-resistance, and a fresh zone.
                        z.side := -z.side
                        z.state := 0
                        z.born := bar_index
                        z.touches := 0
 
        // New zones last, so none can be tested on the bar that made it.
        float maxH = na(s.atr) ? na : c.maxZoneAtr * s.atr
        float rs = nz(f.rowSize)
        // Absorption zones sit on the row where the ABSORBED side traded most
        // -- the price the passive side defended -- `edgeRows` rows tall.
        float halfH = c.edgeRows * rs / 2.0
        if s.sellersAbsorbed and not na(f.maxSellRowPrice)
            f_addZone(b, f.maxSellRowPrice + halfH, f.maxSellRowPrice - halfH, 1, 1, f.total, maxH)
        if s.buyersAbsorbed and not na(f.maxBuyRowPrice)
            f_addZone(b, f.maxBuyRowPrice + halfH, f.maxBuyRowPrice - halfH, -1, 1, f.total, maxH)
        if f.stackBuy >= c.minStack
            f_addZone(b, f.stackBuyTop, f.stackBuyBot, 1, 2, f.total, maxH)
        if f.stackSell >= c.minStack
            f_addZone(b, f.stackSellTop, f.stackSellBot, -1, 2, f.total, maxH)
        if s.heavyLevel and not na(f.maxRowPrice)
            f_addZone(b, f.maxRowPrice + rs / 2.0, f.maxRowPrice - rs / 2.0, close >= f.maxRowPrice ? 1 : -1, 3, f.maxRowVol, maxH)
    ev
 
// @function All 18 scored signals for one bar, indexed by signal id.
export fireArray(Signals s, ZoneEvents z) =>
    array<bool> a = array.copy(s.fire)
    array.push(a, z.defendedBull)
    array.push(a, z.defendedBear)
    array.push(a, z.reclaimedBull)
    array.push(a, z.reclaimedBear)
    array.push(a, z.breachedBull)
    array.push(a, z.breachedBear)
    array.push(a, z.heavyHeldBull)
    array.push(a, z.heavyHeldBear)
    a
 
// ============================================================================
// Scorecard
// ============================================================================
 
// @function Creates a scorecard for `nIds` signals.
// @param horizon Bars a signal has to reach its target.
// @param barrierAtr Target and stop distance, in ATRs, either side of close.
export newScorecard(int nIds, int horizon, float barrierAtr) =>
    Scorecard.new(nIds, horizon, barrierAtr, array.new<Probe>(), array.new<int>(nIds * 2, 0), array.new<int>(nIds * 2, 0), array.new<int>(4, 0), array.new<int>(4, 0), array.new<int>(2, 0))
 
f_bump(array<int> a, int k) =>
    array.set(a, k, array.get(a, k) + 1)
 
// @function Resolves open probes against this bar, then opens new ones for
// this bar's fired signals and for the baseline. Call ONCE per CONFIRMED bar
// -- an unconfirmed bar's high and low are still moving.
// @param fired Fired flags by signal id.
// @param atr ATR at this bar.
// @param half 0 for the early half of history, 1 for the late half.
// @param canOpen False on bars with no flow data. Open tests still resolve on
//   those bars, but no new ones start -- the baseline has to be scored over
//   exactly the bars a signal COULD have fired on, or the comparison between
//   them is not like for like.
export method step(Scorecard sc, array<bool> fired, float atr, int half, bool canOpen) =>
    int n = array.size(sc.live)
    if n > 0
        for j = 0 to n - 1
            int i = n - 1 - j
            Probe p = array.get(sc.live, i)
            if bar_index > p.bar
                bool up = high >= p.up
                bool dn = low <= p.dn
                // Both touched on one bar resolves as a MISS: stop first.
                int res = p.dir == 1 ? (dn ? 2 : up ? 1 : 0) : (up ? 2 : dn ? 1 : 0)
                if res == 0 and bar_index - p.bar >= sc.horizon
                    res := 2
                if res != 0
                    if p.id < 0
                        int k = (p.dir == 1 ? 0 : 1) * 2 + p.half
                        f_bump(sc.baseTot, k)
                        if res == 1
                            f_bump(sc.baseWin, k)
                    else
                        int k = p.id * 2 + p.half
                        f_bump(sc.tot, k)
                        if res == 1
                            f_bump(sc.win, k)
                    array.remove(sc.live, i)
    if canOpen and not na(atr) and atr > 0
        f_bump(sc.bars, half)
        float u = close + sc.barrierAtr * atr
        float dd = close - sc.barrierAtr * atr
        array.push(sc.live, Probe.new(-1, 1, u, dd, bar_index, half))
        array.push(sc.live, Probe.new(-1, -1, u, dd, bar_index, half))
        int m = math.min(sc.nIds, array.size(fired))
        for id = 0 to m - 1
            if array.get(fired, id)
                array.push(sc.live, Probe.new(id, signalDir(id), u, dd, bar_index, half))
 
// @function Results for one signal in one half.
// @returns [resolved count, hit %, baseline hit % for its direction, fires per 1,000 bars]
export method stats(Scorecard sc, int id, int half) =>
    int k = id * 2 + half
    int t = array.get(sc.tot, k)
    int bk = (signalDir(id) == 1 ? 0 : 1) * 2 + half
    int bt = array.get(sc.baseTot, bk)
    int bars = array.get(sc.bars, half)
    float hit = t > 0 ? 100.0 * array.get(sc.win, k) / t : na
    float base = bt > 0 ? 100.0 * array.get(sc.baseWin, bk) / bt : na
    float rate = bars > 0 ? 1000.0 * t / bars : na
    [t, hit, base, rate]
 
// ============================================================================
// HOOKS -- the part other scripts integrate with
// ============================================================================
// Contract, all hooks:
//   - classify() still runs on EVERY bar at global scope (ta.* state).
//   - LevelWatch.update() runs on EVERY CONFIRMED bar (it keeps its own
//     previous close and touch state; skipping a bar corrupts it). It holds
//     no ta.* state, so gating it with barstate.isconfirmed is correct.
//   - levelRead(), stopBehind(), opposingStack() are stateless: call them
//     whenever, including inside a condition.
//   - Every hook reads the bar it is called on. On the live bar the footprint
//     is still moving: act on confirmed bars.
 
// @type Thresholds for the level hooks.
// @field tolTicks A bar touches a level when its range comes within this many ticks of it.
// @field fbMinPenTicks Failed break: price went at least this far through the level...
// @field fbMinBeyond ...with at least this share of the bar's volume traded beyond it...
// @field absMinHeavyX Absorbed: the heaviest row at the level is at least this multiple of the bar's median non-empty row...
// @field absMinInto ...at least this share of the volume at the level was aggression INTO it...
// @field absMaxPenTicks ...and price got no further than this through it.
// @field retestBars A break must be retested within this many bars to count.
export type LevelConfig
    int   tolTicks = 2
    float fbMinPenTicks = 2.0
    float fbMinBeyond = 0.30
    float absMinHeavyX = 3.0
    float absMinInto = 0.65
    float absMaxPenTicks = 4.0
    int   retestBars = 60
 
// @type The footprint at one level, on one bar.
// @field ok True when the bar had flow data AND side is +1/-1 (else only the price fields are set).
// @field side +1 = the level is BELOW price (a support test), -1 = above (resistance). Caller-supplied.
// @field touched The bar's range came within tolTicks of the level.
// @field held Closed back on the side it came from.
// @field broke Closed through the level by more than tolTicks.
// @field penTicks How far price went through the level, in ticks (negative = stopped short of it).
// @field beyondShare Share of the bar's volume in rows beyond the level (0-1).
// @field intoShare Of the volume in rows AT the level, the share that was aggression INTO it (selling into support, buying into resistance).
// @field heavyX The heaviest row at the level / the bar's median non-empty row.
// @field defenseDelta side x bar delta. Positive = net aggression was on the DEFENDING side.
// @field failedBreak touched, held, penTicks >= fbMinPenTicks, beyondShare >= fbMinBeyond, defenseDelta < 0: aggressors pushed through, volume traded beyond, and price came back -- they are offside.
// @field absorbed touched, held, heavyX >= absMinHeavyX, intoShare >= absMinInto, penTicks <= absMaxPenTicks: heavy aggression into the level, and it held.
export type LevelRead
    bool  ok = false
    float level = na
    int   side = 0
    bool  touched = false
    bool  held = false
    bool  broke = false
    float penTicks = na
    float beyondShare = na
    float intoShare = na
    float heavyX = na
    float defenseDelta = na
    bool  failedBreak = false
    bool  absorbed = false
 
// @function Which side a level is being approached from: +1 if the previous
// close was above it (support test), -1 if below, 0 if exactly on it. Pass
// close[1] from GLOBAL scope -- a history reference inside a conditional
// call is unreliable in Pine.
export approachSide(float level, float prevClose) =>
    na(level) or na(prevClose) ? 0 : prevClose > level ? 1 : prevClose < level ? -1 : 0
 
// @function The footprint at a caller-owned level on this bar. Stateless.
// @param f This bar's BarFlow (from fromFootprint or fromSubBars).
// @param level The level's price.
// @param side +1 support test (level below price), -1 resistance. See approachSide().
// @param lc Thresholds.
// @returns LevelRead. Rows are matched by price, so row order does not matter.
export levelRead(BarFlow f, float level, int side, LevelConfig lc) =>
    LevelRead r = LevelRead.new()
    float tol = lc.tolTicks * syminfo.mintick
    r.level := level
    r.side := side
    if not na(level) and side != 0
        r.touched := low <= level + tol and high >= level - tol
        r.held := side == 1 ? close > level : close < level
        r.broke := side == 1 ? close < level - tol : close > level + tol
        r.penTicks := (side == 1 ? level - low : high - level) / syminfo.mintick
        if f.ok and not na(f.rowDn) and not na(f.rowSize)
            int n = array.size(f.rowDn)
            if n > 0
                array<float> tots = array.new<float>()
                float bandTot = 0.0
                float bandInto = 0.0
                float bandMax = 0.0
                float beyond = 0.0
                for i = 0 to n - 1
                    float dn = array.get(f.rowDn, i)
                    float up = dn + f.rowSize
                    float rb = array.get(f.rowBuy, i)
                    float rsl = array.get(f.rowSell, i)
                    float rt = rb + rsl
                    if rt > 0
                        array.push(tots, rt)
                    if dn <= level + tol and up >= level - tol
                        bandTot += rt
                        bandInto += side == 1 ? rsl : rb
                        bandMax := math.max(bandMax, rt)
                    float mid = (dn + up) / 2.0
                    if (side == 1 and mid < level) or (side == -1 and mid > level)
                        beyond += rt
                float med = array.size(tots) > 0 ? array.median(tots) : na
                r.ok := true
                r.intoShare := bandTot > 0 ? bandInto / bandTot : na
                r.heavyX := not na(med) and med > 0 ? bandMax / med : na
                r.beyondShare := f.total > 0 ? beyond / f.total : na
                r.defenseDelta := side * f.delta
                r.failedBreak := r.touched and r.held and r.penTicks >= lc.fbMinPenTicks and not na(r.beyondShare) and r.beyondShare >= lc.fbMinBeyond and r.defenseDelta < 0
                r.absorbed := r.touched and r.held and not na(r.heavyX) and r.heavyX >= lc.absMinHeavyX and not na(r.intoShare) and r.intoShare >= lc.absMinInto and r.penTicks <= lc.absMaxPenTicks
    r
 
// @type State for tracking one level through time. Make it with
// newLevelWatch(), keep it in a `var`, point it at a price with setLevel(),
// and call update() on every confirmed bar.
export type LevelWatch
    float level = na
    bool  prevTouched = true
    float prevClose = na
    int   touches = 0
    int   pendingDir = 0
    int   pendingBar = na
 
// @type What happened at a watched level on one bar.
// @field fresh A new touch: this bar touched and the previous one did not.
// @field touchN Touches since the level was set (1 = first touch).
// @field read The footprint read for the fresh touch (all na/false when fresh is false).
// @field retest The first bar to touch the level again within retestBars of a break, closing on the BREAK side.
// @field retestDir Direction of the break being retested: +1 up through resistance, -1 down through support.
// @field retestWithDelta A retest whose bar delta points in the break direction.
export type LevelEvent
    bool fresh = false
    int  touchN = 0
    LevelRead read
    bool held = false
    bool broke = false
    bool failedBreak = false
    bool absorbed = false
    bool retest = false
    int  retestDir = 0
    bool retestWithDelta = false
 
// @function A LevelWatch with no level yet.
export newLevelWatch() =>
    LevelWatch.new()
 
// @function Points the watch at a level. A CHANGED price resets the touch
// count and any pending retest -- a new level is a new level. The first bar
// after a reset cannot be a fresh touch.
export method setLevel(LevelWatch w, float level) =>
    // Pine comparisons against na are false, so a first level (w.level na)
    // needs its own test or it would never be set.
    if na(w.level) != na(level) or (not na(level) and level != w.level)
        w.level := level
        w.touches := 0
        w.pendingDir := 0
        w.pendingBar := na
        w.prevTouched := true
    w
 
// @function Advances the watch by one CONFIRMED bar. Call it on every one.
// A retest is resolved BEFORE this bar's own touch is read, so a bar can be
// both the retest of an earlier break and a fresh touch.
export method update(LevelWatch w, BarFlow f, LevelConfig lc) =>
    LevelEvent ev = LevelEvent.new()
    ev.read := LevelRead.new()
    float L = w.level
    if not na(L)
        float tol = lc.tolTicks * syminfo.mintick
        bool touched = low <= L + tol and high >= L - tol
        if w.pendingDir != 0
            if bar_index - w.pendingBar > lc.retestBars
                w.pendingDir := 0
            else if touched and bar_index > w.pendingBar
                bool holdBreak = w.pendingDir == -1 ? close < L : close > L
                if holdBreak
                    ev.retest := true
                    ev.retestDir := w.pendingDir
                    ev.retestWithDelta := f.ok and w.pendingDir * f.delta > 0
                w.pendingDir := 0
        if touched and not w.prevTouched and not na(w.prevClose)
            int side = w.prevClose > L ? 1 : w.prevClose < L ? -1 : 0
            if side != 0
                w.touches += 1
                LevelRead r = levelRead(f, L, side, lc)
                ev.fresh := true
                ev.touchN := w.touches
                ev.read := r
                ev.held := r.held
                ev.broke := r.broke
                ev.failedBreak := r.failedBreak
                ev.absorbed := r.absorbed
                if r.broke
                    w.pendingDir := -side
                    w.pendingBar := bar_index
        w.prevTouched := touched
    w.prevClose := close
    ev
 
// @function A protective stop placed behind the row that did the absorbing
// on this bar: for a long, below the row where SELLING was heaviest (the
// passive buyers held there); for a short, above the heaviest BUYING row.
// Untested as a stop rule -- compare it with your own stop on the same
// entries before using it. It can sit on the wrong side of price; check it
// against the entry.
// @param dir +1 long, -1 short.
// @param padTicks Extra distance beyond the row, in ticks.
// @returns Stop price, or na when the bar has no flow data.
export stopBehind(BarFlow f, int dir, float padTicks) =>
    float pad = padTicks * syminfo.mintick
    float half = nz(f.rowSize) / 2.0
    f.ok ? (dir == 1 ? f.maxSellRowPrice - half - pad : f.maxBuyRowPrice + half + pad) : na
 
// @function True when this bar printed a stacked imbalance AGAINST a
// position in direction `dir` -- an exit or tighten-stop cue (untested).
export opposingStack(BarFlow f, int dir, int minStack) =>
    f.ok and (dir == 1 ? f.stackSell >= minStack : f.stackBuy >= minStack)
 
f_bit(int id) =>
    int(math.pow(2, id))
 
// @function Packs fired signal flags (index = signal id) into one integer:
// bit k set = signal k fired. Plot it (display.data_window) and another
// script reads it with input.source() and maskHas().
export signalMask(array<bool> fired) =>
    int m = 0
    int n = array.size(fired)
    if n > 0
        for i = 0 to n - 1
            if array.get(fired, i)
                m += f_bit(i)
    m
 
// @function Packs a LevelEvent into one integer. Bits: 0 fresh touch,
// 1 held, 2 broke, 3 failed break, 4 absorbed, 5 retest, 6 retest with
// delta, 7 the touch was a support test (side +1), 8 the retest was of an
// upward break (retestDir +1).
export levelMask(LevelEvent e) =>
    int m = 0
    m += e.fresh ? f_bit(0) : 0
    m += e.held ? f_bit(1) : 0
    m += e.broke ? f_bit(2) : 0
    m += e.failedBreak ? f_bit(3) : 0
    m += e.absorbed ? f_bit(4) : 0
    m += e.retest ? f_bit(5) : 0
    m += e.retestWithDelta ? f_bit(6) : 0
    m += e.fresh and e.read.side == 1 ? f_bit(7) : 0
    m += e.retest and e.retestDir == 1 ? f_bit(8) : 0
    m
 
// @function True when bit `bit` is set in a mask from signalMask() or
// levelMask(). Reads a float source safely (plots carry floats).
export maskHas(float mask, int bit) =>
    not na(mask) and int(math.floor(mask / math.pow(2, bit))) % 2 == 1
 
// ============================================================================
// Experimental: same-size prints
// ============================================================================
 
// @function Finds the most repeated (price, size) pair among trades at or
// above minSize. Needs TRADE-LEVEL input: feed it request.security_lower_tf
// (..., "1T", [close, volume]) if tick data is served -- UNVERIFIED.
// minSize exists because one-lot trades repeat constantly and mean nothing.
// @returns [found, price, size, count]
export repeatPrints(array<float> px, array<float> vol, float minSize, int minRepeat) =>
    map<string, int> seen = map.new<string, int>()
    bool found = false
    float bestPx = na
    float bestSz = na
    int bestN = 0
    if not na(px) and not na(vol)
        int n = math.min(array.size(px), 5000)
        if n > 0
            for i = 0 to n - 1
                float p = array.get(px, i)
                float q = array.get(vol, i)
                if not na(p) and not na(q) and q >= minSize
                    string key = str.tostring(p) + "|" + str.tostring(q)
                    int cnt = (map.contains(seen, key) ? map.get(seen, key) : 0) + 1
                    map.put(seen, key, cnt)
                    if cnt > bestN
                        bestN := cnt
                        bestPx := p
                        bestSz := q
    found := bestN >= minRepeat
    [found, bestPx, bestSz, bestN]

← 返回列表