나의 strategy//@version=6
strategy("Jimb0ws Strategy + All Bubble Zones + Golden Candles + Limited Signals", overlay=true, calc_on_every_tick=true, max_bars_back=5000)
// ─── INPUTS ─────────────────────────────────────────────────────────────────
pipBodyTol = input.float(0, title="Pip Tolerance for Body Touch", step=0.0001)
pipWickTol = input.float(0.002, title="Pip Tolerance for Wick Touch", step=0.0001)
maxBodyDrive = input.float(0, title="Max Drive from EMA for Body", step=0.0001)
maxWickDrive = input.float(0.002, title="Max Drive from EMA for Wick", step=0.0001)
fractalSizeOpt = input.string("small", title="Fractal Size", options= )
minBodySize = input.float(0, title="Min Body Size for Golden Candle", step=0.0001)
longOffsetPips = input.int(25, title="Long Label Offset (pips)", minval=0)
shortOffsetPips = input.int(25, title="Short Label Offset (pips)", minval=0)
consolOffsetPips = input.int(25, title="Consolidation Label Offset (pips)", minval=0)
longSignType = input.string("Label Down", title="Long Bubble Sign Type", options= )
shortSignType = input.string("Label Up", title="Short Bubble Sign Type", options= )
consolSignType = input.string("Label Down", title="Consolidation Bubble Sign Type", options= )
enable1hEmaFilter = input.bool(true, title="Disable Signals beyond 1H EMA50")
showZones = input.bool(true, title="Show Bubble Zones")
showSigns = input.bool(true, title="Show Bubble Signs")
maxSignalsPerBubble = input.int(3, title="Max Signals Per Bubble", minval=1)
// Toggle for session filter
enableSessionFilter = input.bool(true, title="Enable Active Trading Session Filter")
sessionInput = input.session("0100-1900", title="Active Trading Session")
tzInput = input.string("Europe/London", title="Session Timezone",
options= )
actualTZ = tzInput == "Exchange" ? syminfo.timezone : tzInput
infoOffsetPips = input.int(5, title="Info Line Offset Above Price (pips)", minval=0)
warnOffsetPips = input.int(10, title="Warning Label Offset Above Infobar (pips)", minval=0)
show1HInfo = input.bool(true, title="Show 1H Bubble Info")
bufferLimit = 5000 - 1
enableProxFilter = input.bool(true, title="Disable Signals Near 1H EMA50")
proxRangePips = input.int(10, title="Proximity Range (pips)", minval=0)
enableWickFilter = input.bool(true, title="Filter Golden-Candle Wick Overdrive")
wickOverdrivePips = input.int(0, title="Wick Overdrive Range (pips)", minval=0)
// turn Robin candles on/off
enableRobin = input.bool(true, title="Enable Robin Candles")
// ATR panel attached to 4H info
showPrevDayATR = input.bool(true, title="Show Previous Day ATR Panel")
atrLenPrevDay = input.int(14, title="ATR Length (Daily)", minval=1)
atrPanelOffsetPips = input.int(3, title="ATR Panel Offset Above 4H Info (pips)", minval=0)
// ─── STRATEGY TRADES (EMA200 SL, RR=2 TP) ───────────────────────────────────
enableAutoTrades = input.bool(true, title="Enable Strategy Entries/Exits")
takeProfitRR = input.float(2.0, title="TP Risk:Reward (x)", step=0.1, minval=0.1)
// ─── SL/TP info label on signals ─────────────────────────────────────────────
showSLTPPanel = input.bool(true, title="Show SL/TP Info Above Signals")
sltpOffsetPips = input.int(4, title="SL/TP Label Offset (pips)", minval=0)
// Previous Day ATR (D1, lookahead OFF) -> lock to yesterday with
dailyATR = request.security(syminfo.tickerid, "D", ta.atr(atrLenPrevDay),
lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
prevDayATR = dailyATR
// Convert to pips (FX: pip ≈ mintick*10)
pipValueFX = syminfo.mintick * 10.0
prevATR_pips_1d = na(prevDayATR) ? na : math.round((prevDayATR / pipValueFX) * 10.0) / 10.0
// Create table once
var table atrPanel = na
if barstate.isfirst and na(atrPanel)
// columns=1, rows=2 (title row + value row)
atrPanel := table.new(position.top_right, 1, 2, border_width=1,
frame_color=color.new(color.gray, 0), border_color=color.new(color.gray, 0))
// Update cells each last bar
if barstate.islast and not na(atrPanel)
if showPrevDayATR
titleTxt = "Prev Day ATR (" + str.tostring(atrLenPrevDay) + ")"
valTxt = na(prevDayATR) ? "n/a"
: str.tostring(prevATR_pips_1d) + " pips (" + str.tostring(prevDayATR, format.mintick) + ")"
table.cell(atrPanel, 0, 0, titleTxt, text_color=color.white, bgcolor=color.new(color.blue, 25))
table.cell(atrPanel, 0, 1, valTxt, text_color=color.white, bgcolor=color.new(color.black, 0))
else
// Hide panel by writing empty strings
table.cell(atrPanel, 0, 0, "")
table.cell(atrPanel, 0, 1, "")
// Visuals for orders
showSLTP = input.bool(true, title="Show SL/TP Lines & Labels")
// ─── EMA CALCULATIONS & PLOTTING ──────────────────────────────────────────────
ema20 = ta.ema(close, 20)
ema50 = ta.ema(close, 50)
ema100 = ta.ema(close, 100)
ema200 = ta.ema(close, 200)
ema50_1h = request.security(syminfo.tickerid, "60", ta.ema(close, 50), lookahead=barmerge.lookahead_on)
plot(ema20, color=color.white, linewidth=4, title="EMA20")
plot(ema50, color=color.yellow, linewidth=4, title="EMA50")
plot(ema100, color=color.blue, linewidth=4, title="EMA100")
plot(ema200, color=color.purple, linewidth=6, title="EMA200") // ← and this
plot(ema50_1h, title="EMA50 (1H)", color=color.yellow, linewidth=2)
// pip-unit helper
pipUnit1h = syminfo.mintick * proxRangePips * 10
upperBand1h = ema50_1h + pipUnit1h
lowerBand1h = ema50_1h - pipUnit1h
// draw top/bottom lines in one-liner plots, then fill the gap
p_top = plot(enableProxFilter ? upperBand1h : na, title="Prox Zone Top", color=color.new(color.yellow,90), linewidth=1)
p_bottom = plot(enableProxFilter ? lowerBand1h : na, title="Prox Zone Bottom", color=color.new(color.yellow,90), linewidth=1)
fill(p_top, p_bottom, color.new(color.yellow,90))
// ─── BUBBLE CONDITIONS & ZONES ───────────────────────────────────────────────
longBub = ema20 > ema50 and ema50 > ema100
shortBub = ema20 < ema50 and ema50 < ema100
consolOn = not longBub and not shortBub
longCol = color.new(color.green, 85)
shortCol = color.new(color.red, 85)
consCol = color.new(color.orange, 85)
bgcolor(showZones ? (longBub ? longCol : shortBub ? shortCol : consCol) : na)
// convert pips to price‐units
wickOverUnit = syminfo.mintick * wickOverdrivePips * 10
// detect when the wick “pierces” EMA50 by more than that amount
overdriveLong = low < ema50 - wickOverUnit // long bubble: wick dipped below EMA50
overdriveShort = high > ema50 + wickOverUnit // short bubble: wick rose above EMA50
// ─── GOLDEN-CANDLE LOGIC & COLORING ──────────────────────────────────────────
trendLong = longBub
trendShort = shortBub
bodySize = math.abs(close - open)
hasBigBody = bodySize >= minBodySize
bodyLow = math.min(open, close)
bodyHigh = math.max(open, close)
wickLow = low
wickHigh = high
bOK20_L = bodyLow <= ema20 + pipBodyTol and bodyLow >= ema20 - maxBodyDrive and close > ema20
bOK50_L = bodyLow <= ema50 + pipBodyTol and bodyLow >= ema50 - maxBodyDrive and close > ema50
wOK20_L = wickLow <= ema20 + pipWickTol and wickLow >= ema20 - maxWickDrive and close > ema20
wOK50_L = wickLow <= ema50 + pipWickTol and wickLow >= ema50 - maxWickDrive and close > ema50
isGoldenLong = trendLong and hasBigBody and (bOK20_L or bOK50_L or wOK20_L or wOK50_L)
bOK20_S = bodyHigh >= ema20 - pipBodyTol and bodyHigh <= ema20 + maxBodyDrive and close < ema20
bOK50_S = bodyHigh >= ema50 - pipBodyTol and bodyHigh <= ema50 + maxBodyDrive and close < ema50
wOK20_S = wickHigh >= ema20 - pipWickTol and wickHigh <= ema20 + maxWickDrive and close < ema20
wOK50_S = wickHigh >= ema50 - pipWickTol and wickHigh <= ema50 + maxWickDrive and close < ema50
isGoldenShort= trendShort and hasBigBody and (bOK20_S or bOK50_S or wOK20_S or wOK50_S)
// ─── WICK-OVERDRIVE VETO ────────────────────────────────────────────────────
if enableWickFilter
// veto any golden on which the wick over-drove the EMA50
isGoldenLong := isGoldenLong and not overdriveLong
isGoldenShort := isGoldenShort and not overdriveShort
barcolor((isGoldenLong or isGoldenShort) ? color.new(#FFD700, 0) : na)
// ─── ROBIN CANDLES ──────────────────────────────────────────────────────────
goldShort1 = isGoldenShort
goldLong1 = isGoldenLong
goldLow1 = math.min(open , close )
goldHigh1 = math.max(open , close )
robinShort = shortBub and goldShort1 and math.min(open, close) < goldLow1
robinLong = longBub and goldLong1 and math.max(open, close) > goldHigh1
barcolor(enableRobin and (robinShort or robinLong) ? color.purple : na)
// ─── FRACTALS ─────────────────────────────────────────────────────────────────
pL = ta.pivotlow(low, 2, 2)
pH = ta.pivothigh(high, 2, 2)
plotshape(not shortBub and not consolOn and not na(pL) and fractalSizeOpt == "tiny",
style=shape.triangleup, location=location.belowbar, offset=-2, color=color.green, size=size.tiny)
plotshape(not shortBub and not consolOn and not na(pL) and fractalSizeOpt == "small",
style=shape.triangleup, location=location.belowbar, offset=-2, color=color.green, size=size.small)
plotshape(not shortBub and not consolOn and not na(pL) and fractalSizeOpt == "normal",
style=shape.triangleup, location=location.belowbar, offset=-2, color=color.green, size=size.normal)
plotshape(not shortBub and not consolOn and not na(pL) and fractalSizeOpt == "large",
style=shape.triangleup, location=location.belowbar, offset=-2, color=color.green, size=size.large)
plotshape(not longBub and not consolOn and not na(pH) and fractalSizeOpt == "tiny",
style=shape.triangledown, location=location.abovebar, offset=-2, color=color.red, size=size.tiny)
plotshape(not longBub and not consolOn and not na(pH) and fractalSizeOpt == "small",
style=shape.triangledown, location=location.abovebar, offset=-2, color=color.red, size=size.small)
plotshape(not longBub and not consolOn and not na(pH) and fractalSizeOpt == "normal",
style=shape.triangledown, location=location.abovebar, offset=-2, color=color.red, size=size.normal)
plotshape(not longBub and not consolOn and not na(pH) and fractalSizeOpt == "large",
style=shape.triangledown, location=location.abovebar, offset=-2, color=color.red, size=size.large)
// ─── BUY/SELL SIGNALS & LIMIT ─────────────────────────────────────────────────
var int buyCount = 0
var int sellCount = 0
if longBub and not longBub
buyCount := 0
if shortBub and not shortBub
sellCount := 0
goldLong2 = isGoldenLong
goldShort2 = isGoldenShort
roofCheck = math.max(open , close ) >= math.max(open , close )
floorCheck = math.min(open , close ) <= math.min(open , close )
buySignal = goldLong2 and not na(pL) and roofCheck
sellSignal = goldShort2 and not na(pH) and floorCheck
// Original: inSession = not na(time(timeframe.period, sessionInput, actualTZ))
inSessionRaw = not na(time(timeframe.period, sessionInput, actualTZ))
sessionOK = enableSessionFilter ? inSessionRaw : true
// Apply 1H EMA50 filter
disableBy1h = enable1hEmaFilter and ((request.security(syminfo.tickerid, "60", ema20 ema50_1h) or (request.security(syminfo.tickerid, "60", ema20>ema50 and ema50>ema100) and close < ema50_1h))
// ─── PROXIMITY VETO ────────────────────────────────────────────────
near1hZone = enableProxFilter and close >= lowerBand1h and close <= upperBand1h
validBuy = buySignal and sessionOK and buyCount < maxSignalsPerBubble and not disableBy1h and not near1hZone
validSell = sellSignal and sessionOK and sellCount < maxSignalsPerBubble and not disableBy1h and not near1hZone
plotshape(validBuy, title="BUY", style=shape.labelup, location=location.belowbar,
color=color.green, text="BUY $", textcolor=color.white, size=size.large)
plotshape(validSell, title="SELL", style=shape.labeldown, location=location.abovebar,
color=color.red, text="SELL $", textcolor=color.white, size=size.large)
if validBuy
buyCount += 1
if validSell
sellCount += 1
// ─── 4H BUBBLE INFO LINE ──────────────────────────────────────────────────────
var line infoLine4h = na
var label infoLbl4h = na
var label atrPrevLbl = na // ATR label handle
var string bubble4hType = na
var int bubble4hStartTime = na
var int bubble4hStartIdx = na
time4h = request.security(syminfo.tickerid, "240", time, lookahead=barmerge.lookahead_on)
ema20_4h = request.security(syminfo.tickerid, "240", ta.ema(close, 20), lookahead=barmerge.lookahead_on)
ema50_4h = request.security(syminfo.tickerid, "240", ta.ema(close, 50), lookahead=barmerge.lookahead_on)
ema100_4h = request.security(syminfo.tickerid, "240", ta.ema(close,100), lookahead=barmerge.lookahead_on)
long4h = ema20_4h > ema50_4h and ema50_4h > ema100_4h
short4h = ema20_4h < ema50_4h and ema50_4h < ema100_4h
cons4h = not long4h and not short4h
if long4h and not long4h
bubble4hType := "LONG"
bubble4hStartTime := time4h
bubble4hStartIdx := bar_index
else if short4h and not short4h
bubble4hType := "SHORT"
bubble4hStartTime := time4h
bubble4hStartIdx := bar_index
else if cons4h and not cons4h
bubble4hType := "CONS"
bubble4hStartTime := time4h
bubble4hStartIdx := bar_index
active4h = ((bubble4hType=="LONG" and long4h) or (bubble4hType=="SHORT" and short4h) or (bubble4hType=="CONS" and cons4h)) and not na(bubble4hStartTime)
if active4h
durH4 = math.floor((time - bubble4hStartTime) / 3600000)
ts4 = str.format("{0,date,yyyy-MM-dd} {0,time,HH:mm}", bubble4hStartTime)
txt4 = "4H " + bubble4hType + " Bubble since " + ts4 + " Dur: " + str.tostring(durH4) + "h"
col4 = bubble4hType=="LONG" ? color.green : bubble4hType=="SHORT" ? color.red : color.orange
pipUnit4 = syminfo.mintick * 10
infoPrice4 = high + (infoOffsetPips + warnOffsetPips + 5) * pipUnit4
xStart4 = math.max(bubble4hStartIdx, bar_index - bufferLimit)
if na(infoLine4h)
infoLine4h := line.new(xStart4, infoPrice4, bar_index, infoPrice4, extend=extend.none, color=col4, width=2)
else
line.set_xy1(infoLine4h, xStart4, infoPrice4)
line.set_xy2(infoLine4h, bar_index, infoPrice4)
line.set_color(infoLine4h, col4)
if na(infoLbl4h)
infoLbl4h := label.new(bar_index, infoPrice4, txt4, xloc.bar_index, yloc.price, col4, label.style_label_left, color.white, size.small)
else
label.set_xy(infoLbl4h, bar_index, infoPrice4)
label.set_text(infoLbl4h, txt4)
label.set_color(infoLbl4h, col4)
// Prev Day ATR label just above the 4H info panel
if showPrevDayATR
atrValTxt = na(prevDayATR) ? "n/a" : str.tostring(prevATR_pips_1d) + " pips (" + str.tostring(prevDayATR, format.mintick) + ")"
atrTxt = "Prev Day ATR (" + str.tostring(atrLenPrevDay) + ") " + atrValTxt
atrY = infoPrice4 + pipUnit4 * atrPanelOffsetPips
if na(atrPrevLbl)
atrPrevLbl := label.new(bar_index, atrY, atrTxt, xloc.bar_index, yloc.price, color.new(color.blue, 25), label.style_label_left, color.white, size.small)
else
label.set_xy(atrPrevLbl, bar_index, atrY)
label.set_text(atrPrevLbl, atrTxt)
label.set_color(atrPrevLbl, color.new(color.blue, 25))
else
if not na(atrPrevLbl)
label.delete(atrPrevLbl)
atrPrevLbl := na
else
// Cleanup when 4H panel is not active
if not na(infoLine4h)
line.delete(infoLine4h)
infoLine4h := na
if not na(infoLbl4h)
label.delete(infoLbl4h)
infoLbl4h := na
bubble4hType := na
if not na(atrPrevLbl)
label.delete(atrPrevLbl)
atrPrevLbl := na
// ─── 1H BUBBLE INFO & WARNING PANEL ─────────────────────────────────────────
var line infoLine1h = na
var label infoLbl1h = na
var label warnLbl1h = na
var string bubble1hType = na
var int bubble1hStartTime = na
var int bubble1hStartIdx = na
var float pipUnit = na
var color col = na
var int xStart = na
var float infoPrice = na
var string txt = ""
// 1H trend state (kept same logic as your original)
long1h = request.security(syminfo.tickerid, "60", ema20>ema50 and ema50>ema100, lookahead=barmerge.lookahead_on)
short1h = request.security(syminfo.tickerid, "60", ema20 ema50_1h
warnY = infoPrice1h + warnOffsetPips * pipUnit1h
if na(warnLbl1h)
warnLbl1h := label.new(bar_index, warnY, "Potential Consolidation Warning",
xloc.bar_index, yloc.price, color.new(color.yellow,0),
label.style_label_up, color.black, size.small)
else
label.set_xy(warnLbl1h, bar_index, warnY)
label.set_text(warnLbl1h, "Potential Consolidation Warning")
else
if not na(warnLbl1h)
label.delete(warnLbl1h)
warnLbl1h := na
else
if not na(infoLine1h)
line.delete(infoLine1h)
infoLine1h := na
if not na(infoLbl1h)
label.delete(infoLbl1h)
infoLbl1h := na
if not na(warnLbl1h)
label.delete(warnLbl1h)
warnLbl1h := na
bubble1hType := na
// ─── ALERTS ─────────────────────────────────────────────────────────────────
alertcondition(validBuy, title="Jimb0ws Strategy – BUY", message="🔥 BUY signal on {{ticker}} at {{close}}")
alertcondition(validSell, title="Jimb0ws Strategy – SELL", message="🔻 SELL signal on {{ticker}} at {{close}}")
if validBuy
alert("🔥 BUY signal on " + syminfo.ticker + " at " + str.tostring(close), alert.freq_once_per_bar_close)
if validSell
alert("🔻 SELL signal on " + syminfo.ticker + " at " + str.tostring(close), alert.freq_once_per_bar_close)
// ─── SL/TP drawing handles (globals) ────────────────────────────────────────
var line slLine = na
var line tpLine = na
var label slLabel = na
var label tpLabel = na
var float slPrice = na
var float tpPrice = na
// Working vars so they exist on all bars
var float longEntry = na
var float longSL = na
var float longTP = na
var float riskL = na
var float shortEntry = na
var float shortSL = na
var float shortTP = na
var float riskS = na
// last SL/TP info label so we can replace it each time
var label sltpInfoLbl = na
// ─── Draw SL/TP info label exactly when a signal fires ──────────────────────
if showSLTPPanel and (validBuy or validSell)
// delete prior info label
if not na(sltpInfoLbl)
label.delete(sltpInfoLbl)
float pipUnit = syminfo.mintick * 10.0
float yAbove = high + sltpOffsetPips * pipUnit
// Entry is the close of the signal bar
float entry = close
// Choose SL by your rule:
// - LONG: if ema200 > ema100 -> SL = ema100, else SL = ema200
// - SHORT: if ema200 < ema100 -> SL = ema100, else SL = ema200
bool isLong = validBuy
float sl = isLong ? (ema200 > ema100 ? ema100 : ema200)
: (ema200 < ema100 ? ema100 : ema200)
// Compute TP using RR; guard for bad risk
float rr = takeProfitRR // your RR input (e.g., 2.0)
float risk = isLong ? (entry - sl) : (sl - entry)
float tp = na
if risk > syminfo.mintick
tp := isLong ? (entry + rr * risk) : (entry - rr * risk)
// Build label text (mintick formatting)
string slTxt = "SL " + str.tostring(sl, format.mintick)
string tpTxt = na(tp) ? "TP n/a" : "TP " + str.tostring(tp, format.mintick)
string txt = slTxt + " " + tpTxt
// Color by side and draw
color bgCol = isLong ? color.new(color.green, 10) : color.new(color.red, 10)
sltpInfoLbl := label.new(bar_index, yAbove, txt,
xloc.bar_index, yloc.price,
bgCol, label.style_label_left, color.white, size.small)
// ─── ORDERS: dynamic SL (EMA100 vs EMA200), TP = RR * risk + draw SL/TP ─────
if enableAutoTrades and barstate.isconfirmed and not na(ema100) and not na(ema200)
// LONGS — if EMA200 > EMA100 ⇒ SL = EMA100; else ⇒ SL = EMA200
if validBuy and strategy.position_size <= 0
longEntry := close
longSL := ema200 > ema100 ? ema100 : ema200
if longSL < longEntry - syminfo.mintick
riskL := longEntry - longSL
longTP := longEntry + takeProfitRR * riskL
if strategy.position_size < 0
strategy.close("Short", comment="Flip→Long")
strategy.entry("Long", strategy.long)
strategy.exit("Long-EXIT", from_entry="Long", stop=longSL, limit=longTP)
// store & draw
slPrice := longSL
tpPrice := longTP
if showSLTP
if not na(slLine)
line.delete(slLine)
if not na(tpLine)
line.delete(tpLine)
if not na(slLabel)
label.delete(slLabel)
if not na(tpLabel)
label.delete(tpLabel)
// lines
slLine := line.new(bar_index, slPrice, bar_index + 1, slPrice, extend=extend.right, color=color.red, width=2)
tpLine := line.new(bar_index, tpPrice, bar_index + 1, tpPrice, extend=extend.right, color=color.green, width=2)
// labels with exact prices
slLabel := label.new(bar_index + 1, slPrice, "SL " + str.tostring(slPrice, format.mintick), xloc.bar_index, yloc.price, color.new(color.red, 10), label.style_label_right, color.white, size.small)
tpLabel := label.new(bar_index + 1, tpPrice, "TP " + str.tostring(tpPrice, format.mintick), xloc.bar_index, yloc.price, color.new(color.green, 10), label.style_label_right, color.white, size.small)
// SHORTS — if EMA200 < EMA100 ⇒ SL = EMA100; else ⇒ SL = EMA200
if validSell and strategy.position_size >= 0
shortEntry := close
shortSL := ema200 < ema100 ? ema100 : ema200
if shortSL > shortEntry + syminfo.mintick
riskS := shortSL - shortEntry
shortTP := shortEntry - takeProfitRR * riskS
if strategy.position_size > 0
strategy.close("Long", comment="Flip→Short")
strategy.entry("Short", strategy.short)
strategy.exit("Short-EXIT", from_entry="Short", stop=shortSL, limit=shortTP)
// store & draw
slPrice := shortSL
tpPrice := shortTP
if showSLTP
if not na(slLine)
line.delete(slLine)
if not na(tpLine)
line.delete(tpLine)
if not na(slLabel)
label.delete(slLabel)
if not na(tpLabel)
label.delete(tpLabel)
slLine := line.new(bar_index, slPrice, bar_index + 1, slPrice, extend=extend.right, color=color.red, width=2)
tpLine := line.new(bar_index, tpPrice, bar_index + 1, tpPrice, extend=extend.right, color=color.green, width=2)
slLabel := label.new(bar_index + 1, slPrice, "SL " + str.tostring(slPrice, format.mintick), xloc.bar_index, yloc.price, color.new(color.red, 10), label.style_label_right, color.white, size.small)
tpLabel := label.new(bar_index + 1, tpPrice, "TP " + str.tostring(tpPrice, format.mintick), xloc.bar_index, yloc.price, color.new(color.green, 10), label.style_label_right, color.white, size.small)
// Keep labels pinned to the right of current bar while trade is open
if showSLTP and strategy.position_size != 0 and not na(slPrice) and not na(tpPrice)
label.set_xy(slLabel, bar_index + 1, slPrice)
label.set_text(slLabel, "SL " + str.tostring(slPrice, format.mintick))
label.set_xy(tpLabel, bar_index + 1, tpPrice)
label.set_text(tpLabel, "TP " + str.tostring(tpPrice, format.mintick))
// Clean up drawings when flat
if strategy.position_size == 0
slPrice := na
tpPrice := na
if not na(slLine)
line.delete(slLine)
slLine := na
if not na(tpLine)
line.delete(tpLine)
tpLine := na
if not na(slLabel)
label.delete(slLabel)
slLabel := na
if not na(tpLabel)
label.delete(tpLabel)
tpLabel := na
Candlestick analysis
Legendx// ──────────────────────────────────────────────────────────────
// 📘 STRATEGY DESCRIPTION — LEGENDX (with Telegram Alerts)
// ──────────────────────────────────────────────────────────────
//
// The **LegendX Strategy** is a next-generation market analysis
// and execution framework built for traders who demand precision,
// automation, and clarity in both backtesting and live execution.
//
// 🔹 CORE LOGIC
// • Uses adaptive Moving Averages (EMA, HMA, RMA, SMA, VWAP, VWMA, or WMA)
// to track trend direction and detect high-probability entries.
// • Entry triggers are dynamically adjusted by volatility filters
// (ATR and Standard Deviation), ensuring trades align with market momentum.
// • Supports up to **8 Take-Profit levels** for progressive scaling out.
// • Includes automatic Stop-Loss generation based on renormalized
// percentage distance from entry.
//
// 🔹 BACKTESTING FEATURES
// • Built-in simulation of entries/exits with adjustable ATR, deviation, and risk.
// • Displays detailed statistics such as peak profit, drawdown, and cumulative results.
// • Suitable for any symbol, including crypto, forex, indices, and commodities.
//
// 🔹 TELEGRAM AUTOMATION
// • Integrated **Telegram Signal System** sends real-time alerts
// (Entry, TP1–TP8, SL, Symbol, and Timestamp) to your Telegram channel.
// • Uses simple webhook integration via TradingView alerts —
// no external servers or scripts required.
// • Perfect for signal groups, prop firm monitoring, and portfolio tracking.
//
// 🔹 BEST FOR
// • Crypto traders (e.g., Binance, Bybit) who want automated, transparent signals.
// • Commodity & index traders who use multi-level profit scaling.
// • Traders who combine **quantitative backtesting** with **live alert automation**.
//
// 🔹 USAGE TIPS
// • Set alert frequency to “Once Per Bar Close” for clean, non-duplicate signals.
// • Configure your Telegram bot & channel ID once — signals will post automatically.
// • For automated execution, combine with tools like PineConnector or Alertatron.
//
// 🏆 LEGENDX — Precision Meets Automation.
// Built for traders who want clarity, control, and real-time communication.
//
// ──────────────────────────────────────────────────────────────
SuperBulls - Heiken Ashi StrategyA streamlined, trade-ready strategy from the SuperBulls universe that turns noisy charts into clear decisions. It combines a smoothed price view, adaptive momentum gating, and a dynamic support/resistance overlay so you can spot high-probability turns without overthinking every candle. Entries and exits are signalled visually and designed to work with simple position sizing — perfect for discretionary traders and systematic setups alike.
Why traders like it
Clean visual signals reduce analysis paralysis and speed up decision-making.
Built-in momentum filter helps avoid chop and chase only the stronger moves.
Dynamic S/R zones provide objective areas for targets and stop placement.
Works with simple risk rules — position sizing and pyramiding kept conservative by default.
Who it’s for
Traders who want a reliable, low-friction strategy to trade intraday or swing setups without rebuilding indicators from scratch. Minimal tuning required; plug in your size and let the SuperBulls logic do the heavy lifting.
Use it, don’t overfit it, and try not to blame the indicator when you ignore risk management.
SOL 15分钟MACD全自动策略//@version=5
strategy("30分钟高胜率MACD+RSI全自动策略", overlay=true, shorttitle="HighWin-30min Auto",
initial_capital=10000, // 初始资金
default_qty_type=strategy.cash, // 按资金比例开仓
default_qty_value=2000, // 单次开仓金额(可调整)
commission_type=strategy.commission.percent,
commission_value=0.1, // 匹配欧易0.1%默认手续费
margin_long=100, margin_short=100, // 现货交易无杠杆
pyramiding=0, // 禁止加仓,控制风险
close_entries_rule=strategy.close_entries_rule.all,
calc_on_every_tick=false, // 关闭逐Tick计算,避免报错
title_color=#1E90FF, line_color=#FF6347)
// ———— 1. 核心参数设置(高胜率优化版,可微调) ————
// MACD参数(30分钟周期适配,比默认更稳定)
macd_fast = input.int(12, title="MACD快线周期", minval=1)
macd_slow = input.int(26, title="MACD慢线周期", minval=1)
macd_signal = input.int(9, title="MACD信号线周期", minval=1)
// RSI参数(过滤超买超卖,避免追涨杀跌)
rsi_length = input.int(14, title="RSI周期", minval=1)
rsi_long_thresh = input.int(40, title="多头RSI阈值(低于该值可开多)", minval=10, maxval=50)
rsi_short_thresh = input.int(60, title="空头RSI阈值(高于该值可开空)", minval=50, maxval=90)
// 成交量参数(验证资金动能)
vol_multiplier = input.float(1.5, title="成交量放大倍数", step=0.1, minval=1.0)
// ATR止损与止盈参数(科学风控)
atr_length = input.int(14, title="ATR周期(衡量波动)", minval=1)
atr_sl_multi = input.float(2.0, title="止损ATR倍数(2倍更安全)", step=0.1, minval=1.0)
risk_reward = input.float(2.0, title="风险回报比(1:2,赚2倍于亏)", step=0.1, minval=1.5)
// 信号过滤(避免连续交易)
signal_gap = input.int(4, title="多空信号最小间隔K线数", minval=2)
// ———— 2. 指标计算(三重验证,降低假信号) ————
// 2.1 MACD计算(多空趋势核心)
= ta.macd(close, macd_fast, macd_slow, macd_signal)
// 多头趋势:MACD在零轴上+红柱放大;空头趋势:MACD在零轴下+绿柱放大
macd_long_trend = macd_line > 0 and hist_line > hist_line
macd_short_trend = macd_line < 0 and hist_line < hist_line
// 2.2 RSI计算(过滤超买超卖)
rsi_value = ta.rsi(close, rsi_length)
rsi_long_condition = rsi_value < rsi_long_thresh // 未超买,有上涨空间
rsi_short_condition = rsi_value > rsi_short_thresh // 未超卖,有下跌空间
// 2.3 成交量计算(验证资金动能)
vol_condition = volume >= volume * vol_multiplier and volume > 0 // 成交量比前根放大50%+
vol_long = vol_condition and close > open // 放量上涨,多头资金进场
vol_short = vol_condition and close < open // 放量下跌,空头资金进场
// 2.4 ATR计算(动态止损基础)
atr_value = ta.atr(atr_length)
atr_value := nz(atr_value, ta.sma(ta.tr, atr_length)) // 空值兜底,避免报错
// ———— 3. 多空信号生成(三重条件共振,高胜率核心) ————
// 3.1 多头信号(4个条件同时满足)
var int last_long_bar = 0
long_condition = ta.crossover(macd_line, signal_line) // MACD金叉
and macd_long_trend // 多头趋势
and rsi_long_condition // RSI未超买
and vol_long // 放量上涨
and (bar_index - last_long_bar) >= signal_gap // 间隔过滤
final_long = long_condition
// 3.2 空头信号(4个条件同时满足)
var int last_short_bar = 0
short_condition = ta.crossunder(macd_line, signal_line) // MACD死叉
and macd_short_trend // 空头趋势
and rsi_short_condition // RSI未超卖
and vol_short // 放量下跌
and (bar_index - last_short_bar) >= signal_gap // 间隔过滤
final_short = short_condition
// ———— 4. 动态止盈止损计算(适配30分钟波动,不被洗盘) ————
// 4.1 记录开仓关键数据
var float long_entry = na // 多头入场价
var float short_entry = na // 空头入场价
var float long_entry_low = na // 多头开仓K线低点
var float short_entry_high = na // 空头开仓K线高点
var float entry_atr = na // 开仓时ATR值
// 多头开仓数据记录
if final_long
long_entry := close
long_entry_low := low
entry_atr := atr_value
last_long_bar := bar_index // 更新最后多头信号K线
// 空头开仓数据记录
if final_short
short_entry := close
short_entry_high := high
entry_atr := atr_value
last_short_bar := bar_index // 更新最后空头信号K线
// 4.2 多头止盈止损(双逻辑防护)
long_sl = math.max(long_entry - (entry_atr * atr_sl_multi), long_entry_low * 0.997) // 0.3%缓冲防插针
long_loss = long_entry - long_sl // 止损幅度
long_tp = long_entry + (long_loss * risk_reward) // 1:2风险回报比止盈
// 额外绑定中期压力:前10根K线高点(30分钟周期趋势更稳,周期稍长)
long_resistance = ta.highest(high, 10)
long_tp = math.min(long_tp, long_resistance * 1.003) // 0.3%缓冲防踏空
// 4.3 空头止盈止损(对称逻辑)
short_sl = math.min(short_entry + (entry_atr * atr_sl_multi), short_entry_high * 1.003)
short_loss = short_sl - short_entry
short_tp = short_entry - (short_loss * risk_reward)
// 额外绑定中期支撑:前10根K线低点
short_support = ta.lowest(low, 10)
short_tp = math.max(short_tp, short_support * 0.997)
// ———— 5. 全自动交易执行(严格仓位控制,避免冲突) ————
// 多头开仓:无仓位时执行(避免多空对冲)
if final_long and strategy.position_size == 0
strategy.entry("Long-Position", strategy.long)
strategy.exit("Long-Exit", "Long-Position", stop=long_sl, limit=long_tp) // 自动挂止盈止损
// 空头开仓:无仓位时执行
if final_short and strategy.position_size == 0
strategy.entry("Short-Position", strategy.short)
strategy.exit("Short-Exit", "Short-Position", stop=short_sl, limit=short_tp)
// ———— 6. 可视化与预警(清晰监控,欧易同步提醒) ————
// 6.1 多空信号标记(直观区分)
plotshape(final_long, title="多头信号", location=location.belowbar,
color=color.new(color.green, 0), style=shape.labelup,
text="多", textcolor=color.white, size=size.small)
plotshape(final_short, title="空头信号", location=location.abovebar,
color=color.new(color.red, 0), style=shape.labeldown,
text="空", textcolor=color.white, size=size.small)
// 6.2 止盈止损线(开仓后自动显示,红色止损、绿色止盈)
plot(strategy.position_size > 0 ? long_sl : na, title="多头止损",
color=color.red, linewidth=2, style=plot.style_linebr)
plot(strategy.position_size > 0 ? long_tp : na, title="多头止盈",
color=color.green, linewidth=2, style=plot.style_linebr)
plot(strategy.position_size < 0 ? short_sl : na, title="空头止损",
color=color.red, linewidth=2, style=plot.style_linebr)
plot(strategy.position_size < 0 ? short_tp : na, title="空头止盈",
color=color.green, linewidth=2, style=plot.style_linebr)
// 6.3 副图指标(辅助验证趋势)
// MACD副图
plot(macd_line, title="MACD线", color=color.blue, linewidth=1)
plot(signal_line, title="MACD信号线", color=color.orange, linewidth=1)
barcolor(hist_line > 0 ? color.new(color.green, 60) : color.new(color.red, 60), title="MACD柱")
hline(0, "MACD零轴线", color=color.gray, linestyle=hline.style_dashed)
// RSI副图(显示超买超卖区间)
plot(rsi_value, title="RSI", color=color.purple, linewidth=1, display=display.data_window)
hline(rsi_long_thresh, "多头RSI阈值", color=color.green, linestyle=hline.style_dotted)
hline(rsi_short_thresh, "空头RSI阈值", color=color.red, linestyle=hline.style_dotted)
hline(30, "超卖线", color=color.gray, linestyle=hline.style_dashed)
hline(70, "超买线", color=color.gray, linestyle=hline.style_dashed)
// 6.4 关键预警(欧易同步通知,无需盯盘)
alertCondition(final_long, title="多头开仓提醒",
message="30分钟触发高胜率多头信号,入场价:" + str.tostring(long_entry) + ",止损:" + str.tostring(long_sl))
alertCondition(final_short, title="空头开仓提醒",
message="30分钟触发高胜率空头信号,入场价:" + str.tostring(short_entry) + ",止损:" + str.tostring(short_sl))
alertCondition(strategy.position_size > 0 and close <= long_sl, title="多头止损提醒",
message="多头触及止损位:" + str.tostring(long_sl) + ",已自动平仓")
alertCondition(strategy.position_size > 0 and close >= long_tp, title="多头止盈提醒",
message="多头触及止盈位:" + str.tostring(long_tp) + ",已自动平仓")
alertCondition(strategy.position_size < 0 and close >= short_sl, title="空头止损提醒",
message="空头触及止损位:" + str.tostring(short_sl) + ",已自动平仓")
alertCondition(strategy.position_size < 0 and close <= short_tp, title="空头止盈提醒",
message="空头触及止盈位:" + str.tostring(short_tp) + ",已自动平仓")
FVG Donchian Channel strategy30min FVG + Donchian Channel strategy
buy sell by 30min fvg
and stoploss , take profit by Donchian Channel
Run the strategy on the 1min timeframe!
Amiya's Doji / Hammer / Spinning Top Breakout Strategy v5How it works
1. Pattern Detection (Previous Candle):
• Checks if total shadow length ≥ 2 × body.
• Checks if candle height (high − low) is between 10 and 21.5 points.
• If true → marks that candle as a potential Doji, Hammer, or Spinning Top.
2. Long Setup:
• LTP (close) crosses above previous candle high.
• Previous candle is a valid pattern candle.
• Stop Loss = 3 points below previous candle low.
• Take Profit = 5 × (high − low) of previous candle added to previous high.
3. Short Setup:
• LTP (close) crosses below previous candle low.
• Previous candle is a valid pattern candle.
• Stop Loss = 3 points above previous candle high.
• Take Profit = 5 × (high − low) of previous candle subtracted from previous low.
4. Visualization:
• Yellow background highlights pattern candles.
• Green ▲ and Red ▼ markers show entry points.
Deep yellow candles → represent Doji / Hammer / Spinning Top patterns
• Green triangle → Buy signal
• Red triangle → Sell signal
• Dotted green line + label → Target
• Dotted red line + label → Stop loss
• Gray background → Outside trading hours
• Auto close → All trades square off at 3:29 PM IST
Multi-Module Full-Featured Trading Strategy System v1🧠 Key Features Summary:
🧩 Full Modular Structure: Entry / Position Adding / Take Profit & Stop Loss / Delay / Capital Management.
⏱️ Delay & Reverse System: Prevents frequent long-short switching with minute-based delay intervals.
💰 Capital Management System:
• Controls opening/adding positions based on account equity percentage;
• Limits maximum position ratio;
• Supports leverage multiplier.
⚙️ Each module is independently configurable and can be disabled;
📈 Unified variable naming for easy expansion with more indicators.
saodisengxiaoyu-lianghua-2.1- This indicator is a modular, signal-building framework designed to generate long and short signals by combining a chosen leading indicator with selectable confirmation filters. It runs on Pine Script version 5, overlays directly on price, and is built to be highly configurable so traders can tailor the signal logic to their market, timeframe, and trading style. It includes a dashboard to visualize which conditions are active and whether they validate a signal, and it outputs clear buy/sell labels and alert conditions so you can automate or monitor trades with confidence.
Core Design
- Leading Indicator: You choose one primary signal generator from a broad list (for example, Range Filter, Supertrend, MACD, RSI, Ichimoku, and many others). This serves as the anchor of the system and determines when a preliminary long or short setup exists.
- Confirmation Filters: You can enable additional filters that validate the leading signal before it becomes actionable. Each “respect…” input toggles a filter on or off. These filters include popular tools like EMA, 2/3 EMA crosses, RQK (Nadaraya Watson), ADX/DMI, Bollinger-based oscillators, MACD variations, QQE, Hull, VWAP, Choppiness Index, Damiani Volatility, and more.
- Signal Expiry: To avoid waiting indefinitely for confirmations, the indicator counts how many consecutive bars the leading condition holds. If confirmations do not align within a defined number of bars, the setup expires. This controls latency and helps reduce late or stale entries.
- Alternating Signals: An optional mode enforces alternation (long must follow short and vice versa), helping avoid repeated entries in the same direction without a meaningful reset.
- Aggregation Logic: The final long/short conditions are formed by combining the leading condition with all selected confirmation filters through logical conjunction. Only if all enabled filters validate the signal (within expiry constraints) does the indicator consider it a confirmed long or short.
- Visualization and Alerts: The script plots buy/sell labels at signal points, provides alert conditions for automation, and displays a compact dashboard summarizing the leading indicator’s status and each confirmation’s pass/fail result using checkmarks.
Leading Indicator Options
- The indicator includes a very large menu of leading tools, each with its own logic to determine uptrend or downtrend impulses. Highlights include:
- Range Filter: Uses a dynamic centerline and bands computed via conditional EMA/SMA and range sizing to define directional movement. It can operate in a default mode or an alternative “DW” mode.
- Rational Quadratic Kernel (RQK): Applies a kernel smoothing model (Nadaraya Watson) to detect uptrends and downtrends with a focus on noise reduction.
- Supertrend, Half Trend, SSL Channel: Classic trend-following tools that derive direction from ATR-based bands or moving average channels.
- Ichimoku Cloud and SuperIchi: Multi-component systems validating trend via cloud position, conversion/base line relationships, projected cloud, and lagging span.
- TSI (True Strength Index), DPO (Detrended Price Oscillator), AO (Awesome Oscillator), MACD, STC (Schaff Trend Cycle), QQE Mod: Momentum and cycle tools that parse direction from crossovers, zero-line behavior, and momentum shifts.
- Donchian Trend Ribbon, Chandelier Exit: Trend and exit tools that can validate breakouts or sustained trend strength.
- ADX/DMI: Measures trend strength and directional movement via +DI/-DI relationships and minimum ADX thresholds.
- RSI and Stochastic: Use crossovers, level exits, or threshold filters to gate entries based on overbought/oversold dynamics or relative strength trends.
- Vortex, Chaikin Money Flow, VWAP, Bull Bear Power, ROC, Wolfpack Id, Hull Suite: A diverse set of directional, momentum, and volume-based indicators to suit different markets and styles.
- Trendline Breakout and Range Detector: Price-behavior filters that confirm signals during breakouts or within defined ranges.
Confirmation Filters
- Each filter is optional. When enabled, it must validate the leading condition for a signal to pass. Examples:
- EMA Filter: Requires price to be above a specified EMA for longs and below for shorts, filtering signals that contradict broader trend or baseline levels.
- 2 EMA Cross and 3 EMA Cross: Enforce moving average cross conditions (fast above slow for long, the reverse for short) or a three-line stacking logic for more stringent trend alignment.
- RQK, Supertrend, Half Trend, Donchian, QQE, Hull, MACD (crossover vs. zero-line), AO (zero line or AC momentum variants), SSL: Each adds its characteristic validation pattern.
- RSI family (MA cross, exits OB/OS zones, threshold levels) plus RSI MA direction and RSI/RSI MA limits: Multiple ways to constrain signals via relative strength behavior and trajectories.
- Choppiness Index and Damiani Volatility: Prevent entries during ranging conditions or insufficient volatility; choppiness thresholds and volatility states gate the trade.
- VWAP, Volume modes (above MA, simple up/down, delta), Chaikin Money Flow: Volume and flow conditions that ensure signals happen in supportive liquidity or accumulation/distribution contexts.
- ADX/DMI thresholds: Demand a minimum trend strength and directional DI alignment to reduce whipsaw trades.
- Trendline Breakout and Range Detector: Confirm that the price is breaking structure or remains within active range consistent with the leading setup.
- By combining several filters you can create strict, conservative entries or looser setups depending on your goals.
Range Filter Engine
- A core building block, the Range Filter uses conditional EMA and SMA functions to compute adaptive bands around a dynamic centerline. It supports two types:
- Type 1: The centerline updates when price exceeds the band thresholds; bands define acceptable drift ranges.
- Type 2: Uses quantized steps (via floor operations) relative to the previous centerline to handle larger moves in discrete increments.
- The engine offers smoothing for range values using a secondary EMA and can switch between raw and averaged outputs. Its hi/lo bands and centerline compose a corridor that defines directional movement and potential breakout confirmation.
Signal Construction
- The script computes:
- leadinglongcond and leadingshortcond : The primary directional signals from the chosen leading indicator.
- longCond and shortCond : Final signals formed by combining the leading conditions with all enabled confirmations. Each confirmation contributes a boolean gate. If a filter is disabled, it contributes a neutral pass-through, keeping the logic intact without enforcing that condition.
- Expiry Logic: The code counts consecutive bars where the leading condition remains true. If confirmations do not line up within the user-defined “Signal Expiry Candle Count,” the setup is abandoned and the signal does not trigger.
- Alternation: An optional state ensures that long and short signals alternate. This can reduce repeated entries in the same direction without a clear reset.
- Finally, longCondition and shortCondition represent the actionable signals after expiry and alternation logic. These drive the label plotting and alert conditions.
Visualization
- Buy and Sell Labels: When longCondition or shortCondition confirm, the script plots annotated labels directly on the chart, making entries easy to see at a glance. The labels use color coding and clear text tags (“long” vs. “short”).
- Dashboard: A table summarizes the status of the leading indicator and all confirmations. Each row shows the indicator label and whether it passed (✔️) or failed (❌) on the current bar. This intensely practical UI helps you diagnose why a signal did or did not trigger, empowering faster strategy iteration and parameter tuning.
- Failed Confirmation Markers: If a setup expires (count exceeds the limit) and confirmations failed to align, the script can mark the chart with a small label and provide a tooltip listing which confirmations did not pass. It’s a helpful audit trail to understand missed trades or prevent “chasing” invalid signals.
- Data Window Values: The script outputs signal states to the data window, which can be useful for debugging or building composite conditions in multi-indicator templates.
Inputs and Parameters
- You control the indicator from a comprehensive input panel:
- Setup: Signal expiry count, whether to enforce alternating signals, and whether to display labels and the dashboard (including position and size).
- Leading Indicator: Choose the primary signal generator from the large list.
- Per-Filter Toggles: For each confirmation, a respect... toggle enables or disables it. Many include sub-options (like MACD type, Stochastic mode, RSI mode, ADX variants, thresholds for choppiness/volatility, etc.) to fine-tune behavior.
- Range Filter Settings: Choose type and behavior; select default vs. DW mode and smoothing. The underlying functions adjust band sizes using ATR, average change, standard deviation, or user-defined scales.
- Because everything is customizable, you can adapt the indicator to different assets, volatility regimes, and timeframes.
Alerts and Automation
- The script defines alert conditions tied to longCondition and shortCondition . You can set these alerts in your chart to trigger notifications or webhook calls for automated execution in external bots. The alert text is simple, and you can configure your own message template when creating alerts in the chart, including JSON payloads for algorithmic integration.
Typical Workflow
- Select a Leading Indicator aligned with your style. For trend following, Supertrend or SSL may be appropriate; for momentum, MACD or TSI; for range/trend-change detection, Range Filter, RQK, or Donchian.
- Add a few key Confirmation Filters that complement the leading signal. For example:
- Pair Supertrend with EMA Filter and RSI MA Direction to ensure trend alignment and positive momentum.
- Combine MACD Crossover with ADX/DMI and Volume Above MA to avoid signals in low-trend or low-liquidity conditions.
- Use RQK with Choppiness Index and Damiani Volatility to only act when the market is trending and volatile enough.
- Set a sensible Signal Expiry Candle Count. Shorter expiry keeps entries timely and reduces lag; longer expiry captures setups that mature slowly.
- Observe the Dashboard during live markets to see which filters pass or fail, then iterate. Tighten or loosen thresholds and filter combinations as needed.
- For automation, turn on alerts for the final conditions and use webhook payloads to notify your trading robot.
Strengths and Practical Notes
- Flexibility: The indicator is a toolkit rather than a single rigid model. It lets you test different combinations rapidly and visualize outcomes immediately.
- Clarity: Labels, dashboard, and failed-confirmation markers make it easy to audit behavior and refine settings without digging into code.
- Robustness: The expiry and alternation options add discipline, avoiding the temptation to enter late or repeatedly in one direction without a reset.
- Modular Design: The logical gates (“respect…”) make the behavior transparent: if a filter is on, it must pass; if it’s off, the signal ignores it. This keeps reasoning clean.
- Avoiding Overfitting: Because you can stack many filters, it’s tempting to over-constrain signals. Start simple (one leading indicator and one or two confirmations). Add complexity only if it demonstrably improves your edge across varied market regimes.
Limitations and Recommendations
- No single configuration is universally optimal. Markets change; tune filters for the instrument and timeframe you trade and revisit settings periodically.
- Trend filters can underperform in choppy markets; likewise, momentum filters can false-trigger in quiet periods. Consider using Choppiness Index or Damiani to gate signals by regime.
- Use expiry wisely. Too short may miss good setups that need a few bars to confirm; too long may cause late entries. Balance responsiveness and accuracy.
- Always consider risk management externally (position sizing, stops, profit targets). The indicator focuses on signal quality; combining it with robust trade management methods will improve results.
Example Configurations
- Trend-Following Setup:
- Leading: Supertrend uptrend for longs and downtrend for shorts.
- Confirmations: EMA Filter (price above 200 EMA for long, below for short), ADX/DMI (trend strength above threshold with +DI/-DI alignment), Volume Above MA.
- Expiry: 3–4 bars to keep entries timely.
- Result: Strong bias toward sustained moves while avoiding weak trends and thin liquidity.
- Mean-Reversion to Momentum Crossover:
- Leading: RSI exits from OB/OS zones (e.g., RSI leaves oversold for long and leaves overbought for short).
- Confirmations: 2 EMA Cross (fast crossing slow in the same direction), MACD zero-line behavior for added momentum validation.
- Expiry: 2–3 bars for responsive re-entry.
- Result: Captures momentum transitions after short-term extremes, with extra confirmation to reduce head-fakes.
- Range Breakout Focus:
- Leading: Range Filter Type 2 or Donchian Trend Ribbon to detect breakouts.
- Confirmations: Damiani Volatility (avoid low-volatility false breaks), Choppiness Index (prefer trend-ready states), ROC positive/negative threshold.
- Expiry: 1–3 bars to act on breakout windows.
- Result: Better alignment to breakout dynamics, gating trades by volatility and regime.
Conclusion
- This indicator is a comprehensive, configurable framework that merges a chosen leading signal with an array of corroborating filters, disciplined expiry handling, and intuitive visualization. It’s designed to help you build high-quality entry signals tailored to your approach, whether that’s trend-following, breakout trading, momentum capturing, or a hybrid. By surfacing pass/fail states in a dashboard and allowing alert-based automation, it bridges the gap between discretionary analysis and systematic execution. With sensible parameter tuning and thoughtful filter selection, it can serve as a robust backbone for signal generation across diverse instruments and timeframes.
Enhanced OB Retest Strategy v7.0The OB Retest Strategy is a full Order Block retest trading system that detects, plots, and trades OB zones across multiple timeframes. It uses structure breaks, retrace depth, and ATR filters to identify strong reversal or continuation setups.
⸻
⚙️ Core Features
• Multi-timeframe OB detection using break-of-structure (BOS) logic
• Automatic zone creation for bullish and bearish order blocks
• Smart merging of overlapping OB zones
• Dynamic flip-zone logic that turns invalidated OBs into new zones
• Wick zone detection for high-precision entries
• ATR-based trailing stop and optional breakeven
• Adjustable retrace depth, breakout %, and ATR filters
• Built-in performance table showing PnL, win rate, and total trades
• Fully backtestable with date range and commission control
⸻
🧠 Logic Summary
1. Detects a BOS on the higher timeframe.
2. Identifies the last opposing candle as the valid OB.
3. Validates the OB based on ATR size and breakout strength.
4. Waits for price to retest the zone to a set depth.
5. Executes trades and manages exits using trailing stop or breakeven.
6. Flips invalidated zones automatically.
⸻
💡 Usage Tips
• Best used on 1H to 4H charts for swing setups.
• Tune ATR and breakout thresholds for your market’s volatility.
• Combine with higher-timeframe bias or liquidity levels for better accuracy.
⸻
⚠️ Notes
• For educational and testing purposes only.
• Backtested results do not predict future performance.
• Always test before live use.
ICT Liquidity Sweep Asia/London 1 Trade per High & Low🧠 ICT Liquidity Sweep Asia/London — 1 Trade per High & Low
This strategy is inspired by the ICT (Inner Circle Trader) concepts of liquidity sweeps and market structure, focusing on the Asia and London sessions.
It automatically identifies liquidity grabs (sweeps) above or below key session highs/lows and enters trades with a fixed risk/reward ratio (RR).
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
⚙️ Core Logic
-Asia Session: 8:00 PM – 11:59 PM (New York time)
-London Session: 2:00 AM – 5:00 AM (New York time)
-The script marks the Asia High/Low and London High/Low ranges for each day.
-When the market sweeps above a session high → potential Short setup
-When the market sweeps below a session low → potential Long setup
-A trade is triggered when the confirmation candle closes in the opposite direction of the sweep (bearish after a high sweep, bullish after a low sweep).
-Only one trade per sweep type (1 per High, 1 per Low) is allowed per session.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
📈 Risk Management
-Configurable Risk/Reward Target (default = 2:1)
-Configurable Position Size (number of contracts)
-Each trade uses a fixed Stop Loss (beyond the wick of the sweep) and a Take Profit calculated from the RR setting.
-All trades are automatically logged in the Strategy Tester with performance metrics.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
💡 Features
✅ Visual session highlighting (Asia = Aqua, London = Orange)
✅ Automatic liquidity line plotting (session highs/lows)
✅ Entry & exit labels (optional visual display)
✅ Customizable RR and contract size
✅ Works on any instrument (ideal for indices, futures, or forex)
✅ Compatible with all timeframes (optimized for 1M–15M)
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
⚠️ Notes
-Best used on New York time-based charts.
-Designed for educational and backtesting purposes — not financial advice.
-Use as a foundation for further optimization (e.g., SMT confirmation, FVG filter, or time-based restrictions).
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
🧩 Recommended Use
Pair this with:
-ICT’s concepts like CISD (Change in State of Delivery) and FVGs (Fair Value Gaps)
-Higher timeframe liquidity maps
-Session bias or daily narrative filters
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
Author: jygirouard
Strategy Version: 1.3
Type: ICT Liquidity Sweep Automation
Timezone: America/New_York
TriAnchor Elastic Reversion US Market SPY and QQQ adaptedSummary in one paragraph
Mean-reversion strategy for liquid ETFs, index futures, large-cap equities, and major crypto on intraday to daily timeframes. It waits for three anchored VWAP stretches to become statistically extreme, aligns with bar-shape and breadth, and fades the move. Originality comes from fusing daily, weekly, and monthly AVWAP distances into a single ATR-normalized energy percentile, then gating with a robust Z-score and a session-safe gap filter.
Scope and intent
• Markets: SPY QQQ IWM NDX large caps liquid futures liquid crypto
• Timeframes: 5 min to 1 day
• Default demo: SPY on 60 min
• Purpose: fade stretched moves only when multi-anchor context and breadth agree
• Limits: strategy uses standard candles for signals and orders only
Originality and usefulness
• Unique fusion: tri-anchor AVWAP energy percentile plus robust Z of close plus shape-in-range gate plus breadth Z of SPY QQQ IWM
• Failure mode addressed: chasing extended moves and fading during index-wide thrusts
• Testability: each component is an input and visible in orders list via L and S tags
• Portable yardstick: distances are ATR-normalized so thresholds transfer across symbols
• Open source: method and implementation are disclosed for community review
Method overview in plain language
Base measures
• Range basis: ATR(length = atr_len) as the normalization unit
• Return basis: not used directly; we use rank statistics for stability
Components
• Tri-Anchor Energy: squared distances of price from daily, weekly, monthly AVWAPs, each divided by ATR, then summed and ranked to a percentile over base_len
• Robust Z of Close: median and MAD based Z to avoid outliers
• Shape Gate: position of close inside bar range to require capitulation for longs and exhaustion for shorts
• Breadth Gate: average robust Z of SPY QQQ IWM to avoid fading when the tape is one-sided
• Gap Shock: skip signals after large session gaps
Fusion rule
• All required gates must be true: Energy ≥ energy_trig_prc, |Robust Z| ≥ z_trig, Shape satisfied, Breadth confirmed, Gap filter clear
Signal rule
• Long: energy extreme, Z negative beyond threshold, close near bar low, breadth Z ≤ −breadth_z_ok
• Short: energy extreme, Z positive beyond threshold, close near bar high, breadth Z ≥ +breadth_z_ok
What you will see on the chart
• Standard strategy arrows for entries and exits
• Optional short-side brackets: ATR stop and ATR take profit if enabled
Inputs with guidance
Setup
• Base length: window for percentile ranks and medians. Typical 40 to 80. Longer smooths, shorter reacts.
• ATR length: normalization unit. Typical 10 to 20. Higher reduces noise.
• VWAP band stdev: volatility bands for anchors. Typical 2.0 to 4.0.
• Robust Z window: 40 to 100. Larger for stability.
• Robust Z entry magnitude: 1.2 to 2.2. Higher means stronger extremes only.
• Energy percentile trigger: 90 to 99.5. Higher limits signals to rare stretches.
• Bar close in range gate long: 0.05 to 0.25. Larger requires deeper capitulation for longs.
Regime and Breadth
• Use breadth gate: on when trading indices or broad ETFs.
• Breadth Z confirm magnitude: 0.8 to 1.8. Higher avoids fighting thrusts.
• Gap shock percent: 1.0 to 5.0. Larger allows more gaps to trade.
Risk — Short only
• Enable short SL TP: on to bracket shorts.
• Short ATR stop mult: 1.0 to 3.0.
• Short ATR take profit mult: 1.0 to 6.0.
Properties visible in this publication
• Initial capital: 25000USD
• Default order size: Percent of total equity 3%
• Pyramiding: 0
• Commission: 0.03 percent
• Slippage: 5 ticks
• Process orders on close: OFF
• Bar magnifier: OFF
• Recalculate after order is filled: OFF
• Calc on every tick: OFF
• request.security lookahead off where used
Realism and responsible publication
• No performance claims. Past results never guarantee future outcomes
• Fills and slippage vary by venue
• Shapes can move during bar formation and settle on close
• Standard candles only for strategies
Honest limitations and failure modes
• Economic releases or very thin liquidity can overwhelm mean-reversion logic
• Heavy gap regimes may require larger gap filter or TR-based tuning
• Very quiet regimes reduce signal contrast; extend windows or raise thresholds
Open source reuse and credits
• None
Strategy notice
Orders are simulated by TradingView on standard candles. request.security uses lookahead off where applicable. Non-standard charts are not supported for execution.
Entries and exits
• Entry logic: as in Signal rule above
• Exit logic: short side optional ATR stop and ATR take profit via brackets; long side closes on opposite setup
• Risk model: ATR-based brackets on shorts when enabled
• Tie handling: stop first when both could be touched inside one bar
Dataset and sample size
• Test across your visible history. For robust inference prefer 100 plus trades.
FluxGate Daily Swing StrategySummary in one paragraph
FluxGate treats long and short as different ecosystems. It runs two independent engines so the long side can be bold when the tape rewards upside persistence while the short side can stay selective when downside is messy. The core reads three directional drivers from price geometry then removes overlap before gating with clean path checks. The complementary risk module anchors stop distance to a higher timeframe ATR so a unit means the same thing on SPY and BTC. It can add take profit breakeven and an ATR trail that only activates after the trade earns it. If a stop is hit the strategy can re enter in the same direction on the next bar with a daily retry cap that you control. Add it to a clean chart. Use defaults to see the intended behavior. For conservative workflows evaluate on bar close.
Scope and intent
• Markets. Large cap equities and liquid ETFs major FX pairs US index futures and liquid crypto pairs
• Timeframes. From one minute to daily
• Default demo in this publication. SPY on one day timeframe
• Purpose. Reduce false starts without missing sustained trends by fusing independent drivers and suppressing activity when the path is noisy
• Limits. This is a strategy. Orders are simulated on standard candles. Non standard chart types are not supported for execution
Originality and usefulness
• Unique fusion. FluxGate extracts three drivers that look at price from different angles. Direction measures slope of a smoothed guide and scales by realized volatility so a point of slope does not mean a different thing on different symbols. Persistence looks at short sign agreement to reward series of closes that keep direction. Curvature measures the second difference of a local fit to wake up during convex pushes. These three are then orthonormalized so a strong reading in one does not double count through another.
• Gates that matter. Efficiency ratio prefers direct paths over treadmills. Entropy turns up versus down frequency into an information read. Light fractal cohesion punishes wrinkly paths. Together they slow the system in chop and allow it to open up when the path is clean.
• Separate long and short engines. Threshold tilts adapt to the skew of score excursions. That lets long engage earlier when upside distribution supports it and keeps short cautious where downside surprise and venue frictions are common.
• Practical risk behavior. Stops are ATR anchored on a higher timeframe so the unit is portable. Take profit is expressed in R so two R means the same concept across symbols. Breakeven and trailing only activate after a chosen R so early noise does not squeeze a good entry. Re entry after stop lets the system try again without you babysitting the chart.
• Testability. Every major window and the aggression controls live in Inputs. There is no hidden magic number.
Method overview in plain language
Base measures
• Return basis. Natural log of close over prior close for stability and easy aggregation through time. Realized volatility is the standard deviation of returns over a moving window.
• Range basis for risk. ATR computed on a higher timeframe anchor such as day week or month. That anchor is steady across venues and avoids chasing chart specific quirks.
Components
• Directional intensity. Use an EMA of typical price as a guide. Take the day to day slope as raw direction. Divide by realized volatility to get a unit free measure. Soft clip to keep outliers from dominating.
• Persistence. Encode whether each bar closed up or down. Measure short sign agreement so a string of higher closes scores better than a jittery sequence. This favors push continuity without guessing tops or bottoms.
• Curvature. Fit a short linear regression and compute the second difference of the fitted series. Strong curvature flags acceleration that slope alone may miss.
• Efficiency gate. Compare net move to path length over a gate window. Values near one indicate direct paths. Values near zero indicate treadmill behavior.
• Entropy gate. Convert up versus down frequency into a probability of direction. High entropy means coin toss. The gate narrows there.
• Fractal cohesion. A light read of path wrinkliness relative to span. Lower cohesion reduces the urge to act.
• Phase assist. Map price inside a recent channel to a small signed bias that grows with confidence. This helps entries lean toward the right half of the channel without becoming a breakout rule.
• Shock control. Compare short volatility to long volatility. When short term volatility spikes the shock gate temporarily damps activity so the system waits for pressure to normalize.
Fusion rule
• Normalize the three drivers after removing overlap
• Blend with weights that adapt to your aggression input
• Multiply by the gates to respect path quality
• Smooth just enough to avoid jitter while keeping timing responsive
• Compute an adaptive mean and deviation of the score and set separate long and short thresholds with a small tilt informed by skew sign
• The result is one long score and one short score that can cross their thresholds at different times for the same tape which is a feature not a bug
Signal rule
• A long suggestion appears when the long score crosses above its long threshold while all gates are active
• A short suggestion appears when the short score crosses below its short threshold while all gates are active
• If any required gate is missing the state is wait
• When a position is open the status is in long or in short until the complementary risk engine exits or your entry mode closes and flips
Inputs with guidance
Setup Long
• Base length Long. Master window for the long engine. Typical range twenty four to eighty. Raising it improves selectivity and reduces trade count. Lowering it reacts faster but can increase noise
• Aggression Long. Zero to one. Higher values make thresholds more permissive and shorten smoothing
Setup Short
• Base length Short. Master window for the short engine. Typical range twenty eight to ninety six
• Aggression Short. Zero to one. Lower values keep shorts conservative which is often useful on upward drifting symbols
Entries and UI
• Entry mode. Both or Long only or Short only
Complementary risk engine
• Enable risk engine. Turns on bracket exits while keeping your signal logic untouched
• ATR anchor timeframe. Day Week or Month. This sets the structural unit of stop distance
• ATR length. Default fourteen
• Stop multiple. Default one point five times the anchor ATR
• Use take profit. On by default
• Take profit in R. Default two R
• Breakeven trigger in R. Default one R
Usage recipes
Intraday trend focus
• Entry mode Both
• ATR anchor Week
• Aggression Long zero point five Aggression Short zero point three
• Stop multiple one point five Take profit two R
• Expect fewer trades that stick to directional pushes and skip treadmill noise
Intraday mean reversion focus
• Session windows optional if you add them in your copy
• ATR anchor Day
• Lower aggression both sides
• Breakeven later and trailing later so the first bounce has room
• This favors fade entries that still convert into trends when the path stays clean
Swing continuation
• Signal timeframe four hours or one day
• Confirm timeframe one day if you choose to include bias
• ATR anchor Week or Month
• Larger base windows and a steady two R target
• This accepts fewer entries and aims for larger holds
Properties visible in this publication
• Initial capital 25.000
• Base currency USD
• Default order size percent of equity value three - 3% of the total capital
• Pyramiding zero
• Commission zero point zero three percent - 0.03% of total capital
• Slippage five ticks
• Process orders on close off
• Recalculate after order is filled off
• Calc on every tick off
• Bar magnifier off
• Any request security calls use lookahead off everywhere
Realism and responsible publication
• No performance promises. Past results never guarantee future outcomes
• Fills and slippage vary by venue and feed
• Strategies run on standard candles only
• Shapes can update while a bar is forming and settle on close
• Keep risk per trade sensible. Around one percent is typical for study. Above five to ten percent is rarely sustainable
Honest limitations and failure modes
• Sudden news and thin liquidity can break assumptions behind entropy and cohesion reads
• Gap heavy symbols often behave better with a True Range basis for risk than a simple range
• Very quiet regimes can reduce score contrast. Consider longer windows or higher thresholds when markets sleep
• Session windows follow the exchange time of the chart if you add them
• If stop and target can both be inside a single bar this strategy prefers stop first to keep accounting conservative
Open source reuse and credits
• No reused open source beyond public domain building blocks such as ATR EMA and linear regression concepts
Legal
Education and research only. Not investment advice. You are responsible for your decisions. Test on history and in simulation with realistic costs
om bdethis is to make research this is to make research this is to make research this is to make research
MACD + Supertrend + DEMA StrategySTRATEGY 📊 STRATEGY LOGIC:
Long Entry: When ALL of these occur simultaneously:
MACD histogram crosses above 0
Supertrend is bullish (green)
Short DEMA > Long DEMA
Short Entry: When ALL of these occur simultaneously:
MACD histogram crosses below 0
Supertrend is bearish (red)
Short DEMA < Long DEMA
Exits: Based on your TP/SL percentages from entry price
This follows the same clean structure as your MACD strategy but adds the alignment concept and proper risk management!
Moving Average Trend Strategy V2.1 — With Stop Loss and Add Posi**Strategy Feature Description:**
---
### **Entry Logic:**
* When **MA7** crosses **MA15**, and the distance between **MA15** and **MA99** is less than **0.5%**
* When **MA15** crosses **MA99**, and the distance between **MA7** and **MA15** is less than **0.5%**
* When the distance among all three MAs (**MA7**, **MA15**, **MA99**) is less than **0.5%** (adjustable via parameters)
---
### **Capital Management:**
* Initial capital: **$100**
* Each position uses **15%** of total capital
* Opens **both long and short positions simultaneously** (dual-direction mode)
---
### **Risk Control:**
* **Long position stop-loss:** Entry price − 2%
* **Short position stop-loss:** Entry price + 2%
* Uses a **five-level take-profit grid**:
* Every 5% profit → close 20% of position
* Any pending take-profit orders are automatically canceled when stop-loss triggers
---
### **Visualization Features:**
* Real-time display of the three moving averages
* Chart annotations for entry signal points
* All trade signals and performance can be viewed through **TradingView backtest reports**
---
### **Notes:**
* Parameters can be adjusted based on the volatility of the instrument (historical backtesting is recommended first)
* Dual-direction positions may generate **hedging costs** — recommended for low-fee markets
* Real trading must consider **exchange minimum order size limits**
* Suggest enabling a **volume filter mechanism** (extension interface already reserved)
* Always perform **historical backtesting and parameter optimization** in TradingView before connecting to live trading systems
Swing Breakout Strategy ver 1Overview
A multi-confirmation swing strategy that seeks trend breakouts and adds three optional confluence modules: candlestick patterns, RSI/MACD regular divergences, and simple chart patterns (double top/bottom). Built for clarity, fast testing, and togglable debug markers.
Core Logic
Trend filter: SMA(50) vs SMA(200) + price vs SMA(21).
Breakout engine: Close breaks prior N-bar high/low (lookback configurable).
Momentum: Stochastic cross (optional view), MACD cross/zone, RSI regime (>50 or <50).
Volume: Above SMA(volume) filter.
Optional Confluence Modules
Candlestick analysis (enable/disable):
Bull/Bear Engulfing, Hammer, Shooting Star, Inside Bar (bull/bear flavors).
Divergence (enable/disable):
Regular divergences on RSI and MACD histogram using confirmed pivots (HH/LH or LL/HL).
Chart patterns (enable/disable):
Double Bottom (two similar lows + neckline break).
Double Top (two similar highs + neckline break).
Tolerance and pivot width are configurable.
Entries & Exits
Entry Long: Any of (Base Breakout + Trend + Momentum + Volume) OR enabled confluences (candles / divergence / pattern).
Entry Short: Symmetric logic for downside.
Risk management: Optional ATR-based stop loss and take profit (configurable length & multipliers).
Note: If you prefer confluences to be filters (AND), change the final buySignal/sellSignal lines accordingly.
Inputs (key)
SMA lengths (21/50/200), RSI length, Stochastic lengths & smoothing, MACD (12/26/9).
Breakout lookback, Volume SMA.
ATR exits (on/off, ATR length, SL/TP multipliers).
Toggles for Candlesticks, Divergences, Patterns, plus per-module debug markers.
Plots & Markers
Plots SMA 21/50/200.
Buy/Sell arrows on chart.
Optional debug markers for each condition (global-scope safe).
Divergence/pattern markers offset to the actual pivot/neckline bars.
Good Practices
Test on multiple timeframes and instruments; tune lookbacks and ATR multipliers.
Consider using the modules as filters in trending markets to reduce whipsaws.
Always forward-test and combine with position sizing.
Disclaimer
For educational purposes only. This is not financial advice. Trading involves risk.
Version & Credits
Pine Script® v6 — Strategy.
Developed by: Mohammed Bedaiwi.
Swing Breakout Strategy — Candles + Divergences + Patterns (rev)Overview
A multi-confirmation swing strategy that seeks trend breakouts and adds three optional confluence modules: candlestick patterns, RSI/MACD regular divergences, and simple chart patterns (double top/bottom). Built for clarity, fast testing, and togglable debug markers.
Core Logic
Trend filter: SMA(50) vs SMA(200) + price vs SMA(21).
Breakout engine: Close breaks prior N-bar high/low (lookback configurable).
Momentum: Stochastic cross (optional view), MACD cross/zone, RSI regime (>50 or <50).
Volume: Above SMA(volume) filter.
Optional Confluence Modules
Candlestick analysis (enable/disable):
Bull/Bear Engulfing, Hammer, Shooting Star, Inside Bar (bull/bear flavors).
Divergence (enable/disable):
Regular divergences on RSI and MACD histogram using confirmed pivots (HH/LH or LL/HL).
Chart patterns (enable/disable):
Double Bottom (two similar lows + neckline break).
Double Top (two similar highs + neckline break).
Tolerance and pivot width are configurable.
Entries & Exits
Entry Long: Any of (Base Breakout + Trend + Momentum + Volume) OR enabled confluences (candles / divergence / pattern).
Entry Short: Symmetric logic for downside.
Risk management: Optional ATR-based stop loss and take profit (configurable length & multipliers).
Note: If you prefer confluences to be filters (AND), change the final buySignal/sellSignal lines accordingly.
Inputs (key)
SMA lengths (21/50/200), RSI length, Stochastic lengths & smoothing, MACD (12/26/9).
Breakout lookback, Volume SMA.
ATR exits (on/off, ATR length, SL/TP multipliers).
Toggles for Candlesticks, Divergences, Patterns, plus per-module debug markers.
Plots & Markers
Plots SMA 21/50/200.
Buy/Sell arrows on chart.
Optional debug markers for each condition (global-scope safe).
Divergence/pattern markers offset to the actual pivot/neckline bars.
Good Practices
Test on multiple timeframes and instruments; tune lookbacks and ATR multipliers.
Consider using the modules as filters in trending markets to reduce whipsaws.
Always forward-test and combine with position sizing.
Disclaimer
For educational purposes only. This is not financial advice. Trading involves risk.
Version & Credits
Pine Script® v6 — Strategy.
Developed by: Mohammed Bedaiwi.
nadia
Gold ramon strategy based on 50 candles and atr of 12
You enter the maximum of 50 candles once the most bearish starts to rise, we expect 10 candles, if you don't go up in 10 candles, you don't enter, if you go up before 10 candles, you enter.
When is TP? Enough with 5 candles
The temporality is 1 hour. It can be adjusted to 1 minute temporality for scalping.
It is never lost, because it always exceeds the previous maximums.
Crypto Pro Strategy (Entry Model + Risk)Imma try to use this on a prop firm but if you want to use it itss free or im going to try to make it free
Quantum Flux Universal Strategy Summary in one paragraph
Quantum Flux Universal is a regime switching strategy for stocks, ETFs, index futures, major FX pairs, and liquid crypto on intraday and swing timeframes. It helps you act only when the normalized core signal and its guide agree on direction. It is original because the engine fuses three adaptive drivers into the smoothing gains itself. Directional intensity is measured with binary entropy, path efficiency shapes trend quality, and a volatility squash preserves contrast. Add it to a clean chart, watch the polarity lane and background, and trade from positive or negative alignment. For conservative workflows use on bar close in the alert settings when you add alerts in a later version.
Scope and intent
• Markets. Large cap equities and ETFs. Index futures. Major FX pairs. Liquid crypto
• Timeframes. One minute to daily
• Default demo used in the publication. QQQ on one hour
• Purpose. Provide a robust and portable way to detect when momentum and confirmation align, while dampening chop and preserving turns
• Limits. This is a strategy. Orders are simulated on standard candles only
Originality and usefulness
• Unique concept or fusion. The novelty sits in the gain map. Instead of gating separate indicators, the model mixes three drivers into the adaptive gains that power two one pole filters. Directional entropy measures how one sided recent movement has been. Kaufman style path efficiency scores how direct the path has been. A volatility squash stabilizes step size. The drivers are blended into the gains with visible inputs for strength, windows, and clamps.
• What failure mode it addresses. False starts in chop and whipsaw after fast spikes. Efficiency and the squash reduce over reaction in noise.
• Testability. Every component has an input. You can lengthen or shorten each window and change the normalization mode. The polarity plot and background provide a direct readout of state.
• Portable yardstick. The core is normalized with three options. Z score, percent rank mapped to a symmetric range, and MAD based Z score. Clamp bounds define the effective unit so context transfers across symbols.
Method overview in plain language
The strategy computes two smoothed tracks from the chart price source. The fast track and the slow track use gains that are not fixed. Each gain is modulated by three drivers. A driver for directional intensity, a driver for path efficiency, and a driver for volatility. The difference between the fast and the slow tracks forms the raw flux. A small phase assist reduces lag by subtracting a portion of the delayed value. The flux is then normalized. A guide line is an EMA of a small lead on the flux. When the flux and its guide are both above zero, the polarity is positive. When both are below zero, the polarity is negative. Polarity changes create the trade direction.
Base measures
• Return basis. The step is the change in the chosen price source. Its absolute value feeds the volatility estimate. Mean absolute step over the window gives a stable scale.
• Efficiency basis. The ratio of net move to the sum of absolute step over the window gives a value between zero and one. High values mean trend quality. Low values mean chop.
• Intensity basis. The fraction of up moves over the window plugs into binary entropy. Intensity is one minus entropy, which maps to zero in uncertainty and one in very one sided moves.
Components
• Directional Intensity. Measures how one sided recent bars have been. Smoothed with RMA. More intensity increases the gain and makes the fast and slow tracks react sooner.
• Path Efficiency. Measures the straightness of the price path. A gamma input shapes the curve so you can make trend quality count more or less. Higher efficiency lifts the gain in clean trends.
• Volatility Squash. Normalizes the absolute step with Z score then pushes it through an arctangent squash. This caps the effect of spikes so they do not dominate the response.
• Normalizer. Three modes. Z score for familiar units, percent rank for a robust monotone map to a symmetric range, and MAD based Z for outlier resistance.
• Guide Line. EMA of the flux with a small lead term that counteracts lag without heavy overshoot.
Fusion rule
• Weighted sum of the three drivers with fixed weights visible in the code comments. Intensity has fifty percent weight. Efficiency thirty percent. Volatility twenty percent.
• The blend power input scales the driver mix. Zero means fixed spans. One means full driver control.
• Minimum and maximum gain clamps bound the adaptive gain. This protects stability in quiet or violent regimes.
Signal rule
• Long suggestion appears when flux and guide are both above zero. That sets polarity to plus one.
• Short suggestion appears when flux and guide are both below zero. That sets polarity to minus one.
• When polarity flips from plus to minus, the strategy closes any long and enters a short.
• When flux crosses above the guide, the strategy closes any short.
What you will see on the chart
• White polarity plot around the zero line
• A dotted reference line at zero named Zen
• Green background tint for positive polarity and red background tint for negative polarity
• Strategy long and short markers placed by the TradingView engine at entry and at close conditions
• No table in this version to keep the visual clean and portable
Inputs with guidance
Setup
• Price source. Default ohlc4. Stable for noisy symbols.
• Fast span. Typical range 6 to 24. Raising it slows the fast track and can reduce churn. Lowering it makes entries more reactive.
• Slow span. Typical range 20 to 60. Raising it lengthens the baseline horizon. Lowering it brings the slow track closer to price.
Logic
• Guide span. Typical range 4 to 12. A small guide smooths without eating turns.
• Blend power. Typical range 0.25 to 0.85. Raising it lets the drivers modulate gains more. Lowering it pushes behavior toward fixed EMA style smoothing.
• Vol window. Typical range 20 to 80. Larger values calm the volatility driver. Smaller values adapt faster in intraday work.
• Efficiency window. Typical range 10 to 60. Larger values focus on smoother trends. Smaller values react faster but accept more noise.
• Efficiency gamma. Typical range 0.8 to 2.0. Above one increases contrast between clean trends and chop. Below one flattens the curve.
• Min alpha multiplier. Typical range 0.30 to 0.80. Lower values increase smoothing when the mix is weak.
• Max alpha multiplier. Typical range 1.2 to 3.0. Higher values shorten smoothing when the mix is strong.
• Normalization window. Typical range 100 to 300. Larger values reduce drift in the baseline.
• Normalization mode. Z score, percent rank, or MAD Z. Use MAD Z for outlier heavy symbols.
• Clamp level. Typical range 2.0 to 4.0. Lower clamps reduce the influence of extreme runs.
Filters
• Efficiency filter is implicit in the gain map. Raising efficiency gamma and the efficiency window increases the preference for clean trends.
• Micro versus macro relation is handled by the fast and slow spans. Increase separation for swing, reduce for scalping.
• Location filter is not included in v1.0. If you need distance gates from a reference such as VWAP or a moving mean, add them before publication of a new version.
Alerts
• This version does not include alertcondition lines to keep the core minimal. If you prefer alerts, add names Long Polarity Up, Short Polarity Down, Exit Short on Flux Cross Up in a later version and select on bar close for conservative workflows.
Strategy has been currently adapted for the QQQ asset with 30/60min timeframe.
For other assets may require new optimization
Properties visible in this publication
• Initial capital 25000
• Base currency Default
• Default order size method percent of equity with value 5
• Pyramiding 1
• Commission 0.05 percent
• Slippage 10 ticks
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
Honest limitations and failure modes
• Past results do not guarantee future outcomes
• Economic releases, circuit breakers, and thin books can break the assumptions behind intensity and efficiency
• Gap heavy symbols may benefit from the MAD Z normalization
• Very quiet regimes can reduce signal contrast. Use longer windows or higher guide span to stabilize context
• Session time is the exchange time of the chart
• If both stop and target can be hit in one bar, tie handling would matter. This strategy has no fixed stops or targets. It uses polarity flips for exits. If you add stops later, declare the preference
Open source reuse and credits
• None beyond public domain building blocks and Pine built ins such as EMA, SMA, standard deviation, RMA, and percent rank
• Method and fusion are original in construction and disclosure
Legal
Education and research only. Not investment advice. You are responsible for your decisions. Test on historical data and in simulation before any live use. Use realistic costs.
Strategy add on block
Strategy notice
Orders are simulated by the TradingView engine on standard candles. No request.security() calls are used.
Entries and exits
• Entry logic. Enter long when both the normalized flux and its guide line are above zero. Enter short when both are below zero
• Exit logic. When polarity flips from plus to minus, close any long and open a short. When the flux crosses above the guide line, close any short
• Risk model. No initial stop or target in v1.0. The model is a regime flipper. You can add a stop or trail in later versions if needed
• Tie handling. Not applicable in this version because there are no fixed stops or targets
Position sizing
• Percent of equity in the Properties panel. Five percent is the default for examples. Risk per trade should not exceed five to ten percent of equity. One to two percent is a common choice
Properties used on the published chart
• Initial capital 25000
• Base currency Default
• Default order size percent of equity with value 5
• Pyramiding 1
• Commission 0.05 percent
• Slippage 10 ticks
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
Dataset and sample size
• Test window Jan 2, 2014 to Oct 16, 2025 on QQQ one hour
• Trade count in sample 324 on the example chart
Release notes template for future updates
Version 1.1.
• Add alertcondition lines for long, short, and exit short
• Add optional table with component readouts
• Add optional stop model with a distance unit expressed as ATR or a percent of price
Notes. Backward compatibility Yes. Inputs migrated Yes.
Pump-Smart Shorting StrategyThis strategy is built to keep your portfolio hedged as much as possible while maximizing profitability. Shorts are opened after pumps cool off and on new highs (when safe), and closed quickly during strong upward moves or if stop loss/profit targets are hit. It uses visual overlays to clearly show when hedging is on, off, or blocked due to momentum, ensuring you’re protected in most market conditions but never short against the pump. Fast re-entry keeps the hedge active with minimal downtime.
Pump Detection:
RSI (Relative Strength Index): Calculated over a custom period (default 14 bars). If RSI rises above a threshold (default 70), the strategy considers the market to be in a pump (strong upward momentum).
Volume Spike: The current volume is compared to a 20-bar simple moving average of volume. If it exceeds the average by 1.5× and price increases at least 5% in one bar, pump conditions are triggered.
Price Jump: Measured by (close - close ) / close . A single-bar change > 5% helps confirm rapid momentum.
Pump Zone (No Short): If any of these conditions is true, an orange or red background is shown and shorts are blocked.
Cooldown and Re-Entry:
Cooldown Detection: After the pump ends, RSI must fall below a set value (default ≤ 60), and either volume returns towards average or price momentum is less than half the original spike (oneBarUp <= pctUp/2).
barsWait Parameter: You can specify a waiting period after cooldown before a short is allowed.
Short Entry After Pump/Cooldown: When these cooldown conditions are met, and no short is active, a blue background is shown and a short position is opened at the next signal.
New High Entry:
Lookback New High: If the current high is greater than the highest high in the last N bars (default 20), and pump is NOT active, a short can be opened.
Take Profit (TP) & Stop Loss (SL):
Take Profit: Short is closed if price falls to a threshold below the entry (minProfitPerc, default 2%).
Stop Loss: Short is closed if price rises to a threshold above the entry (stopLossPerc, default 6%).
Preemptive Exit:
Any time a pump is detected while a short position is open, the strategy closes the short immediately to avoid losses.
Visual Feedback:
Orange Background: Market is pumping, do not short.
Red Background: Other conditions block shorts (cooldown or waiting).
Blue Background: Shorts allowed.
Triangles/Circles: Mark entries, pump start/end, for clear trading signals.
LW Outside Day Strategy[SpeculationLab]This strategy is inspired by the “Outside Day” concept introduced by Larry Williams in Long-Term Secrets to Short-Term Trading, and has been extended with configurable risk management tools and realistic backtesting parameters.
Concept
The “Outside Day” is a classic price action pattern that reflects strong market rejection or continuation pressure.
An Outside Bar occurs when the current bar’s high exceeds the previous high and the low falls below the previous low.
A body-size filter ensures only significant candles are included.
Entry Logic
Buy setup: Price closes below the previous low (bullish rejection).
Sell setup: Price closes above the previous high (bearish rejection).
Only confirmed bars are used (no intrabar signals).
Stop-Loss Modes
Prev Low/High: Uses the previous swing point ± ATR-based buffer.
ATR: Dynamic stop based on Average True Range × multiplier.
Fixed Pips: User-defined fixed distance (for forex testing).
Take-Profit Modes
Prev High/Low (PHL): Exits near the opposite swing.
Risk-Reward (RR): Targets a user-defined multiple of the stop distance (default = 2 : 1).
Following Price Open (FPO): Exits on the next bar’s open if price opens in profit (used to test overnight price continuation).
Risk Management & Backtest Settings
Default risk per trade is set at 10% of account equity (user-adjustable).
Commission = 0.1% and slippage = 2 ticks are applied to simulate realistic conditions.
For reliable statistics, test on data that yields over 100 trades.
Suitable for daily and 4-hour timeframes across stocks, forex, and crypto markets.
Visual Elements
Green and red triangles show entry signals.
Stop-loss (red) and take-profit (green) reference lines are drawn for clarity.
Optional alerts notify when a valid setup forms.
Disclaimer
This script is for educational and research purposes only.
It does not constitute financial advice or guarantee profits.
Always backtest thoroughly and manage your own risk.
Enhancements over Classic Outside Bar Models
Adjustable stop and target logic with ATR and buffer multipliers.
“Following Price Open” exit logic for realistic day-end management.
Optimized to avoid repainting and bar-confirmation issues.
Built with realistic trading costs and position sizing.
策略逻辑
外包线识别
当日最高价高于前一日最高价,且当日最低价低于前一日最低价,即形成外包线。
同时过滤掉较小实体的 K 线,仅保留实体显著大于前一根的形态。
方向过滤
收盘价低于前一日最低价 → 视为买入信号。
收盘价高于前一日最高价 → 视为卖出信号。
止损设置(可选参数)
前低/高止损:以形态前低/前高为止损,带有缓冲倍数。
ATR 止损:根据平均波动率(ATR)动态调整。
固定点数止损:按照用户设定的点数作为止损范围。
止盈设置(可选参数)
前高/低止盈(PHL):以前高/前低为目标。
固定盈亏比(RR):根据用户设定的风险回报比自动计算。
隔夜开盘(FPO):若次日开盘价高于进场价(多单)或低于进场价(空单),则平仓。
信号标记
在图表中标注买入/卖出信号(三角形标记)。
绘制止损与目标位参考线。
使用说明
适用周期:建议用于 日线图(Daily)。
适用市场:股票、外汇、加密货币等各类市场均可。
提示:此策略为历史研究与学习用途,不构成投资建议。实际交易请结合自身风险管理。
Larry Williams Oops StrategyThis strategy is a modern take on Larry Williams’ classic Oops setup. It trades intraday while referencing daily bars to detect opening gaps and align entries with the prior day’s direction. Risk is managed with day-based stops, and—unlike the original—all positions are closed at the end of the session (or at the last bar’s close), not at a fixed profit target or the first profitable open.
Entry Rules
Long setup (bullish reversion): Today opens below yesterday’s low (down gap) and yesterday’s candle was bearish. Place a buy stop at yesterday’s low + Filter (ticks).
Short setup (bearish reversion): Today opens above yesterday’s high (up gap) and yesterday’s candle was bullish. Place a sell stop at yesterday’s high − Filter (ticks).
Longs are only taken on down-gap days; shorts only on up-gap days.
Protective Stop
If long, stop loss trails the current day’s low.
If short, stop loss trails the current day’s high.
Exit Logic
Positions are force-closed at the end of the session (in the last bar), ensuring no overnight exposure. There is no take-profit; only stop loss or end-of-day flat.
Notes
This strategy is designed for intraday charts (minutes/seconds) using daily data for gaps and prior-day direction.
Longs/shorts can be enabled or disabled independently.






















