本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chetasmahajan
//@version=6
// Traditional Renko built from 5-second closes and drawn on a candle chart. A brick completes only when a 5S bar
// closes one box beyond the last brick (two boxes to reverse), and the box size changes only between candles.
// The Supertrend follows KivancOzbilgic's open-source "SuperTrend" script, run on the bricks as on a Renko chart.
indicator("Intraday Non-Repainting Renko with Supertrend", "Renko + Supertrend", overlay = true, max_lines_count = 100)
GRP_SIZE = "Brick size"
GRP_ST = "Supertrend on the bricks"
GRP_VIEW = "Display"
// 5S closes kept to redraw the bricks when the auto size changes (about 4 NSE sessions).
KEEP = 20000
// Longest straight move tried when looking for the brick that flips the Supertrend.
MAX_SIM = 500
string sizeMode = input.string("Auto (ATR)", "Brick size", options = ["Auto (ATR)", "Fixed"], group = GRP_SIZE)
float fixedSize = input.float(25.0, "Fixed size", minval = 0.05, step = 0.05, group = GRP_SIZE)
string atrTf = input.timeframe("360", "Auto: ATR timeframe", group = GRP_SIZE)
int atrLen = input.int(5, "Auto: ATR length", minval = 1, group = GRP_SIZE)
string scaleTf = input.timeframe("30", "Auto: scale to", group = GRP_SIZE, tooltip = "Brick = ATR box of the last completed candle on the ATR timeframe (Regular session) ÷ (ATR timeframe ÷ this timeframe), rounded to the tick. 6h box 400 ÷ (6h ÷ 30m = 12) = 33.35.")
string dataTf = input.timeframe("5S", "Renko timeframe", group = GRP_SIZE)
bool showSt = input.bool(true, "Supertrend", group = GRP_ST)
int stLen = input.int(1, "ATR period", minval = 1, group = GRP_ST, tooltip = "Wilder's ATR of the bricks, as with \"Change ATR Calculation Method\" ticked in the Supertrend script.")
string stSrc = input.string("close", "Source", options = ["close", "open", "high", "low", "hl2", "hlc3", "ohlc4", "hlcc4"], group = GRP_ST)
float stMult = input.float(3.1, "ATR multiplier", minval = 0.1, step = 0.1, group = GRP_ST)
bool stLabels = input.bool(true, "Buy/Sell labels", group = GRP_ST)
string hlMode = input.string("To candle high/low", "Highlighter", options = ["Cloud to next brick", "To candle high/low", "Background tint", "To brick middle", "Off"], group = GRP_ST, tooltip = "Cloud to next brick: from the Supertrend line through price to the next brick level beyond it, stretched over any wick past that level. To candle high/low: to each candle's far end. Background tint: the whole background in the trend color. To brick middle: to the middle of the latest brick, as the script fills on a Renko chart.")
bool stFlip = input.bool(true, "Flip level", group = GRP_ST, tooltip = "Dashed ray from the candle of the latest brick at the brick close that flips the Supertrend if price moves straight against the trend from there.")
int gridCount = input.int(5, "Dotted levels above/below", minval = 1, maxval = 40, group = GRP_VIEW)
int gridWidth = input.int(2, "Level thickness", minval = 1, maxval = 5, group = GRP_VIEW)
bool fitGrid = input.bool(false, "Keep all levels on screen", group = GRP_VIEW, tooltip = "Auto-scale ignores lines, so levels outside the visible price range are off-screen. On: the price scale stretches to show every level.")
bool showMarks = input.bool(true, "Brick markers", group = GRP_VIEW)
bool showTable = input.bool(true, "Table", inline = "tbl", group = GRP_VIEW)
string tablePos = input.string(position.bottom_right, "", options = [position.top_right, position.middle_right, position.bottom_right, position.bottom_left, position.top_left], inline = "tbl", group = GRP_VIEW)
color upColor = input.color(#089981, "Colors: up", inline = "col", group = GRP_VIEW)
color dnColor = input.color(#F23645, "down", inline = "col", group = GRP_VIEW)
color gridColor = input.color(color.new(color.gray, 30), "levels", inline = "col", group = GRP_VIEW)
// Rounds the ATR to one significant digit in ticks (NIFTY 6h: to the nearest 50).
roundBrick(float x) =>
float result = na
if x > 0
float ticks = x / syminfo.mintick
float step = math.pow(10, math.floor(math.log10(ticks)))
result := math.round(ticks / step) * step * syminfo.mintick
result
fmt(float x) => str.tostring(x, "#.####")
// The last brick closed at idx × box; dir is its direction (0 before the first brick). The other fields are the
// Supertrend after that brick (prices in ticks); buys and sells count its flips.
type Renko
int idx
int dir = 0
int cnt = 0
float atr
float up
float dn
int trend = 1
int buys = 0
int sells = 0
float buyAt
float sellAt
// Runs the Supertrend script on one brick that opened at box o and closed at box c. Bricks have no wicks; the
// previous close is the last brick's, or the starting level for the first brick.
method onBrick(Renko r, int o, int c, int bt) =>
float op = o * bt
float cl = c * bt
float hi = math.max(op, cl)
float lo = math.min(op, cl)
float pc = r.idx * bt
float trueRange = math.max(hi, pc) - math.min(lo, pc)
r.cnt := r.cnt + 1
// Wilder's RMA seeded with the mean of the first stLen ranges, like ta.atr().
r.atr := na(r.atr) ? trueRange : r.atr + (trueRange - r.atr) / math.min(r.cnt, stLen)
float atrNow = r.cnt >= stLen ? r.atr : na
float src = switch stSrc
"open" => op
"high" => hi
"low" => lo
"hl2" => (hi + lo) / 2
"hlc3" => (hi + lo + cl) / 3
"ohlc4" => (op + hi + lo + cl) / 4
"hlcc4" => (hi + lo + 2 * cl) / 4
=> cl
float up = src - stMult * atrNow
float up1 = na(r.up) ? up : r.up
if pc > up1
up := math.max(up, up1)
float dn = src + stMult * atrNow
float dn1 = na(r.dn) ? dn : r.dn
if pc < dn1
dn := math.min(dn, dn1)
if r.trend == -1 and cl > dn1
r.trend := 1
r.buys := r.buys + 1
r.buyAt := up
else if r.trend == 1 and cl < up1
r.trend := -1
// The script can't signal on its first bar, where trend[1] is na.
r.sells := r.sells + (r.cnt > 1 ? 1 : 0)
r.sellAt := dn
r.up := up
r.dn := dn
r.idx := c
// Feeds one 5S close in ticks and returns the bricks it completed (+ up, - down).
method feed(Renko r, int t, int bt) =>
int made = 0
if na(r.idx)
r.idx := math.floor(t / bt)
else if t >= (r.idx + (r.dir == -1 ? 2 : 1)) * bt
// A reversal brick opens at the previous brick's open.
int o = r.dir == -1 ? r.idx + 1 : r.idx
while t >= (o + 1) * bt
r.onBrick(o, o + 1, bt)
o += 1
made += 1
r.dir := 1
else if t <= (r.idx - (r.dir == 1 ? 2 : 1)) * bt
int o = r.dir == 1 ? r.idx - 1 : r.idx
while t <= (o - 1) * bt
r.onBrick(o, o - 1, bt)
o -= 1
made -= 1
r.dir := -1
made
bool autoMode = sizeMode == "Auto (ATR)"
// Heikin Ashi and other non-standard charts would feed synthetic prices to the bricks.
bool tfOk = chart.is_standard and timeframe.in_seconds() > timeframe.in_seconds(dataTf)
// A lower-timeframe request would repaint, so the ATR timeframe can't be below the chart's.
if autoMode and timeframe.in_seconds(atrTf) < timeframe.in_seconds()
runtime.error("Auto: the ATR timeframe must not be lower than the chart timeframe.")
// ATR of the last completed ATR-timeframe candle on the Regular session, requested with an offset so it can't look
// ahead. If a new ATR candle starts while a live chart candle is open, that candle keeps the ATR it opened with, as on
// history, so the box never changes inside a candle.
string regTicker = ticker.new(syminfo.prefix, syminfo.ticker, session.regular)
[atrLast, atrEarlier] = request.security(regTicker, atrTf, [ta.atr(atrLen)[1], ta.atr(atrLen)[2]], lookahead = barmerge.lookahead_on)
int atrOpen = request.security(regTicker, atrTf, time, lookahead = barmerge.lookahead_off)
float atrPrev = barstate.isrealtime and atrOpen > time ? atrEarlier : atrLast
float atrBox = roundBrick(atrPrev)
float ratio = float(timeframe.in_seconds(atrTf)) / timeframe.in_seconds(scaleTf)
float wantSize = autoMode ? atrBox / ratio : fixedSize
int wantTicks = na(wantSize) ? na : math.max(1, math.round(wantSize / syminfo.mintick))
var Renko eng = Renko.new()
var int engTicks = na
var array<int> ring = array.new<int>()
var int head = 0
// The replay result for the current bar. varip keeps it across live updates; otherwise rollback would
// repeat the replay on every tick of the first candle after a size change.
varip int replayBar = na
varip int replayTicks = na
varip int replayIdx = na
varip int replayDir = 0
varip int replayCnt = 0
varip float replayAtr = na
varip float replayUp = na
varip float replayDn = na
varip int replayTrend = 1
// A new size rebuilds the bricks from the kept closes; candles already plotted keep their earlier size.
bool rebuilt = false
if not na(wantTicks) and (na(engTicks) or wantTicks != engTicks)
rebuilt := true
if na(replayBar) or replayBar != bar_index or replayTicks != wantTicks
Renko replay = Renko.new()
int m = ring.size()
if m > 0
int start = m < KEEP ? 0 : head
for k = 0 to m - 1
replay.feed(ring.get((start + k) % m), wantTicks)
replayBar := bar_index
replayTicks := wantTicks
replayIdx := replay.idx
replayDir := replay.dir
replayCnt := replay.cnt
replayAtr := replay.atr
replayUp := replay.up
replayDn := replay.dn
replayTrend := replay.trend
eng := Renko.new(idx = replayIdx, dir = replayDir, cnt = replayCnt, atr = replayAtr, up = replayUp, dn = replayDn, trend = replayTrend)
engTicks := wantTicks
[closes, openTimes] = request.security_lower_tf(syminfo.tickerid, dataTf, [close, time], ignore_invalid_timeframe = true, calc_bars_count = 100000)
// Open time of the newest 5S bar. On a live candle, only 5S bars that opened before it have closed.
int newestOpen = request.security(syminfo.tickerid, dataTf, time, calc_bars_count = 100)
int buys0 = eng.buys
int sells0 = eng.sells
int n = 0
if tfOk
n := closes.size()
int greens = 0
int reds = 0
if n > 0
for i = 0 to n - 1
float c = closes.get(i)
if not na(c) and (barstate.isconfirmed or openTimes.get(i) < newestOpen)
int t = math.round(c / syminfo.mintick)
if autoMode
if ring.size() < KEEP
ring.push(t)
else
ring.set(head, t)
head := (head + 1) % KEEP
if not na(engTicks)
int made = eng.feed(t, engTicks)
greens += math.max(made, 0)
reds += math.max(-made, 0)
bool buySig = eng.buys > buys0
bool sellSig = eng.sells > sells0
// Candle of the latest brick or size change, where the flip level was last recalculated.
var int brickBar = na
if rebuilt or greens + reds > 0
brickBar := bar_index
float boxPts = engTicks * syminfo.mintick
float brickClose = eng.idx * boxPts
// The next brick closes; a 5S close can't pass them without completing a brick.
float nextUp = brickClose + (eng.dir == -1 ? 2 : 1) * boxPts
float nextDn = brickClose - (eng.dir == 1 ? 2 : 1) * boxPts
color dirColor = eng.dir == 1 ? upColor : eng.dir == -1 ? dnColor : chart.fg_color
plot(brickClose, "Last brick", dirColor, 2, plot.style_stepline, trackprice = true)
plot(boxPts, "Brick size", display = display.data_window)
plotshape(showMarks and greens > 0, "Green brick", shape.triangleup, location.belowbar, upColor, size = size.tiny)
plotshape(showMarks and reds > 0, "Red brick", shape.triangledown, location.abovebar, dnColor, size = size.tiny)
// Supertrend band after the latest brick, with the script's flip circles, Buy/Sell labels and highlighter.
float stUp = showSt and eng.trend == 1 ? eng.up * syminfo.mintick : na
float stDn = showSt and eng.trend == -1 ? eng.dn * syminfo.mintick : na
float buyBand = buySig ? eng.buyAt * syminfo.mintick : na
float sellBand = sellSig ? eng.sellAt * syminfo.mintick : na
float buyY = showSt ? buyBand : na
float sellY = showSt ? sellBand : na
// Far edge of the highlighter. The cloud reaches the next brick level beyond price, or the wick if it pokes past.
// The script fills to each bar's ohlc4, which on a brick without wicks is its middle. Steps keep the edges square.
float hlEdge = switch
not showSt or eng.dir == 0 => float(na)
hlMode == "Cloud to next brick" => eng.trend == 1 ? math.max(nextUp, high) : math.min(nextDn, low)
hlMode == "To candle high/low" => eng.trend == 1 ? math.max(high, stUp) : math.min(low, stDn)
hlMode == "To brick middle" => brickClose - eng.dir * boxPts / 2
=> float(na)
pEdge = plot(hlEdge, "Highlighter edge", color.new(color.gray, 100), style = plot.style_steplinebr, display = display.pane, editable = false)
pUp = plot(stUp, "Supertrend up", upColor, 2, plot.style_steplinebr)
pDn = plot(stDn, "Supertrend down", dnColor, 2, plot.style_steplinebr)
fill(pEdge, pUp, color = color.new(upColor, 90), title = "Uptrend highlighter")
fill(pEdge, pDn, color = color.new(dnColor, 90), title = "Downtrend highlighter")
bgcolor(hlMode == "Background tint" ? (not na(stUp) ? color.new(upColor, 92) : not na(stDn) ? color.new(dnColor, 92) : na) : na, title = "Trend background")
plotshape(buyY, "Uptrend begins", shape.circle, location.absolute, upColor, size = size.tiny)
plotshape(sellY, "Downtrend begins", shape.circle, location.absolute, dnColor, size = size.tiny)
plotshape(stLabels ? buyY : na, "Buy", shape.labelup, location.absolute, upColor, text = "Buy", textcolor = color.white, size = size.tiny)
plotshape(stLabels ? sellY : na, "Sell", shape.labeldown, location.absolute, dnColor, text = "Sell", textcolor = color.white, size = size.tiny)
// Band at this candle's flip, for the alert messages.
plot(buyBand, "Buy band", display = display.none)
plot(sellBand, "Sell band", display = display.none)
// Invisible points at the outer levels so auto-scale includes them.
bool fitNow = fitGrid and barstate.islast and not na(brickClose)
plot(fitNow ? brickClose + gridCount * boxPts : na, "Top level", color.new(color.gray, 100), show_last = 1, display = display.pane, editable = false)
plot(fitNow ? brickClose - gridCount * boxPts : na, "Bottom level", color.new(color.gray, 100), show_last = 1, display = display.pane, editable = false)
// The brick close that flips the Supertrend if price moves straight against the trend from here: replays
// those bricks on a copy (a reversal brick first if the last brick went with the trend).
float flipLevel = na
if barstate.islast and showSt and eng.dir != 0 and not na(eng.trend == 1 ? eng.up : eng.dn)
Renko sim = eng.copy()
int simStep = -eng.trend
int simOpen = sim.dir == eng.trend ? sim.idx + simStep : sim.idx
for i = 1 to MAX_SIM
sim.onBrick(simOpen, simOpen + simStep, engTicks)
simOpen += simStep
if sim.trend != eng.trend
flipLevel := simOpen * boxPts
break
var array<line> grid = array.new<line>()
var line flipLine = na
if barstate.isfirst
for i = 0 to 2 * gridCount
grid.push(line.new(bar_index, float(na), bar_index + 1, float(na), extend = extend.both, color = gridColor, style = line.style_dotted, width = gridWidth))
flipLine := line.new(bar_index, float(na), bar_index + 1, float(na), extend = extend.right, style = line.style_dashed, width = gridWidth)
if barstate.islast and not na(brickClose)
for i = 0 to 2 * gridCount
float y = brickClose + (i - gridCount) * boxPts
line ln = grid.get(i)
ln.set_xy1(math.max(0, bar_index - 1), y)
ln.set_xy2(bar_index, y)
float flipY = stFlip ? flipLevel : na
// A ray from the latest brick's candle; drawings can't start more than 9,999 bars back.
int flipX = math.max(nz(brickBar, bar_index), bar_index - 9999)
flipLine.set_xy1(flipX, flipY)
flipLine.set_xy2(flipX + 1, flipY)
flipLine.set_color(eng.trend == 1 ? dnColor : upColor)
var table tb = table.new(tablePos, 1, 4, bgcolor = color.new(chart.bg_color, 15), frame_color = color.new(chart.fg_color, 80), frame_width = 1)
if showTable and barstate.islast
color fg = chart.fg_color
if not tfOk
tb.cell(0, 0, "Use a standard candle chart above " + dataTf, text_color = dnColor)
else if na(brickClose)
tb.cell(0, 0, autoMode and na(wantTicks) ? "Waiting for the " + atrTf + " ATR" : "No " + dataTf + " data yet", text_color = dnColor)
else
string sizeText = "Renko " + dataTf + " · brick " + fmt(boxPts)
if autoMode
sizeText += " = ATR box " + fmt(atrBox) + " ÷ " + fmt(ratio)
string arrow = eng.dir == 1 ? "▲ " : eng.dir == -1 ? "▼ " : ""
tb.cell(0, 0, sizeText, text_color = fg, text_halign = text.align_left)
tb.cell(0, 1, "Last " + arrow + fmt(brickClose), text_color = dirColor, text_halign = text.align_left)
tb.cell(0, 2, "Next ▲ " + fmt(nextUp) + " ▼ " + fmt(nextDn), text_color = fg, text_halign = text.align_left)
if showSt
float band = eng.trend == 1 ? eng.up : eng.dn
if na(band)
tb.cell(0, 3, "Supertrend: waiting for " + str.tostring(stLen) + " bricks", text_color = fg, text_halign = text.align_left)
else
string stText = "Supertrend " + (eng.trend == 1 ? "▲ " : "▼ ") + str.tostring(band * syminfo.mintick, "#.##")
if not na(flipLevel)
stText += " · flips " + (eng.trend == 1 ? "▼ at " : "▲ at ") + fmt(flipLevel)
tb.cell(0, 3, stText, text_color = eng.trend == 1 ? upColor : dnColor, text_halign = text.align_left)
alertcondition(greens > 0, "Green brick", 'Green Renko brick, last brick {{plot("Last brick")}}')
alertcondition(reds > 0, "Red brick", 'Red Renko brick, last brick {{plot("Last brick")}}')
alertcondition(engTicks != engTicks[1], "Brick size changed", 'Renko brick size is now {{plot("Brick size")}}')
alertcondition(buySig, "SuperTrend Buy", 'Renko Supertrend Buy, band {{plot("Buy band")}}')
alertcondition(sellSig, "SuperTrend Sell", 'Renko Supertrend Sell, band {{plot("Sell band")}}')
alertcondition(buySig or sellSig, "SuperTrend Direction Change", "Renko Supertrend has changed direction")