// ============================================================================ // © algonexta // This script is for education and research; it does not guarantee results. // Verify this source in TradingView before use. // ============================================================================ // Breakout Ladder. A channel breakout in the spirit of the classic trend-following rules: it enters on a // close beyond the 55-bar range, closes in steps, and lets the last part ride until the 20-bar exit channel. // Backtest results describe the past only and do not predict future results. Not financial advice. //@version=6 strategy("Breakout Ladder: Channel Breakout Strategy [AlgoNexta]", shorttitle = "Breakout Ladder", overlay = true, initial_capital = 10000, currency = currency.NONE, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, commission_type = strategy.commission.percent, commission_value = 0.01, slippage = 2, pyramiding = 0, max_boxes_count = 300, max_lines_count = 300, max_labels_count = 300) string NAME = "Breakout Ladder" //────────────────────────────────────────────────────────────────────────────── // Strategy inputs //────────────────────────────────────────────────────────────────────────────── string G_CH = "Channel" string G_ENT = "Entry and exit" int entryLen = input.int(55, "Breakout channel (bars)", minval = 5, maxval = 400, group = G_CH, tooltip = "A long starts when a bar closes above the highest high of this many earlier bars. Mirrored for shorts.", display = display.none) int exitLen = input.int(20, "Exit channel (bars)", minval = 2, maxval = 200, group = G_CH, tooltip = "The remaining position closes when a bar closes below the lowest low of this many earlier bars (above the highest high for a short).", display = display.none) bool useBase = input.bool(true, "Trade only on the right side of the base EMA", group = G_CH, display = display.none) int baseLen = input.int(200, "Base EMA", minval = 20, group = G_CH, display = display.none) float stopAtr = input.float(2.0, "Initial stop (ATR)", minval = 0.5, step = 0.25, group = G_ENT, tooltip = "Distance from the signal close to the initial stop, in ATR(20). This distance is 1R.", display = display.none) bool useExit = input.bool(true, "Close on the exit channel", group = G_ENT, display = display.none) //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // LADDER RISK ENGINE, part 1 of 3: inputs. This block is the same in all AlgoNexta Ladder // strategies; only the default values differ. //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ string G_RISK = "Risk" string G_TP = "Targets: the position is closed in steps" string G_STOP = "Stop management" string G_DAY = "Daily guard" string G_VIS = "Display" string SM_OFF = "Never" string SM_BE = "To entry after target 1" string SM_STEP = "To entry after target 1, then one target behind" string LE_FIX = "Its fixed target" string LE_TRL = "A trailing stop" string LE_NONE = "Only the stop or the strategy's own exit" float riskPct = input.float(1.0, "Risk per trade (% of equity)", minval = 0.1, maxval = 5.0, step = 0.1, group = G_RISK, tooltip = "The position size is set so that a full stop-out from the signal price loses this share of equity. 1R is the distance from the signal bar's close to the initial stop.", display = display.none) float maxLev = input.float(0.9, "Largest position (multiple of equity)", minval = 0.1, maxval = 20.0, step = 0.1, group = G_RISK, tooltip = "Caps the position when the stop is very close. With the default 100% margin, keep this below 1.", display = display.none) string tradeDir = input.string("Both", "Direction", options = ["Both", "Long only", "Short only"], group = G_RISK, display = display.none) int nT = input.int(3, "Number of targets", minval = 1, maxval = 4, group = G_TP, tooltip = "1 to 4 steps. Each step closes part of the position at its target. The last active step always closes whatever is left.", display = display.none) float t1R = input.float(1.5, "Target 1 (R)", minval = 0.2, step = 0.25, group = G_TP, display = display.none) float p1 = input.float(30, "Target 1 closes (% of the position)", minval = 1, maxval = 100, group = G_TP, display = display.none) float t2R = input.float(3.0, "Target 2 (R)", minval = 0.2, step = 0.25, group = G_TP, display = display.none) float p2 = input.float(30, "Target 2 closes (% of the position)", minval = 1, maxval = 100, group = G_TP, display = display.none) float t3R = input.float(5.0, "Target 3 (R)", minval = 0.2, step = 0.25, group = G_TP, display = display.none) float p3 = input.float(20, "Target 3 closes (% of the position)", minval = 1, maxval = 100, group = G_TP, display = display.none) float t4R = input.float(6.0, "Target 4 (R)", minval = 0.2, step = 0.25, group = G_TP, tooltip = "Percentages are shares of the initial position. Keep their sum below 100 so that the last step has something left to close.", display = display.none) string lastExit = input.string(LE_NONE, "The last part exits by", options = [LE_FIX, LE_TRL, LE_NONE], group = G_TP, tooltip = "Its fixed target: the last step closes at its own target. A trailing stop: the last step has no target and leaves when the trailing stop is hit. Only the stop or the strategy's own exit: no target and no trailing; the last part rides until the (moved) stop, the session end or a trend flip, depending on the strategy.", display = display.none) int trailFrom = input.int(1, "Trailing starts after target", minval = 0, maxval = 3, group = G_TP, tooltip = "0: the stop trails from the entry. 1: after target 1 is reached, and so on. Used only when the last part exits by a trailing stop.", display = display.none) float trailMult = input.float(3.0, "Trailing distance (ATR)", minval = 0.5, step = 0.25, group = G_TP, display = display.none) string stopMove = input.string(SM_BE, "Move the stop", options = [SM_OFF, SM_BE, SM_STEP], group = G_STOP, tooltip = "The stop only ever moves in the trade's favour. A move decided on one bar takes effect from the next bar.", display = display.none) int maxDayTrades = input.int(0, "Max new positions per day (0 = no limit)", minval = 0, group = G_DAY, display = display.none) float maxDayLoss = input.float(0.0, "No new entries after a daily loss of % (0 = off)", minval = 0.0, step = 0.5, group = G_DAY, tooltip = "Measured on equity since the first bar of the day. Open trades are not closed by this rule.", display = display.none) bool showLevels = input.bool(true, "Show stop and targets", group = G_VIS, display = display.none) bool showTable = input.bool(true, "Show status table", group = G_VIS, display = display.none) string tblPos = input.string("Top right", "Table position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G_VIS, display = display.none) color upCol = input.color(#22ab94, "Long / target colour", group = G_VIS, display = display.none) color dnCol = input.color(#f23645, "Short / stop colour", group = G_VIS, display = display.none) //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // LADDER RISK ENGINE, part 2 of 3: state and order functions (identical in all five strategies). // One position at a time. Entry is a market order sent at the close of the signal bar; it fills // at the next bar's open. Stop and targets are fixed prices measured from the signal bar's close. //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ type Trade int dir = 0 // 1 long, -1 short, 0 no trade float entry = na // signal bar close (planned entry) float stop = na // live stop price float risk = na // 1R as a price distance float qty = na // initial position size float t1 = na float t2 = na float t3 = na float t4 = na bool h1 = false // price has reached target 1 bool h2 = false bool h3 = false int bar = na // signal bar int count = 0 // positions taken so far var Trade tr = Trade.new() // Daily guard bool newDay = timeframe.change("D") var float dayEq = na var int dayTrades = 0 if newDay or na(dayEq) dayEq := strategy.equity dayTrades := 0 bool dayOk = (maxDayTrades == 0 or dayTrades < maxDayTrades) and (maxDayLoss == 0 or (strategy.equity - dayEq) / dayEq * 100.0 > -maxDayLoss) f_pos(string s) => s == "Top left" ? position.top_left : s == "Bottom right" ? position.bottom_right : s == "Bottom left" ? position.bottom_left : position.top_right // The stop that protects more: the higher one for a long, the lower one for a short. f_better(int dir, float a, float b) => dir == 1 ? math.max(a, b) : math.min(a, b) // Units that risk riskPct of equity over the stop distance, capped by the position limit. f_qty(float dist) => float riskCash = strategy.equity * riskPct / 100.0 float byRisk = riskCash / (dist * syminfo.pointvalue) float byCap = strategy.equity * maxLev / (close * syminfo.pointvalue) math.max(0.0, math.min(byRisk, byCap)) // Call once per bar BEFORE the entry logic: forgets a trade that has been fully closed. f_sync(Trade t) => if t.dir != 0 and strategy.position_size == 0 and bar_index > t.bar t.dir := 0 t.dir // Opens a trade if none is open. Returns true when the entry order was sent. f_open(Trade t, int dir, float stop) => bool opened = false float dist = math.abs(close - stop) bool side = dir == 1 ? stop < close : stop > close if strategy.position_size == 0 and t.dir == 0 and side and dist > syminfo.mintick float q = f_qty(dist) if q > 0 t.dir := dir t.entry := close t.stop := stop t.risk := dist t.qty := q t.t1 := close + dir * t1R * dist t.t2 := close + dir * t2R * dist t.t3 := close + dir * t3R * dist t.t4 := close + dir * t4R * dist t.h1 := false t.h2 := false t.h3 := false t.bar := bar_index t.count := t.count + 1 strategy.entry(dir == 1 ? "Long" : "Short", dir == 1 ? strategy.long : strategy.short, qty = q) alert(NAME + ": " + (dir == 1 ? "LONG " : "SHORT ") + syminfo.ticker + " at about " + str.tostring(close, format.mintick) + ", stop " + str.tostring(stop, format.mintick) + ", target 1 " + str.tostring(t.t1, format.mintick), alert.freq_once_per_bar_close) opened := true opened // Call once per bar AFTER the entry logic: marks reached targets, moves the stop, and keeps one // exit order per remaining step. trailPx is the trailing price that the strategy logic proposes, or na for none. f_manage(Trade t, float trailPx) => if t.dir != 0 int d = t.dir string id = d == 1 ? "Long" : "Short" string px = d == 1 ? "L" : "S" if strategy.position_size != 0 if not t.h1 and (d == 1 ? high >= t.t1 : low <= t.t1) t.h1 := true alert(NAME + ": target 1 reached on " + syminfo.ticker, alert.freq_once_per_bar_close) if nT >= 2 and not t.h2 and (d == 1 ? high >= t.t2 : low <= t.t2) t.h2 := true alert(NAME + ": target 2 reached on " + syminfo.ticker, alert.freq_once_per_bar_close) if nT >= 3 and not t.h3 and (d == 1 ? high >= t.t3 : low <= t.t3) t.h3 := true alert(NAME + ": target 3 reached on " + syminfo.ticker, alert.freq_once_per_bar_close) float ns = t.stop if stopMove != SM_OFF and t.h1 ns := f_better(d, ns, strategy.position_avg_price) if stopMove == SM_STEP if t.h2 ns := f_better(d, ns, t.t1) if t.h3 ns := f_better(d, ns, t.t2) int hits = (t.h1 ? 1 : 0) + (t.h2 ? 1 : 0) + (t.h3 ? 1 : 0) if lastExit == LE_TRL and hits >= trailFrom and not na(trailPx) and (d == 1 ? trailPx < close : trailPx > close) ns := f_better(d, ns, trailPx) t.stop := ns // Steps before the last one: a fixed share of the initial position each. if nT >= 2 and not t.h1 strategy.exit(px + "1", id, qty = t.qty * p1 / 100.0, limit = t.t1, stop = t.stop, comment_profit = "T1", comment_loss = "Stop") if nT >= 3 and not t.h2 strategy.exit(px + "2", id, qty = t.qty * p2 / 100.0, limit = t.t2, stop = t.stop, comment_profit = "T2", comment_loss = "Stop") if nT >= 4 and not t.h3 strategy.exit(px + "3", id, qty = t.qty * p3 / 100.0, limit = t.t3, stop = t.stop, comment_profit = "T3", comment_loss = "Stop") // Last step: whatever is left, at its target or with no target when it trails. float lastT = nT == 1 ? t.t1 : nT == 2 ? t.t2 : nT == 3 ? t.t3 : t.t4 float lim = lastExit == LE_FIX ? lastT : na strategy.exit(px + "F", id, limit = lim, stop = t.stop, comment_profit = "Last target", comment_loss = "Stop") t.dir //────────────────────────────────────────────────────────────────────────────── // Channels //────────────────────────────────────────────────────────────────────────────── float atr = ta.atr(20) float emaB = ta.ema(close, baseLen) float upE = ta.highest(high, entryLen)[1] float dnE = ta.lowest(low, entryLen)[1] float upX = ta.highest(high, exitLen)[1] float dnX = ta.lowest(low, exitLen)[1] bool longSig = close > upE and close[1] <= upE[1] and (not useBase or close > emaB) bool shortSig = close < dnE and close[1] >= dnE[1] and (not useBase or close < emaB) float longStop = close - stopAtr * atr float shortStop = close + stopAtr * atr //────────────────────────────────────────────────────────────────────────────── // Orders: confirmed bars only //────────────────────────────────────────────────────────────────────────────── f_sync(tr) bool opened = false if barstate.isconfirmed and dayOk if longSig and tradeDir != "Short only" opened := f_open(tr, 1, longStop) else if shortSig and tradeDir != "Long only" opened := f_open(tr, -1, shortStop) if opened dayTrades += 1 if useExit and barstate.isconfirmed and strategy.position_size != 0 and bar_index > tr.bar if tr.dir == 1 and close < dnX strategy.close("Long", comment = "Exit channel") if tr.dir == -1 and close > upX strategy.close("Short", comment = "Exit channel") // Trailing price, used only when the last part exits by a trailing stop: the exit channel. f_manage(tr, tr.dir == 1 ? dnX : upX) plot(upE, "Breakout high", color = color.new(upCol, 40), display = display.all - display.status_line) plot(dnE, "Breakout low", color = color.new(dnCol, 40), display = display.all - display.status_line) plot(tr.dir == 1 ? dnX : tr.dir == -1 ? upX : na, "Exit channel", color = color.new(chart.fg_color, 50), style = plot.style_linebr, display = display.all - display.status_line) plot(useBase ? emaB : na, "Base EMA", color = color.new(chart.fg_color, 65), display = display.all - display.status_line) //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // LADDER RISK ENGINE, part 3 of 3: stop and target lines, status table (identical in all five). //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ f_lvl(int i, float price, bool reached) => showLevels and tr.dir != 0 and nT >= i and not reached and not (i == nT and lastExit != LE_FIX) ? price : na plot(showLevels and tr.dir != 0 ? tr.stop : na, "Stop", color = dnCol, style = plot.style_linebr, linewidth = 2, display = display.all - display.status_line) plot(f_lvl(1, tr.t1, tr.h1), "Target 1", color = upCol, style = plot.style_linebr, display = display.all - display.status_line) plot(f_lvl(2, tr.t2, tr.h2), "Target 2", color = upCol, style = plot.style_linebr, display = display.all - display.status_line) plot(f_lvl(3, tr.t3, tr.h3), "Target 3", color = upCol, style = plot.style_linebr, display = display.all - display.status_line) plot(f_lvl(4, tr.t4, false), "Target 4", color = upCol, style = plot.style_linebr, display = display.all - display.status_line) var table tb = table.new(f_pos(tblPos), 2, 8, bgcolor = color.new(chart.bg_color, 10), border_color = color.new(chart.fg_color, 85), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1) f_cell(int col, int row, string txt, color c) => table.cell(tb, col, row, txt, text_color = c, text_size = size.small, text_halign = text.align_left) // Two rows (k1/v1 and k2/v2) belong to the strategy; the rest is the same everywhere. f_dash(string k1, string v1, string k2, string v2) => if showTable and (barstate.islastconfirmedhistory or barstate.isrealtime) color fg = chart.fg_color int hits = (tr.h1 ? 1 : 0) + (tr.h2 ? 1 : 0) + (tr.h3 ? 1 : 0) string stateTxt = tr.dir == 0 ? "No trade" : (tr.dir == 1 ? "Long" : "Short") + ", now " + str.tostring((close - tr.entry) * tr.dir / tr.risk, "#.##") + " R" string plan = str.tostring(t1R) + "R" + (nT >= 2 ? " / " + str.tostring(t2R) + "R" : "") + (nT >= 3 ? " / " + str.tostring(t3R) + "R" : "") + (nT >= 4 ? " / " + str.tostring(t4R) + "R" : "") + (lastExit == LE_TRL ? ", last part trails" : lastExit == LE_NONE ? ", last part rides" : "") string tgtTxt = tr.dir == 0 ? plan : str.tostring(math.min(hits, nT)) + " of " + str.tostring(nT) + " reached (" + plan + ")" f_cell(0, 0, NAME, fg) f_cell(1, 0, stateTxt, tr.dir == 1 ? upCol : tr.dir == -1 ? dnCol : fg) f_cell(0, 1, "Targets", fg) f_cell(1, 1, tgtTxt, fg) f_cell(0, 2, "Stop", fg) f_cell(1, 2, tr.dir == 0 ? "-" : str.tostring(tr.stop, format.mintick), fg) f_cell(0, 3, k1, fg) f_cell(1, 3, v1, fg) f_cell(0, 4, k2, fg) f_cell(1, 4, v2, fg) f_cell(0, 5, "Positions taken", fg) f_cell(1, 5, str.tostring(tr.count), fg) f_cell(0, 6, "Net result", fg) f_cell(1, 6, str.tostring(strategy.netprofit / strategy.initial_capital * 100.0, "#.#") + "% at " + str.tostring(riskPct, "#.##") + "% risk", fg) f_cell(0, 7, "Profit factor", fg) f_cell(1, 7, strategy.grossloss > 0 ? str.tostring(strategy.grossprofit / strategy.grossloss, "#.##") : "-", fg) f_dash("Channel", str.tostring(entryLen) + "-bar breakout, " + str.tostring(exitLen) + "-bar exit", "Base EMA", not useBase ? "off" : close > emaB ? "above: longs only" : "below: shorts only")