Flip Break Momentum Pyramid

TaninWiselyWealth · study · 311 行 · 点赞 61 · TradingView 原页

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

Pine Script

//@version=6
indicator(title = "Flip Break Momentum Pyramid", shorttitle = "FBM Pyramid", overlay = true, max_labels_count = 500, max_lines_count = 500)
 
// =====================================================================
// FLIP BREAK MOMENTUM PYRAMID
// Core idea : a colour-flip candle (red -> green / green -> red) that
//             breaks the prior candle's reference level by an ATR buffer,
//             with a strong body and a close near the extreme.
// Additions : trend filter (EMA + slope), chop filter (ADX), optional
//             volume filter, cooldown, same-side repeat block,
//             confirmed-bar signals, ATR/Points risk lines, pyramid orders.
// =====================================================================
 
// ==========================================
// GROUPS
// ==========================================
string G_SIG  = "1. Signal Core"
string G_FIX  = "2. Weakness Fixes"
string G_TIME = "3. Session & Lookback"
string G_PYR  = "4. Pyramid Orders"
string G_RISK = "5. Stop Loss & Take Profit"
string G_LVL  = "6. Break Level Line"
string G_VIS  = "7. Visuals & Colors"
 
// ==========================================
// 1. SIGNAL CORE
// ==========================================
tradeMode   = input.string("Both", "Trade Mode", options = ["Long Only", "Short Only", "Both"], group = G_SIG, tooltip = "Choose which side produces signals. Long Only shows Buy orders, Short Only shows Sell orders, Both shows all.")
breakRef    = input.string("Prior Body Edge", "Break Reference", options = ["Prior Close", "Prior Body Edge", "Prior Wick Extreme"], group = G_SIG, tooltip = "Level of the previous candle that the flip candle must close beyond. Prior Close is loosest (more signals); Prior Wick Extreme is strictest (fewer, stronger signals).")
atrLen      = input.int(14, "ATR Length", minval = 1, group = G_SIG, tooltip = "ATR period used for the break buffer, body-strength test and ATR-based risk lines. Higher = smoother volatility estimate; lower = reacts faster to recent volatility.")
breakBufAtr = input.float(0.05, "Break Buffer (x ATR)", minval = 0.0, step = 0.01, group = G_SIG, tooltip = "Extra distance beyond the break level, in ATR multiples, the close must exceed. Increase to filter marginal breaks; set 0 to accept any close beyond the level.")
minBodyAtr  = input.float(0.30, "Min Body Size (x ATR)", minval = 0.0, step = 0.05, group = G_SIG, tooltip = "Minimum candle body size as a multiple of ATR. Higher values require more decisive candles and give fewer signals; 0 disables the body test.")
clvMin      = input.float(0.60, "Min Close Location (0.5-1)", minval = 0.5, maxval = 1.0, step = 0.05, group = G_SIG, tooltip = "Where the close must sit inside the candle range. 0.6 means the top 40% for longs (bottom 40% for shorts). Higher = stronger closes required, fewer signals.")
 
// ==========================================
// 2. WEAKNESS FIXES
// ==========================================
useConfirm   = input.bool(true, "FIX: Confirmed Bar Only", group = G_FIX, tooltip = "Signals and orders only print after the candle closes, so they never appear and disappear in real time. Disable for earlier but repainting intrabar signals.")
useTrend     = input.bool(true, "FIX: Trend Filter (EMA + Slope)", group = G_FIX, tooltip = "Longs only above a rising EMA, shorts only below a falling EMA. Reduces counter-trend reversals that usually fail.")
trendLen     = input.int(50, "Trend EMA Length", minval = 2, group = G_FIX, tooltip = "EMA period for the trend filter. Higher = slower, broader trend; lower = faster but noisier trend definition.")
slopeBars    = input.int(3, "EMA Slope Lookback (Bars)", minval = 1, group = G_FIX, tooltip = "EMA must be higher (longs) or lower (shorts) than it was this many bars ago. Larger values demand a more established slope.")
useChop      = input.bool(true, "FIX: Chop Filter (ADX)", group = G_FIX, tooltip = "Blocks signals when ADX is below the threshold, avoiding sideways markets where colour-flip candles happen constantly.")
adxLen       = input.int(14, "ADX Length", minval = 1, group = G_FIX, tooltip = "DMI/ADX period. Higher = smoother, slower ADX; lower = faster but noisier.")
adxMin       = input.float(18.0, "Min ADX", minval = 0.0, step = 1.0, group = G_FIX, tooltip = "Minimum ADX needed for a signal. Raise to trade only strong directional moves; lower to allow more signals in weaker trends.")
useVol       = input.bool(false, "FIX: Volume Confirmation", group = G_FIX, tooltip = "Requires signal-bar volume above its average. Leave off for symbols without reliable volume data, otherwise no signals will appear.")
volLen       = input.int(20, "Volume Average Length", minval = 1, group = G_FIX, tooltip = "SMA period of volume used as the baseline for the volume filter.")
volMult      = input.float(1.0, "Volume Multiplier", minval = 0.1, step = 0.1, group = G_FIX, tooltip = "Signal volume must be at least average volume times this value. Higher = only high-participation candles qualify.")
useCooldown  = input.bool(true, "FIX: Signal Cooldown", group = G_FIX, tooltip = "Enforces a minimum number of bars between main signals, preventing clusters of back-to-back flips.")
cooldownBars = input.int(3, "Cooldown Bars", minval = 1, group = G_FIX, tooltip = "Bars that must pass after a main signal before another main signal is allowed. Higher = fewer, more spaced signals.")
blockRepeat  = input.bool(true, "FIX: Block Same-Side Repeats", group = G_FIX, tooltip = "After a Buy, another Buy main signal is ignored until a Sell appears (and vice versa). Extra entries then come only from the pyramid logic.")
 
// ==========================================
// 3. SESSION & LOOKBACK
// ==========================================
useTimeFilter = input.bool(true, "Enable Session Window", group = G_TIME, tooltip = "Only allow signals and pyramid adds inside the session below. Disable to trade around the clock.")
sessionInput  = input.session("1630-2300", "Session Time (HHMM-HHMM)", group = G_TIME, tooltip = "Active trading window in the selected timezone. Signals outside this window are ignored.")
sessionTz     = input.string("Asia/Jerusalem", "Session Timezone", group = G_TIME, tooltip = "IANA timezone for the session window, e.g. Asia/Bangkok, America/New_York, Asia/Jerusalem.")
useLookback   = input.bool(true, "Limit Historical Days", group = G_TIME, tooltip = "Only show signals from the last N days to keep the chart clean. Display filter only; the visible start date moves forward over time.")
lookbackDays  = input.int(5, "Lookback Days", minval = 1, group = G_TIME, tooltip = "Number of calendar days back from now in which signals are displayed. Higher = more history shown, more labels and lines used.")
 
// ==========================================
// 4. PYRAMID ORDERS
// ==========================================
pyrOn         = input.bool(true, "Enable Pyramid Orders", group = G_PYR, tooltip = "Allows extra orders on the same side after the first signal, up to the maximum count, when price moves the set distance.")
pyrMax        = input.int(3, "Max Orders Per Side", minval = 1, maxval = 10, group = G_PYR, tooltip = "Total orders allowed per side including the first one. 1 = no pyramiding. Higher = more scaling, more exposure.")
pyrDir        = input.string("Pullback (Average In)", "Add Direction", options = ["Pullback (Average In)", "Continuation (Add In Profit)"], group = G_PYR, tooltip = "Pullback: Buy adds below the last buy, Sell adds above the last sell. Continuation: Buy adds above the last buy, Sell adds below the last sell.")
pyrMode       = input.string("ATR", "Distance Mode", options = ["Ticks", "ATR"], group = G_PYR, tooltip = "How the distance from the last order is measured: fixed number of ticks, or a multiple of ATR that adapts to volatility.")
pyrTicks      = input.int(40, "Distance (Ticks)", minval = 1, group = G_PYR, tooltip = "Distance in ticks (syminfo.mintick) from the last order when Distance Mode is Ticks. Larger = fewer, wider-spaced adds.")
pyrAtrLen     = input.int(14, "Distance ATR Length", minval = 1, group = G_PYR, tooltip = "ATR period used for pyramid spacing when Distance Mode is ATR.")
pyrAtrMult    = input.float(1.0, "Distance ATR Multiplier", minval = 0.1, step = 0.1, group = G_PYR, tooltip = "Pyramid spacing = ATR x this value. Higher = wider spacing and fewer adds.")
pyrNeedCandle = input.bool(true, "Require Directional Candle for Adds", group = G_PYR, tooltip = "Buy adds need a green candle and Sell adds need a red candle, so adds wait for price to turn instead of catching a falling move.")
pyrMinGap     = input.int(2, "Min Bars Between Orders", minval = 1, group = G_PYR, tooltip = "Minimum bars between consecutive orders on the same side. Prevents several adds on neighbouring bars.")
 
// ==========================================
// 5. STOP LOSS & TAKE PROFIT
// ==========================================
showSL         = input.bool(true, "Draw Stop Loss Lines", group = G_RISK, tooltip = "Draws two stop-loss reference lines at each main entry.")
showTP         = input.bool(true, "Draw Take Profit Lines", group = G_RISK, tooltip = "Draws two take-profit reference lines at each main entry.")
riskUnit       = input.string("Points", "Risk Unit", options = ["Points", "ATR"], group = G_RISK, tooltip = "Points: SL/TP values are price units. ATR: values are multiples of ATR, adapting distances to current volatility.")
riskAnchor     = input.string("Entry Close", "SL & TP Anchor", options = ["Entry Close", "Candle High/Low"], group = G_RISK, tooltip = "Price SL/TP distances are measured from: the entry close, or the candle low (longs) / high (shorts).")
sl1Val         = input.float(10.0, "Stop Loss 1", minval = 0.01, group = G_RISK, tooltip = "Distance of the first stop line from the anchor, in the chosen Risk Unit. Larger = wider stop.")
sl2Val         = input.float(15.0, "Stop Loss 2", minval = 0.01, group = G_RISK, tooltip = "Distance of the second (wider) stop line from the anchor, in the chosen Risk Unit.")
tp1Val         = input.float(10.0, "Take Profit 1", minval = 0.01, group = G_RISK, tooltip = "Distance of the first target from the anchor, in the chosen Risk Unit. Smaller = quicker but smaller target.")
tp2Val         = input.float(20.0, "Take Profit 2", minval = 0.01, group = G_RISK, tooltip = "Distance of the second (extended) target from the anchor, in the chosen Risk Unit.")
riskLen        = input.int(15, "Risk Line Length (Bars)", minval = 1, group = G_RISK, tooltip = "How many bars to the right the SL/TP lines extend.")
riskOnAdds     = input.bool(false, "Draw Risk Lines on Pyramid Adds", group = G_RISK, tooltip = "Also draws SL/TP lines at each pyramid add. Useful for per-order management but adds many lines.")
showRiskPrices = input.bool(true, "Show SL/TP Price Labels", group = G_RISK, tooltip = "Prints the price value at the end of each SL/TP line.")
sl1Color       = input.color(color.orange, "SL 1 Color", group = G_RISK, tooltip = "Colour of the first stop-loss line and its label.")
sl2Color       = input.color(color.maroon, "SL 2 Color", group = G_RISK, tooltip = "Colour of the second stop-loss line and its label.")
tp1Color       = input.color(color.teal, "TP 1 Color", group = G_RISK, tooltip = "Colour of the first take-profit line and its label.")
tp2Color       = input.color(color.blue, "TP 2 Color", group = G_RISK, tooltip = "Colour of the second take-profit line and its label.")
 
// ==========================================
// 6. BREAK LEVEL LINE
// ==========================================
showBreakLine  = input.bool(true, "Draw Broken Level Line", group = G_LVL, tooltip = "Draws the prior-candle level that the signal candle broke, starting from the prior candle.")
breakLineLen   = input.int(15, "Level Line Length (Bars)", minval = 1, group = G_LVL, tooltip = "How many bars to the right the broken level line extends.")
breakWidth     = input.int(2, "Level Line Width", minval = 1, maxval = 4, group = G_LVL, tooltip = "Thickness of the broken level line.")
showBreakPrice = input.bool(true, "Show Level Price Label", group = G_LVL, tooltip = "Prints the broken level price at the end of the line.")
 
// ==========================================
// 7. VISUALS & COLORS
// ==========================================
longColor      = input.color(color.green, "Buy Color", group = G_VIS, tooltip = "Colour for Buy signals, Buy order labels and the long break level line.")
shortColor     = input.color(color.red, "Sell Color", group = G_VIS, tooltip = "Colour for Sell signals, Sell order labels and the short break level line.")
labelSizeStr   = input.string("Small", "Label Text Size", options = ["Tiny", "Small", "Normal", "Large"], group = G_VIS, tooltip = "Text size of all order and price labels.")
showOrderLabel = input.bool(true, "Show Order Labels (B1/S1...)", group = G_VIS, tooltip = "Shows numbered labels: B1/S1 for the first order, B2, B3... for pyramid adds.")
showBarColor   = input.bool(true, "Color Signal Candles", group = G_VIS, tooltip = "Colours main signal candles in the Buy/Sell colours.")
showTrendLine  = input.bool(true, "Plot Trend EMA", group = G_VIS, tooltip = "Plots the trend-filter EMA on the chart when the trend filter is enabled.")
 
// ==========================================
// HELPERS
// ==========================================
f_labelSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
string lblSize = f_labelSize(labelSizeStr)
 
// Draw a horizontal reference line with optional price label
f_hline(float y, color c, string st) =>
    line.new(bar_index, y, bar_index + riskLen, y, color = c, width = 2, style = st)
    if showRiskPrices
        label.new(bar_index + riskLen, y, str.tostring(y, format.mintick), color = color.new(color.white, 100), textcolor = c, style = label.style_label_left, size = lblSize)
    true
 
// ==========================================
// CORE CALCULATIONS
// ==========================================
float atrVal      = ta.atr(atrLen)
bool  isGreen     = close > open
bool  isRed       = close < open
float candleRange = high - low
float body        = math.abs(close - open)
float clvLong     = candleRange > 0 ? (close - low) / candleRange : 0.0
float clvShort    = candleRange > 0 ? (high - close) / candleRange : 0.0
 
float longLevel = switch breakRef
    "Prior Close"     => close[1]
    "Prior Body Edge" => math.max(open[1], close[1])
    => high[1]
 
float shortLevel = switch breakRef
    "Prior Close"     => close[1]
    "Prior Body Edge" => math.min(open[1], close[1])
    => low[1]
 
float breakBuf = nz(atrVal) * breakBufAtr
 
// Colour flip + ATR-buffered break + body strength + close location
bool flipLong  = isGreen and isRed[1]   and close > longLevel + breakBuf  and body >= minBodyAtr * atrVal and clvLong  >= clvMin
bool flipShort = isRed   and isGreen[1] and close < shortLevel - breakBuf and body >= minBodyAtr * atrVal and clvShort >= clvMin
 
// FIX: Trend filter (EMA position + slope)
float trendEma    = ta.ema(close, trendLen)
bool  trendLongOk  = not useTrend or (close > trendEma and trendEma > trendEma[slopeBars])
bool  trendShortOk = not useTrend or (close < trendEma and trendEma < trendEma[slopeBars])
 
// FIX: Chop filter (ADX)
[diPlus, diMinus, adxVal] = ta.dmi(adxLen, adxLen)
bool chopOk = not useChop or adxVal >= adxMin
 
// FIX: Volume confirmation
float volAvg = ta.sma(volume, volLen)
bool  volOk  = not useVol or volume >= volAvg * volMult
 
// Session / lookback / confirmed-bar
bool inSession = not na(time(timeframe.period, sessionInput + ":1234567", sessionTz))
bool timeOk    = not useTimeFilter or inSession
bool daysOk    = not useLookback or time >= timenow - lookbackDays * 86400000
// FIX: Confirmed bar only (no intrabar repaint)
bool confirmOk = not useConfirm or barstate.isconfirmed
bool filterOk  = timeOk and daysOk and confirmOk
 
bool allowLong  = tradeMode != "Short Only"
bool allowShort = tradeMode != "Long Only"
 
// ==========================================
// STATE (pyramid counters)
// ==========================================
var int   side          = 0      // 1 = long cycle, -1 = short cycle, 0 = none
var int   buyCount      = 0
var int   sellCount     = 0
var float lastBuyPrice  = na
var float lastSellPrice = na
var int   lastSignalBar = na
var int   lastOrderBar  = na
 
// FIX: Cooldown between main signals
bool cooldownOk = not useCooldown or na(lastSignalBar) or bar_index - lastSignalBar >= cooldownBars
 
bool rawLong  = filterOk and allowLong  and flipLong  and trendLongOk  and chopOk and volOk
bool rawShort = filterOk and allowShort and flipShort and trendShortOk and chopOk and volOk
 
// FIX: Block same-side repeats
bool longEntry  = rawLong  and cooldownOk and (not blockRepeat or side != 1)
bool shortEntry = rawShort and cooldownOk and (not blockRepeat or side != -1)
 
// ==========================================
// PYRAMID LOGIC
// Pullback mode     : Buy adds when close <= lastBuyPrice - distance,
//                     Sell adds when close >= lastSellPrice + distance.
// Continuation mode : Buy adds when close >= lastBuyPrice + distance,
//                     Sell adds when close <= lastSellPrice - distance.
// Counters reset when the opposite main signal fires.
// ==========================================
float pyrAtr     = ta.atr(pyrAtrLen)
float pyrDist    = pyrMode == "Ticks" ? pyrTicks * syminfo.mintick : pyrAtr * pyrAtrMult
bool  isPullback = pyrDir == "Pullback (Average In)"
bool  orderGapOk = na(lastOrderBar) or bar_index - lastOrderBar >= pyrMinGap
 
bool longDistOk  = not na(lastBuyPrice)  and (isPullback ? close <= lastBuyPrice - pyrDist  : close >= lastBuyPrice + pyrDist)
bool shortDistOk = not na(lastSellPrice) and (isPullback ? close >= lastSellPrice + pyrDist : close <= lastSellPrice - pyrDist)
bool longCandleOk  = not pyrNeedCandle or isGreen
bool shortCandleOk = not pyrNeedCandle or isRed
 
bool longAdd  = pyrOn and not longEntry  and not shortEntry and side == 1  and buyCount  >= 1 and buyCount  < pyrMax and longDistOk  and longCandleOk  and orderGapOk and filterOk and allowLong
bool shortAdd = pyrOn and not shortEntry and not longEntry  and side == -1 and sellCount >= 1 and sellCount < pyrMax and shortDistOk and shortCandleOk and orderGapOk and filterOk and allowShort
 
if longEntry
    side          := 1
    buyCount      := 1
    lastBuyPrice  := close
    sellCount     := 0
    lastSellPrice := na
    lastSignalBar := bar_index
    lastOrderBar  := bar_index
else if shortEntry
    side          := -1
    sellCount     := 1
    lastSellPrice := close
    buyCount      := 0
    lastBuyPrice  := na
    lastSignalBar := bar_index
    lastOrderBar  := bar_index
else if longAdd
    buyCount     += 1
    lastBuyPrice := close
    lastOrderBar := bar_index
else if shortAdd
    sellCount     += 1
    lastSellPrice := close
    lastOrderBar  := bar_index
 
// ==========================================
// DRAWINGS: ORDER LABELS
// ==========================================
if showOrderLabel and (longEntry or longAdd)
    label.new(bar_index, low, "B" + str.tostring(buyCount), yloc = yloc.belowbar, style = label.style_label_up, color = longEntry ? longColor : color.new(longColor, 35), textcolor = color.white, size = lblSize)
 
if showOrderLabel and (shortEntry or shortAdd)
    label.new(bar_index, high, "S" + str.tostring(sellCount), yloc = yloc.abovebar, style = label.style_label_down, color = shortEntry ? shortColor : color.new(shortColor, 35), textcolor = color.white, size = lblSize)
 
// ==========================================
// DRAWINGS: BROKEN LEVEL LINE
// ==========================================
if showBreakLine and longEntry
    line.new(bar_index - 1, longLevel, bar_index + breakLineLen, longLevel, color = longColor, width = breakWidth, style = line.style_solid)
    if showBreakPrice
        label.new(bar_index + breakLineLen, longLevel, str.tostring(longLevel, format.mintick), color = color.new(color.white, 100), textcolor = longColor, style = label.style_label_left, size = lblSize)
 
if showBreakLine and shortEntry
    line.new(bar_index - 1, shortLevel, bar_index + breakLineLen, shortLevel, color = shortColor, width = breakWidth, style = line.style_solid)
    if showBreakPrice
        label.new(bar_index + breakLineLen, shortLevel, str.tostring(shortLevel, format.mintick), color = color.new(color.white, 100), textcolor = shortColor, style = label.style_label_left, size = lblSize)
 
// ==========================================
// DRAWINGS: STOP LOSS & TAKE PROFIT
// ==========================================
float riskMult = riskUnit == "Points" ? 1.0 : nz(atrVal)
 
if longEntry or (riskOnAdds and longAdd)
    float anchorL = riskAnchor == "Entry Close" ? close : low
    if showSL
        f_hline(anchorL - sl1Val * riskMult, sl1Color, line.style_dashed)
        f_hline(anchorL - sl2Val * riskMult, sl2Color, line.style_dotted)
    if showTP
        f_hline(anchorL + tp1Val * riskMult, tp1Color, line.style_dashed)
        f_hline(anchorL + tp2Val * riskMult, tp2Color, line.style_dotted)
 
if shortEntry or (riskOnAdds and shortAdd)
    float anchorS = riskAnchor == "Entry Close" ? close : high
    if showSL
        f_hline(anchorS + sl1Val * riskMult, sl1Color, line.style_dashed)
        f_hline(anchorS + sl2Val * riskMult, sl2Color, line.style_dotted)
    if showTP
        f_hline(anchorS - tp1Val * riskMult, tp1Color, line.style_dashed)
        f_hline(anchorS - tp2Val * riskMult, tp2Color, line.style_dotted)
 
// ==========================================
// PLOTS
// ==========================================
plot(showTrendLine and useTrend ? trendEma : na, "Trend EMA", color = color.new(color.gray, 20), linewidth = 2)
 
plotshape(longEntry,  "Buy Entry",    style = shape.triangleup,   location = location.belowbar, color = longColor,                  size = size.small)
plotshape(longAdd,    "Pyramid Buy",  style = shape.diamond,      location = location.belowbar, color = color.new(longColor, 30),   size = size.tiny)
plotshape(shortEntry, "Sell Entry",   style = shape.triangledown, location = location.abovebar, color = shortColor,                 size = size.small)
plotshape(shortAdd,   "Pyramid Sell", style = shape.diamond,      location = location.abovebar, color = color.new(shortColor, 30),  size = size.tiny)
 
barcolor(showBarColor ? (longEntry ? longColor : shortEntry ? shortColor : na) : na)
 
// ==========================================
// ALERTS
// ==========================================
alertcondition(longEntry,  "FBM Buy",          "FBM Buy (B1) on {{ticker}} at {{close}}")
alertcondition(shortEntry, "FBM Sell",         "FBM Sell (S1) on {{ticker}} at {{close}}")
alertcondition(longAdd,    "FBM Pyramid Buy",  "FBM Pyramid Buy add on {{ticker}} at {{close}}")
alertcondition(shortAdd,   "FBM Pyramid Sell", "FBM Pyramid Sell add on {{ticker}} at {{close}}")

← 返回列表