Indicator

Wait 5 sec.

IndicatorGoldOANDA:XAUUSDsdgardeningserv//@version=6 indicator("Bman Studios Buy/Sell Indicator v7", shorttitle="Bman Studios v7", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500) // ===================================================================================== // Bman Studios Buy/Sell Indicator // 1) Distance-weighted historical pattern classifier for directional ML bias, // configurable features // 2) Filters: Volatility, Regime (trend-strength), ADX, EMA, SMA // 3) Smoothed trend confirmation line based on weighted historical price averaging, // optional trade filter // 4) Breaker Block detection - ONLY drawn once flipped, deleted once invalidated // 5) Fair Value Gaps tracked internally (not drawn) - feed BPR only // 6) BPR (overlapping opposing FVGs) - deleted once filled // 7) Buy/Sell trigger = ML trend FLIP (armed once per regime change) + breaker reaction, // so signals print sparsely instead of every bar // 8) TP1 = 1:1 risk:reward from SL, TP2 = 1:2 risk:reward from SL; one clean Entry/SL/TP1/TP2 // line set per open trade, replaced on next trade // 9) Trade stats table (trades / wins / winrate / W-L ratio) // ===================================================================================== // ============================ GENERAL SETTINGS ============================ grpGen = "General Settings" neighborsCount = input.int(8, "Neighbors Count (K)", minval=1, maxval=30, group=grpGen) maxTrainingSamples = input.int(300, "Max Bars Back (training samples)", minval=50, maxval=2000, group=grpGen) predictionBars = input.int(4, "Prediction Lookahead (bars)", minval=1, maxval=20, group=grpGen) normLen = input.int(100, "Feature Normalization Length", minval=20, group=grpGen) // ============================ FEATURE ENGINEERING ============================ grpFeat = "Feature Engineering" featureCount = input.int(5, "Feature Count", minval=1, maxval=5, group=grpFeat) feat1Type = input.string("RSI", "Feature 1 Type", options=, group=grpFeat) feat1A = input.int(14, "Feature 1 Param A", group=grpFeat) feat1B = input.int(1, "Feature 1 Param B", group=grpFeat) feat2Type = input.string("WT", "Feature 2 Type", options=, group=grpFeat) feat2A = input.int(10, "Feature 2 Param A", group=grpFeat) feat2B = input.int(11, "Feature 2 Param B", group=grpFeat) feat3Type = input.string("CCI", "Feature 3 Type", options=, group=grpFeat) feat3A = input.int(20, "Feature 3 Param A", group=grpFeat) feat3B = input.int(1, "Feature 3 Param B", group=grpFeat) feat4Type = input.string("ADX", "Feature 4 Type", options=, group=grpFeat) feat4A = input.int(20, "Feature 4 Param A", group=grpFeat) feat4B = input.int(2, "Feature 4 Param B", group=grpFeat) feat5Type = input.string("RSI", "Feature 5 Type", options=, group=grpFeat) feat5A = input.int(9, "Feature 5 Param A", group=grpFeat) feat5B = input.int(1, "Feature 5 Param B", group=grpFeat) // ============================ FILTERS ============================ grpFilt = "Filters" useVolatilityFilter = input.bool(true, "Use Volatility Filter", group=grpFilt) useRegimeFilter = input.bool(true, "Use Regime Filter", group=grpFilt) regimeThreshold = input.float(-0.1, "Regime Threshold", group=grpFilt) useADXFilter = input.bool(false, "Use ADX Filter", group=grpFilt) adxThreshold = input.int(20, "ADX Threshold", group=grpFilt) useEMAFilter = input.bool(false, "Use EMA Filter", group=grpFilt) emaFilterPeriod = input.int(200, "EMA Filter Period", group=grpFilt) useSMAFilter = input.bool(false, "Use SMA Filter", group=grpFilt) smaFilterPeriod = input.int(200, "SMA Filter Period", group=grpFilt) // ============================ CHOP FILTER ============================ // Uses the Choppiness Index, a standard public-domain formula (E.W. Dreiss, 1994), // the same category of well-known technique as RSI or ADX - not tied to any single // published script. Acts as a hard block, not just one vote among the filters above: // signals are suppressed outright when chop is very high, regardless of everything else. grpChop = "Chop Filter" useChopFilter = input.bool(true, "Avoid Chop (block signals in high-chop conditions)", group=grpChop) chopLen = input.int(14, "Chop Lookback Length", minval=5, group=grpChop) chopThreshold = input.float(61.8, "Chop Threshold (0-100)", minval=0.0, maxval=100.0, group=grpChop) useFlipFilter = input.bool(true, "Avoid Whipsaw Zones (trend line flip count)", group=grpChop) flipLookback = input.int(15, "Whipsaw Lookback (bars)", minval=5, group=grpChop) maxFlipsAllowed = input.int(2, "Max Trend Flips Allowed", minval=1, group=grpChop) // ============================ KERNEL SETTINGS ============================ grpKernel = "Trend Confirmation Settings" tradeWithKernel = input.bool(true, "Require Trend Line Agreement", group=grpKernel) showKernelEstimate = input.bool(true, "Show Trend Confirmation Line", group=grpKernel) kernelLookback = input.int(8, "Trend Line Period", minval=2, maxval=100, group=grpKernel) kernelRelWeight = input.float(8, "Trend Line Sensitivity", minval=0.1, group=grpKernel) kernelSmoothingOn = input.bool(false, "Extra Trend Line Smoothing", group=grpKernel) kernelSmoothingLag = input.int(2, "Smoothing Length", minval=1, group=grpKernel) // ============================ BREAKER BLOCKS ============================ grpBB = "Breaker Blocks" pivotLen = input.int(5, "Pivot Lookback (Swing Detection)", minval=2, group=grpBB) maxOrderBlocks = input.int(25, "Max Tracked Order Blocks", minval=5, maxval=50, group=grpBB) // ============================ FVG / BPR ============================ grpBPR = "Balanced Price Range" showBPR = input.bool(true, "Show BPR (overlapping FVGs)", group=grpBPR) // ============================ TP / SL ============================ grpTPSL = "Take Profit / Stop Loss (PD Arrays)" slBufferATRmult = input.float(0.25, "SL Buffer (x ATR)", minval=0.0, step=0.05, group=grpTPSL) slExtraATRmult = input.float(0.75, "Extra SL Distance (x ATR)", minval=0.0, group=grpTPSL) tradeZoneWidth = input.int(30, "Trade Zone Width (bars)", minval=5, group=grpTPSL) showTPSL = input.bool(true, "Show TP/SL Levels", group=grpTPSL) grpSession = "Session-Based Tightening" useSessionTighten = input.bool(true, "Tighten SL/TP during Asia & London", group=grpSession) asiaSession = input.session("0000-0900", "Asia Session (exchange time)", group=grpSession) londonSession = input.session("0700-1600", "London Session (exchange time)", group=grpSession) sessionTightenATRmult = input.float(0.25, "Tighten Amount (x ATR)", minval=0.0, group=grpSession) minSLDistanceATRmult = input.float(0.1, "Minimum SL Distance (x ATR)", minval=0.01, group=grpSession) // ============================ TRADE STATS ============================ grpStats = "Trade Stats" showTradeStats = input.bool(true, "Show Trade Stats", group=grpStats) beOffsetATRmult = input.float(0.15, "Breakeven+ Offset (x ATR)", minval=0.0, group=grpStats) // ============================ DISPLAY ============================ grpDisp = "Display" bullColor = input.color(color.new(color.teal, 0), "Bullish Color", group=grpDisp) bearColor = input.color(color.new(color.red, 0), "Bearish Color", group=grpDisp) // ============================ FEATURE FUNCTIONS ============================ f_norm(src) => lo = ta.lowest(src, normLen) hi = ta.highest(src, normLen) (src - lo) / (hi - lo + 1e-10) f_feature(ftype, pA, pB) => float result = na if ftype == "RSI" result := ta.rsi(close, pA) else if ftype == "WT" ap2 = hlc3 esa2 = ta.ema(ap2, pA) d2 = ta.ema(math.abs(ap2 - esa2), pA) ci2 = (ap2 - esa2) / (0.015 * d2) result := ta.ema(ci2, pB) else if ftype == "CCI" result := ta.cci(close, pA) else if ftype == "ADX" = ta.dmi(pA, pB) result := adxv else if ftype == "MOM" result := ta.mom(close, pA) result f1 = f_norm(f_feature(feat1Type, feat1A, feat1B)) f2 = f_norm(f_feature(feat2Type, feat2A, feat2B)) f3 = f_norm(f_feature(feat3Type, feat3A, feat3B)) f4 = f_norm(f_feature(feat4Type, feat4A, feat4B)) f5 = f_norm(f_feature(feat5Type, feat5A, feat5B)) // ============================ TRAINING SET ============================ var f1Arr = array.new_float(0) var f2Arr = array.new_float(0) var f3Arr = array.new_float(0) var f4Arr = array.new_float(0) var f5Arr = array.new_float(0) var labelArr = array.new_float(0) if bar_index >= predictionBars pastLabel = close - close > 0 ? 1.0 : (close - close < 0 ? -1.0 : 0.0) array.push(f1Arr, f1) array.push(f2Arr, f2) array.push(f3Arr, f3) array.push(f4Arr, f4) array.push(f5Arr, f5) array.push(labelArr, pastLabel) if array.size(labelArr) > maxTrainingSamples array.shift(f1Arr) array.shift(f2Arr) array.shift(f3Arr) array.shift(f4Arr) array.shift(f5Arr) array.shift(labelArr) // ============================ HISTORICAL PATTERN CLASSIFICATION ============================ float prediction = na size = array.size(labelArr) if size > neighborsCount distances = array.new_float(size) for i = 0 to size - 1 dd1 = featureCount >= 1 ? math.log(1 + math.abs(f1 - array.get(f1Arr, i))) : 0.0 dd2 = featureCount >= 2 ? math.log(1 + math.abs(f2 - array.get(f2Arr, i))) : 0.0 dd3 = featureCount >= 3 ? math.log(1 + math.abs(f3 - array.get(f3Arr, i))) : 0.0 dd4 = featureCount >= 4 ? math.log(1 + math.abs(f4 - array.get(f4Arr, i))) : 0.0 dd5 = featureCount >= 5 ? math.log(1 + math.abs(f5 - array.get(f5Arr, i))) : 0.0 array.set(distances, i, dd1 + dd2 + dd3 + dd4 + dd5) usedIdx = array.new_bool(size, false) sumLabel = 0.0 for k = 0 to neighborsCount - 1 minDist = 1e10 minIdx = -1 for i = 0 to size - 1 if not array.get(usedIdx, i) dv = array.get(distances, i) if dv < minDist minDist := dv minIdx := i if minIdx >= 0 array.set(usedIdx, minIdx, true) sumLabel += array.get(labelArr, minIdx) prediction := sumLabel mlBullishRaw = not na(prediction) and prediction > 0 mlBearishRaw = not na(prediction) and prediction < 0 // ============================ FILTERS ============================ atrShort = ta.atr(2) atrLong = ta.atr(20) volOK = not useVolatilityFilter or (atrShort >= atrLong * 0.75) regimeValue = (ta.ema(close, 20) - ta.ema(close, 20)) / (ta.atr(20) + 1e-10) regimeOK = not useRegimeFilter or (regimeValue > regimeThreshold) = ta.dmi(14, 14) adxOK = not useADXFilter or (adxFilterVal > adxThreshold) emaVal = ta.ema(close, emaFilterPeriod) smaVal = ta.sma(close, smaFilterPeriod) commonFiltersOK = volOK and regimeOK and adxOK filterBullOK = commonFiltersOK and (not useEMAFilter or close > emaVal) and (not useSMAFilter or close > smaVal) filterBearOK = commonFiltersOK and (not useEMAFilter or close < emaVal) and (not useSMAFilter or close < smaVal) // ============================ TREND CONFIRMATION LINE ============================ f_kernelRegression(len, relWeight) => float num = 0.0 float den = 0.0 for i = 0 to len - 1 w = math.pow(1 + (math.pow(i, 2) / (2 * relWeight * math.pow(len, 2))), -relWeight) num += close * w den += w num / den kernelRaw = f_kernelRegression(kernelLookback, kernelRelWeight) kernelLine = kernelSmoothingOn ? ta.ema(kernelRaw, kernelSmoothingLag) : kernelRaw kernelBullish = kernelLine > kernelLine kernelBearish = kernelLine < kernelLine plot(showKernelEstimate ? kernelLine : na, title="Kernel Regression Estimate", color=kernelBullish ? bullColor : bearColor, linewidth=2) // ============================ CHOP INDEX ============================ chopATRSum = math.sum(ta.atr(1), chopLen) chopRange = ta.highest(high, chopLen) - ta.lowest(low, chopLen) chopIndex = 100 * math.log10(chopATRSum / (chopRange + 1e-10)) / math.log10(chopLen) chopActive = useChopFilter and chopIndex >= chopThreshold chopOK = not chopActive // Counts how many times the trend confirmation line has flipped direction in the // recent lookback window - catches tight back-and-forth ranging zones where price // whipsaws repeatedly, even if the broader Choppiness Index doesn't flag it. kernelFlip = kernelBullish != kernelBullish ? 1 : 0 flipCount = math.sum(kernelFlip, flipLookback) whipsawActive = useFlipFilter and flipCount > maxFlipsAllowed whipsawOK = not whipsawActive // (background tint removed - bgcolor() paints the full chart height, too visually heavy) // ============================ FINAL ML BIAS ============================ mlBullish = mlBullishRaw and filterBullOK and (not tradeWithKernel or kernelBullish) and chopOK and whipsawOK mlBearish = mlBearishRaw and filterBearOK and (not tradeWithKernel or kernelBearish) and chopOK and whipsawOK // Trend-flip arming: only "arm" a signal search once per regime change, so we don't // re-fire on every bar the ML bias happens to stay bullish/bearish var int mlTrend = 0 if mlBullish mlTrend := 1 if mlBearish mlTrend := -1 var int pendingDir = 0 // 0 = none armed, 1 = armed for buy, -1 = armed for sell if mlTrend == 1 and mlTrend != 1 pendingDir := 1 if mlTrend == -1 and mlTrend != -1 pendingDir := -1 // ============================ SWING / ORDER BLOCK / BREAKER TRACKING ============================ // Order blocks are tracked internally but NOT drawn until they flip into breaker blocks. // Breaker blocks are deleted once invalidated (price closes back through the far side). ph = ta.pivothigh(high, pivotLen, pivotLen) pl = ta.pivotlow(low, pivotLen, pivotLen) var float lastSwingHigh = na var float lastSwingLow = na if not na(ph) lastSwingHigh := ph if not na(pl) lastSwingLow := pl var obTop = array.new_float(0) var obBottom = array.new_float(0) var obIsBull = array.new_bool(0) var obIsBreaker= array.new_bool(0) var obLeftBar = array.new_int(0) var box obBoxId = array.new(0) f_removeOB(idx) => bx = array.get(obBoxId, idx) if not na(bx) box.delete(bx) array.remove(obTop, idx) array.remove(obBottom, idx) array.remove(obIsBull, idx) array.remove(obIsBreaker, idx) array.remove(obLeftBar, idx) array.remove(obBoxId, idx) if not na(lastSwingHigh) and close > lastSwingHigh and close maxOrderBlocks f_removeOB(0) if not na(lastSwingLow) and close < lastSwingLow and close >= lastSwingLow upIdx = -1 for i = 1 to pivotLen + 2 if close > open upIdx := i break if upIdx != -1 array.push(obTop, high) array.push(obBottom, low) array.push(obIsBull, false) array.push(obIsBreaker, false) array.push(obLeftBar, bar_index) array.push(obBoxId, na) if array.size(obTop) > maxOrderBlocks f_removeOB(0) // Flip violated order blocks into breaker blocks (drawn here for the first time) if array.size(obTop) > 0 for i = 0 to array.size(obTop) - 1 isBull = array.get(obIsBull, i) isBreaker = array.get(obIsBreaker, i) top = array.get(obTop, i) bot = array.get(obBottom, i) leftBar = array.get(obLeftBar, i) if isBull and not isBreaker and close < bot array.set(obIsBreaker, i, true) bx = box.new(leftBar, top, bar_index + 20, bot, border_color=bearColor, bgcolor=color.new(bearColor, 85), extend=extend.right, text="Breaker Block", text_color=color.white, text_size=size.tiny) array.set(obBoxId, i, bx) if not isBull and not isBreaker and close > top array.set(obIsBreaker, i, true) bx = box.new(leftBar, top, bar_index + 20, bot, border_color=bullColor, bgcolor=color.new(bullColor, 85), extend=extend.right, text="Breaker Block", text_color=color.white, text_size=size.tiny) array.set(obBoxId, i, bx) // Remove invalidated breaker blocks (price closes back through the far side) if array.size(obTop) > 0 for i = array.size(obTop) - 1 to 0 if array.get(obIsBreaker, i) top = array.get(obTop, i) bot = array.get(obBottom, i) invalid = array.get(obIsBull, i) ? close > top : close < bot if invalid f_removeOB(i) // ============================ FAIR VALUE GAPS (tracked only, not drawn) ============================ var fvgTop = array.new_float(0) var fvgBottom = array.new_float(0) var fvgIsBull = array.new_bool(0) var fvgFilled = array.new_bool(0) var fvgLeftBar = array.new_int(0) bullFVG = low > high bearFVG = high < low if bullFVG array.push(fvgTop, low) array.push(fvgBottom, high) array.push(fvgIsBull, true) array.push(fvgFilled, false) array.push(fvgLeftBar, bar_index) if array.size(fvgTop) > maxOrderBlocks * 2 array.shift(fvgTop) array.shift(fvgBottom) array.shift(fvgIsBull) array.shift(fvgFilled) array.shift(fvgLeftBar) if bearFVG array.push(fvgTop, low) array.push(fvgBottom, high) array.push(fvgIsBull, false) array.push(fvgFilled, false) array.push(fvgLeftBar, bar_index) if array.size(fvgTop) > maxOrderBlocks * 2 array.shift(fvgTop) array.shift(fvgBottom) array.shift(fvgIsBull) array.shift(fvgFilled) array.shift(fvgLeftBar) if array.size(fvgTop) > 0 for i = 0 to array.size(fvgTop) - 1 if not array.get(fvgFilled, i) t = array.get(fvgTop, i) b = array.get(fvgBottom, i) if low = b isBull = array.get(fvgIsBull, i) filledNow = isBull ? close < b : close > t if filledNow array.set(fvgFilled, i, true) // ============================ BPR (overlapping opposing FVGs) - redrawn fresh each bar ============================ // Anchored to where the overlap actually formed and extended right, same as breaker // blocks, instead of a small window sliding forward with the current bar. var box bprBoxId = array.new(0) if showBPR if array.size(bprBoxId) > 0 for i = 0 to array.size(bprBoxId) - 1 box.delete(array.get(bprBoxId, i)) array.clear(bprBoxId) if array.size(fvgTop) > 0 for i = 0 to array.size(fvgTop) - 1 if not array.get(fvgFilled, i) and array.get(fvgIsBull, i) for j = 0 to array.size(fvgTop) - 1 if not array.get(fvgFilled, j) and not array.get(fvgIsBull, j) t1 = array.get(fvgTop, i) b1 = array.get(fvgBottom, i) t2 = array.get(fvgTop, j) b2 = array.get(fvgBottom, j) ovTop = math.min(t1, t2) ovBot = math.max(b1, b2) if ovTop > ovBot bxLeft = math.min(array.get(fvgLeftBar, i), array.get(fvgLeftBar, j)) bx = box.new(bxLeft, ovTop, bar_index + 20, ovBot, border_color=color.new(color.purple, 0), bgcolor=color.new(color.purple, 75), extend=extend.right, text="BPR", text_color=color.white, text_size=size.tiny) array.push(bprBoxId, bx) // ============================ TRIGGER: ARMED ML FLIP + BREAKER BLOCK CONFLUENCE ============================ bool buySignal = false bool sellSignal = false float triggerBreakerBot = na float triggerBreakerTop = na int triggerIdx = -1 if pendingDir == 1 and array.size(obTop) > 0 for i = 0 to array.size(obTop) - 1 if array.get(obIsBreaker, i) and not array.get(obIsBull, i) top = array.get(obTop, i) bot = array.get(obBottom, i) if low bot buySignal := true triggerBreakerBot := bot triggerBreakerTop := top triggerIdx := i break if pendingDir == -1 and array.size(obTop) > 0 for i = 0 to array.size(obTop) - 1 if array.get(obIsBreaker, i) and array.get(obIsBull, i) top = array.get(obTop, i) bot = array.get(obBottom, i) if high >= bot and close < top sellSignal := true triggerBreakerBot := bot triggerBreakerTop := top triggerIdx := i break if buySignal pendingDir := 0 f_removeOB(triggerIdx) if sellSignal pendingDir := 0 f_removeOB(triggerIdx) // ============================ TP1 / TP2 / SL / ENTRY ============================ atr14 = ta.atr(14) inAsiaSession = useSessionTighten and not na(time(timeframe.period, asiaSession)) inLondonSession = useSessionTighten and not na(time(timeframe.period, londonSession)) sessionAdj = (inAsiaSession or inLondonSession) ? atr14 * sessionTightenATRmult : 0.0 float tp1 = na float tp2 = na float sl = na float entryPrice = na if buySignal rawSl = triggerBreakerBot - atr14 * slBufferATRmult - atr14 * slExtraATRmult entryPrice := close sl := math.min(rawSl + sessionAdj, entryPrice - atr14 * minSLDistanceATRmult) riskDist = entryPrice - sl tp1 := entryPrice + riskDist * 1.0 tp2 := entryPrice + riskDist * 2.0 if sellSignal rawSl = triggerBreakerTop + atr14 * slBufferATRmult + atr14 * slExtraATRmult entryPrice := close sl := math.max(rawSl - sessionAdj, entryPrice + atr14 * minSLDistanceATRmult) riskDist = sl - entryPrice tp1 := entryPrice - riskDist * 1.0 tp2 := entryPrice - riskDist * 2.0 // ============================ TRADE STATE, CLEAN LINES, STATS ============================ var string tradeDir = na var float tradeEntry = na var float tradeTP1 = na var float tradeTP2 = na var float tradeSL = na var float activeStop = na var bool beArmed = false var bool tp1Hit = false var int totalTrades = 0 var int tp2AfterTp1Attempts = 0 var int tp2AfterTp1Hits = 0 var int wins = 0 var int losses = 0 var box riskBox = na var box reward1Box = na var box reward2Box = na var line entryLine = na var label entryLabel = na var label tp1Label = na var label tp2Label = na var label slLabel = na f_clearTradeDrawings() => if not na(riskBox) box.delete(riskBox) if not na(reward1Box) box.delete(reward1Box) if not na(reward2Box) box.delete(reward2Box) if not na(entryLine) line.delete(entryLine) if not na(entryLabel) label.delete(entryLabel) if not na(tp1Label) label.delete(tp1Label) if not na(tp2Label) label.delete(tp2Label) if not na(slLabel) label.delete(slLabel) if not na(tradeDir) and (buySignal or sellSignal) // A new signal arrived while a previous trade was still open. // If it had already reached breakeven, it can no longer lose money from here, // so count it as a win instead of discarding it uncounted. Otherwise it's still // genuinely uncertain, so it's excluded from stats entirely as before. if beArmed wins += 1 totalTrades += 1 tradeDir := na if na(tradeDir) and buySignal and not na(tp1) and not na(sl) tradeDir := "long" tradeEntry := entryPrice tradeTP1 := tp1 tradeTP2 := tp2 tradeSL := sl activeStop := sl beArmed := false tp1Hit := false if showTPSL f_clearTradeDrawings() boxRight = bar_index + tradeZoneWidth riskBox := box.new(bar_index, math.max(entryPrice, sl), boxRight, math.min(entryPrice, sl), border_color=color.red, bgcolor=color.new(color.red, 85)) reward1Box := box.new(bar_index, math.max(entryPrice, tp1), boxRight, math.min(entryPrice, tp1), border_color=color.green, bgcolor=color.new(color.green, 85)) reward2Box := box.new(bar_index, math.max(tp1, tp2), boxRight, math.min(tp1, tp2), border_color=color.green, bgcolor=color.new(color.green, 92)) entryLine := line.new(bar_index, entryPrice, boxRight, entryPrice, color=color.blue, width=2) entryLabel := label.new(boxRight, entryPrice, "Entry: " + str.tostring(entryPrice, format.mintick), style=label.style_label_left, color=color.blue, textcolor=color.white, size=size.small) tp1Label := label.new(boxRight, tp1, "TP1: " + str.tostring(tp1, format.mintick), style=label.style_label_left, color=color.green, textcolor=color.white, size=size.small) tp2Label := label.new(boxRight, tp2, "TP2: " + str.tostring(tp2, format.mintick), style=label.style_label_left, color=color.green, textcolor=color.white, size=size.small) slLabel := label.new(boxRight, sl, "SL: " + str.tostring(sl, format.mintick), style=label.style_label_left, color=color.red, textcolor=color.white, size=size.small) if na(tradeDir) and sellSignal and not na(tp1) and not na(sl) tradeDir := "short" tradeEntry := entryPrice tradeTP1 := tp1 tradeTP2 := tp2 tradeSL := sl activeStop := sl beArmed := false tp1Hit := false if showTPSL f_clearTradeDrawings() boxRight = bar_index + tradeZoneWidth riskBox := box.new(bar_index, math.max(entryPrice, sl), boxRight, math.min(entryPrice, sl), border_color=color.red, bgcolor=color.new(color.red, 85)) reward1Box := box.new(bar_index, math.max(entryPrice, tp1), boxRight, math.min(entryPrice, tp1), border_color=color.green, bgcolor=color.new(color.green, 85)) reward2Box := box.new(bar_index, math.max(tp1, tp2), boxRight, math.min(tp1, tp2), border_color=color.green, bgcolor=color.new(color.green, 92)) entryLine := line.new(bar_index, entryPrice, boxRight, entryPrice, color=color.blue, width=2) entryLabel := label.new(boxRight, entryPrice, "Entry: " + str.tostring(entryPrice, format.mintick), style=label.style_label_left, color=color.blue, textcolor=color.white, size=size.small) tp1Label := label.new(boxRight, tp1, "TP1: " + str.tostring(tp1, format.mintick), style=label.style_label_left, color=color.green, textcolor=color.white, size=size.small) tp2Label := label.new(boxRight, tp2, "TP2: " + str.tostring(tp2, format.mintick), style=label.style_label_left, color=color.green, textcolor=color.white, size=size.small) slLabel := label.new(boxRight, sl, "SL: " + str.tostring(sl, format.mintick), style=label.style_label_left, color=color.red, textcolor=color.white, size=size.small) if tradeDir == "long" halfwayLong = tradeEntry + (tradeTP1 - tradeEntry) * 0.5 if not beArmed and high >= halfwayLong beArmed := true activeStop := tradeEntry + atr14 * beOffsetATRmult if not tp1Hit and high >= tradeTP1 tp1Hit := true activeStop := tradeSL if tp1Hit and high >= tradeTP2 wins += 1 totalTrades += 1 tp2AfterTp1Attempts += 1 tp2AfterTp1Hits += 1 tradeDir := na else if low 0 ? (float(tp2AfterTp1Hits) / float(tp2AfterTp1Attempts)) * 100 : na var table statsTable = table.new(position.top_right, 2, 5, bgcolor=color.new(color.black, 20), border_width=1, border_color=color.gray) if showTradeStats and barstate.islast table.cell(statsTable, 0, 0, "Trades", text_color=color.white) table.cell(statsTable, 1, 0, str.tostring(totalTrades), text_color=color.white) table.cell(statsTable, 0, 1, "Wins", text_color=color.white) table.cell(statsTable, 1, 1, str.tostring(wins), text_color=color.white) table.cell(statsTable, 0, 2, "Winrate", text_color=color.white) table.cell(statsTable, 1, 2, na(winratePct) ? "n/a" : str.tostring(winratePct, "#.#") + "%", text_color=color.white) table.cell(statsTable, 0, 3, "W/L Ratio", text_color=color.white) table.cell(statsTable, 1, 3, na(wlRatio) ? "n/a" : str.tostring(wlRatio, "#.##"), text_color=color.white) table.cell(statsTable, 0, 4, "TP1→TP2 Rate", text_color=color.white) table.cell(statsTable, 1, 4, na(tp2AfterTp1Pct) ? "n/a" : str.tostring(tp2AfterTp1Pct, "#.#") + "%", text_color=color.white) // ============================ PLOTS / ALERTS ============================ plotshape(buySignal, style=shape.triangleup, location=location.belowbar, color=bullColor, size=size.small, title="Buy Signal", text="Buy!", textcolor=bullColor) plotshape(sellSignal, style=shape.triangledown, location=location.abovebar, color=bearColor, size=size.small, title="Sell Signal", text="Sell!", textcolor=bearColor) alertcondition(buySignal, title="ML + Breaker Buy Signal", message="BUY: ML trend flip + bullish breaker block reaction") alertcondition(sellSignal, title="ML + Breaker Sell Signal", message="SELL: ML trend flip + bearish breaker block reaction")