本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator(title = "Adaptive Pressure Corridor Pyramid", shorttitle = "APC Pyramid", overlay = true, max_labels_count = 500, max_bars_back = 500)
// ───────────────────────── Groups ─────────────────────────
gA = "Anchor"
gP = "Pressure Field"
gV = "Visuals"
gS = "Signals"
gF = "Weakness Fixes"
gY = "Pyramid Orders"
// ───────────────────────── Inputs ─────────────────────────
// Anchor
anchType = input.string("KAMA", "Anchor type", options = ["KAMA", "EMA", "HMA", "VWMA"], group = gA,
tooltip = "Reference line the corridor is built from. KAMA adapts speed to trend efficiency and lags less in trends while staying calm in ranges. EMA/HMA/VWMA are fixed-speed alternatives.")
anchLen = input.int(21, "Anchor length", minval = 5, maxval = 200, group = gA,
tooltip = "Lookback of the anchor. Higher values give a smoother, slower anchor and fewer signals. Lower values react faster but produce more noise.")
kamaFast = input.int(2, "KAMA fast period", minval = 1, maxval = 20, group = gA,
tooltip = "Fastest smoothing KAMA uses in strong trends. Lower values make the anchor hug price more tightly during trends.")
kamaSlow = input.int(30, "KAMA slow period", minval = 5, maxval = 100, group = gA,
tooltip = "Slowest smoothing KAMA uses in choppy markets. Higher values flatten the anchor more during ranges, reducing false slope changes.")
// Pressure field
lookback = input.int(50, "Field lookback (bars)", minval = 10, maxval = 100, group = gP,
tooltip = "How many past bars feed the pressure field. More bars give a steadier profile but cost speed and react slower to new pressure.")
halfLife = input.float(6.0, "Pressure half-life (bars)", minval = 1.0, maxval = 30.0, step = 0.5, group = gP,
tooltip = "Bars until a bar's pressure weight halves. Lower values focus on very recent pressure (faster, noisier). Higher values remember older pressure (smoother, slower).")
widthMult = input.float(0.35, "Kernel width (x ATR)", minval = 0.05, maxval = 2.0, step = 0.05, group = gP,
tooltip = "Price spread of each pressure point, as a multiple of ATR. Smaller values create sharper pressure pockets; larger values blend bands into a smooth gradient.")
wickW = input.float(0.8, "Wick rejection weight", minval = 0.0, maxval = 2.5, step = 0.05, group = gP,
tooltip = "Weight of wick rejection. Lower wicks add buying pressure, upper wicks add selling pressure. Set 0 to ignore wicks; raise it to emphasise rejection.")
useVol = input.bool(true, "Volume weighting", group = gP,
tooltip = "Scale each bar's pressure by its relative volume (capped 0.25x to 3x). Turn off for symbols with unreliable volume such as some forex or index feeds.")
minAct = input.float(0.15, "Minimum band activity", minval = 0.01, maxval = 0.9, step = 0.01, group = gP,
tooltip = "Minimum normalised pressure a band needs to be coloured and counted. Higher values show fewer, stronger bands and make signals stricter.")
// Visuals
buyCol = input.color(#00D9A3, "Buying pressure", group = gV, inline = "cols",
tooltip = "Colour for bands dominated by buying pressure and a rising anchor.")
sellCol = input.color(#FF4D73, "Selling pressure", group = gV, inline = "cols",
tooltip = "Colour for bands dominated by selling pressure and a falling anchor.")
brightness = input.float(2.0, "Brightness", minval = 0.5, maxval = 3.0, step = 0.1, group = gV,
tooltip = "Visual opacity of the bands only. Higher values make bands more solid. It does not change any calculation or signal.")
showAnchor = input.bool(true, "Show anchor", group = gV,
tooltip = "Draw the anchor line coloured by its slope.")
showLabels = input.bool(true, "Show order labels (B1, S1...)", group = gV,
tooltip = "Draw numbered labels for each order: B1/S1 for the first order and B2, B3... for pyramid additions.")
// Signals
sigOn = input.bool(true, "Enable BUY / SELL signals", group = gS,
tooltip = "Master switch for signal generation, labels and alerts.")
domTh = input.float(0.25, "Pressure dominance threshold", minval = 0.05, maxval = 0.95, step = 0.05, group = gS,
tooltip = "Minimum net profile bias (buy minus sell over total) required. Higher values demand stronger one-sided pressure, giving fewer but cleaner signals.")
minBands = input.int(5, "Minimum dominant bands (of 10)", minval = 1, maxval = 10, group = gS,
tooltip = "How many of the 10 corridor bands must be coloured in the signal direction. Lower values signal earlier; higher values wait for broader agreement.")
cooldown = input.int(5, "Same-side cooldown (bars)", minval = 1, maxval = 50, group = gS,
tooltip = "Minimum bars between two first-order signals on the same side. Opposite-side signals are not blocked.")
// Weakness fixes
fixConfirm = input.bool(true, "FIX: Confirmed bars only", group = gF,
tooltip = "Signals and pyramid adds trigger only after the bar closes, so they never appear and then vanish. Turn off for earlier but repaint-prone live signals.")
fixRegime = input.bool(true, "FIX: One signal per regime", group = gF,
tooltip = "After a BUY, no new BUY until the regime resets (opposite signal or close crossing back through the anchor). Prevents repeated signals on consecutive bars.")
fixChop = input.bool(true, "FIX: Choppiness filter", group = gF,
tooltip = "Block signals when the Choppiness Index is above the maximum, filtering sideways markets.")
chopLen = input.int(14, "Choppiness length", minval = 5, maxval = 100, group = gF,
tooltip = "Lookback of the Choppiness Index. Longer values judge the market regime over a wider window.")
chopMax = input.float(61.8, "Choppiness maximum", minval = 40.0, maxval = 80.0, step = 0.1, group = gF,
tooltip = "Signals require the Choppiness Index below this value. Lower values are stricter and allow only clearly trending conditions.")
fixAdx = input.bool(true, "FIX: ADX trend-strength filter", group = gF,
tooltip = "Require a minimum ADX so signals only fire when a trend has measurable strength.")
adxLen = input.int(14, "ADX length", minval = 5, maxval = 50, group = gF,
tooltip = "Smoothing length of DMI/ADX. Longer values are steadier but react slower.")
adxMin = input.float(18.0, "ADX minimum", minval = 5.0, maxval = 50.0, step = 0.5, group = gF,
tooltip = "Minimum ADX for signals. Higher values filter more ranging periods but can skip early trend entries.")
fixVolat = input.bool(true, "FIX: Volatility filter", group = gF,
tooltip = "Require current ATR to be at least a fraction of its 100-bar average, avoiding dead, low-volatility periods.")
volMin = input.float(0.8, "Min ATR ratio (ATR / avg ATR)", minval = 0.3, maxval = 2.0, step = 0.05, group = gF,
tooltip = "Signals need ATR(14) divided by its 100-bar average at or above this value. Raise to trade only active markets.")
fixHtf = input.bool(false, "FIX: Higher-timeframe trend filter", group = gF,
tooltip = "Only BUY when the higher-timeframe close is above its EMA, only SELL when below. Uses the previous closed HTF bar to avoid repainting.")
htfTf = input.timeframe("240", "HTF timeframe", group = gF,
tooltip = "Higher timeframe used for the trend filter. Choose one clearly above the chart timeframe.")
htfLen = input.int(50, "HTF EMA length", minval = 5, maxval = 300, group = gF,
tooltip = "EMA length on the higher timeframe. Longer values define the larger trend more conservatively.")
// Pyramid
pyrOn = input.bool(true, "Enable pyramid orders", group = gY,
tooltip = "Allow additional orders in the same direction after the first signal, until the maximum is reached or an opposite signal resets the count.")
pyrMax = input.int(4, "Max orders per side", minval = 1, maxval = 10, group = gY,
tooltip = "Total orders allowed per side including the first one. 1 disables additions; higher values allow more scaling.")
pyrMode = input.string("ATR", "Spacing mode", options = ["Ticks", "ATR"], group = gY,
tooltip = "How the distance between orders is measured: a fixed number of ticks or a multiple of ATR that adapts to volatility.")
pyrTicks = input.int(100, "Spacing (ticks)", minval = 1, maxval = 100000, group = gY,
tooltip = "Distance in minimum ticks from the last order before a new one can be added. Used in Ticks mode. Larger values mean fewer, wider-spaced adds.")
pyrAtrLen = input.int(14, "Spacing ATR length", minval = 1, maxval = 100, group = gY,
tooltip = "ATR length used for spacing in ATR mode.")
pyrAtrMult = input.float(1.0, "Spacing ATR multiplier", minval = 0.1, maxval = 10.0, step = 0.1, group = gY,
tooltip = "Spacing equals ATR times this value in ATR mode. Higher values require larger moves before adding.")
pyrDir = input.string("Pullback", "Add direction", options = ["Pullback", "Continuation"], group = gY,
tooltip = "Pullback: add BUY when price falls below the last buy by the spacing (SELL: rises above). Continuation: add BUY when price rises above the last buy (SELL: falls below).")
pyrNeedBias = input.bool(true, "Adds require supporting bias", group = gY,
tooltip = "Pyramid adds only when the profile bias still favours the trade direction. Prevents adding into reversing pressure.")
// ───────────────────────── Helpers ─────────────────────────
clamp(float x, float lo, float hi) => math.max(lo, math.min(hi, x))
gauss(float d) => math.exp(-0.5 * d * d)
kamaCalc(float src, int len, int fastL, int slowL) =>
change = math.abs(src - nz(src[len], src))
noise = math.sum(math.abs(src - nz(src[1], src)), len)
er = nz(noise) != 0.0 ? nz(change) / noise : 0.0
fastSC = 2.0 / (fastL + 1)
slowSC = 2.0 / (slowL + 1)
sc = math.pow(er * (fastSC - slowSC) + slowSC, 2)
float k = na
k := na(k[1]) ? src : k[1] + sc * (src - k[1])
k
// ───────────────────────── Anchor ─────────────────────────
emaA = ta.ema(close, anchLen)
hmaA = ta.hma(close, anchLen)
vwmaA = ta.vwma(close, anchLen)
kamaA = kamaCalc(close, anchLen, kamaFast, kamaSlow)
float anchor = switch anchType
"EMA" => emaA
"HMA" => hmaA
"VWMA" => na(vwmaA) ? emaA : vwmaA
=> kamaA
// ───────────────────────── Per-bar pressure ─────────────────────────
atr = ta.atr(14)
rng = math.max(high - low, syminfo.mintick)
bodyR = clamp((close - open) / rng, -1.0, 1.0)
clvR = clamp((2.0 * close - high - low) / rng, -1.0, 1.0)
travR = clamp((close - nz(close[1], open)) / rng, -1.5, 1.5)
resp = clamp(0.45 * travR + 0.30 * bodyR + 0.25 * clvR, -1.0, 1.0)
volAvg = ta.sma(nz(volume), 50)
volW = useVol and nz(volume) > 0.0 and nz(volAvg) > 0.0 ? clamp(volume / volAvg, 0.25, 3.0) : 1.0
moveBuy = math.max(resp, 0.0) * volW
moveSell = math.max(-resp, 0.0) * volW
lowWickR = math.max(0.0, math.min(open, close) - low) / rng
upWickR = math.max(0.0, high - math.max(open, close)) / rng
wickBuy = lowWickR * wickW * volW
wickSell = upWickR * wickW * volW
moveBuyCtr = close * 0.7 + high * 0.3
moveSellCtr = close * 0.7 + low * 0.3
wickBuyCtr = (low + math.min(open, close)) * 0.5
wickSellCtr = (high + math.max(open, close)) * 0.5
pressBase = nz(ta.sma(moveBuy + moveSell + wickBuy + wickSell, 50), 1.0)
// ───────────────────────── Corridor geometry ─────────────────────────
const int BANDS = 10
ready = not na(anchor) and not na(atr) and bar_index > lookback + anchLen and math.abs(close - anchor) > 2 * syminfo.mintick
step = ready ? (close - anchor) / BANDS : na
decayF = math.pow(0.5, 1.0 / halfLife)
decaySum = (1.0 - math.pow(decayF, lookback)) / (1.0 - decayF)
var array<color> bandCols = array.new_color(BANDS, na)
for i = 0 to BANDS - 1
bandCols.set(i, na)
profBuy = 0.0
profSell = 0.0
buyBands = 0
sellBands = 0
neutralCol = #7A869A
if ready
kw = math.max(math.max(atr * widthMult, math.abs(step) * 1.2), syminfo.mintick)
for b = 0 to BANDS - 1
here = anchor + step * (b + 0.5)
bF = 0.0
sF = 0.0
age = 1.0
for k = 0 to lookback - 1
bF += (nz(moveBuy[k]) * gauss((here - nz(moveBuyCtr[k], here)) / kw) + nz(wickBuy[k]) * gauss((here - nz(wickBuyCtr[k], here)) / (kw * 0.7))) * age
sF += (nz(moveSell[k]) * gauss((here - nz(moveSellCtr[k], here)) / kw) + nz(wickSell[k]) * gauss((here - nz(wickSellCtr[k], here)) / (kw * 0.7))) * age
age *= decayF
tot = bF + sF
imb = tot > 0.0 ? (bF - sF) / tot : 0.0
activity = clamp(tot / math.max(pressBase * decaySum * 0.35, 1e-10), 0.0, 1.0)
if activity >= minAct and math.abs(imb) >= 0.10
tint = imb > 0.0 ? color.from_gradient(imb, 0.0, 1.0, neutralCol, buyCol) : color.from_gradient(imb, -1.0, 0.0, sellCol, neutralCol)
transp = clamp(85.0 - brightness * 12.0 - 30.0 * activity - 15.0 * math.abs(imb), 5.0, 92.0)
bandCols.set(b, color.new(tint, transp))
profBuy += bF
profSell += sF
if imb > 0.0
buyBands += 1
else
sellBands += 1
profTot = profBuy + profSell
profBias = profTot > 0.0 ? (profBuy - profSell) / profTot : 0.0
// ───────────────────────── Corridor rendering ─────────────────────────
l0 = plot(ready ? anchor : na, "Level 0", color = na, editable = false)
l1 = plot(ready ? anchor + step * 1 : na, "Level 1", color = na, editable = false)
l2 = plot(ready ? anchor + step * 2 : na, "Level 2", color = na, editable = false)
l3 = plot(ready ? anchor + step * 3 : na, "Level 3", color = na, editable = false)
l4 = plot(ready ? anchor + step * 4 : na, "Level 4", color = na, editable = false)
l5 = plot(ready ? anchor + step * 5 : na, "Level 5", color = na, editable = false)
l6 = plot(ready ? anchor + step * 6 : na, "Level 6", color = na, editable = false)
l7 = plot(ready ? anchor + step * 7 : na, "Level 7", color = na, editable = false)
l8 = plot(ready ? anchor + step * 8 : na, "Level 8", color = na, editable = false)
l9 = plot(ready ? anchor + step * 9 : na, "Level 9", color = na, editable = false)
l10 = plot(ready ? close : na, "Level 10", color = na, editable = false)
fill(l0, l1, color = bandCols.get(0), title = "Band 1")
fill(l1, l2, color = bandCols.get(1), title = "Band 2")
fill(l2, l3, color = bandCols.get(2), title = "Band 3")
fill(l3, l4, color = bandCols.get(3), title = "Band 4")
fill(l4, l5, color = bandCols.get(4), title = "Band 5")
fill(l5, l6, color = bandCols.get(5), title = "Band 6")
fill(l6, l7, color = bandCols.get(6), title = "Band 7")
fill(l7, l8, color = bandCols.get(7), title = "Band 8")
fill(l8, l9, color = bandCols.get(8), title = "Band 9")
fill(l9, l10, color = bandCols.get(9), title = "Band 10")
anchUp = not na(anchor[1]) and anchor > anchor[1]
anchDn = not na(anchor[1]) and anchor < anchor[1]
plot(showAnchor ? anchor : na, "Anchor Glow", color = color.new(anchUp ? buyCol : sellCol, 70), linewidth = 5)
plot(showAnchor ? anchor : na, "Anchor", color = anchUp ? buyCol : sellCol, linewidth = 2)
// ───────────────────────── Filters (FIX) ─────────────────────────
// FIX: Choppiness Index — blocks sideways markets
hhC = ta.highest(high, chopLen)
llC = ta.lowest(low, chopLen)
chop = hhC - llC > 0.0 ? 100.0 * math.log10(math.sum(ta.atr(1), chopLen) / (hhC - llC)) / math.log10(chopLen) : 100.0
chopOk = not fixChop or chop < chopMax
// FIX: ADX — requires measurable trend strength
[diP, diM, adxV] = ta.dmi(adxLen, adxLen)
adxOk = not fixAdx or nz(adxV) >= adxMin
// FIX: Volatility — avoid dead markets
atrRatio = atr / math.max(nz(ta.sma(atr, 100), atr), syminfo.mintick)
volOk = not fixVolat or nz(atrRatio) >= volMin
// FIX: HTF trend — previous closed HTF bar only, lookahead off (no repaint)
htfClose = request.security(syminfo.tickerid, htfTf, close[1], lookahead = barmerge.lookahead_off)
htfEma = request.security(syminfo.tickerid, htfTf, ta.ema(close, htfLen)[1], lookahead = barmerge.lookahead_off)
htfLongOk = not fixHtf or (not na(htfEma) and htfClose > htfEma)
htfShortOk = not fixHtf or (not na(htfEma) and htfClose < htfEma)
commonOk = chopOk and adxOk and volOk
// ───────────────────────── Signal conditions ─────────────────────────
// BUY: bias >= threshold, enough buy bands, buy bands > sell bands, close above rising anchor, filters pass
// SELL: bias <= -threshold, enough sell bands, sell bands > buy bands, close below falling anchor, filters pass
longCond = sigOn and ready and profBias >= domTh and buyBands >= minBands and buyBands > sellBands and close > anchor and anchUp and commonOk and htfLongOk
shortCond = sigOn and ready and profBias <= -domTh and sellBands >= minBands and sellBands > buyBands and close < anchor and anchDn and commonOk and htfShortOk
// FIX: confirmed bars only (anti-repaint)
confirmOk = not fixConfirm or barstate.isconfirmed
var int regime = 0
var int lastBuyBar = na
var int lastSellBar = na
var int buyCount = 0
var int sellCount = 0
var float lastBuyPx = na
var float lastSellPx = na
pyrDist = pyrMode == "Ticks" ? pyrTicks * syminfo.mintick : nz(ta.atr(pyrAtrLen), rng) * pyrAtrMult
bool buySig = false
bool sellSig = false
bool pyrBuy = false
bool pyrSell = false
if confirmOk
// FIX: regime reset — close crossing back through the anchor returns to neutral
if fixRegime and regime == 1 and close < anchor
regime := 0
if fixRegime and regime == -1 and close > anchor
regime := 0
// FIX: one signal per regime / edge-trigger + cooldown (no repeated signals)
buyFresh = fixRegime ? regime != 1 : not longCond[1]
sellFresh = fixRegime ? regime != -1 : not shortCond[1]
buyCdOk = na(lastBuyBar) or bar_index - lastBuyBar >= cooldown
sellCdOk = na(lastSellBar) or bar_index - lastSellBar >= cooldown
if longCond and buyFresh and buyCdOk
buySig := true
regime := 1
lastBuyBar := bar_index
buyCount := 1
lastBuyPx := close
sellCount := 0
lastSellPx := na
else if shortCond and sellFresh and sellCdOk
sellSig := true
regime := -1
lastSellBar := bar_index
sellCount := 1
lastSellPx := close
buyCount := 0
lastBuyPx := na
// ───── Pyramid engine ─────
// Pullback mode : BUY add when close <= last buy - spacing ; SELL add when close >= last sell + spacing
// Continuation : BUY add when close >= last buy + spacing ; SELL add when close <= last sell - spacing
if pyrOn and not buySig and not sellSig
buyLive = buyCount >= 1 and (not fixRegime or regime == 1)
sellLive = sellCount >= 1 and (not fixRegime or regime == -1)
if buyLive and buyCount < pyrMax and not na(lastBuyPx) and (not pyrNeedBias or profBias > 0.0)
buyDistOk = pyrDir == "Pullback" ? close <= lastBuyPx - pyrDist : close >= lastBuyPx + pyrDist
if buyDistOk
pyrBuy := true
buyCount += 1
lastBuyPx := close
if sellLive and sellCount < pyrMax and not na(lastSellPx) and (not pyrNeedBias or profBias < 0.0)
sellDistOk = pyrDir == "Pullback" ? close >= lastSellPx + pyrDist : close <= lastSellPx - pyrDist
if sellDistOk
pyrSell := true
sellCount += 1
lastSellPx := close
// ───────────────────────── Plots & labels ─────────────────────────
plotshape(buySig, "Buy", shape.triangleup, location.belowbar, color = #22C55E, size = size.small)
plotshape(sellSig, "Sell", shape.triangledown, location.abovebar, color = #F23645, size = size.small)
plotshape(pyrBuy, "Pyramid Buy", shape.circle, location.belowbar, color = color.new(#22C55E, 30), size = size.tiny)
plotshape(pyrSell, "Pyramid Sell", shape.circle, location.abovebar, color = color.new(#F23645, 30), size = size.tiny)
labOff = nz(atr, rng) * 0.6
biasTxt = str.tostring(profBias * 100.0, "#.0") + "%"
if showLabels and (buySig or pyrBuy)
label.new(bar_index, low - labOff, "B" + str.tostring(buyCount), style = label.style_label_up,
color = buySig ? #22C55E : color.new(#22C55E, 35), textcolor = color.white, size = size.small,
tooltip = (buySig ? "First BUY" : "Pyramid BUY") + "\nPrice: " + str.tostring(close, format.mintick) + "\nProfile bias: " + biasTxt + "\nBuy bands: " + str.tostring(buyBands) + "/10")
if showLabels and (sellSig or pyrSell)
label.new(bar_index, high + labOff, "S" + str.tostring(sellCount), style = label.style_label_down,
color = sellSig ? #F23645 : color.new(#F23645, 35), textcolor = color.white, size = size.small,
tooltip = (sellSig ? "First SELL" : "Pyramid SELL") + "\nPrice: " + str.tostring(close, format.mintick) + "\nProfile bias: " + biasTxt + "\nSell bands: " + str.tostring(sellBands) + "/10")
// ───────────────────────── Alerts ─────────────────────────
alertcondition(buySig, "APC Buy", "APC Pyramid: first BUY on {{ticker}} {{interval}} at {{close}}")
alertcondition(sellSig, "APC Sell", "APC Pyramid: first SELL on {{ticker}} {{interval}} at {{close}}")
alertcondition(pyrBuy, "APC Pyramid Buy", "APC Pyramid: pyramid BUY add on {{ticker}} {{interval}} at {{close}}")
alertcondition(pyrSell, "APC Pyramid Sell", "APC Pyramid: pyramid SELL add on {{ticker}} {{interval}} at {{close}}")