BTM - Price Action Toolkit

BeyondTheMarkets · study · 206 行 · 点赞 119 · TradingView 原页

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

Pine Script

//@version=6
indicator("BTM - Price Action Toolkit", "BTM PA Toolkit", overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 100, max_bars_back = 500)
 
// ───────────── Settings ─────────────
sensitivity  = input.string("Medium", "Sensitivity", options = ["High (more signals)", "Medium", "Low (fewer, stronger)"], tooltip = "High reacts to small swings. Low only reacts to big swings. On 1–5 minute charts, Medium or Low is usually cleaner.")
showTrend    = input.bool(true, "Show trend break lines")
showSwings   = input.bool(true, "Label swing points (HH / HL / LH / LL)", tooltip = "HH = higher high, HL = higher low (uptrend). LH = lower high, LL = lower low (downtrend).")
showZones    = input.bool(true, "Show buy / sell zones")
showSignals  = input.bool(true, "Show setups", tooltip = "A setup appears when a strong candle (engulfing or pin bar) closes at a zone, in the direction of the trend.")
zonesPerSide = input.int(2, "Zones to keep on each side", minval = 1, maxval = 5)
lineWidth    = input.int(2, "Line thickness", minval = 1, maxval = 5)
 
grpP = "Info panel"
showPanel = input.bool(true, "Show info panel", group = grpP)
panelPos  = input.string("Top right", "Panel position", options = ["Top left", "Top center", "Top right", "Middle left", "Middle center", "Middle right", "Bottom left", "Bottom center", "Bottom right"], group = grpP)
panelSize = input.string("Normal", "Panel size", options = ["Small", "Normal", "Large", "Huge"], group = grpP)
 
upCol = input.color(#089981, "Up colour",   group = "Colours")
dnCol = input.color(#f23645, "Down colour", group = "Colours")
 
swingLen = sensitivity == "High (more signals)" ? 5 : sensitivity == "Medium" ? 10 : 20
 
// ───────────── Helpers ─────────────
// Remove zones that price has closed through; keep the rest stretched to the current bar.
updateZones(array<box> a, bool isDemand) =>
    if a.size() > 0
        for i = a.size() - 1 to 0
            b = a.get(i)
            broken = isDemand ? close < b.get_bottom() : close > b.get_top()
            if broken
                a.remove(i)
                b.delete()
            else
                b.set_right(bar_index + 10)
 
// Does a new zone overlap one we already have?
overlaps(array<box> a, float top, float btm) =>
    bool hit = false
    for b in a
        if top >= b.get_bottom() and btm <= b.get_top()
            hit := true
    hit
 
// Is the current candle trading inside one of the zones?
touching(array<box> a, bool isDemand) =>
    bool hit = false
    for b in a
        if isDemand ? (low <= b.get_top() and close >= b.get_bottom()) : (high >= b.get_bottom() and close <= b.get_top())
            hit := true
    hit
 
// Turn the panel settings into TradingView values
getPos(string p) =>
    switch p
        "Top left"      => position.top_left
        "Top center"    => position.top_center
        "Top right"     => position.top_right
        "Middle left"   => position.middle_left
        "Middle center" => position.middle_center
        "Middle right"  => position.middle_right
        "Bottom left"   => position.bottom_left
        "Bottom center" => position.bottom_center
        => position.bottom_right
 
getSize(string s) =>
    switch s
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.huge
 
// ───────────── State ─────────────
var array<box> demandZones = array.new<box>()
var array<box> supplyZones = array.new<box>()
var int   trend      = 0      // 1 = up, -1 = down, 0 = not decided yet
var float lastPH     = na
var float lastPL     = na
var float topLvl     = na
var int   topIdx     = na
var bool  topCrossed = true
var float btmLvl     = na
var int   btmIdx     = na
var bool  btmCrossed = true
var int   lastSignal = -1000
 
// ───────────── Swing points ─────────────
ph = ta.pivothigh(high, swingLen, swingLen)
pl = ta.pivotlow(low, swingLen, swingLen)
 
if not na(ph)
    pIdx = bar_index - swingLen
    if showSwings and not na(lastPH)
        isHH = ph > lastPH
        label.new(pIdx, ph, isHH ? "HH" : "LH", style = label.style_label_down, color = color(na), textcolor = isHH ? upCol : dnCol, size = size.normal, text_formatting = text.format_bold)
    lastPH     := ph
    topLvl     := ph
    topIdx     := pIdx
    topCrossed := false
 
if not na(pl)
    pIdx = bar_index - swingLen
    if showSwings and not na(lastPL)
        isHL = pl > lastPL
        label.new(pIdx, pl, isHL ? "HL" : "LL", style = label.style_label_up, color = color(na), textcolor = isHL ? upCol : dnCol, size = size.normal, text_formatting = text.format_bold)
    lastPL     := pl
    btmLvl     := pl
    btmIdx     := pIdx
    btmCrossed := false
 
// ───────────── Trend breaks + zones ─────────────
bool bullFlip = false
bool bearFlip = false
 
if not topCrossed and close > topLvl
    topCrossed := true
    bullFlip   := trend == -1
    trend      := 1
    if showTrend
        line.new(topIdx, topLvl, bar_index, topLvl, color = upCol, width = lineWidth, style = bullFlip ? line.style_dashed : line.style_solid)
        label.new(math.round((topIdx + bar_index) / 2), topLvl, bullFlip ? "Reversal ▲" : "Break ▲", style = label.style_label_down, color = upCol, textcolor = color.white, size = size.small, text_formatting = text.format_bold, tooltip = bullFlip ? "Price broke above a high while the trend was down — the trend has flipped up." : "Price broke above the last high — the uptrend continues.")
    if showZones
        // Buy zone = the lowest down candle before the move that broke the high
        span = math.min(bar_index - topIdx, 300)
        float zTop = na
        float zBtm = na
        int   zIdx = na
        for i = 1 to span
            if close[i] < open[i] and (na(zBtm) or low[i] < zBtm)
                zTop := high[i]
                zBtm := low[i]
                zIdx := bar_index - i
        if not na(zIdx) and not overlaps(demandZones, zTop, zBtm)
            demandZones.push(box.new(zIdx, zTop, bar_index + 10, zBtm, border_color = color.new(upCol, 40), border_width = 1, bgcolor = color.new(upCol, 85), text = "Buy zone", text_color = upCol, text_size = size.small, text_halign = text.align_right, text_formatting = text.format_bold))
            if demandZones.size() > zonesPerSide
                demandZones.shift().delete()
 
if not btmCrossed and close < btmLvl
    btmCrossed := true
    bearFlip   := trend == 1
    trend      := -1
    if showTrend
        line.new(btmIdx, btmLvl, bar_index, btmLvl, color = dnCol, width = lineWidth, style = bearFlip ? line.style_dashed : line.style_solid)
        label.new(math.round((btmIdx + bar_index) / 2), btmLvl, bearFlip ? "Reversal ▼" : "Break ▼", style = label.style_label_up, color = dnCol, textcolor = color.white, size = size.small, text_formatting = text.format_bold, tooltip = bearFlip ? "Price broke below a low while the trend was up — the trend has flipped down." : "Price broke below the last low — the downtrend continues.")
    if showZones
        // Sell zone = the highest up candle before the move that broke the low
        span = math.min(bar_index - btmIdx, 300)
        float zTop = na
        float zBtm = na
        int   zIdx = na
        for i = 1 to span
            if close[i] > open[i] and (na(zTop) or high[i] > zTop)
                zTop := high[i]
                zBtm := low[i]
                zIdx := bar_index - i
        if not na(zIdx) and not overlaps(supplyZones, zTop, zBtm)
            supplyZones.push(box.new(zIdx, zTop, bar_index + 10, zBtm, border_color = color.new(dnCol, 40), border_width = 1, bgcolor = color.new(dnCol, 85), text = "Sell zone", text_color = dnCol, text_size = size.small, text_halign = text.align_right, text_formatting = text.format_bold))
            if supplyZones.size() > zonesPerSide
                supplyZones.shift().delete()
 
updateZones(demandZones, true)
updateZones(supplyZones, false)
 
// ───────────── Setups: strong candle at a zone, with the trend ─────────────
body   = math.abs(close - open)
rng    = high - low
upWick = high - math.max(open, close)
dnWick = math.min(open, close) - low
 
bullCandle = (close > open and close[1] < open[1] and close >= open[1] and open <= close[1]) or (rng > 0 and dnWick >= 2 * body and dnWick >= 0.6 * rng)
bearCandle = (close < open and close[1] > open[1] and close <= open[1] and open >= close[1]) or (rng > 0 and upWick >= 2 * body and upWick >= 0.6 * rng)
 
atDemand = touching(demandZones, true)
atSupply = touching(supplyZones, false)
cooled   = bar_index - lastSignal >= swingLen
 
bullSetup = barstate.isconfirmed and trend == 1  and bullCandle and atDemand and cooled
bearSetup = barstate.isconfirmed and trend == -1 and bearCandle and atSupply and cooled
 
if showSignals and bullSetup
    label.new(bar_index, low, "Bull setup", style = label.style_label_up, color = upCol, textcolor = color.white, size = size.small, text_formatting = text.format_bold, tooltip = "Bullish candle at a buy zone while the trend is up. Not a guarantee — confirm it yourself and keep your stop below the zone.")
    lastSignal := bar_index
if showSignals and bearSetup
    label.new(bar_index, high, "Bear setup", style = label.style_label_down, color = dnCol, textcolor = color.white, size = size.small, text_formatting = text.format_bold, tooltip = "Bearish candle at a sell zone while the trend is down. Not a guarantee — confirm it yourself and keep your stop above the zone.")
    lastSignal := bar_index
 
// ───────────── Info panel ─────────────
var table panel = table.new(getPos(panelPos), 2, 3, bgcolor = color.new(#131722, 0), frame_color = color.new(color.white, 60), frame_width = 2, border_color = color.new(color.white, 80), border_width = 1)
if showPanel and barstate.islast
    tSize    = getSize(panelSize)
    trendTxt = trend == 1 ? "UP ▲" : trend == -1 ? "DOWN ▼" : "UNCLEAR"
    trendClr = trend == 1 ? upCol : trend == -1 ? dnCol : color.gray
    lookTxt  = trend == 1 ? "Buys at green zones" : trend == -1 ? "Sells at red zones" : "Wait for a break"
    table.cell(panel, 0, 0, "BTM PRICE ACTION", text_color = color.white, text_size = tSize, text_formatting = text.format_bold, bgcolor = color.new(color.white, 85))
    table.merge_cells(panel, 0, 0, 1, 0)
    table.cell(panel, 0, 1, "Trend",    text_color = color.white, text_size = tSize, text_halign = text.align_left, text_formatting = text.format_bold)
    table.cell(panel, 1, 1, trendTxt,   text_color = color.white, text_size = tSize, text_formatting = text.format_bold, bgcolor = trendClr)
    table.cell(panel, 0, 2, "Look for", text_color = color.white, text_size = tSize, text_halign = text.align_left, text_formatting = text.format_bold)
    table.cell(panel, 1, 2, lookTxt,    text_color = trendClr,    text_size = tSize, text_formatting = text.format_bold)
if not showPanel
    table.clear(panel, 0, 0, 1, 2)
 
// ───────────── Alerts ─────────────
alertcondition(bullSetup, "Bull setup",          "{{ticker}}: bullish candle at a buy zone, trend up")
alertcondition(bearSetup, "Bear setup",          "{{ticker}}: bearish candle at a sell zone, trend down")
alertcondition(bullFlip,  "Trend reversal up",   "{{ticker}}: trend flipped up")
alertcondition(bearFlip,  "Trend reversal down", "{{ticker}}: trend flipped down")

← 返回列表