Titpaud Trend Arcs

Titpaud · study · 722 行 · 点赞 42 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Titpaud
 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Titpaud
// Titpaud Trend Arcs: curves (arcs) drawn through the pivots of one layer and projected forward as estimated
// resistance and support. TEMPORARY indicator to look at the idea on the charts before any backtest.
// v1-v5 (2026-11-06): first drafts, built inside a copy of Titpaud Pivot Channel MTF.
// v6 (2026-11-06): rewritten from scratch (own code only, no code of the channel indicator left).
//                  Living arcs: a new pivot that comes near a running arc joins it and the arc is computed again
//                  on all its pivots (one long arc instead of a new arc at each pivot). The part already drawn is
//                  never changed: only what is after the bar of the new computation is drawn again.
//                  Polarity flip: the broken arc is kept in its first color and goes on in the flip color, fed by
//                  the pivots of its new role; its projection is prolonged from the break.
//                  Merged zones between any two running arcs of the same role that agree, whatever their age.
//                  Accelerating arc = the whole pivot range on one branch that bends the way it goes; a dome or
//                  a bowl with its turn inside the pivots (e.g. computed after a top) is a turn arc, kept normal.
//                  Longer projections by default.
// v7 (2026-11-06): duplicates hidden: when two running arcs of the same role agree over their whole common projection,
//                  only the one with the most pivots is drawn (the other still counts for the merged zones and can
//                  still take new pivots). An arc born as a duplicate is never drawn; an older one stops being drawn
//                  from that bar. Arcs stop 3 ATR50 beyond their pivots by default (long flat arcs stay long, arcs
//                  that shoot up or dive stop early).
// v8 (2026-11-06): an arc changes role at each break (support, resistance, support...) instead of ending at the second
//                  break; each part keeps its color. It still ends at the end of its projection (no new pivot and no
//                  break for that long) or after the max number of role changes. The arc through the latest pivots is
//                  always computed, also when the new pivot joins an older arc (a duplicate is hidden).
// v9 (2026-11-06): curvature turns: at each new pivot, the bend of the curve through the latest pivots of that side is
//                  read (dome, flat or bowl). When it changes from dome to bowl (or bowl to dome), a label marks the turn
//                  ("both" when the other side already bends the same way) and the new arc with the new bend is drawn
//                  dashed and thicker. A turn arc is never hidden as a duplicate.
// v10 (2026-11-06): longer arcs (projection 4 x the gap between pivots, stop 5 ATR50 beyond the pivots). Confirmed arc
//                   (a later pivot joined it, or it already changed role) drawn bold; the others thin and pale (option
//                   to hide them). Accelerating arcs hidden by default. Curvature labels off by default (the dashed
//                   turn arc stays).
// v11 (2026-11-06): birth marker: a diamond where each drawn arc is born (computed for the first time). Left of it the
//                   arc is fitted on pivots already known; right of it the arc is a real forecast. Marker size and
//                   transparency adjustable (make it discreet once the settings are chosen).
// v12 (2026-11-06): one arc per new pivot (no more bundles of near-identical arcs born together): among the arcs through
//                   the latest N to M pivots, the one with the most pivots that still passes within the "joins an arc"
//                   distance of each of them is kept (a non-accelerating one first). Option to get all of them back.
// v13 (2026-11-06): an arc beyond its pivots (15 ATR50 by default, was 5) is no longer cut at once: it is cut only when it
//                   is also far from the price (5 ATR50 by default) and still going away from it. An arc coming back
//                   toward the price goes on. The projection drawn ahead still stops at that distance beyond the pivots,
//                   and is drawn further bar by bar while the arc lives.
// v14 (2026-11-06): a touch renews the projection: when the price comes to the arc (within the zone margin) without
//                   breaking it, the projection is prolonged from that bar (same length as at birth), so an arc that is
//                   still respected goes on.
// v15 (2026-11-06): the projection length is no longer capped at 499 bars in the history (the TradingView limit only
//                   holds for drawings beyond the last bar): only the part drawn ahead of the current bar is limited to
//                   499 bars, and it is drawn further as the bars come.
// v16 (2026-11-07): an arc that reaches the end of its projection while it is still coming toward the price goes on
//                   (one more average gap between its pivots at a time); it ends only when it goes away from the price.
// v17 (2026-11-07): arcs near the price go on: at the end of its projection, an arc within the "far from the price" distance
//                   is prolonged a few bars ahead, again and again (flat arcs stay alive while the price is around them).
//                   The part drawn ahead of the current bar stops where the arc goes further than that distance from the
//                   price (no more arcs shooting to the sky or diving). When a new pivot joins an arc, the new curve is
//                   joined smoothly to the old one (no more vertical steps).
// v18 (2026-11-07): the projection drawn ahead is stopped only where the arc is far from the price AND still going away
//                   from it (an arc coming back toward the price is drawn on). Arcs near the price prolonged by one
//                   average gap at a time by default (was 0.25).
// v19 (2026-11-07): Fred's defaults: stop an arc beyond its pivots by 30 ATR50 (was 15), far from the price 50 ATR50 (was 5).
// v20 (2026-11-07): "far from the price" measured at the scale of each arc: the larger of 5 ATR50 and 2 x the height of its
//                   pivots (a small arc on 1m and a big arc on 1D are judged at their own size). Flat arcs (moving less
//                   than 1 ATR50 per average gap between their pivots) always go on, whatever the distance to the price,
//                   and their projection is always drawn: the price may come back to them after a pump or a dump.
 
//@version=6
indicator("Titpaud Trend Arcs", "TitpaudARC", overlay = true, max_polylines_count = 100, max_labels_count = 500)
 
// ───────────────────────────────────── INPUTS ─────────────────────────────────────
const string G_SH = "Display"
bool   showH    = input.bool(true, "Arcs of the highs", group = G_SH, tooltip = "Arcs through the pivot highs (resistance). Display only: everything is computed anyway.")
bool   showL    = input.bool(true, "Arcs of the lows", group = G_SH, tooltip = "Arcs through the pivot lows (support).")
bool   showFlip = input.bool(true, "Broken arcs (polarity flip)", group = G_SH, tooltip = "A broken support arc goes on as resistance (other color), a broken resistance arc goes on as support. The part before the break keeps its first color.")
bool   showZ    = input.bool(true, "Merged zones", group = G_SH, tooltip = "Band where two running arcs of the same role agree, drawn from the bar where both are known. The more arcs agree, the darker.")
bool   showPast = input.bool(true, "Past merged zones", group = G_SH, tooltip = "When the arcs change (new pivot, break), the merged zones drawn so far stay faded up to that bar.")
bool   showDup  = input.bool(false, "Duplicate arcs", group = G_SH, tooltip = "Off: when two running arcs of the same role agree over their whole common projection, only the one with the most pivots is drawn. The hidden one still counts for the merged zones.")
bool   showUnc  = input.bool(true, "Unconfirmed arcs (thin and pale)", group = G_SH, tooltip = "An arc is confirmed when a later pivot comes to join it, or when it has already changed role: it is then drawn bold. Off: the unconfirmed arcs are not drawn (they still count for the merged zones).")
bool   showTurn = input.bool(true, "Curvature turn arcs (dashed)", group = G_SH, tooltip = "Where the arcs of one side change their bend (domes becoming bowls, or the other way), the new arc is drawn dashed and thicker. To be tested before any use.")
bool   showTLb  = input.bool(false, "Curvature turn labels", group = G_SH, tooltip = "Label on the pivot of each curvature turn (\"both\" when the other side already bends the same way). A turn on the highs and on the lows in the same direction hints at a reversal taking shape.")
bool   showDots = input.bool(false, "Pivot dots", group = G_SH)
bool   showBorn = input.bool(true, "Birth markers (diamond)", group = G_SH, tooltip = "Diamond on each drawn arc at the bar where it was born (when its last pivot was confirmed). Left of it the arc is fitted on pivots already known: touches there prove nothing. Right of it the arc is a real forecast.")
string bornSz   = input.string("Small", "Birth marker size", options = ["Tiny", "Small", "Normal"], group = G_SH)
int    bornTr   = input.int(0, "Birth marker transparency", minval = 0, maxval = 95, group = G_SH, tooltip = "Raise it to make the markers discreet.")
 
const string G_P = "Pivots"
string srcIn   = input.string("Wicks (high / low)", "Pivot source", options = ["Wicks (high / low)", "Candle bodies (open / close)"], group = G_P)
int    baseLen = input.int(15, "Pivot length (x1 layer)", minval = 1, maxval = 100, group = G_P, tooltip = "Bars on each side of a pivot for the x1 layer.")
string layIn   = input.string("x4", "Pivot layer", options = ["x1", "x4", "x16", "x64"], group = G_P, tooltip = "Pivot length multiplied by 1, 4, 16 or 64 (x4 = 60 bars on each side by default). The larger the layer, the fewer and bigger the swings.")
 
const string G_A = "Arcs"
int    cvMin    = input.int(3, "New arcs from N pivots", minval = 3, maxval = 8, group = G_A, tooltip = "When a new pivot joins no running arc, new arcs are computed through the latest N to M pivots of its kind (4 arcs at most). 3 = exact arc through the last three pivots, more = closest fit.")
int    cvMax    = input.int(5, "New arcs up to M pivots", minval = 3, maxval = 11, group = G_A, tooltip = "M is capped at N + 3.")
bool   oneArc   = input.bool(true, "One arc per new pivot", group = G_A, tooltip = "On: of the arcs through the latest N to M pivots, only one is made: the one with the most pivots that still passes near each of them (within the \"joins an arc\" distance), a non-accelerating one first. Off: all of them (bundles of near-identical arcs).")
float  cvAbs    = input.float(1.5, "A new pivot joins an arc if within (x ATR50)", minval = 0.1, maxval = 5.0, step = 0.1, group = G_A, tooltip = "A new pivot high joins every running resistance arc that passes at most this distance from it (pivot low: support arcs). The arc is then computed again on all its pivots, and it goes on.")
int    cvPts    = input.int(8, "Max pivots in one arc", minval = 3, maxval = 20, group = G_A, tooltip = "Beyond this number, the oldest pivot of the arc is dropped when a new one joins.")
float  cvAgree  = input.float(2.0, "Arcs agree within (x ATR50)", minval = 0.1, maxval = 5.0, step = 0.1, group = G_A, tooltip = "Two running arcs of the same role make a merged zone where they are at most this distance apart.")
float  cvW      = input.float(0.25, "Zone margin (x ATR50)", minval = 0.0, maxval = 3.0, step = 0.05, group = G_A)
float  cvProj   = input.float(4.0, "Projection (x average gap between the pivots)", minval = 0.2, maxval = 10.0, step = 0.1, group = G_A, tooltip = "Length of the projection after the bar where the arc is computed (or joined by a new pivot, or broken). 1 = the average number of bars between its pivots. Only the part drawn ahead of the last bar is limited to 499 bars (TradingView limit).")
float  cvClip   = input.float(30.0, "Stop an arc beyond its pivots by (x ATR50)", minval = 0.5, maxval = 50.0, step = 0.5, group = G_A, tooltip = "The projection drawn ahead stops at this distance above the highest or below the lowest pivot of the arc. When the price gets there, the arc goes on unless it is also far from the price (setting below) and still going away from it. Below zero an arc always stops.")
float  cvFar    = input.float(5.0, "...and far from the price by (x ATR50)", minval = 0.5, maxval = 200.0, step = 0.5, group = G_A, tooltip = "An arc beyond its pivots is cut only when it is more than this distance from the close and still going away from it.")
float  cvFarK   = input.float(2.0, "...or by (x the height of the arc's pivots)", minval = 0.0, maxval = 20.0, step = 0.5, group = G_A, tooltip = "Far from the price = the larger of the distance above (in ATR50) and this multiple of the height between the highest and the lowest pivot of the arc. The arc is judged at its own size. 0 = ATR50 only.")
bool   flatKeep = input.bool(true, "Flat arcs always go on", group = G_A, tooltip = "A flat arc (setting below) is never cut for being far from the price and is prolonged at the end of its projection, again and again: the price may come back to it after a pump or a dump. It still ends when it breaks too many times.")
float  cvFlatS  = input.float(1.0, "Flat if it moves less than (x ATR50 per average gap)", minval = 0.1, maxval = 10.0, step = 0.1, group = G_A, tooltip = "Move of the arc over one average gap between its pivots, at the current bar.")
bool   toward   = input.bool(true, "Arcs coming toward the price go on", group = G_A, tooltip = "At the end of its projection, an arc that is still coming toward the price (above it and going down, or below it and going up) is prolonged by one average gap between its pivots, again and again, until it goes away from the price, breaks or is touched.")
bool   keepNear = input.bool(true, "Arcs near the price go on", group = G_A, tooltip = "At the end of its projection, an arc that is within the \"far from the price\" distance is prolonged a few bars ahead (setting below), again and again, while the price stays around it.")
float  nearAh   = input.float(1.0, "...drawn ahead by (x average gap between the pivots)", minval = 0.05, maxval = 2.0, step = 0.05, group = G_A, tooltip = "Length of each prolongation of an arc near the price (at least 5 bars).")
bool   limFar   = input.bool(true, "Hide the projection far from the price", group = G_A, tooltip = "The part of an arc drawn ahead of the current bar stops where it is further than the \"far from the price\" distance from the close and still going away from it: arcs shooting to the sky or diving are not drawn there, arcs coming back toward the price are.")
bool   renew    = input.bool(true, "A touch renews the projection", group = G_A, tooltip = "When the price comes to a running arc (within the zone margin) without breaking it, its projection starts again from that bar.")
float  cvBrk    = input.float(0.5, "Break: close beyond the arc by (x ATR50)", minval = 0.0, maxval = 5.0, step = 0.1, group = G_A, tooltip = "Distance beyond the arc and its zone margin for a close to break it.")
string cvAcc    = input.string("Hidden", "Accelerating arcs", options = ["Faded", "Hidden", "Normal"], group = G_A, tooltip = "Accelerating arc = all its pivots on one branch that bends the way it already goes (rising faster and faster, or falling faster and faster). Their projection rarely holds. An arc whose turn lies inside its pivots (dome after a top, bowl after a bottom) is a turn arc and stays normal. Faded: faint line, no merged zone, no flip (a break ends it). Hidden: same, not drawn. Normal: like the others.")
float  cvAccMin = input.float(0.5, "Accelerating if the bend is at least (x ATR50)", minval = 0.0, maxval = 10.0, step = 0.1, group = G_A, tooltip = "Size of the bend of the arc over its pivots. Below this value the arc is almost straight and stays normal.")
int    cvMaxA   = input.int(10, "Running arcs kept (each side)", minval = 2, maxval = 20, group = G_A, tooltip = "Beyond this number the oldest running arc (accelerating ones first) stops being followed. Its drawing stays.")
int    cvFlipMax = input.int(4, "Max role changes per arc", minval = 1, maxval = 20, group = G_A, tooltip = "An arc changes role at each break (support then resistance then support...). After this number of changes, the next break ends it. It also ends at the end of its projection: no new pivot and no break for that long.")
float  cvFlat   = input.float(0.5, "Curvature turn: bend of at least (x ATR50)", minval = 0.0, maxval = 10.0, step = 0.1, group = G_A, tooltip = "The bend is read on the curve through the latest N + 1 pivots of the side. Below this value the curve counts as flat and does not change the reading: a turn is a dome followed (maybe after flat curves) by a bowl, or a bowl followed by a dome.")
int    cvKeep   = input.int(4, "Ended arcs kept on the chart (each side)", minval = 0, maxval = 20, group = G_A)
 
const string G_C = "Colors"
color  cvColH  = input.color(#FF9800, "Arcs of the highs (resistance)", group = G_C)
color  cvColL  = input.color(#00BCD4, "Arcs of the lows (support)", group = G_C)
color  cvColFR = input.color(#E040FB, "Broken support (now resistance)", group = G_C)
color  cvColFS = input.color(#B2FF59, "Broken resistance (now support)", group = G_C)
int    cvTr    = input.int(80, "Merged zone transparency (each pair of arcs)", minval = 0, maxval = 98, group = G_C, tooltip = "Each pair of agreeing arcs adds one band: where three arcs agree, three bands stack and the zone gets darker.")
 
// ───────────────────────────────────── PIVOTS ─────────────────────────────────────
bool  useBody = srcIn == "Candle bodies (open / close)"
float srcH    = useBody ? math.max(open, close) : high
float srcL    = useBody ? math.min(open, close) : low
int   lenP    = baseLen * (layIn == "x1" ? 1 : layIn == "x4" ? 4 : layIn == "x16" ? 16 : 64)
float pH      = ta.pivothigh(srcH, lenP, lenP)
float pL      = ta.pivotlow(srcL, lenP, lenP)
float atr50   = ta.atr(50)
int   cvMaxE  = math.max(cvMin, math.min(cvMax, cvMin + 3))
 
// ───────────────────────────────────── TYPES ─────────────────────────────────────
// parabola y = a + b t + c t^2, t = (bar - last pivot) / sc, sc = bars from the first to the last pivot
type Curve
    float a
    float b
    float c
    int   x0
    float sc
    float lo      // the curve stops below lo or above hi
    float hi
 
type Arc
    array<int>         px
    array<float>       py
    Curve              cv
    bool               isHi            // made from pivot highs
    bool               isRes           // current role: resistance or support
    int                flips = 0
    bool               acc   = false
    int                xd              // bar where the drawing of the current curve starts
    int                xc              // bar where the current curve was computed
    int                xe              // end of the projection
    int                xs    = na      // bar where it was broken for good (na = runs to xe)
    bool               alive = true
    array<chart.point> frz             // frozen path of its earlier versions (current color)
    polyline           pl              // current drawing
    array<polyline>    pls0            // parts before each role change (their colors)
    int                gap   = 1       // average bars between its pivots
    int                born  = na      // bar where it was created
    bool               turn  = false   // first arc of a new bend (curvature turn)
    bool               conf  = false   // confirmed: a later pivot joined it, or it changed role
    int                xh    = na      // hidden as a duplicate from this bar
    float              mky   = na      // price of the arc at its birth bar
    label              mk              // birth marker
    Curve              cvO             // previous curve, for the smooth join after a new pivot
    int                xbs   = na      // smooth join: from this bar
    int                xbl   = na      // ...to this bar
    int                xdr   = na      // last bar of the current drawing
 
type Band
    array<chart.point> top
    array<chart.point> bot
    polyline           pl
 
var array<Arc>      arcs  = array.new<Arc>()      // running arcs, oldest first
var array<Arc>      endH  = array.new<Arc>()      // ended arcs still drawn
var array<Arc>      endL  = array.new<Arc>()
var array<Band>     bndR  = array.new<Band>()     // current merged zones
var array<Band>     bndS  = array.new<Band>()
var array<polyline> bHist = array.new<polyline>() // past merged zones
var array<int>      hx    = array.new<int>()      // latest pivot highs
var array<float>    hy    = array.new<float>()
var array<int>      lx    = array.new<int>()      // latest pivot lows
var array<float>    ly    = array.new<float>()
 
// ───────────────────────────────────── CURVES ─────────────────────────────────────
f_cy(Curve cv, int x) =>
    float t = (x - cv.x0) / cv.sc
    cv.a + cv.b * t + cv.c * t * t
 
f_ok(Curve cv, float y) =>
    not na(y) and y >= cv.lo and y <= cv.hi and y > 0
 
// closest parabola through the latest n pivots (least squares, Cramer's rule); na if not enough pivots
f_fit(array<int> px, array<float> py, int n) =>
    Curve res = na
    int m = px.size()
    if m >= n and n >= 3
        int   x0 = px.get(m - 1)
        int   xf = px.get(m - n)
        float sc = math.max(1.0, float(x0 - xf))
        float S0 = 0.0
        float S1 = 0.0
        float S2 = 0.0
        float S3 = 0.0
        float S4 = 0.0
        float Y0 = 0.0
        float Y1 = 0.0
        float Y2 = 0.0
        float pmin = py.get(m - 1)
        float pmax = py.get(m - 1)
        for i = m - n to m - 1
            float t = (px.get(i) - x0) / sc
            float y = py.get(i)
            pmin := math.min(pmin, y)
            pmax := math.max(pmax, y)
            S0 += 1.0
            S1 += t
            S2 += t * t
            S3 += t * t * t
            S4 += t * t * t * t
            Y0 += y
            Y1 += y * t
            Y2 += y * t * t
        float det = S0 * (S2 * S4 - S3 * S3) - S1 * (S1 * S4 - S3 * S2) + S2 * (S1 * S3 - S2 * S2)
        if math.abs(det) > 1e-12
            float a = (Y0 * (S2 * S4 - S3 * S3) - S1 * (Y1 * S4 - S3 * Y2) + S2 * (Y1 * S3 - S2 * Y2)) / det
            float b = (S0 * (Y1 * S4 - S3 * Y2) - Y0 * (S1 * S4 - S3 * S2) + S2 * (S1 * Y2 - Y1 * S2)) / det
            float c = (S0 * (S2 * Y2 - Y1 * S3) - S1 * (S1 * Y2 - Y1 * S2) + Y0 * (S1 * S3 - S2 * S2)) / det
            res := Curve.new(a, b, c, x0, sc, pmin - cvClip * atr50, pmax + cvClip * atr50)
    res
 
// accelerating: slope b and bend c of the same sign, a real bend, and the turn of the parabola (t = -b / 2c) in the first
// quarter of the pivots or before (t <= -0.75; first pivot t = -1), so that the pivots sit on one accelerating branch
f_isAcc(Curve cv) =>
    bool same = (cv.b > 0 and cv.c > 0) or (cv.b < 0 and cv.c < 0)
    cvAcc != "Normal" and same and math.abs(cv.c) >= cvAccMin * atr50 and math.abs(cv.b) >= 1.5 * math.abs(cv.c)
 
f_gap(array<int> px) =>
    int n = px.size()
    n > 1 ? math.max(1, int((px.last() - px.first()) / (n - 1))) : 1
 
f_end(int gap) =>
    bar_index + math.max(1, int(cvProj * gap))
 
// price of an arc at bar x: its curve, joined smoothly to its previous curve just after a new pivot
f_ay(Arc a, int x) =>
    float y = f_cy(a.cv, x)
    if not na(a.cvO) and not na(a.xbl) and x < a.xbl and a.xbl > a.xbs
        float w = math.max(0.0, float(x - a.xbs) / float(a.xbl - a.xbs))
        y := f_cy(a.cvO, x) * (1.0 - w) + y * w
    y
 
// distance from the price beyond which an arc counts as far: at the scale of the arc
f_far(Arc a) =>
    math.max(cvFar * atr50, cvFarK * (a.py.max() - a.py.min()))
 
// points of an arc from xa to xb, stopped where it leaves its range (and, ahead of the current bar, too far from the price)
f_path(Arc a, int xa, int xb, array<chart.point> out, int maxK, bool lim) =>
    if xb >= xa
        int   kN = math.max(1, math.min(maxK, xb - xa))
        float d0 = na
        float yp = na
        int   xp = na
        float fd = f_far(a)
        for k = 0 to kN
            int   x  = xa + int(math.round((xb - xa) * k / kN))
            float y  = f_ay(a, x)
            float dd = math.abs(y - close)
            bool  fl = flatKeep and not na(yp) and math.abs(y - yp) / math.max(1, x - xp) * a.gap <= cvFlatS * atr50
            bool  aw = not na(d0) and dd > d0 and dd > fd and not fl
            bool okp = x <= bar_index ? (not na(y) and y > 0) : (fl or f_ok(a.cv, y)) and y > 0 and (not lim or not limFar or not aw)
            if not okp
                break
            out.push(chart.point.from_index(x, y))
            yp := y
            xp := x
            if x > bar_index
                d0 := dd
    out.size()
 
// ───────────────────────────────────── ARCS ─────────────────────────────────────
f_col(Arc a) =>
    a.flips == 0 ? (a.isHi ? cvColH : cvColL) : (a.isRes ? cvColFR : cvColFS)
 
// whole drawing of the current color: frozen path + current curve from xd to its end
f_draw(Arc a) =>
    polyline.delete(a.pl)
    a.pl := na
    label.delete(a.mk)
    a.mk := na
    bool vis = a.flips == 0 ? (a.isHi ? showH : showL) : showFlip
    bool hid = (a.acc and cvAcc == "Hidden") or (not a.conf and not a.turn and not showUnc)
    if vis and not hid
        bool  cut = not na(a.xh) and not showDup
        array<chart.point> pts = array.new<chart.point>()
        for p in a.frz
            if not cut or p.index <= a.xh
                pts.push(p)
        int xb = na(a.xs) ? a.xe : math.min(a.xe, a.xs)
        xb := math.min(xb, bar_index + 499)
        if cut
            xb := math.min(xb, a.xh)
        f_path(a, a.xd, xb, pts, 100, true)
        if pts.size() >= 2
            bool   fad = a.acc
            bool   tn  = a.turn and a.flips == 0 and showTurn and not fad
            bool   pal = not a.conf and not tn
            string sty = tn ? line.style_dashed : a.flips > 0 and not fad ? line.style_solid : line.style_dotted
            int    tr  = fad ? 70 : pal ? 60 : a.flips > 0 or tn ? 0 : 10
            int    wd  = fad or pal ? 1 : tn ? 3 : 2
            a.pl := polyline.new(pts, false, false, xloc.bar_index, color.new(f_col(a), tr), na, sty, wd)
            a.xdr := pts.last().index
            bool bornIn = not na(a.mky) and (not cut or a.xh >= a.born)
            if showBorn and bornIn
                color  mc = color.new(a.isHi ? cvColH : cvColL, math.min(95, bornTr + (pal ? 40 : 0)))
                string ms = bornSz == "Tiny" ? size.tiny : bornSz == "Normal" ? size.normal : size.small
                a.mk := label.new(a.born, a.mky, "", style = label.style_diamond, size = ms, color = mc, tooltip = "Arc born here: fitted before, forecast after")
 
// the current curve is frozen up to bar x (what is already drawn never changes)
f_freeze(Arc a, int x) =>
    int xb = math.min(x, a.xe)
    if xb > a.xd
        f_path(a, a.xd, xb, a.frz, 40, false)
    a.xd := x
 
f_new(array<int> px, array<float> py, int n, bool isHi) =>
    Arc res = na
    Curve cv = f_fit(px, py, n)
    if not na(cv)
        int m = px.size()
        array<int>   qx = px.slice(m - n, m).copy()
        array<float> qy = py.slice(m - n, m).copy()
        int g = f_gap(qx)
        float y0 = f_cy(cv, bar_index)
        res := Arc.new(px = qx, py = qy, cv = cv, isHi = isHi, isRes = isHi, acc = f_isAcc(cv), xd = qx.first(), xc = bar_index, xe = f_end(g), frz = array.new<chart.point>(), pls0 = array.new<polyline>(), gap = g, born = bar_index, mky = f_ok(cv, y0) ? y0 : na)
        f_draw(res)
    res
 
// a new pivot near a running arc of the same role joins it; the arc is computed again on all its pivots
f_absorb(Arc a, int x, float y) =>
    bool res = false
    if a.alive and x > a.px.last() and x <= a.xe
        float yc = f_cy(a.cv, x)
        if not na(yc) and yc > 0 and math.abs(y - yc) <= cvAbs * atr50
            a.px.push(x)
            a.py.push(y)
            if a.px.size() > cvPts
                a.px.shift()
                a.py.shift()
            Curve nc = f_fit(a.px, a.py, a.px.size())
            if not na(nc)
                f_freeze(a, bar_index)
                a.cvO := a.cv
                a.xbs := bar_index
                a.xbl := bar_index + math.max(2, int(a.gap / 2))
                a.cv  := nc
                a.acc := f_isAcc(nc)
                a.xc  := bar_index
                a.gap := f_gap(a.px)
                a.xe  := math.max(a.xe, f_end(a.gap))
                a.conf := true
                f_draw(a)
                res := true
    res
 
// polarity flip: the part so far keeps its color, the arc goes on in its new role, projection prolonged
f_flip(Arc a) =>
    f_freeze(a, bar_index)
    polyline.delete(a.pl)
    a.pl := na
    array<chart.point> p0 = array.new<chart.point>()
    for p in a.frz
        if na(a.xh) or showDup or p.index <= a.xh
            p0.push(p)
    bool vis0 = a.flips == 0 ? (a.isHi ? showH : showL) : showFlip
    if vis0 and p0.size() >= 2 and not (a.acc and cvAcc == "Hidden")
        string sty0 = a.flips > 0 ? line.style_solid : line.style_dotted
        int    tr0  = a.flips > 0 ? 0 : 20
        a.pls0.push(polyline.new(p0, false, false, xloc.bar_index, color.new(f_col(a), tr0), na, sty0, 2))
    a.frz   := array.new<chart.point>()
    a.flips += 1
    a.conf  := true
    a.isRes := not a.isRes
    a.xc    := bar_index
    a.xe    := math.max(a.xe, f_end(a.gap))
    f_draw(a)
 
// one bar of a running arc: end of projection, out of range, break (flip, or end if already flipped or accelerating)
f_step(Arc a) =>
    bool hit = false
    if a.alive
        float y   = f_ay(a, bar_index)
        bool  out = not f_ok(a.cv, y)
        bool  cut = false
        float yn  = f_ay(a, bar_index + 1)
        bool  tow = not na(y) and y > 0 and (y > close ? yn < y : yn > y)
        float fd  = f_far(a)
        bool  nea = not na(y) and y > 0 and math.abs(y - close) <= fd
        bool  fla = flatKeep and not na(y) and not na(yn) and y > 0 and math.abs(yn - y) * a.gap <= cvFlatS * atr50
        if bar_index > a.xe and ((toward and tow) or (keepNear and nea) or fla)
            a.xe := bar_index + ((toward and tow) or fla ? a.gap : math.max(5, int(a.gap * nearAh)))
            f_draw(a)
        if out and not na(y) and y > 0
            float y1   = f_ay(a, bar_index + 1)
            bool  away = y > close ? y1 > y : y1 < y
            cut := math.abs(y - close) > fd and away and not fla
        if bar_index > a.xe
            a.alive := false
        else if na(y) or y <= 0 or cut
            a.alive := false
            a.xs := bar_index
            f_draw(a)
        else if bar_index > a.xc
            float d = (cvW + cvBrk) * atr50
            bool brk = a.isRes ? close > y + d : close < y - d
            if brk
                hit := true
                if a.acc or a.flips >= cvFlipMax
                    a.alive := false
                    a.xs := bar_index
                    f_draw(a)
                else
                    f_flip(a)
            else if renew
                float w   = cvW * atr50
                bool  tch = a.isRes ? high >= y - w : low <= y + w
                if tch
                    int xn = f_end(a.gap)
                    if xn - a.xe >= a.gap
                        a.xe := xn
                        f_draw(a)
        // beyond its pivots but kept: the drawing goes on bar by bar
        // projection longer than the 499 bars that can be drawn ahead: drawn further now and then
        bool far = a.xe > bar_index + 499 and (barstate.islastconfirmedhistory or (bar_index - a.xc) % 20 == 0)
        // drawing stopped near the current bar (projection too far from the price at that time): drawn again now and then
        bool lag = limFar and not na(a.xdr) and a.xdr <= bar_index + 5 and a.xdr < a.xe and (barstate.islastconfirmedhistory or (bar_index - a.xc) % 10 == 0)
        if a.alive and (out or far or lag)
            f_draw(a)
    hit
 
f_retire(Arc a) =>
    array<Arc> q = a.isHi ? endH : endL
    q.push(a)
    while q.size() > cvKeep
        Arc o = q.shift()
        polyline.delete(o.pl)
        label.delete(o.mk)
        for q0 in o.pls0
            polyline.delete(q0)
 
// too many running arcs on one side: the oldest (accelerating ones first) stops being followed
f_cap(bool isHi) =>
    int cnt = 0
    for a in arcs
        if a.isHi == isHi
            cnt += 1
    while cnt > cvMaxA
        int idx = -1
        for i = 0 to arcs.size() - 1
            Arc a = arcs.get(i)
            if idx < 0 and a.isHi == isHi and a.acc
                idx := i
        if idx < 0
            for i = 0 to arcs.size() - 1
                if idx < 0 and arcs.get(i).isHi == isHi
                    idx := i
        Arc o = arcs.remove(idx)
        o.alive := false
        f_retire(o)
        cnt -= 1
 
// ───────────────────────────────────── MERGED ZONES ─────────────────────────────────────
f_ring(array<chart.point> top, array<chart.point> bot, color c, int tr) =>
    polyline res = na
    if top.size() >= 2
        array<chart.point> ring = top.copy()
        for i = bot.size() - 1 to 0
            ring.push(bot.get(i))
        res := polyline.new(ring, false, true, xloc.bar_index, color.new(c, math.min(100, tr + 10)), color.new(c, tr))
    res
 
f_addBand(array<chart.point> top, array<chart.point> bot, bool isRes, array<Band> cur) =>
    polyline p = showZ ? f_ring(top, bot, isRes ? cvColH : cvColL, cvTr) : na
    cur.push(Band.new(top, bot, p))
 
// band where two arcs agree, from now to the end of the shorter projection
f_pair(Arc a, Arc b, bool isRes, array<Band> cur) =>
    int xa = bar_index
    int xb = math.min(math.min(a.xe, b.xe), bar_index + 499)
    if xb > xa
        int   kN = math.max(1, math.min(100, xb - xa))
        float ag = cvAgree * atr50
        float w  = cvW * atr50
        array<chart.point> top = array.new<chart.point>()
        array<chart.point> bot = array.new<chart.point>()
        for k = 0 to kN
            int   x  = xa + int(math.round((xb - xa) * k / kN))
            float ya = f_cy(a.cv, x)
            float yb = f_cy(b.cv, x)
            bool  on = f_ok(a.cv, ya) and f_ok(b.cv, yb) and math.abs(ya - yb) <= ag
            if on
                top.push(chart.point.from_index(x, math.max(ya, yb) + w))
                bot.push(chart.point.from_index(x, math.min(ya, yb) - w))
            if not on and top.size() > 0
                if top.size() >= 2
                    f_addBand(top, bot, isRes, cur)
                top := array.new<chart.point>()
                bot := array.new<chart.point>()
        if top.size() >= 2
            f_addBand(top, bot, isRes, cur)
 
// two arcs agree over their whole common projection (from now)
f_same(Arc a, Arc b) =>
    int  xa  = bar_index
    int  xb  = math.min(a.xe, b.xe)
    bool res = xb > xa
    if res
        int   kN = math.max(1, math.min(60, xb - xa))
        float ag = cvAgree * atr50
        for k = 0 to kN
            int   x  = xa + int(math.round((xb - xa) * k / kN))
            float ya = f_cy(a.cv, x)
            float yb = f_cy(b.cv, x)
            if not (f_ok(a.cv, ya) and f_ok(b.cv, yb) and math.abs(ya - yb) <= ag)
                res := false
                break
    res
 
// hides an arc as a duplicate: never drawn if born now, otherwise drawn up to now only
f_hide(Arc a) =>
    a.xh := a.born == bar_index ? a.xd : bar_index
    f_draw(a)
 
// the arcs of one role changed: the zones drawn so far stay (faded) up to now, new zones from now
f_bands(bool isRes, array<Band> cur) =>
    color c = isRes ? cvColH : cvColL
    for bd in cur
        polyline.delete(bd.pl)
        if showZ and showPast
            array<chart.point> top = array.new<chart.point>()
            array<chart.point> bot = array.new<chart.point>()
            for p in bd.top
                if p.index <= bar_index
                    top.push(p)
            for p in bd.bot
                if p.index <= bar_index
                    bot.push(p)
            polyline h = f_ring(top, bot, c, math.min(95, cvTr + 8))
            if not na(h)
                bHist.push(h)
                while bHist.size() > 20
                    polyline.delete(bHist.shift())
    cur.clear()
    array<Arc> sel = array.new<Arc>()
    for a in arcs
        if a.alive and a.isRes == isRes and not a.acc
            sel.push(a)
    int n = sel.size()
    if n >= 2
        for i = 0 to n - 2
            for j = i + 1 to n - 1
                Arc ai = sel.get(i)
                Arc aj = sel.get(j)
                if na(ai.xh) and na(aj.xh)
                    if f_same(ai, aj)
                        if ai.turn != aj.turn
                            f_hide(ai.turn ? aj : ai)
                        else
                            f_hide(aj.px.size() > ai.px.size() ? ai : aj)
        for i = 0 to n - 2
            for j = i + 1 to n - 1
                if cur.size() < 12
                    f_pair(sel.get(i), sel.get(j), isRes, cur)
 
// number of pivots of the single new arc: the most pivots with every pivot within cvAbs ATR50 of the curve,
// a non-accelerating arc first; cvMin if none fits
f_bestN(array<int> px, array<float> py) =>
    int m  = px.size()
    int rN = na
    int rA = na
    for n = cvMin to cvMaxE
        if m >= n
            Curve cv = f_fit(px, py, n)
            if not na(cv)
                float er = 0.0
                for i = m - n to m - 1
                    er := math.max(er, math.abs(f_cy(cv, px.get(i)) - py.get(i)))
                if er <= cvAbs * atr50
                    if f_isAcc(cv)
                        rA := n
                    else
                        rN := n
    na(rN) ? (na(rA) ? cvMin : rA) : rN
 
// ───────────────────────────────────── MAIN ─────────────────────────────────────
bool chgR = false
bool chgS = false
var int stH = 0      // last bend read on the highs: 1 bowl, -1 dome
var int stL = 0
 
// bend of the curve through the latest pivots of one side: 1 bowl, -1 dome, 0 flat or unknown
f_bend(array<int> px, array<float> py) =>
    int nK = math.min(cvMin + 1, cvMaxE)
    Curve ck = f_fit(px, py, math.min(nK, px.size()))
    na(ck) ? 0 : ck.c > cvFlat * atr50 ? 1 : ck.c < -cvFlat * atr50 ? -1 : 0
 
// the newest arc with the new bend (most pivots) becomes the turn arc
f_mark(array<Arc> made, int st) =>
    Arc best = na
    for a in made
        if not a.acc and (st > 0 ? a.cv.c > 0 : a.cv.c < 0)
            if na(best) or a.px.size() > best.px.size()
                best := a
    if not na(best)
        best.turn := true
        f_draw(best)
 
if barstate.isconfirmed and not na(atr50)
    // running arcs: end, break, flip
    int nA = arcs.size()
    if nA > 0
        for i = nA - 1 to 0
            Arc a = arcs.get(i)
            bool r0  = a.isRes
            bool hit = f_step(a)
            if hit
                chgR := true
                chgS := true
            if not a.alive
                arcs.remove(i)
                f_retire(a)
                if r0
                    chgR := true
                else
                    chgS := true
 
    // new pivot high: joins the resistance arcs near it, and new arcs through the latest highs
    if not na(pH)
        int x = bar_index - lenP
        hx.push(x)
        hy.push(pH)
        if hx.size() > cvMaxE
            hx.shift()
            hy.shift()
        for a in arcs
            if a.isRes
                f_absorb(a, x, pH)
        array<Arc> made = array.new<Arc>()
        if oneArc
            if hx.size() >= cvMin
                Arc nw1 = f_new(hx, hy, f_bestN(hx, hy), true)
                if not na(nw1)
                    arcs.push(nw1)
                    made.push(nw1)
        else
            for n = cvMin to cvMaxE
                if hx.size() >= n
                    Arc nw = f_new(hx, hy, n, true)
                    if not na(nw)
                        arcs.push(nw)
                        made.push(nw)
        int st = f_bend(hx, hy)
        if st != 0
            if stH != 0 and st != stH
                f_mark(made, st)
                if showTLb
                    string tx = "Highs bend " + (st > 0 ? "up" : "down") + (stL == st ? " (both)" : "")
                    label.new(x, pH, tx, style = label.style_label_down, size = size.small, color = color.new(cvColH, 30), textcolor = color.white)
            stH := st
        f_cap(true)
        chgR := true
        if showDots
            label.new(x, pH, "", style = label.style_circle, size = size.tiny, color = color.new(cvColH, 40))
 
    // new pivot low: joins the support arcs near it, and new arcs through the latest lows
    if not na(pL)
        int x = bar_index - lenP
        lx.push(x)
        ly.push(pL)
        if lx.size() > cvMaxE
            lx.shift()
            ly.shift()
        for a in arcs
            if not a.isRes
                f_absorb(a, x, pL)
        array<Arc> made = array.new<Arc>()
        if oneArc
            if lx.size() >= cvMin
                Arc nw1 = f_new(lx, ly, f_bestN(lx, ly), false)
                if not na(nw1)
                    arcs.push(nw1)
                    made.push(nw1)
        else
            for n = cvMin to cvMaxE
                if lx.size() >= n
                    Arc nw = f_new(lx, ly, n, false)
                    if not na(nw)
                        arcs.push(nw)
                        made.push(nw)
        int st = f_bend(lx, ly)
        if st != 0
            if stL != 0 and st != stL
                f_mark(made, st)
                if showTLb
                    string tx = "Lows bend " + (st > 0 ? "up" : "down") + (stH == st ? " (both)" : "")
                    label.new(x, pL, tx, style = label.style_label_up, size = size.small, color = color.new(cvColL, 30), textcolor = color.white)
            stL := st
        f_cap(false)
        chgS := true
        if showDots
            label.new(x, pL, "", style = label.style_circle, size = size.tiny, color = color.new(cvColL, 40))
 
    if chgR
        f_bands(true, bndR)
    if chgS
        f_bands(false, bndS)

← 返回列表