Overextension Map Rejection vs Acceptance

x-creed · study · 312 行 · 点赞 12 · TradingView 原页

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

Pine Script

//@version=6
indicator("Overextension Map", shorttitle = "OEM", overlay = true, max_lines_count = 500, max_labels_count = 50)
 
// Overextension Map
// Most band indicators show where price is stretched. This one also answers the next question:
// is the stretch being rejected or accepted?
//
// 1) Three ways to measure overextension, each with six levels:
//    Rolling STDV       - moving average +/- standard deviations
//    Session STDV       - running mean and deviation since the start of the trading day
//    Rolling Percentile - empirical distance from the moving average (no normal-distribution assumption)
// 2) When a bar closes beyond a band after closing inside it, the band value is frozen as a line.
// 3) The break is classified on bar closes only:
//    Snapback     - N consecutive closes back inside the frozen line (rejection)
//    Push-through - N consecutive closes beyond the frozen line (acceptance)
//    Open         - neither within the decision window
// 4) A small table shows how breaks of each level were classified on the loaded history.
//
// Everything is evaluated on confirmed bars, so markers and statistics do not repaint.
// Educational tool. It does not place trades and is not a forecast.
 
// =============================================================================
// Inputs
// =============================================================================
 
string G_MET = "Method"
string method = input.string("Rolling STDV", "Method", options = ["Rolling STDV", "Session STDV", "Rolling Percentile"], group = G_MET,
     tooltip = "Rolling STDV: moving average +/- standard deviations. Session STDV: mean and deviation since the start of the trading day (intraday charts). Rolling Percentile: distance from the moving average that was exceeded only X % of the time.")
float src = input.source(hlc3, "Source", group = G_MET)
int roll_len = input.int(100, "Rolling length", minval = 20, maxval = 1000, group = G_MET)
int sess_min = input.int(10, "Session: minimum bars before bands start", minval = 3, maxval = 200, group = G_MET)
int pctl_len = input.int(1000, "Percentile lookback", minval = 200, maxval = 5000, group = G_MET)
 
string G_LVL = "Levels (STDV multiple | percentile)"
float z1 = input.float(2.0, "Level 1", minval = 0.25, step = 0.25, group = G_LVL, inline = "1")
float p1 = input.float(95.0, "", minval = 50.1, maxval = 99.99, step = 0.05, group = G_LVL, inline = "1")
float z2 = input.float(2.25, "Level 2", minval = 0.25, step = 0.25, group = G_LVL, inline = "2")
float p2 = input.float(97.5, "", minval = 50.1, maxval = 99.99, step = 0.05, group = G_LVL, inline = "2")
float z3 = input.float(2.5, "Level 3", minval = 0.25, step = 0.25, group = G_LVL, inline = "3")
float p3 = input.float(99.0, "", minval = 50.1, maxval = 99.99, step = 0.05, group = G_LVL, inline = "3")
float z4 = input.float(4.0, "Level 4", minval = 0.25, step = 0.25, group = G_LVL, inline = "4")
float p4 = input.float(99.5, "", minval = 50.1, maxval = 99.99, step = 0.05, group = G_LVL, inline = "4")
float z5 = input.float(4.25, "Level 5", minval = 0.25, step = 0.25, group = G_LVL, inline = "5")
float p5 = input.float(99.75, "", minval = 50.1, maxval = 99.99, step = 0.05, group = G_LVL, inline = "5")
float z6 = input.float(4.5, "Level 6", minval = 0.25, step = 0.25, group = G_LVL, inline = "6")
float p6 = input.float(99.9, "", minval = 50.1, maxval = 99.99, step = 0.05, group = G_LVL, inline = "6")
 
string G_CLS = "Classification"
int confirm_closes = input.int(2, "Confirming closes", minval = 1, maxval = 10, group = G_CLS,
     tooltip = "Snapback: this many consecutive closes back inside the frozen line. Push-through: this many consecutive closes beyond it.")
int decision_bars = input.int(6, "Decision window (bars)", minval = 2, maxval = 100, group = G_CLS,
     tooltip = "A break without a classification after this many bars is counted as open.")
 
string G_VIS = "Display"
string band_view = input.string("All", "Bands", options = ["All", "Levels 1-3", "Levels 4-6", "None"], group = G_VIS)
bool show_basis = input.bool(true, "Equilibrium line", group = G_VIS)
string event_view = input.string("Levels 1-3", "Frozen lines and markers", options = ["All", "Levels 1-3", "Levels 4-6", "Off"], group = G_VIS)
int max_event_lines = input.int(60, "Maximum frozen lines on chart", minval = 10, maxval = 400, group = G_VIS)
bool show_table = input.bool(true, "Classification table", group = G_VIS)
string table_pos = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G_VIS)
color col_low = input.color(color.new(color.orange, 40), "Levels 1-3", group = G_VIS, inline = "c")
color col_high = input.color(color.new(color.red, 20), "Levels 4-6", group = G_VIS, inline = "c")
color col_snap = input.color(color.new(color.teal, 0), "Snapback", group = G_VIS, inline = "e")
color col_push = input.color(color.new(color.orange, 0), "Push-through", group = G_VIS, inline = "e")
 
// =============================================================================
// Bands
// =============================================================================
 
float roll_basis = ta.sma(src, roll_len)
float roll_sd = ta.stdev(src, roll_len)
float roll_absdev = math.abs(src - roll_basis)
float q1 = ta.percentile_nearest_rank(roll_absdev, pctl_len, p1)
float q2 = ta.percentile_nearest_rank(roll_absdev, pctl_len, p2)
float q3 = ta.percentile_nearest_rank(roll_absdev, pctl_len, p3)
float q4 = ta.percentile_nearest_rank(roll_absdev, pctl_len, p4)
float q5 = ta.percentile_nearest_rank(roll_absdev, pctl_len, p5)
float q6 = ta.percentile_nearest_rank(roll_absdev, pctl_len, p6)
 
// Session mean and sample deviation, restarted at every new trading day (Welford update).
var int sess_n = 0
var float sess_mean = na
var float sess_m2 = 0.0
if timeframe.change("D") or na(sess_mean)
    sess_n := 1
    sess_mean := src
    sess_m2 := 0.0
else
    sess_n += 1
    float delta = src - sess_mean
    sess_mean += delta / sess_n
    sess_m2 += delta * (src - sess_mean)
float sess_basis = sess_n >= sess_min ? sess_mean : na
float sess_sd = sess_n >= sess_min ? math.sqrt(math.max(sess_m2 / (sess_n - 1), 0.0)) : na
 
int m = method == "Rolling STDV" ? 0 : method == "Session STDV" ? 1 : 2
float basis = m == 1 ? sess_basis : roll_basis
float sd = m == 1 ? sess_sd : roll_sd
 
float w1 = m == 2 ? q1 : sd * z1
float w2 = m == 2 ? q2 : sd * z2
float w3 = m == 2 ? q3 : sd * z3
float w4 = m == 2 ? q4 : sd * z4
float w5 = m == 2 ? q5 : sd * z5
float w6 = m == 2 ? q6 : sd * z6
 
float up1 = basis + w1
float up2 = basis + w2
float up3 = basis + w3
float up4 = basis + w4
float up5 = basis + w5
float up6 = basis + w6
float lo1 = basis - w1
float lo2 = basis - w2
float lo3 = basis - w3
float lo4 = basis - w4
float lo5 = basis - w5
float lo6 = basis - w6
 
float up1_prev = up1[1]
float up2_prev = up2[1]
float up3_prev = up3[1]
float up4_prev = up4[1]
float up5_prev = up5[1]
float up6_prev = up6[1]
float lo1_prev = lo1[1]
float lo2_prev = lo2[1]
float lo3_prev = lo3[1]
float lo4_prev = lo4[1]
float lo5_prev = lo5[1]
float lo6_prev = lo6[1]
 
f_up(int k) => k == 0 ? up1 : k == 1 ? up2 : k == 2 ? up3 : k == 3 ? up4 : k == 4 ? up5 : up6
f_lo(int k) => k == 0 ? lo1 : k == 1 ? lo2 : k == 2 ? lo3 : k == 3 ? lo4 : k == 4 ? lo5 : lo6
f_up_prev(int k) => k == 0 ? up1_prev : k == 1 ? up2_prev : k == 2 ? up3_prev : k == 3 ? up4_prev : k == 4 ? up5_prev : up6_prev
f_lo_prev(int k) => k == 0 ? lo1_prev : k == 1 ? lo2_prev : k == 2 ? lo3_prev : k == 3 ? lo4_prev : k == 4 ? lo5_prev : lo6_prev
f_level_name(int k) =>
    float z = k == 0 ? z1 : k == 1 ? z2 : k == 2 ? z3 : k == 3 ? z4 : k == 4 ? z5 : z6
    float p = k == 0 ? p1 : k == 1 ? p2 : k == 2 ? p3 : k == 3 ? p4 : k == 4 ? p5 : p6
    m == 2 ? "P" + str.tostring(p) : str.tostring(z) + " SD"
f_event_shown(int k) => event_view == "All" or (event_view == "Levels 1-3" and k <= 2) or (event_view == "Levels 4-6" and k >= 3)
 
bool show_low = band_view == "All" or band_view == "Levels 1-3"
bool show_high = band_view == "All" or band_view == "Levels 4-6"
plot(show_low ? up1 : na, "Upper 1", color.new(col_low, 60))
plot(show_low ? up2 : na, "Upper 2", color.new(col_low, 40))
plot(show_low ? up3 : na, "Upper 3", col_low)
plot(show_high ? up4 : na, "Upper 4", color.new(col_high, 50), 2)
plot(show_high ? up5 : na, "Upper 5", color.new(col_high, 30), 2)
plot(show_high ? up6 : na, "Upper 6", col_high, 2)
plot(show_low ? lo1 : na, "Lower 1", color.new(col_low, 60))
plot(show_low ? lo2 : na, "Lower 2", color.new(col_low, 40))
plot(show_low ? lo3 : na, "Lower 3", col_low)
plot(show_high ? lo4 : na, "Lower 4", color.new(col_high, 50), 2)
plot(show_high ? lo5 : na, "Lower 5", color.new(col_high, 30), 2)
plot(show_high ? lo6 : na, "Lower 6", col_high, 2)
plot(show_basis ? basis : na, "Equilibrium", color.new(color.gray, 45))
 
// =============================================================================
// Breaks and classification (state index = level * 2 + side, side 0 = lower, 1 = upper)
// =============================================================================
 
var bool[] st_active = array.new_bool(12, false)
var int[] st_start = array.new_int(12, 0)
var int[] st_in = array.new_int(12, 0)
var int[] st_out = array.new_int(12, 0)
var float[] st_line = array.new_float(12, na)
var line[] st_ln = array.new_line(12)
var line[] drawn = array.new_line()
 
var int[] n_snap = array.new_int(6, 0)
var int[] n_push = array.new_int(6, 0)
var int[] n_open = array.new_int(6, 0)
 
f_keep_line(line ln) =>
    array.push(drawn, ln)
    if array.size(drawn) > max_event_lines
        line.delete(array.shift(drawn))
    true
 
bool ready = not na(lo6) and not na(lo6_prev) and not na(up6) and not na(up6_prev)
 
bool any_break = false
bool any_snap = false
bool any_push = false
bool mark_snap_lower = false
bool mark_snap_upper = false
bool mark_push_lower = false
bool mark_push_upper = false
 
if barstate.isconfirmed
    // Classify running breaks against their frozen line.
    for k = 0 to 5
        for side = 0 to 1
            int idx = k * 2 + side
            if array.get(st_active, idx)
                int age = bar_index - array.get(st_start, idx)
                line ln = array.get(st_ln, idx)
                if not na(ln)
                    line.set_x2(ln, bar_index)
                if age > 0
                    float frozen = array.get(st_line, idx)
                    bool outside = side == 0 ? close < frozen : close > frozen
                    int out_run = outside ? array.get(st_out, idx) + 1 : 0
                    int in_run = outside ? 0 : array.get(st_in, idx) + 1
                    array.set(st_out, idx, out_run)
                    array.set(st_in, idx, in_run)
                    int cls = in_run >= confirm_closes ? 0 : out_run >= confirm_closes ? 1 : age >= decision_bars ? 2 : -1
                    if cls >= 0
                        array.set(st_active, idx, false)
                        if cls == 0
                            array.set(n_snap, k, array.get(n_snap, k) + 1)
                        else if cls == 1
                            array.set(n_push, k, array.get(n_push, k) + 1)
                        else
                            array.set(n_open, k, array.get(n_open, k) + 1)
                        if not na(ln)
                            line.set_color(ln, cls == 0 ? col_snap : cls == 1 ? col_push : color.new(color.gray, 50))
                            line.set_style(ln, cls == 2 ? line.style_dotted : line.style_solid)
                        if f_event_shown(k)
                            if cls == 0
                                any_snap := true
                                if side == 0
                                    mark_snap_lower := true
                                else
                                    mark_snap_upper := true
                            else if cls == 1
                                any_push := true
                                if side == 0
                                    mark_push_lower := true
                                else
                                    mark_push_upper := true
 
    // Register fresh breaks: a close beyond a band after a close inside it.
    if ready
        for k = 0 to 5
            float lo = f_lo(k)
            float up = f_up(k)
            bool lower_break = close < lo and close[1] >= f_lo_prev(k)
            bool upper_break = close > up and close[1] <= f_up_prev(k)
            for side = 0 to 1
                bool fresh = side == 0 ? lower_break : upper_break
                if fresh
                    int idx = k * 2 + side
                    if array.get(st_active, idx)
                        // A new break replaces an unfinished one: the old one counts as open.
                        array.set(n_open, k, array.get(n_open, k) + 1)
                        line old_ln = array.get(st_ln, idx)
                        if not na(old_ln)
                            line.set_color(old_ln, color.new(color.gray, 50))
                            line.set_style(old_ln, line.style_dotted)
                    float level_price = side == 0 ? lo : up
                    array.set(st_active, idx, true)
                    array.set(st_start, idx, bar_index)
                    array.set(st_in, idx, 0)
                    array.set(st_out, idx, 0)
                    array.set(st_line, idx, level_price)
                    line new_ln = na
                    if f_event_shown(k)
                        new_ln := line.new(bar_index, level_price, bar_index + 1, level_price, color = color.new(color.gray, 20), width = k >= 3 ? 2 : 1, style = line.style_dashed)
                        f_keep_line(new_ln)
                        any_break := true
                    array.set(st_ln, idx, new_ln)
 
plotshape(mark_snap_lower, "Snapback from lower band", shape.triangleup, location.belowbar, col_snap, size = size.tiny)
plotshape(mark_snap_upper, "Snapback from upper band", shape.triangledown, location.abovebar, col_snap, size = size.tiny)
plotshape(mark_push_lower, "Push-through below lower band", shape.diamond, location.belowbar, col_push, size = size.tiny)
plotshape(mark_push_upper, "Push-through above upper band", shape.diamond, location.abovebar, col_push, size = size.tiny)
 
alertcondition(any_break, "Band break", "{{ticker}} {{interval}}: price closed beyond an overextension band.")
alertcondition(any_snap, "Snapback", "{{ticker}} {{interval}}: a band break was rejected (snapback).")
alertcondition(any_push, "Push-through", "{{ticker}} {{interval}}: a band break was accepted (push-through).")
 
// =============================================================================
// Table
// =============================================================================
 
string tpos = table_pos == "Top right" ? position.top_right : table_pos == "Bottom right" ? position.bottom_right : table_pos == "Top left" ? position.top_left : position.bottom_left
color bg_main = color.new(#151515, 10)
color bg_head = color.new(#262824, 0)
color tx_main = color.new(#F1EDE6, 0)
color tx_muted = color.new(#BDB9AD, 0)
 
var table dash = table.new(tpos, 5, 9, bgcolor = bg_main, frame_color = color.new(#3A3D37, 0), frame_width = 1, border_color = color.new(#3A3D37, 0), border_width = 1)
 
f_cell(int col, int row, string txt, color tc, color bg) =>
    table.cell(dash, col, row, txt, text_color = tc, bgcolor = bg, text_size = size.small)
 
f_pct(int part, int whole) => whole > 0 ? str.tostring(100.0 * part / whole, "#") + "%" : "–"
 
if show_table and barstate.islast
    table.clear(dash, 0, 0, 4, 8)
    f_cell(0, 0, "Overextension Map · " + method + " · " + syminfo.ticker + " " + timeframe.period, tx_main, bg_head)
    table.merge_cells(dash, 0, 0, 4, 0)
    f_cell(0, 1, "Level", tx_muted, bg_head)
    f_cell(1, 1, "Breaks", tx_muted, bg_head)
    f_cell(2, 1, "Snapback", tx_muted, bg_head)
    f_cell(3, 1, "Push-through", tx_muted, bg_head)
    f_cell(4, 1, "Open", tx_muted, bg_head)
    for k = 0 to 5
        int sn = array.get(n_snap, k)
        int pn = array.get(n_push, k)
        int op = array.get(n_open, k)
        int total = sn + pn + op
        color tc = total < 30 ? tx_muted : tx_main
        f_cell(0, 2 + k, f_level_name(k), tx_main, bg_main)
        f_cell(1, 2 + k, str.tostring(total), tc, bg_main)
        f_cell(2, 2 + k, f_pct(sn, total), sn > pn and total >= 30 ? col_snap : tc, bg_main)
        f_cell(3, 2 + k, f_pct(pn, total), pn > sn and total >= 30 ? col_push : tc, bg_main)
        f_cell(4, 2 + k, f_pct(op, total), tc, bg_main)
    f_cell(0, 8, "Classified breaks on the loaded bars. Grey = fewer than 30. Not a forecast.", tx_muted, bg_main)
    table.merge_cells(dash, 0, 8, 4, 8)

← 返回列表