Triple EMA Candle Painter + Signals

Quince2010 · study · 279 行 · 点赞 38 · TradingView 原页

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

Pine Script

//@version=6
indicator("Triple EMA Candle Painter + Signals", shorttitle="3EMA Paint", overlay=true, behind_chart=false, explicit_plot_zorder=true, max_lines_count=500, max_labels_count=500)
 
// ============================================================================
// INPUTS
// ============================================================================
grpEma = "EMA Settings"
fastLen = input.int(21, "Fast EMA", minval=1, group=grpEma)
midLen  = input.int(34, "Mid EMA",  minval=1, group=grpEma)
slowLen = input.int(55, "Slow EMA", minval=1, group=grpEma)
src     = input.source(close, "Source", group=grpEma)
 
grpCandle = "Candle Colours"
paintCandles = input.bool(true, "Paint Candles", group=grpCandle)
paintBody    = input.bool(true, "Paint Body",   group=grpCandle)
paintBorder  = input.bool(true, "Paint Border", group=grpCandle)
paintWick    = input.bool(true, "Paint Wick",   group=grpCandle)
paintMethod  = input.string("Both", "Paint Method", options=["Both", "Plot Candles", "Bar Color"], group=grpCandle, tooltip="Plot Candles draws the candle body, border and wick in the trend colour. Bar Color recolours the chart's own candles. Both uses the two together so the candle is always painted.")
bullCol    = input.color(color.new(color.green, 0), "Green (Fast and Mid above Slow)", group=grpCandle)
bearCol    = input.color(color.new(color.red, 0),   "Red (Fast and Mid below Slow)",   group=grpCandle)
neutralCol = input.color(color.new(color.gray, 0),  "Grey (conditions not met)",       group=grpCandle)
 
grpLines = "EMA Lines"
showEmas = input.bool(true, "Show EMA Lines", group=grpLines)
fastCol  = input.color(color.new(color.aqua, 0),    "Fast EMA Colour", group=grpLines)
midCol   = input.color(color.new(color.yellow, 0),  "Mid EMA Colour",  group=grpLines)
slowCol  = input.color(color.new(color.fuchsia, 0), "Slow EMA Colour", group=grpLines)
 
grpSig = "Signals"
showSignals = input.bool(true, "Show BUY / SELL Signals", group=grpSig)
minGap = input.int(9, "Min Candles Between Signals", minval=1, group=grpSig, tooltip="If a new signal appears fewer than this many candles after the previous signal, the previous signal and its entry setup are deleted from the chart. Alerts that already fired cannot be taken back.")
 
grpSetup = "Entry Setup (SL / TP)"
showSetup  = input.bool(true, "Show Entry / SL / TP Setup", group=grpSetup)
atrLen     = input.int(14, "ATR Length", minval=1, group=grpSetup)
atrMult    = input.float(1.5, "SL ATR Multiplier", minval=0.1, step=0.1, group=grpSetup)
tp1R       = input.float(1.0, "TP1 (R)", minval=0.1, step=0.5, group=grpSetup)
tp2R       = input.float(2.0, "TP2 (R)", minval=0.1, step=0.5, group=grpSetup)
tp3R       = input.float(3.0, "TP3 (R)", minval=0.1, step=0.5, group=grpSetup)
extBars    = input.int(20, "Setup Line Length (bars)", minval=1, group=grpSetup)
removeMarkerOnSL = input.bool(true, "Also Remove BUY / SELL Marker When SL Is Hit", group=grpSetup, tooltip="On: when the SL is hit, the Entry, SL and TP lines and the BUY / SELL marker are all removed. Off: only the Entry, SL and TP lines are removed.")
 
grpStruct = "Market Structure (HH / LL / BOS / CHoCH)"
swingLen     = input.int(5, "Swing Length", minval=1, group=grpStruct, tooltip="Bars on each side of a pivot. Lower = faster but noisier. Higher = slower but cleaner.")
hhMarker     = input.string("Triangle", "HH Marker (above candle)", options=["Off", "Triangle", "Arrow", "Circle", "Diamond", "Square", "Cross", "X Cross"], group=grpStruct, tooltip="Marker at a Higher High. Size follows the candle width. Off = hidden.")
llMarker     = input.string("Triangle", "LL Marker (below candle)", options=["Off", "Triangle", "Arrow", "Circle", "Diamond", "Square", "Cross", "X Cross"], group=grpStruct, tooltip="Marker at a Lower Low. Size follows the candle width. Off = hidden.")
markDownCol  = input.color(color.new(color.red, 0),    "HH Marker Colour", group=grpStruct)
markUpCol    = input.color(color.new(color.green, 0),  "LL Marker Colour", group=grpStruct)
showBosChoch = input.bool(true, "Show BOS / CHoCH", group=grpStruct)
bosCol       = input.color(color.new(color.blue, 0),   "BOS Colour",   group=grpStruct)
chochCol     = input.color(color.new(color.orange, 0), "CHoCH Colour", group=grpStruct)
 
// ============================================================================
// EMAs AND TREND STATE
// ============================================================================
fastEma = ta.ema(src, fastLen)
midEma  = ta.ema(src, midLen)
slowEma = ta.ema(src, slowLen)
atrVal  = ta.atr(atrLen)
 
bullState = fastEma > slowEma and midEma > slowEma
bearState = fastEma < slowEma and midEma < slowEma
 
// ============================================================================
// CANDLE PAINTING (body, border and wick)
// ============================================================================
candleCol = paintCandles ? (bullState ? bullCol : bearState ? bearCol : neutralCol) : na
useBar  = paintMethod == "Both" or paintMethod == "Bar Color"
usePlot = paintMethod == "Both" or paintMethod == "Plot Candles"
 
bodyCol   = paintBody   ? candleCol : na
borderCol = paintBorder ? candleCol : na
wickCol   = paintWick   ? candleCol : na
 
barcolor(useBar and paintBody ? candleCol : na, title="Trend Candles (Bar Color)")
plotcandle(open, high, low, close, title="Trend Candles (Body + Border + Wick)", color=usePlot ? bodyCol : na, bordercolor=usePlot ? borderCol : na, wickcolor=usePlot ? wickCol : na)
 
// ============================================================================
// PLOTS
// ============================================================================
plot(showEmas ? fastEma : na, "Fast EMA", color=fastCol, linewidth=1)
plot(showEmas ? midEma  : na, "Mid EMA",  color=midCol,  linewidth=1)
plot(showEmas ? slowEma : na, "Slow EMA", color=slowCol, linewidth=2)
 
// ============================================================================
// SIGNALS: the first bar where the green (BUY) or red (SELL) state starts
// ============================================================================
ready   = bar_index >= math.max(math.max(fastLen, midLen), math.max(slowLen, atrLen))
buySig  = ready and barstate.isconfirmed and bullState and not bullState[1]
sellSig = ready and barstate.isconfirmed and bearState and not bearState[1]
 
// ============================================================================
// MARKET STRUCTURE: HH, LL, BOS and CHoCH
// ============================================================================
sPH = ta.pivothigh(high, swingLen, swingLen)
sPL = ta.pivotlow(low,   swingLen, swingLen)
 
var float prevPH   = na      // previous confirmed swing high
var float prevPL   = na      // previous confirmed swing low
var float phLevel  = na      // swing high to break upward
var float plLevel  = na      // swing low to break downward
var int   phIdx    = na
var int   plIdx    = na
var bool  phBroken = true
var bool  plBroken = true
var int   structTrend = 0    // 1 = bullish structure, -1 = bearish structure
 
bool hhFound   = false
bool llFound   = false
bool bullBOS   = false
bool bullCHoCH = false
bool bearBOS   = false
bool bearCHoCH = false
 
// New swing high: HH if above the previous swing high
if not na(sPH)
    if not na(prevPH) and sPH > prevPH
        hhFound := true
    prevPH := sPH
    phLevel := sPH
    phIdx := bar_index - swingLen
    phBroken := false
 
// New swing low: LL if below the previous swing low
if not na(sPL)
    if not na(prevPL) and sPL < prevPL
        llFound := true
    prevPL := sPL
    plLevel := sPL
    plIdx := bar_index - swingLen
    plBroken := false
 
// Close breaks the latest swing high: BOS if already bullish, CHoCH if it was bearish
bullBreak = not na(phLevel) and not phBroken and close > phLevel
if bullBreak
    isChoch = structTrend == -1
    if isChoch
        bullCHoCH := true
    else
        bullBOS := true
    if showBosChoch
        cU = isChoch ? chochCol : bosCol
        line.new(phIdx, phLevel, bar_index, phLevel, color=cU, style=line.style_dashed)
        label.new(int(math.round((phIdx + bar_index) / 2.0)), phLevel, isChoch ? "CHoCH" : "BOS", style=label.style_label_down, color=color.new(cU, 100), textcolor=cU, size=size.small)
    structTrend := 1
    phBroken := true
 
// Close breaks the latest swing low: BOS if already bearish, CHoCH if it was bullish
bearBreak = not na(plLevel) and not plBroken and close < plLevel
if bearBreak
    isChochD = structTrend == 1
    if isChochD
        bearCHoCH := true
    else
        bearBOS := true
    if showBosChoch
        cD = isChochD ? chochCol : bosCol
        line.new(plIdx, plLevel, bar_index, plLevel, color=cD, style=line.style_dashed)
        label.new(int(math.round((plIdx + bar_index) / 2.0)), plLevel, isChochD ? "CHoCH" : "BOS", style=label.style_label_up, color=color.new(cD, 100), textcolor=cD, size=size.small)
    structTrend := -1
    plBroken := true
 
// HH / LL markers: drawn on the pivot candle itself (offset back by the swing length)
plotshape(hhFound and hhMarker == "Triangle", "HH Triangle", shape.triangledown, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
plotshape(hhFound and hhMarker == "Arrow", "HH Arrow", shape.arrowdown, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
plotshape(hhFound and hhMarker == "Circle", "HH Circle", shape.circle, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
plotshape(hhFound and hhMarker == "Diamond", "HH Diamond", shape.diamond, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
plotshape(hhFound and hhMarker == "Square", "HH Square", shape.square, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
plotshape(hhFound and hhMarker == "Cross", "HH Cross", shape.cross, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
plotshape(hhFound and hhMarker == "X Cross", "HH X Cross", shape.xcross, location.abovebar, color=markDownCol, size=size.auto, offset=-swingLen)
 
plotshape(llFound and llMarker == "Triangle", "LL Triangle", shape.triangleup, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
plotshape(llFound and llMarker == "Arrow", "LL Arrow", shape.arrowup, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
plotshape(llFound and llMarker == "Circle", "LL Circle", shape.circle, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
plotshape(llFound and llMarker == "Diamond", "LL Diamond", shape.diamond, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
plotshape(llFound and llMarker == "Square", "LL Square", shape.square, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
plotshape(llFound and llMarker == "Cross", "LL Cross", shape.cross, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
plotshape(llFound and llMarker == "X Cross", "LL X Cross", shape.xcross, location.belowbar, color=markUpCol, size=size.auto, offset=-swingLen)
 
// ============================================================================
// ENTRY SETUP FROM THE BUY / SELL SIGNALS
// Entry = signal bar close, SL = ATR x multiplier, TP1 / TP2 / TP3 = 1R / 2R / 3R.
// SL hit -> the setup is removed.  A new signal fewer than "minGap" candles after the previous one deletes the previous signal.
// ============================================================================
type Trade
    bool         isLong
    float        entry
    float        sl
    float        tp1
    float        tp2
    float        tp3
    int          barIdx
    int          expiry
    array<line>  lines
    array<label> labels
    label        sigLbl = na
    bool         dead   = false
 
var array<Trade> trades = array.new<Trade>()
var Trade lastTrade = na
 
fmt(float p) => str.tostring(p, format.mintick)
 
buildTrade(bool isLong) =>
    entry = close
    sl = isLong ? entry - atrVal * atrMult : entry + atrVal * atrMult
    r  = math.abs(entry - sl)
    dir = isLong ? 1 : -1
    Trade.new(isLong, entry, sl, entry + dir * r * tp1R, entry + dir * r * tp2R, entry + dir * r * tp3R, bar_index, bar_index + extBars, array.new<line>(), array.new<label>())
 
addLevel(Trade t, float price, string txt, color lineCol, color lblCol, string styl) =>
    array.push(t.lines, line.new(bar_index, price, t.expiry, price, color=lineCol, style=styl))
    array.push(t.labels, label.new(t.expiry, price, txt + " " + fmt(price), style=label.style_label_left, color=color.new(lblCol, 20), textcolor=color.white, size=size.small))
    true
 
drawTrade(Trade t) =>
    addLevel(t, t.entry, "Entry", color.new(color.white, 0), color.gray,  line.style_solid)
    addLevel(t, t.sl,    "SL",    color.new(color.red, 0),   color.red,   line.style_dashed)
    addLevel(t, t.tp1,   "TP1",   color.new(color.green, 0), color.green, line.style_dotted)
    addLevel(t, t.tp2,   "TP2",   color.new(color.green, 0), color.green, line.style_dotted)
    addLevel(t, t.tp3,   "TP3",   color.new(color.green, 0), color.green, line.style_dotted)
    true
 
// Delete a setup from the chart (lines and labels, and the BUY / SELL marker when asked)
killTrade(Trade t, bool delMarker) =>
    for ln in t.lines
        line.delete(ln)
    for lb in t.labels
        label.delete(lb)
    if delMarker and not na(t.sigLbl)
        label.delete(t.sigLbl)
    t.dead := true
    true
 
// New signal
if buySig or sellSig
    // Previous signal too close: delete it (marker and setup)
    if not na(lastTrade) and bar_index - lastTrade.barIdx < minGap
        killTrade(lastTrade, true)
 
    newTrade = buildTrade(buySig)
    if showSignals
        if buySig
            newTrade.sigLbl := label.new(bar_index, low, "BUY", style=label.style_label_up, color=color.new(color.green, 0), textcolor=color.white, size=size.small)
        else
            newTrade.sigLbl := label.new(bar_index, high, "SELL", style=label.style_label_down, color=color.new(color.red, 0), textcolor=color.white, size=size.small)
    if showSetup
        drawTrade(newTrade)
    array.push(trades, newTrade)
    lastTrade := newTrade
    if array.size(trades) > 50
        array.shift(trades)
 
// Watch every open setup until its SL or TP3 is reached
if array.size(trades) > 0
    for i = array.size(trades) - 1 to 0
        td = array.get(trades, i)
        if td.dead
            array.remove(trades, i)
        else if bar_index > td.barIdx
            hitSL  = td.isLong ? low <= td.sl : high >= td.sl
            hitTP3 = td.isLong ? high >= td.tp3 : low <= td.tp3
            if hitSL
                killTrade(td, removeMarkerOnSL)
                array.remove(trades, i)
            else if hitTP3
                array.remove(trades, i)
 
// ============================================================================
// ALERTS
// ============================================================================
alertcondition(buySig,    "BUY Signal",     "BUY: Fast and Mid EMA are now above the Slow EMA")
alertcondition(sellSig,   "SELL Signal",    "SELL: Fast and Mid EMA are now below the Slow EMA")
alertcondition(hhFound,   "Higher High",    "HH: a Higher High has formed")
alertcondition(llFound,   "Lower Low",      "LL: a Lower Low has formed")
alertcondition(bullBOS,   "Bullish BOS",    "Bullish BOS: close broke the last swing high")
alertcondition(bearBOS,   "Bearish BOS",    "Bearish BOS: close broke the last swing low")
alertcondition(bullCHoCH, "Bullish CHoCH",  "Bullish CHoCH: structure flipped from bearish to bullish")
alertcondition(bearCHoCH, "Bearish CHoCH",  "Bearish CHoCH: structure flipped from bullish to bearish")

← 返回列表