WVPO LPS Three-Point Detector

WVPO · study · 663 行 · 点赞 6 · TradingView 原页

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

Pine Script

//@version=6
// =============================================================================
// WVPO LPS Three-Point Detector
//
// Purpose   : Reads the low of the pullback after a sign of strength against the
//             rules of Setup 2 (LPS continuation): how deep it ran below the buy
//             zone, where it sits against the zone of the rising Spring AVWAP,
//             whether buy zone, Spring AVWAP and higher low lie in one band (the
//             three-point confirmation), and which entry mode the volume of the
//             last two candles into the low allows.
// Reference : The Composite-Man Code, Volume II, chapter 21: conditions and
//             volume switch in 21.1, threshold box in 21.5, five hallmarks of a
//             genuine LPS against five symptoms of a trap in 21.7. Three-point
//             confirmation from Volume I, chapter 14 (14.7, check P5); zone of
//             +/- 0.3 x ATR(20) from Volume I, chapter 12.5; time-of-day average
//             as in chapter 21.1.
// Licence   : Mozilla Public License 2.0 - WVPO
//
// It gives no entries, no exits, no targets and no win rates. The roller line
// is the reference level chapter 21 names for the stop; the plan is yours.
//
// -----------------------------------------------------------------------------
// WHAT IT CHECKS - three of the five hallmarks in 21.7
//   2. Depth: the pullback reaches the buy zone, and its low lies at most
//      0.1 x ATR(14) of the range timeframe below the zone's lower edge.
//   3. Spring AVWAP: the line is rising, the low does not fall through its
//      zone (+/- 0.3 x ATR(20) of the entry timeframe, the chart), and no
//      close goes through the zone during the pullback. A close through the
//      zone is trap symptom 3 and gets its own row and alert.
//   4. Three-point confirmation: lower edge of the buy zone, Spring AVWAP and
//      the low lie in one band no wider than 0.15 x ATR(14) of the range
//      timeframe, and the low is a higher low above the spring low - the low
//      of the range-timeframe bar that holds the anchor. The table also says
//      when a later candle broke that low (field 9 of the setup card: the
//      re-accumulation has failed).
//
// WHAT IT DOES NOT CHECK - and why
//   1. Spring and then sign of strength documented on the range timeframe.
//      That is a reading of the structure, not a measurement.
//   5. Four-window consensus at the low of at least B. The consensus reads
//      footprint, delta, CVD and the heatmap together, and no script can see
//      the heatmap of resting orders, so the consensus stays your call.
//      The second half of hallmark 5 - the entry follows the volume switch -
//      is your action; the script only supplies the switch.
//   The table therefore says three of five, never five of five.
//   Not checked either: the regime traffic light (chapter 21 trades only when
//   it is not red), and the buy zone itself. Pine cannot build a real volume
//   profile cheaply, so both edges are yours to enter from your own profile.
//   The micro-BOS of mode B is not detected, because it is an entry trigger.
//
// THE VOLUME SWITCH - not a filter
//   Volume does not decide whether there is a trade, only how to enter. Each
//   of the last two candles into the low (entry timeframe) is divided by the
//   time-of-day average: the mean volume of the candle with the same clock
//   time (exchange time of the symbol) in the ten sessions before. The mean of
//   the two factors at most 1.0 allows mode A (limit at the zone); above it
//   only mode B (after the micro-BOS) is left. A session is a TradingView
//   daily bar; where TradingView merges a holiday session into the next day,
//   its second part counts as a session of its own as soon as a clock time
//   repeats (same rule as the VAH Break script for chapter 22). A time slot
//   missing in a session counts only what is there; with fewer than five
//   values the row reads n/a, as it does on a chart without volume. The switch
//   is read at every new low of the pullback; the reading at the final low is
//   the one the book uses.
//
// HOW THE PULLBACK LOW IS FOUND
//   Automatic: the pullback starts at the highest high since the spring
//   anchor; every confirmed candle that prints a lower low after it becomes
//   the current reading. A new high above that high starts a new pullback.
//   Every reading is taken when its candle closes and is never redrawn; the
//   marker of an earlier low stays where it was. Manual: you pick the candle
//   of the low; the reading is taken there once, for review and testing.
//   On an index future (ES, NQ), the Spring anchor you enter is the low of
//   the regular cash session (9:30 to 16:00 ET), as in the cash index; a
//   news spike before the open is not the anchor (Volume II, 21.4). The
//   Spring low the script checks for a break is the low of the whole
//   range-timeframe bar of the anchor, on a future including the overnight
//   session; chapter 21.4 names the regular-session low as the Spring low.
//
// ON "RISING"
//   This script reads "rising" as: the line stands higher than at the close
//   of the last completed bar of the range timeframe (for a daily range:
//   yesterday's close). A slope over a few bars of the entry timeframe is the
//   wrong scale here: a line anchored days ago moves by fractions of a point
//   per bar. In the worked example below the ten-bar slope on M5 is +0.23
//   ATR(20) and would read flat, while the line rose 31 points in the
//   session before.
//
// ON THE HTF VALUES
//   ATR(14) of the range timeframe and ATR(20) of the roller timeframe are the
//   values of the last completed higher-timeframe bar at the open of the
//   current candle - on historical and on live bars alike, without lookahead.
//
// -----------------------------------------------------------------------------
// ON THE ALERTS
//   There is no alert on an A-consensus trigger, and there cannot be one:
//   A-consensus means three of four order flow windows read together, among
//   them the heatmap of resting orders, which no script can see. The alerts
//   here say exactly the smaller thing the script checks: the pullback
//   reached the buy zone, the three checkable hallmarks are met at a pullback
//   low, a close went through the Spring AVWAP zone.
//   An alert that promises more than it can see is worse than no alert.
//
// -----------------------------------------------------------------------------
// DEFAULTS
//   Max depth below the lower edge ...... 0.1 x ATR(14) of the range timeframe
//                                         (chapter 21.5; calibrate over your
//                                         first thirty documented LPS per
//                                         instrument)
//   Spring AVWAP zone ................... +/- 0.3 x ATR(20) of the entry
//                                         timeframe (Volume I, 12.5)
//   Roller .............................. Spring AVWAP - 0.3 x ATR(20) of M15:
//                                         the lower edge of the zone on the
//                                         15-minute chart (chapter 21.1)
//   Volume switch ....................... 1.0 x, mean of the last two candles
//                                         into the low, each against the same
//                                         clock time in the ten sessions
//                                         before (two weeks, chapter 21.1)
//   Three-point band .................... 0.15 x ATR(14) of the range
//                                         timeframe, about 15 % of ATR(14)
//                                         (Volume I, 14.7, check P5)
//   Range timeframe D, entry = chart .... chapter 21.5 (the ES example: range
//                                         D1, entry M5)
//
// -----------------------------------------------------------------------------
// WORKED EXAMPLE - the ES reference trade of 9 Jan 2024 (Volume II, 21.4)
//   Symbol CME_MINI:ESH2024 (the March 2024 contract itself, not ES1!), 5-minute
//   chart, full CME session. Times in New York (ET) and exchange time (CT).
//   Chart settings: daily close = last trade, not settlement ("Use settlement
//   as close on daily interval" off); the ATR(14) D below is computed so.
//   History: the chart needs the bars back to the session of 22 Dec 2023, the
//   first of the ten sessions before 9 Jan. Counted back from the contract's
//   last bar (15 Mar 2024) that is about 16,000 M5 bars (14,532 up to 7 Mar
//   alone). A plan that loads fewer shows "before the loaded history" in the
//   anchor row. Then start bar replay on 9 Jan 2024 after 09:50 ET or on
//   10 Jan: the history then reaches back far enough (5,000 bars from 9 Jan
//   go back to mid-December).
//   Inputs:
//     Spring anchor   5 Jan 2024 15:30 ET (14:30 CT), candle low 4719.75 - the
//                     low of the cash session, the futures twin of the cash
//                     spring 4,682 and the anchor of the book's 4,729.1. Not
//                     the spike of the payroll release at 8:30 ET (4702.00):
//                     see the negative control below.
//     Buy zone        lower edge 4771.4, upper edge 4781.4 = the buy zone
//                     4,734-4,744 in cash points (Volume II, 21.4) plus the
//                     basis of 37.4 points on that day.
//     Pullback low    Manual, 9 Jan 2024 09:45 ET (08:45 CT). Rest default.
//   Expected table (times in exchange time):
//     a) Spring anchor  2024-01-05 14:30  spring low 4702.00  intact (the low of
//        the 5 Jan session; 8 Jan dipped to 4715.25 and did not break it).
//        The Spring low the script checks for a break is the low of the whole
//        daily bar of the anchor, on a future including the overnight session
//        (here 4702.00); chapter 21.4 names the regular-session low (4719.75)
//        as the Spring low.
//        Pullback low   2024-01-09 08:45  4767.50  manual.
//     b) 2 Depth        +3.90 pt = 0.083 ATR  ok   (ATR(14) D about 46.95).
//     c) 3 Spring AVWAP 4766.52  rising  +2.99 since D close  (8 Jan: 4763.53).
//     d) 3 Low vs zone  +0.37 ATR  above zone  ·  0 closes through
//        (ATR(20) M5 2.62, zone +/- 0.78 = 4765.74 to 4767.31).
//     e) 4 Band         4.88 pt = 0.104 ATR  ok   (higher low).
//     f) Roller         4765.50  (4766.52 - 0.3 x ATR(20) M15 3.24 = 4765.55,
//        rounded down; in cash points 4,728, the stop of the book).
//     g) Volume         1.09 / 1.51  ->  1.30 x   and the switch reads
//        MODE B ONLY. The 9:40 ET candle traded 21,777 against an average of
//        20,039, the 9:45 candle 26,202 against 17,391 (ten sessions 22 Dec 2023
//        to 8 Jan 2024). Volume II, 21.4 says 1.30 and mode B for this low.
//        Christmas and New Year lie inside the ten sessions without changing
//        them: the exchange was closed on 25 Dec and 1 Jan, every session has
//        its 276 bars, and no clock time repeats.
//     h) Hallmarks      3 of 5 met; #1 phase/SOS and #5 consensus not checked.
//   Then: Automatic mode in bar replay. From the close of the 9:45 ET candle
//   to 12:55 ET the table must show the same reading, marked "running" (the
//   pullback started at the high 4803.25 of 8 Jan 15:55 ET); the candle of
//   13:00 ET makes a new high (4803.75) and starts a new pullback.
//   Alerts and markers of the automatic run on 9 Jan: "Pullback in the buy
//   zone" once, at 06:35 ET (low 4781.00). "Three checkable hallmarks met",
//   each with a green marker, at 09:05, 09:15, 09:20, 09:25 and 09:45 ET; the
//   switch reads Mode A allowed at 09:05 and 09:15 (0.89 and 0.91) and Mode B
//   only from 09:20 on (1.15, 1.39, 1.30). The switch is final only at the
//   final low: each lower low reads it again from its own two candles.
//   Negative control: move the spring anchor to the payroll spike, 5 Jan 08:30
//   ET. The line drops to about 4754.33, the band widens to 17.08 pt = 0.364 ATR
//   and hallmark 4 fails: 2 of 5. That is why the anchor is named to the bar.
//   How exact: prices to the tick; line +/- 0.05; ATR(20) M5 and M15 +/- 0.02;
//   ATR(14) D +/- 0.5, because it depends on how much of the contract's daily
//   history before December 2023 your chart loads (depth then 0.082 to 0.084);
//   volume factors +/- 0.02 for late volume corrections. The mode must read B
//   in any case.
//   In cash points (minus 37.4) the low is 4,730.1, the line 4,729.1, the
//   roller 4,728.1: the values of Volume II, 21.4 and 27.6.
//   Why the table is not the book: Volume II, 21.4 gives 4,730.4, 3.6 points
//   and 0.09 ATR. That is the cash low against the cash ATR(14) of 40 points
//   (a simple average over cash sessions only). The table works in ESH2024
//   points: the futures low minus the day's average basis 37.4 is 4,730.1
//   (at the low itself the basis was 37.15), so the depth is 3.90 points, and
//   it divides by ATR(14) D of the futures after Wilder, about 46.95, because
//   the futures day includes the night. 3.90 / 46.95 = 0.083. Both readings
//   stay below 0.10; neither is an error.
// =============================================================================
 
indicator(title = "WVPO LPS Three-Point Detector", shorttitle = "WVPO LPS",
     overlay = true, max_bars_back = 1000)
 
// ------------------------------------------------------------- spring anchor
g1 = "Spring anchor"
spTs = input.time(timestamp("2024-01-05T20:30:00+00:00"), "Spring anchor bar", confirm = true, group = g1,
     tooltip = "The candle the Spring AVWAP starts with. On an index future (ES, NQ), pick the low of the regular cash session (9:30 to 16:00 ET), not a news spike before the open. The Spring low the higher low is measured against is the low of the whole range-timeframe bar that holds this candle, on a future including the overnight session; chapter 21.4 names the regular-session low as the Spring low.")
spCol = input.color(color.rgb(27, 94, 32), "Colour", group = g1)
 
// ---------------------------------------------------------------- buy zone
g2 = "Buy zone - from your own volume profile"
bzLow = input.price(0.0, "Lower edge", group = g2,
     tooltip = "HVN below the POC of the range, at most down to the VAL (Volume I, chapter 14, layer 2a). Read off your own volume profile. Left at zero, hallmarks 2 and 4 read not set and do not count.")
bzHigh = input.price(0.0, "Upper edge", group = g2,
     tooltip = "Needed to check that the pullback reached the zone at all.")
 
// ----------------------------------------------------------- pullback low
g3 = "Pullback low"
pbMode = input.string("Automatic", "Which low", options = ["Automatic", "Manual"], group = g3,
     tooltip = "Automatic: every lower low after the highest high since the spring anchor becomes the reading. Manual: the reading is taken once, on the candle you pick below.")
pbTs = input.time(timestamp("2024-01-09T14:45:00+00:00"), "Manual low bar", group = g3)
 
// ---------------------------------------------------------------- measurement
gM = "Measurement"
src = input.source(hlc3, "Source of the AVWAP", group = gM,
     tooltip = "HLC3 is the default because the figures in Volume I, chapter 12 and Volume II, chapter 21 are calculated on it.")
rangeTf = input.timeframe("D", "Range timeframe", group = gM,
     tooltip = "The timeframe of the trading range. Must be higher than the chart. Its ATR(14) scales the depth and the three-point band.")
rangeAtrLen = input.int(14, "ATR length, range timeframe", minval = 1, group = gM)
entryAtrLen = input.int(20, "ATR length, entry timeframe (chart)", minval = 1, group = gM,
     tooltip = "Scales the Spring AVWAP zone. The chart is the entry timeframe.")
rollerTf = input.timeframe("15", "Roller timeframe", group = gM,
     tooltip = "Chapter 21.1: roller = Spring AVWAP - 0.3 x ATR(20) of M15. Must be equal to or higher than the chart.")
rollerAtrLen = input.int(20, "ATR length, roller timeframe", minval = 1, group = gM)
todSessions = input.int(10, "Time-of-day average: sessions", minval = 5, maxval = 10, group = gM,
     tooltip = "Same clock time in the sessions before. Ten sessions = the two weeks of chapter 21.1. Under five values the reading is n/a.")
 
// ----------------------------------------------------------------- thresholds
gT = "Thresholds (chapter 21.5)"
depthMax = input.float(0.1, "Max depth below the lower edge (x ATR range TF)", minval = 0.0, step = 0.01, group = gT,
     tooltip = "A starting value: calibrate over your first thirty documented LPS per instrument.")
zoneFac = input.float(0.3, "Spring AVWAP zone half width (x ATR entry TF)", minval = 0.05, step = 0.05, group = gT,
     tooltip = "Half width of the zone around the Spring AVWAP, Volume I, chapter 12.5.")
bandMax = input.float(0.15, "Three-point band, max width (x ATR range TF)", minval = 0.01, step = 0.01, group = gT,
     tooltip = "Volume I, chapter 14.7, check P5: about 15 percent of ATR(14).")
rollerFac = input.float(0.3, "Roller distance (x ATR roller TF)", minval = 0.0, step = 0.05, group = gT,
     tooltip = "The roller sits this far below the Spring AVWAP: the lower edge of the zone on the roller timeframe (chapter 21.1).")
volSwitch = input.float(1.0, "Mode A allowed up to (x time-of-day average)", minval = 0.1, step = 0.05, group = gT,
     tooltip = "Mean of the factors of the last two candles into the low, each against its time-of-day average. Up to this value mode A is allowed, above it only mode B. This is a switch, not a filter.")
 
// -------------------------------------------------------------------- display
gD = "Display"
showTable = input.bool(true, "Show table", group = gD)
showZone = input.bool(true, "Shade the Spring AVWAP zone", group = gD)
showRoller = input.bool(true, "Show the roller line", group = gD)
showBuyZone = input.bool(true, "Shade the buy zone", group = gD)
markReadings = input.bool(true, "Mark lows that meet the three checkable hallmarks", group = gD)
tblPos = input.string("top_right", "Table position", group = gD,
     options = ["top_right", "top_left", "bottom_right", "bottom_left"])
 
// -------------------------------------------------- journal webhook, optional
// Optional JSON payload for a journal webhook. Empty by default, so alerts
// stay plain text. This script does not produce a plan: entry, stop and
// target are yours - the human sets the plan.
gJ = "Journal webhook (optional)"
whSecret = input.string("", "Webhook secret", group = gJ,
     tooltip = "Leave empty to keep alerts as plain text.")
whEntry  = input.price(0.0, "Entry (your plan)",  group = gJ)
whStop   = input.price(0.0, "Stop (your plan)",   group = gJ)
whTarget = input.price(0.0, "Target (your plan)", group = gJ)
 
colOk  = color.rgb(27, 94, 32)
colNo  = color.rgb(183, 28, 28)
colMid = color.rgb(120, 120, 120)
 
// =============================================================================
// Higher-timeframe values as of the last completed bar of that timeframe. On a
// historical candle a request without lookahead already returns that value;
// on a live candle it returns the bar still forming, so the value is taken
// from the candle before, which closed together with it. Both paths agree.
// =============================================================================
f_closedHtf(float reqVal, simple string tf) =>
    var float held = na
    float prevReq = reqVal[1]
    if timeframe.change(tf)
        held := barstate.isrealtime ? prevReq : reqVal
    held
 
chartSec = timeframe.in_seconds()
rangeSec = timeframe.in_seconds(rangeTf)
rollSec  = timeframe.in_seconds(rollerTf)
 
// Timeframe as table text, built from seconds so that "D" and "1D" read alike.
f_tfText(int sec) =>
    sec == 604800 ? "W" : sec >= 86400 ? (sec == 86400 ? "D" : str.tostring(math.round(sec / 86400)) + "D") :
     sec >= 3600 ? "H" + str.tostring(math.round(sec / 3600)) : "M" + str.tostring(math.round(sec / 60))
 
rangeTfTxt = f_tfText(rangeSec)
rollTfTxt  = f_tfText(rollSec)
 
atrRangeReq  = request.security(syminfo.tickerid, rangeTf, ta.atr(rangeAtrLen))
atrRollReq   = request.security(syminfo.tickerid, rollerTf, ta.atr(rollerAtrLen))
atrRangeHeld = f_closedHtf(atrRangeReq, rangeTf)
atrRollHeld  = f_closedHtf(atrRollReq, rollerTf)
atrRollOwn   = ta.atr(rollerAtrLen)
atrEntry     = ta.atr(entryAtrLen)
 
// Range timeframe must be above the chart; roller timeframe equal or above.
atrRange = chartSec < rangeSec ? atrRangeHeld : na
atrRoll  = chartSec < rollSec ? atrRollHeld : chartSec == rollSec ? atrRollOwn[1] : na
 
// =============================================================================
// Spring AVWAP, accumulated by hand so that a symbol without a volume series
// degrades to an empty line and n/a rows rather than answering a different
// question in silence.
// =============================================================================
var bool  anchored        = false
var bool  anchorMissing   = false
var int   anchorTime      = na
var float springLow       = na
var bool  springBroken    = false
var bool  anchorRangeOpen = false
var float rangeLowSoFar   = na
var float pv              = 0.0
var float vv              = 0.0
 
// The spring low is the low of the range-timeframe bar that holds the anchor,
// not necessarily the low of the anchor candle: the anchor can sit on the low
// of the cash session while the futures session printed a lower spike.
rangeNew = timeframe.change(rangeTf)
if rangeNew
    rangeLowSoFar := low
    anchorRangeOpen := false
else
    rangeLowSoFar := na(rangeLowSoFar) ? low : math.min(rangeLowSoFar, low)
 
if bar_index == 0 and time > spTs
    anchorMissing := true
anchorBar = time >= spTs and (na(time[1]) ? time == spTs : time[1] < spTs)
if anchorBar
    anchored := true
    anchorTime := time
    springLow := rangeLowSoFar
    springBroken := false
    anchorRangeOpen := true
    pv := 0.0
    vv := 0.0
else if anchorRangeOpen
    springLow := math.min(springLow, low)
if anchored
    v = nz(volume)
    pv += src * v
    vv += v
avw = anchored and vv > 0 ? pv / vv : na
 
zoneHalf = na(avw) or na(atrEntry) ? na : zoneFac * atrEntry
zoneLo   = na(zoneHalf) ? na : avw - zoneHalf
zoneHi   = na(zoneHalf) ? na : avw + zoneHalf
rollerRaw  = na(avw) or na(atrRoll) ? na : avw - rollerFac * atrRoll
rollerTick = na(rollerRaw) ? na : math.floor(rollerRaw / syminfo.mintick + 1e-9) * syminfo.mintick
 
// Rising: higher than at the close of the last completed range-timeframe bar.
var float lineAtRangeClose = na
float avwPrev = avw[1]
if anchorBar
    lineAtRangeClose := na
if rangeNew and not anchorBar
    lineAtRangeClose := avwPrev
riseDelta = na(avw) or na(lineAtRangeClose) ? na : avw - lineAtRangeClose
rising    = not na(riseDelta) and riseDelta > 0
 
// =============================================================================
// Time-of-day average: per clock-time slot (exchange time) the volumes of the
// last ten sessions in a ring, stamped with their session number so that a
// slot missing in a session is not filled from an older one.
// =============================================================================
var array<float> todVol = array.new_float(14400, na)
var array<int>   todSes = array.new_int(14400, -1)
 
// Latest session number stored in a slot (-1 when the slot is still empty).
f_lastSes(array<int> sess, int slotIdx) =>
    int mx = -1
    for k = 0 to 9
        mx := math.max(mx, array.get(sess, slotIdx * 10 + k))
    mx
 
todOk   = not timeframe.isseconds
slot    = hour * 60 + minute
lastSes = todOk ? f_lastSes(todSes, slot) : -1
 
// A new daily bar starts a session. So does a clock time seen twice in one
// daily bar: that is a holiday session TradingView has merged into the next
// day, and its second part counts as a session of its own (same rule as the
// VAH Break script of chapter 22).
var int sessNo = 0
if timeframe.change("D") and bar_index > 0
    sessNo += 1
else if lastSes == sessNo
    sessNo += 1
 
f_todAvg(array<float> vols, array<int> sess, int slotIdx, int cur, int nSess) =>
    float total = 0.0
    int n = 0
    for k = 0 to 9
        int j = slotIdx * 10 + k
        int s = array.get(sess, j)
        float vk = array.get(vols, j)
        if s >= cur - nSess and s < cur and not na(vk)
            total += vk
            n += 1
    n >= 5 ? total / n : na
 
todAvg    = todOk ? f_todAvg(todVol, todSes, slot, sessNo, todSessions) : na
todFactor = na(volume) or na(todAvg) or todAvg <= 0 ? na : volume / todAvg
todFactorPrev = todFactor[1]
volPair   = na(todFactor) or na(todFactorPrev) ? na : (todFactor + todFactorPrev) / 2
 
// Written only once the candle has closed, after its own average was read.
if barstate.isconfirmed and todOk
    int jw = slot * 10 + sessNo % 10
    array.set(todVol, jw, volume)
    array.set(todSes, jw, sessNo)
 
// =============================================================================
// The pullback and its low. Every judgement is taken on a closed candle.
// =============================================================================
isManual = pbMode == "Manual"
manualHit = isManual and time >= pbTs and (na(time[1]) or time[1] < pbTs)
closeThroughNow = anchored and not anchorBar and not na(zoneLo) and close < zoneLo
 
var float pbHigh        = na
var float pbLow         = na
var int   closesThrough = 0
var bool  manualDone    = false
var bool  reachedZone   = false
 
var int   rdTime     = na
var float rdLow      = na
var float rdLine     = na
var float rdAtrEntry = na
var float rdAtrRange = na
var float rdRoller   = na
var float rdF1       = na
var float rdF2       = na
var float rdPair     = na
var float rdRise     = na
var bool  rdRising   = false
 
bool newReading   = false
bool clearReading = false
 
if anchorBar
    pbHigh := high
    pbLow := na
    closesThrough := 0
    manualDone := false
    reachedZone := false
    clearReading := true
else if anchored and barstate.isconfirmed
    if not anchorRangeOpen and low < springLow
        springBroken := true
    if closeThroughNow and (not isManual or not manualDone)
        closesThrough += 1
    if not isManual
        // A new high above the pullback high starts a new pullback; the old
        // reading belongs to the old one and is cleared from the table.
        if high > pbHigh
            pbHigh := high
            pbLow := na
            closesThrough := 0
            reachedZone := false
            clearReading := true
        else if na(pbLow) or low < pbLow
            pbLow := low
            newReading := true
    else if not manualDone
        if manualHit
            pbLow := low
            newReading := true
            manualDone := true
        else if high > pbHigh
            pbHigh := high
            closesThrough := 0
 
if clearReading
    rdTime := na
    rdLow := na
    rdLine := na
    rdAtrEntry := na
    rdAtrRange := na
    rdRoller := na
    rdF1 := na
    rdF2 := na
    rdPair := na
    rdRise := na
    rdRising := false
 
if newReading
    rdTime := time
    rdLow := low
    rdLine := avw
    rdAtrEntry := atrEntry
    rdAtrRange := atrRange
    rdRoller := rollerTick
    rdF1 := todFactorPrev
    rdF2 := todFactor
    rdPair := volPair
    rdRise := riseDelta
    rdRising := rising
 
// =============================================================================
// The three checkable hallmarks, read off the current reading.
// =============================================================================
hasReading = not na(rdTime)
bzSet = bzLow > 0 and bzHigh > bzLow
 
// Hallmark 2: the pullback reached the zone, and the low is not too deep.
rdReached  = hasReading and bzSet and rdLow <= bzHigh
rdDepth    = hasReading and bzSet ? bzLow - rdLow : na               // positive = below the lower edge
rdDepthAtr = na(rdDepth) or na(rdAtrRange) or rdAtrRange <= 0 ? na : rdDepth / rdAtrRange
char2      = rdReached and not na(rdDepthAtr) and rdDepthAtr <= depthMax
 
// Hallmark 3: the line rises, the low stays out of the zone's underside, and no
// close went through the zone in this pullback.
rdLowVsLine = hasReading and not na(rdLine) and not na(rdAtrEntry) and rdAtrEntry > 0 ? (rdLow - rdLine) / rdAtrEntry : na
rdZonePos   = na(rdLowVsLine) ? "n/a" : rdLowVsLine > zoneFac ? "above zone" : rdLowVsLine >= -zoneFac ? "in zone" : "through zone"
char3       = rdRising and not na(rdLowVsLine) and rdLowVsLine >= -zoneFac and closesThrough == 0
 
// Hallmark 4: buy zone edge, Spring AVWAP and higher low in one band.
rdHigherLow = hasReading and not na(springLow) and rdLow > springLow
rdBand      = hasReading and bzSet and not na(rdLine) ? math.max(bzLow, math.max(rdLine, rdLow)) - math.min(bzLow, math.min(rdLine, rdLow)) : na
rdBandAtr   = na(rdBand) or na(rdAtrRange) or rdAtrRange <= 0 ? na : rdBand / rdAtrRange
char4       = rdHigherLow and not na(rdBandAtr) and rdBandAtr <= bandMax
 
metCount   = (char2 ? 1 : 0) + (char3 ? 1 : 0) + (char4 ? 1 : 0)
verdict    = hasReading ? str.tostring(metCount) + " of 5 met" : "no pullback low yet"
verdictCol = not hasReading ? colMid : metCount == 3 ? colOk : colMid
switchWord = na(rdPair) ? "n/a" : rdPair <= volSwitch ? "Mode A allowed" : "Mode B only"
 
zoneReachedNow = false
if newReading and rdReached and not reachedZone
    reachedZone := true
    zoneReachedNow := true
 
// =============================================================================
// Plots
// =============================================================================
plot(avw, "Spring AVWAP", color = spCol, linewidth = 2)
pZh = plot(showZone ? zoneHi : na, "Spring AVWAP zone top", color = color.new(spCol, 75))
pZl = plot(showZone ? zoneLo : na, "Spring AVWAP zone bottom", color = color.new(spCol, 75))
fill(pZh, pZl, color = color.new(spCol, 90), title = "Spring AVWAP zone")
plot(showRoller ? rollerTick : na, "Roller", color = colNo, linewidth = 1, style = plot.style_circles)
pBl = plot(showBuyZone and bzSet ? bzLow : na, "Buy zone lower edge", color = color.new(color.blue, 0))
pBh = plot(showBuyZone and bzSet ? bzHigh : na, "Buy zone upper edge", color = color.new(color.blue, 50))
fill(pBl, pBh, color = color.new(color.blue, 90), title = "Buy zone")
plotshape(markReadings and newReading and metCount == 3, "Low meets the three checkable hallmarks",
     shape.triangleup, location.belowbar, colOk, size = size.tiny)
 
// =============================================================================
// Table
// =============================================================================
f_pos() =>
    tblPos == "top_left" ? position.top_left : tblPos == "bottom_right" ? position.bottom_right :
     tblPos == "bottom_left" ? position.bottom_left : position.top_right
 
var table t = table.new(f_pos(), 2, 13, border_width = 1)
 
// "label" would shadow the built-in type of the same name, hence "caption".
f_row(int r, string caption, string value, color vc) =>
    bg = color.new(color.gray, 90)
    table.cell(t, 0, r, caption, text_size = size.small, text_halign = text.align_left,  bgcolor = bg, text_color = color.new(color.gray, 0))
    table.cell(t, 1, r, value,   text_size = size.small, text_halign = text.align_right, bgcolor = bg, text_color = vc)
 
f_px(float x) =>
    na(x) ? "n/a" : str.tostring(x, "0.00")
 
f_sg(float x, string fmt) =>
    na(x) ? "n/a" : (x >= 0 ? "+" : "") + str.tostring(x, fmt)
 
f_tm(int ts) =>
    str.format_time(ts, "yyyy-MM-dd HH:mm", syminfo.timezone)
 
if showTable and barstate.islast
    txt = color.new(color.gray, 0)
    hdr = color.new(color.gray, 80)
    table.cell(t, 0, 0, "LPS three-point", text_size = size.small, text_halign = text.align_left,  bgcolor = hdr, text_color = txt)
    table.cell(t, 1, 0, "checks 3 of 5 (21.7)", text_size = size.small, text_halign = text.align_right, bgcolor = hdr, text_color = txt)
 
    anchorTxt = anchorMissing ? "before the loaded history" : not anchored ? "not reached" :
         f_tm(anchorTime) + "  spring low " + f_px(springLow) + (springBroken ? "  BROKEN" : "  intact")
    f_row(1, "Spring anchor", anchorTxt, springBroken ? colNo : txt)
 
    lowTxt = hasReading ? f_tm(rdTime) + "  " + f_px(rdLow) + (isManual ? "  manual" : "  running") :
         isManual ? "manual bar not reached" : "none yet"
    f_row(2, "Pullback low", lowTxt, txt)
 
    f_row(3, "Buy zone", bzSet ? f_px(bzLow) + " - " + f_px(bzHigh) : "not set", bzSet ? txt : colMid)
 
    depthTxt = not bzSet ? "buy zone not set" : not hasReading or na(rdDepthAtr) ? "n/a" :
         f_sg(rdDepth, "0.00") + " pt = " + str.tostring(rdDepthAtr, "0.000") + " ATR  " +
         (not rdReached ? "zone not reached" : char2 ? "ok" : "too deep")
    f_row(4, "2 Depth below lower edge (max " + str.tostring(depthMax, "0.00") + ")", depthTxt, char2 ? colOk : colMid)
 
    lineTxt = not hasReading ? "n/a" : f_px(rdLine) + "  " + (na(rdRise) ? "too early" : rdRising ? "rising" : "not rising") +
         (na(rdRise) ? "" : "  " + f_sg(rdRise, "0.00") + " since " + rangeTfTxt + " close")
    f_row(5, "3 Spring AVWAP", lineTxt, rdRising ? colOk : colMid)
 
    zoneTxt = na(rdLowVsLine) ? "n/a" : f_sg(rdLowVsLine, "0.00") + " ATR  " + rdZonePos + "  ·  " +
         str.tostring(closesThrough) + " closes through"
    f_row(6, "3 Low vs zone (+/- " + str.tostring(zoneFac, "0.00") + " ATR)", zoneTxt,
         closesThrough > 0 or rdZonePos == "through zone" ? colNo : char3 ? colOk : colMid)
 
    bandTxt = not bzSet ? "buy zone not set" : na(rdBandAtr) ? "n/a" :
         str.tostring(rdBand, "0.00") + " pt = " + str.tostring(rdBandAtr, "0.000") + " ATR  " +
         (not rdHigherLow ? "no higher low" : char4 ? "ok" : "too wide")
    f_row(7, "4 Three-point band (max " + str.tostring(bandMax, "0.00") + ")", bandTxt, char4 ? colOk : colMid)
 
    f_row(8, "Roller (" + rollTfTxt + ", 21.1)", hasReading ? f_px(rdRoller) : "n/a", txt)
 
    volTxt = na(rdPair) ? "n/a" : str.tostring(rdF1, "0.00") + " / " + str.tostring(rdF2, "0.00") + "  ->  " +
         str.tostring(rdPair, "0.00") + " x"
    f_row(9, "Volume into the low (time of day)", volTxt, txt)
    f_row(10, "Volume switch (not a filter)", switchWord, txt)
    f_row(11, "Hallmarks", verdict, verdictCol)
    f_row(12, "not checked here", "#1 phase/SOS  ·  #5 consensus", color.new(color.gray, 30))
 
// =============================================================================
// Alerts, all on bar close. Nothing repaints: the anchor is a fixed timestamp,
// every reading is taken from a closed candle and stays as it was.
// =============================================================================
allMet       = newReading and metCount == 3
throughStart = barstate.isconfirmed and closeThroughNow and not closeThroughNow[1]
 
alertcondition(zoneReachedNow, "Pullback in the buy zone", "WVPO: the pullback low reached the buy zone - read the volume switch in the table")
alertcondition(allMet,         "Three checkable hallmarks met", "WVPO: depth, Spring AVWAP zone and three-point band are met at this pullback low; phase/SOS and consensus are not checked")
alertcondition(throughStart,   "Close through the Spring AVWAP zone", "WVPO: a close below the Spring AVWAP zone - trap symptom 3 of chapter 21.7")
 
f_plain(string what) =>
    what + " | " + syminfo.ticker + " | low " + f_px(rdLow) +
     " | depth " + (na(rdDepthAtr) ? "n/a" : str.tostring(rdDepthAtr, "0.000") + " ATR") +
     " | band " + (na(rdBandAtr) ? "n/a" : str.tostring(rdBandAtr, "0.000") + " ATR") +
     " | volume " + (na(rdPair) ? "n/a" : str.tostring(rdPair, "0.00") + " x, " + switchWord) +
     " | " + verdict + "; phase/SOS and consensus not checked"
 
f_json() =>
    e  = na(whEntry)  ? 0.0 : whEntry
    s  = na(whStop)   ? 0.0 : whStop
    tg = na(whTarget) ? 0.0 : whTarget
    '{"secret":"' + whSecret +
     '","instrument":"' + syminfo.ticker +
     '","richtung":"long","entry":' + str.tostring(e) +
     ',"stop":' + str.tostring(s) +
     ',"target":' + str.tostring(tg) +
     ',"setup_typ":"2a","ts":"' + str.format_time(time, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC") + '"}'
 
useJson = str.length(whSecret) > 0
 
if barstate.isconfirmed and zoneReachedNow
    alert(useJson ? f_json() : f_plain("WVPO LPS pullback reached the buy zone"), alert.freq_once_per_bar_close)
if barstate.isconfirmed and allMet
    alert(useJson ? f_json() : f_plain("WVPO LPS three checkable hallmarks met"), alert.freq_once_per_bar_close)
if throughStart
    alert(useJson ? f_json() : f_plain("WVPO LPS close through the Spring AVWAP zone"), alert.freq_once_per_bar_close)

← 返回列表