本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy('Renko Donchian Channel Strategy', overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, max_bars_back = 5000, max_lines_count = 100, max_labels_count = 100, max_boxes_count = 500)
// ==========================================
// 1. User settings
// ==========================================
renko_style = input.string('ATR', title = 'Renko Style', options = ['ATR', 'Traditional'], group = 'Renko Settings')
renko_val = input.int(14, title = 'Renko Box Size / ATR Length', group = 'Renko Settings')
dc_length = input.int(20, title = 'Donchian Channel Length', group = 'Renko Settings')
enable_short = input.bool(false, title = 'Enable Short Trades', group = 'Strategy Options')
// ==========================================
// 2. Renko data ticker and security calls
// ==========================================
// Uses ticker.renko, the TradingView non-standard chart data function
renko_ticker = ticker.renko(syminfo.tickerid, renko_style, renko_val)
// Safely extract the High, Low and Close of the Renko bricks (anti-repainting options applied)
renko_high = request.security(renko_ticker, timeframe.period, high, barmerge.gaps_off, barmerge.lookahead_off)
renko_low = request.security(renko_ticker, timeframe.period, low, barmerge.gaps_off, barmerge.lookahead_off)
renko_close = request.security(renko_ticker, timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
// ==========================================
// 3. Donchian channel calculated on Renko
// ==========================================
upper_band = ta.highest(renko_high, dc_length)
lower_band = ta.lowest(renko_low, dc_length)
basis = math.avg(upper_band, lower_band)
// For checking a channel breakout against the previous brick
prev_upper = upper_band[1]
prev_lower = lower_band[1]
// ==========================================
// 4. Chart visualization
// ==========================================
p_upper = plot(upper_band, title = 'Renko Upper Band', color = color.new(color.blue, 0), linewidth = 2)
p_lower = plot(lower_band, title = 'Renko Lower Band', color = color.new(color.red, 0), linewidth = 2)
p_basis = plot(basis, title = 'Renko Basis', color = color.new(color.orange, 20), linewidth = 2)
fill(p_upper, p_lower, color = color.new(color.blue, 95), title = 'Renko Channel Fill')
// ==========================================
// 5. Trading conditions and order execution
// ==========================================
long_condition = ta.crossover(renko_close, prev_upper)
short_condition = ta.crossunder(renko_close, prev_lower)
if long_condition
strategy.entry('Renko Long', strategy.long)
if short_condition
if enable_short
strategy.entry('Renko Short', strategy.short)
else
strategy.close('Renko Long', comment = 'Exit Long')
// ==========================================
// 6. RC Renko (readCrypto) v2 : Up brick / Down brick / Renko Open / Renko Close
// (Same brick formula as RC Renko v2. Display only, separate from the trading logic.)
// - Up brick = Next up brick (price of the next up brick)
// - Down brick = Next down brick (price of the next down brick)
// - Renko Open = open of the latest brick
// - Renko Close = close of the latest brick
// Calculated once on the last bar; one brick size is used for the whole history.
// ==========================================
RC_SIZE_RC = 'RC median range formula'
RC_SIZE_ATR = 'TradingView ATR (14)'
rcManualSize = input.float(0.0, 'Manual brick size (0 = automatic)', minval = 0.0, group = 'RC Renko', display = display.none)
rcSizeMethod = input.string(RC_SIZE_ATR, 'Brick size method', options = [RC_SIZE_RC, RC_SIZE_ATR], group = 'RC Renko', display = display.none)
rcAtrResizePct = input.float(20.0, 'ATR resize threshold (%)', minval = 0.0, maxval = 500.0, step = 5.0, group = 'RC Renko', display = display.none, tooltip = 'ATR brick size only. The brick size stays fixed until the ATR of a closed bar differs from it by at least this percentage.')
rcShowLines = input.bool(true, 'Show RC Renko lines and price labels', group = 'RC Renko')
rcShowBricks = input.bool(true, 'Show RC Renko bricks (up to the last candle) and next bricks (dashed)', group = 'RC Renko')
rcShowPending = input.bool(true, 'Show the next brick (dashed) where candles pierced a confirmed brick', group = 'RC Renko')
rcBrickTransp = input.int(85, 'Brick transparency', minval = 0, maxval = 100, group = 'RC Renko', display = display.none)
rcShowStatus = input.bool(true, 'Show RC Renko levels in the status line', group = 'RC Renko')
rcUpCol = input.color(color.lime, 'Up brick color', group = 'RC Renko')
rcDnCol = input.color(color.red, 'Down brick color', group = 'RC Renko')
rcCloseCol = input.color(color.orange, 'Renko Close color', group = 'RC Renko')
rcOpenCol = input.color(color.gray, 'Renko Open color', group = 'RC Renko')
RC_DAYS = 1826
RC_BARS = 1826
RC_START = 5
RC_STABLE = 100
DAY_MS = 86400000
bool rcIsDaily1 = timeframe.isdaily and timeframe.multiplier == 1
int rcTfSec = timeframe.in_seconds()
int rcLvlMain = rcTfSec >= 86400 ? 4 : rcTfSec >= 14400 ? 3 : rcTfSec >= 3600 ? 2 : rcTfSec >= 900 ? 1 : 0
int rcLvlFine = rcLvlMain >= 3 ? 2 : rcLvlMain == 2 ? 1 : 0
rcPeriodId(int t, int lvl) =>
int y = year(t, 'UTC')
int m = month(t, 'UTC')
int d = int(math.floor(t / 86400000.0))
int w = int(math.floor((d + 3) / 7.0))
lvl == 4 ? y : lvl == 3 ? y * 4 + int(math.floor((m - 1) / 3.0)) : lvl == 2 ? y * 12 + m : lvl == 1 ? w : d
rcSig2(float x) =>
float p10 = math.pow(10, math.floor(math.log10(x)) - 1)
math.max(syminfo.mintick, math.round_to_mintick(math.round(x / p10) * p10))
// ATR brick size with hysteresis (same as RC Renko v2)
float rcAtr14 = ta.atr(14)
var float rcAtrLocked = na
if barstate.isconfirmed and not na(rcAtr14) and rcAtr14 > 0
if na(rcAtrLocked) or math.abs(rcAtr14 - rcAtrLocked) / rcAtrLocked * 100.0 >= rcAtrResizePct
rcAtrLocked := rcSig2(rcAtr14)
var array<box> rcBoxes = array.new<box>()
var line rcLnUp = na
var line rcLnDn = na
var line rcLnOpen = na
var line rcLnClose = na
var label rcLbUp = na
var label rcLbDn = na
var label rcLbOpen = na
var label rcLbClose = na
var float gRcUp = na
var float gRcDn = na
var float gRcOpen = na
var float gRcClose = na
// A strategy runs on the realtime bar only at its close (calc_on_every_tick = false), so barstate.islast alone
// is never true while the last candle is forming. The last historical bar is used as well.
if (barstate.islast or barstate.islastconfirmedhistory) and chart.is_standard
int maxBack = math.min(bar_index, 4999)
// 1) update day (RC median range formula)
int updAgo = na
int updN = 0
int winOldest = maxBack
if maxBack >= 1
for j = maxBack - 1 to 0 by 1
if rcIsDaily1
int fromT = time[j + 1] - (RC_DAYS - 1) * DAY_MS
while time[winOldest] < fromT
winOldest := winOldest - 1
else
winOldest := math.min(maxBack, j + RC_BARS)
int n = winOldest - j
if n >= RC_START
bool newMain = rcPeriodId(time[j], rcLvlMain) != rcPeriodId(time[j + 1], rcLvlMain)
bool newFine = newMain or rcPeriodId(time[j], rcLvlFine) != rcPeriodId(time[j + 1], rcLvlFine)
if na(updAgo) or newMain or n < RC_STABLE and newFine
updAgo := j
updN := n
// 2) base brick size
float boxSize = na
if not na(updAgo)
array<float> rates = array.new<float>()
for k = updAgo + 1 to updAgo + updN by 1
if k < maxBack
float pc = close[k + 1]
if pc > 0
float tr = math.max(high[k] - low[k], math.max(math.abs(high[k] - pc), math.abs(low[k] - pc)))
array.push(rates, tr / pc)
if array.size(rates) > 0
float raw = array.median(rates) * close[updAgo + 1]
float p10 = math.pow(10, math.floor(math.log10(raw)) - 1)
boxSize := math.max(syminfo.mintick, math.round_to_mintick(math.round(raw / p10) * p10))
if rcSizeMethod == RC_SIZE_ATR and not na(rcAtrLocked)
boxSize := math.max(syminfo.mintick, math.round_to_mintick(rcAtrLocked))
if rcManualSize > 0
boxSize := rcManualSize
// 3) build bricks (only the latest brick is needed)
int totalBricks = 0
float lastOpen = na
float lastClose = na
array<float> bO = array.new<float>()
array<float> bC = array.new<float>()
array<int> bA = array.new<int>()
if not na(boxSize)
float b = boxSize
float eps = b * 1e-9
float g = math.floor(close[maxBack] / b) * b
float lo = g
float hi = g
for j = maxBack to 0 by 1
float c = close[j]
int upCount = int(math.floor((c - hi + eps) / b))
if upCount > 0
for q = 1 to upCount
array.push(bO, hi + (q - 1) * b)
array.push(bC, hi + q * b)
array.push(bA, j)
lastOpen := hi + (upCount - 1) * b
lastClose := hi + upCount * b
lo := lastOpen
hi := lastClose
totalBricks += upCount
else
int downCount = int(math.floor((lo - c + eps) / b))
if downCount > 0
for q = 1 to downCount
array.push(bO, lo - (q - 1) * b)
array.push(bC, lo - q * b)
array.push(bA, j)
lastOpen := lo - (downCount - 1) * b
lastClose := lo - downCount * b
hi := lastOpen
lo := lastClose
totalBricks += downCount
if totalBricks > 0
float rOpen = math.round_to_mintick(lastOpen)
float rClose = math.round_to_mintick(lastClose)
float nextUp = math.round_to_mintick(rClose > rOpen ? rClose + boxSize : rOpen + boxSize)
float nextDn = math.round_to_mintick(rClose > rOpen ? rOpen - boxSize : rClose - boxSize)
gRcUp := nextUp
gRcDn := nextDn
gRcOpen := rOpen
gRcClose := rClose
line.delete(rcLnUp)
line.delete(rcLnDn)
line.delete(rcLnOpen)
line.delete(rcLnClose)
label.delete(rcLbUp)
label.delete(rcLbDn)
label.delete(rcLbOpen)
label.delete(rcLbClose)
// Bricks up to the last candle (solid) + the next up / next down brick in the future (dashed)
if array.size(rcBoxes) > 0
for i = 0 to array.size(rcBoxes) - 1 by 1
box.delete(array.get(rcBoxes, i))
array.clear(rcBoxes)
if rcShowBricks
int nbr = array.size(bO)
int fromI = math.max(0, nbr - 220)
for i = fromI to nbr - 1 by 1
int ago = array.get(bA, i)
float bo = array.get(bO, i)
float bc = array.get(bC, i)
color bcol = bc > bo ? rcUpCol : rcDnCol
int leftX = bar_index - ago
int rightX = i < nbr - 1 ? bar_index - array.get(bA, i + 1) : bar_index + 1
if rightX <= leftX
rightX := leftX + 1
// a brick formed by the bar that is still open is not confirmed yet -> dashed
bool forming = ago == 0 and not barstate.isconfirmed
array.push(rcBoxes, box.new(leftX, math.max(bo, bc), rightX, math.min(bo, bc), xloc = xloc.bar_index, border_color = forming ? color.new(bcol, 40) : bcol, border_width = 1, border_style = forming ? line.style_dashed : line.style_solid, bgcolor = color.new(bcol, forming ? 92 : rcBrickTransp)))
// Pending (not confirmed) next brick: after this brick formed, candles went into the next
// up / next down brick area but did not close a full brick. Drawn dashed, from the first
// candle that entered it until the next brick formed (or the last candle).
if rcShowPending
bool brickUp = bc > bo
float upLow = brickUp ? bc : bo
float dnHigh = brickUp ? bo : bc
int endAgo = i < nbr - 1 ? array.get(bA, i + 1) + 1 : 0
int firstUp = na
int firstDn = na
if ago - 1 >= endAgo
for a = ago - 1 to endAgo by 1
if na(firstUp) and high[a] > upLow
firstUp := a
if na(firstDn) and low[a] < dnHigh
firstDn := a
if not na(firstUp) and not na(firstDn)
break
if not na(firstUp) and array.size(rcBoxes) < 496
array.push(rcBoxes, box.new(bar_index - firstUp, upLow + boxSize, rightX, upLow, xloc = xloc.bar_index, border_color = rcUpCol, border_width = 1, border_style = line.style_dashed, bgcolor = color.new(rcUpCol, 100)))
if not na(firstDn) and array.size(rcBoxes) < 496
array.push(rcBoxes, box.new(bar_index - firstDn, dnHigh, rightX, dnHigh - boxSize, xloc = xloc.bar_index, border_color = rcDnCol, border_width = 1, border_style = line.style_dashed, bgcolor = color.new(rcDnCol, 100)))
// future bricks: only a dashed outline (no fill)
array.push(rcBoxes, box.new(bar_index + 1, nextUp, bar_index + 4, nextUp - boxSize, xloc = xloc.bar_index, border_color = rcUpCol, border_width = 1, border_style = line.style_dashed, bgcolor = color.new(rcUpCol, 100)))
array.push(rcBoxes, box.new(bar_index + 1, nextDn + boxSize, bar_index + 4, nextDn, xloc = xloc.bar_index, border_color = rcDnCol, border_width = 1, border_style = line.style_dashed, bgcolor = color.new(rcDnCol, 100)))
if rcShowLines
rcLnUp := line.new(bar_index - 1, nextUp, bar_index, nextUp, xloc = xloc.bar_index, extend = extend.right, color = rcUpCol, style = line.style_dashed, width = 1)
rcLnDn := line.new(bar_index - 1, nextDn, bar_index, nextDn, xloc = xloc.bar_index, extend = extend.right, color = rcDnCol, style = line.style_dashed, width = 1)
rcLnOpen := line.new(bar_index - 1, rOpen, bar_index, rOpen, xloc = xloc.bar_index, extend = extend.right, color = rcOpenCol, style = line.style_dashed, width = 1)
rcLnClose := line.new(bar_index - 1, rClose, bar_index, rClose, xloc = xloc.bar_index, extend = extend.right, color = rcCloseCol, width = 1)
int xl = bar_index + 5
rcLbUp := label.new(xl, nextUp, str.tostring(nextUp, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(rcUpCol, 0), textcolor = color.black, size = size.small)
rcLbDn := label.new(xl, nextDn, str.tostring(nextDn, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(rcDnCol, 0), textcolor = color.white, size = size.small)
rcLbOpen := label.new(xl, rOpen, str.tostring(rOpen, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(rcOpenCol, 0), textcolor = color.white, size = size.small)
rcLbClose := label.new(xl, rClose, str.tostring(rClose, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(rcCloseCol, 0), textcolor = color.white, size = size.small)
// Status line / Data Window (latest bar only)
plot(rcShowStatus ? gRcUp : na, 'Up brick', color = rcUpCol, display = display.status_line + display.data_window, editable = false)
plot(rcShowStatus ? gRcDn : na, 'Down brick', color = rcDnCol, display = display.status_line + display.data_window, editable = false)
plot(rcShowStatus ? gRcOpen : na, 'Renko Open', color = rcOpenCol, display = display.status_line + display.data_window, editable = false)
plot(rcShowStatus ? gRcClose : na, 'Renko Close', color = rcCloseCol, display = display.status_line + display.data_window, editable = false)