//@version=6 // This Pine Scriptâ„¢ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Alerts when a bar closes beyond the high or low of the previous N bars. // The current bar is not part of that range. One alert fires on the cross, not on later bars that stay outside. indicator("Phone Me on Breakout", "Breakout", overlay=true) int length = input.int(20, "Lookback bars", minval=2, maxval=500, group="Range", tooltip="Highest high and lowest low of this many completed bars. The current bar is excluded.") bool useVolume = input.bool(false, "Require volume expansion", group="Volume", tooltip="Leave this off for symbols with no volume, such as many forex pairs and indexes.") int volLength = input.int(20, "Volume average length", minval=1, group="Volume") float volMultiple = input.float(1.5, "Volume multiple", minval=0.1, step=0.1, group="Volume") escapeJson(string source) => string out = str.replace_all(source, "\\", "\\\\") out := str.replace_all(out, "\"", "\\\"") out := str.replace_all(out, "\n", " ") out // side is "buy" or "sell". detail is the sentence placed in action. webhookMessage(string side, string detail) => "{\"strategy\":{\"order_action\":\"" + side + "\"},\"ticker\":\"" + escapeJson(syminfo.ticker) + "\",\"action\":\"" + escapeJson(detail) + "\"}" float priorHigh = ta.highest(high, length)[1] float priorLow = ta.lowest(low, length)[1] float avgVolume = ta.sma(volume, volLength) bool volumeOk = not useVolume or volume > avgVolume * volMultiple // Crossover state must update on every bar, including bars the volume filter rejects. bool rawAbove = ta.crossover(close, priorHigh) bool rawBelow = ta.crossunder(close, priorLow) bool closeAbove = volumeOk and rawAbove bool closeBelow = volumeOk and rawBelow string priceText = str.tostring(close, format.mintick) string barsText = str.tostring(length) if barstate.isconfirmed and barstate.isrealtime and closeAbove alert(webhookMessage("buy", "Closed above the " + barsText + "-bar high at " + priceText + "."), alert.freq_once_per_bar_close) if barstate.isconfirmed and barstate.isrealtime and closeBelow alert(webhookMessage("sell", "Closed below the " + barsText + "-bar low at " + priceText + "."), alert.freq_once_per_bar_close) plot(priorHigh, "Prior high", color=color.teal, linewidth=1) plot(priorLow, "Prior low", color=color.orange, linewidth=1) plotshape(closeAbove and barstate.isconfirmed, "Close above prior high", shape.triangleup, location.belowbar, color.teal, size=size.tiny) plotshape(closeBelow and barstate.isconfirmed, "Close below prior low", shape.triangledown, location.abovebar, color.orange, size=size.tiny)