Darvas Box [OrbitOne]

orbitonetv · study · 159 行 · 点赞 43 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © orbitonetv
//@version=6
indicator("Darvas Box [OrbitOne]", "Darvas Box [OrbitOne]", overlay = true, max_labels_count = 500)
 
// ════════ LANGUAGE ════════
lang = input.string("English", "Chart language", options = ["English", "Türkçe", "Español", "Português", "Deutsch", "Français", "Русский", "中文"], tooltip = "Language of the signal labels, dashboard and alert() messages on the chart.")
 
// ════════ BOX ════════
gB     = "Darvas box"
boxLen = input.int(5, "Box length", minval = 3, maxval = 50, group = gB, tooltip = "A box top is confirmed when a new high is not exceeded for (length - 2) bars. The bottom is the lowest low of the last (length) bars. 5 is the classic value.")
minH   = input.float(0.0, "Min box height % for signals", minval = 0, step = 0.1, group = gB, tooltip = "0 = off. Ignores breakouts from very narrow boxes.")
 
// ════════ SIGNALS ════════
gS       = "Signals"
confirm  = input.bool(true, "Wait for bar close", group = gS, tooltip = "Breakouts are confirmed on closed bars only and never repaint.")
side     = input.string("Both", "Direction", options = ["Both", "Breakouts only (up)", "Breakdowns only (down)"], group = gS)
useVol   = input.bool(false, "Volume confirmation, x average", inline = "v", group = gS)
volMult  = input.float(1.5, "", minval = 0.1, step = 0.1, inline = "v", group = gS, tooltip = "Breakout bar volume must be above its 20-bar average x this value.")
useTrend = input.bool(false, "Trend EMA filter", inline = "t", group = gS)
trendLen = input.int(200, "", minval = 2, inline = "t", group = gS, tooltip = "Up breakouts only above this EMA, down breakouts only below it.")
 
// ════════ DISPLAY ════════
gV      = "Display"
showBox = input.bool(true, "Show boxes", group = gV)
topCol  = input.color(#2962FF, "Top", inline = "c", group = gV)
botCol  = input.color(#2962FF, "Bottom", inline = "c", group = gV)
showFil = input.bool(true, "Fill colored by price position", group = gV, tooltip = "Blue = price inside the box, green = above the box, red = below the box.")
boxTr   = input.int(88, "Fill transparency", minval = 50, maxval = 98, group = gV)
bullCol = input.color(#089981, "Bullish", inline = "b", group = gV)
bearCol = input.color(#F23645, "Bearish", inline = "b", group = gV)
sigSty  = input.string("Labels", "Signal style", options = ["Labels", "Arrows", "None"], group = gV)
barCol  = input.bool(false, "Color bars by position", group = gV)
showTrM = input.bool(false, "Show trend EMA", group = gV)
showDb  = input.bool(true, "Show dashboard", group = gV)
dbPos   = input.string("Bottom right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gV)
dbSize  = input.string("Tiny", "Dashboard size", options = ["Tiny", "Small", "Normal"], group = gV)
 
// ════════ TRANSLATIONS ════════
t(string en, string tr, string es, string pt, string de, string fr, string ru, string zh) =>
    switch lang
        "Türkçe"    => tr
        "Español"   => es
        "Português" => pt
        "Deutsch"   => de
        "Français"  => fr
        "Русский"   => ru
        "中文"       => zh
        => en
 
txtBrkUp = t("BREAKOUT", "YUKARI KIRILIM", "RUPTURA ALCISTA", "ROMPIMENTO ALTA", "AUSBRUCH ↑", "CASSURE HAUSSIÈRE", "ПРОБОЙ ВВЕРХ", "向上突破")
txtBrkDn = t("BREAKDOWN", "AŞAĞI KIRILIM", "RUPTURA BAJISTA", "ROMPIMENTO BAIXA", "AUSBRUCH ↓", "CASSURE BAISSIÈRE", "ПРОБОЙ ВНИЗ", "向下突破")
txtPrice = t("Price", "Fiyat", "Precio", "Preço", "Preis", "Prix", "Цена", "价格")
txtIn    = t("Inside box", "Kutu içinde", "Dentro de la caja", "Dentro da caixa", "In der Box", "Dans la boîte", "Внутри бокса", "箱体内")
txtAbove = t("▲ Above box", "▲ Kutunun üstünde", "▲ Sobre la caja", "▲ Acima da caixa", "▲ Über der Box", "▲ Au-dessus", "▲ Выше бокса", "▲ 箱体上方")
txtBelow = t("▼ Below box", "▼ Kutunun altında", "▼ Bajo la caja", "▼ Abaixo da caixa", "▼ Unter der Box", "▼ En dessous", "▼ Ниже бокса", "▼ 箱体下方")
txtTop   = t("Box top", "Kutu üstü", "Techo", "Topo", "Box-Hoch", "Haut", "Верх", "箱顶")
txtBot   = t("Box bottom", "Kutu altı", "Suelo", "Fundo", "Box-Tief", "Bas", "Низ", "箱底")
txtH     = t("Box height", "Kutu yüksekliği", "Altura", "Altura", "Höhe", "Hauteur", "Высота", "箱高")
txtLast  = t("Last breakout", "Son kırılım", "Última ruptura", "Último rompimento", "Letzter Ausbruch", "Dernière cassure", "Последний пробой", "最近突破")
txtUp    = t("▲ Up", "▲ Yukarı", "▲ Alcista", "▲ Alta", "▲ Aufwärts", "▲ Haussière", "▲ Вверх", "▲ 向上")
txtDn    = t("▼ Down", "▼ Aşağı", "▼ Bajista", "▼ Baixa", "▼ Abwärts", "▼ Baissière", "▼ Вниз", "▼ 向下")
txtAgo   = t("Bars ago", "Kaç mum önce", "Velas atrás", "Velas atrás", "Kerzen her", "Bougies depuis", "Свечей назад", "K线前")
txtCnt   = t("Boxes found", "Bulunan kutu", "Cajas", "Caixas", "Boxen", "Boîtes", "Боксов", "箱体数量")
 
// ════════ DARVAS CALCULATION ════════
LL      = ta.lowest(low, boxLen)
k1      = ta.highest(high, boxLen)
k2      = ta.highest(high, boxLen - 1)
k3      = ta.highest(high, boxLen - 2)
newHigh = high > k1[1]
NH      = ta.valuewhen(newHigh, high, 0)
formed  = ta.barssince(newHigh) == boxLen - 2 and k3 < k2
top     = ta.valuewhen(formed, NH, 0)
bot     = ta.valuewhen(formed, LL, 0)
heightP = na(bot) or bot == 0 ? na : (top - bot) / bot * 100
 
trendMA = ta.ema(close, trendLen)
volAvg  = ta.sma(volume, 20)
okBar   = not confirm or barstate.isconfirmed
 
var bool  upDone  = true
var bool  dnDone  = true
var int   nBoxes  = 0
var int   lastDir = 0
var int   lastBar = na
 
if formed
    upDone := false
    dnDone := false
    nBoxes += 1
 
rawUp = not upDone and not na(top) and close > top and okBar
rawDn = not dnDone and not na(bot) and close < bot and okBar
if rawUp
    upDone := true
if rawDn
    dnDone := true
 
filtOk  = (minH == 0 or heightP >= minH) and (not useVol or volume > volAvg * volMult)
bullBrk = rawUp and filtOk and side != "Breakdowns only (down)" and (not useTrend or close > trendMA)
bearBrk = rawDn and filtOk and side != "Breakouts only (up)" and (not useTrend or close < trendMA)
 
if bullBrk or bearBrk
    lastDir := bullBrk ? 1 : -1
    lastBar := bar_index
 
// ════════ PLOTS ════════
pos     = na(top) ? 0 : close > top ? 1 : close < bot ? -1 : 0
newBox  = top != top[1] or bot != bot[1]
pT = plot(showBox and not newBox ? top : na, "Box top", color = topCol, linewidth = 2, style = plot.style_linebr, display = display.all - display.status_line)
pB = plot(showBox and not newBox ? bot : na, "Box bottom", color = botCol, linewidth = 2, style = plot.style_linebr, display = display.all - display.status_line)
fill(pT, pB, color = showBox and showFil ? color.new(pos == 1 ? bullCol : pos == -1 ? bearCol : topCol, boxTr) : na, title = "Box fill")
plot(showTrM ? trendMA : na, "Trend EMA", color = color.new(color.gray, 20), linewidth = 1, display = display.all - display.status_line)
 
barcolor(barCol ? (pos == 1 ? bullCol : pos == -1 ? bearCol : na) : na)
 
plotshape(sigSty == "Arrows" and bullBrk, "Breakout arrow", shape.triangleup, location.belowbar, bullCol, size = size.small, display = display.all - display.status_line)
plotshape(sigSty == "Arrows" and bearBrk, "Breakdown arrow", shape.triangledown, location.abovebar, bearCol, size = size.small, display = display.all - display.status_line)
 
if sigSty == "Labels" and bullBrk
    label.new(bar_index, low, txtBrkUp, yloc = yloc.belowbar, style = label.style_label_up, color = bullCol, textcolor = color.white, size = size.small)
if sigSty == "Labels" and bearBrk
    label.new(bar_index, high, txtBrkDn, yloc = yloc.abovebar, style = label.style_label_down, color = bearCol, textcolor = color.white, size = size.small)
 
// ════════ DASHBOARD ════════
var table db = table.new(dbPos == "Top right" ? position.top_right : dbPos == "Bottom right" ? position.bottom_right : dbPos == "Top left" ? position.top_left : position.bottom_left, 2, 8, border_width = 1)
tSize = dbSize == "Tiny" ? size.tiny : dbSize == "Normal" ? size.normal : size.small
 
f_row(int r, string k, string v, color c) =>
    table.cell(db, 0, r, k, bgcolor = color.new(color.gray, 35), text_color = color.white, text_size = tSize)
    table.cell(db, 1, r, v, bgcolor = c, text_color = color.white, text_size = tSize)
 
if showDb and barstate.isfirst
    table.merge_cells(db, 0, 0, 1, 0)
 
if showDb and barstate.islast
    color nc = color.new(color.gray, 20)
    table.cell(db, 0, 0, "Darvas Box · " + str.tostring(boxLen) + " · OrbitOne", bgcolor = color.new(color.black, 30), text_color = color.white, text_size = tSize)
    f_row(1, txtPrice, pos == 1 ? txtAbove : pos == -1 ? txtBelow : txtIn, pos == 1 ? bullCol : pos == -1 ? bearCol : color.new(topCol, 30))
    f_row(2, txtTop, na(top) ? "—" : str.tostring(top, format.mintick), nc)
    f_row(3, txtBot, na(bot) ? "—" : str.tostring(bot, format.mintick), nc)
    f_row(4, txtH, na(heightP) ? "—" : str.tostring(heightP, "0.00") + "%", nc)
    f_row(5, txtLast, lastDir == 1 ? txtUp : lastDir == -1 ? txtDn : "—", lastDir == 1 ? bullCol : lastDir == -1 ? bearCol : color.gray)
    f_row(6, txtAgo, na(lastBar) ? "—" : str.tostring(bar_index - lastBar), nc)
    f_row(7, txtCnt, str.tostring(nBoxes), nc)
 
// ════════ ALERTS ════════
alertcondition(bullBrk, "Breakout up", "Darvas breakout UP | {{ticker}} | {{interval}} | {{close}}")
alertcondition(bearBrk, "Breakdown", "Darvas breakdown DOWN | {{ticker}} | {{interval}} | {{close}}")
alertcondition(bullBrk or bearBrk, "Any breakout", "Darvas breakout | {{ticker}} | {{interval}} | {{close}}")
alertcondition(formed and not formed[1], "New box formed", "New Darvas box formed | {{ticker}} | {{interval}} | {{close}}")
 
// alert() messages follow the chart language. Create the alert with "Any alert() function call".
freq = confirm ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
if bullBrk
    alert("Darvas " + txtBrkUp + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)
if bearBrk
    alert("Darvas " + txtBrkDn + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)

← 返回列表