Day Trade Setup - Multi Timeframe Candles

daytradesetupx · study · 347 行 · 点赞 26 · TradingView 原页

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

Pine Script

//@version=6
indicator("Day Trade Setup - Multi Timeframe Candles", shorttitle = "DTS • MTF", overlay = true, max_bars_back = 1000, max_boxes_count = 150, max_lines_count = 150, max_labels_count = 150, dynamic_requests = true)
 
// A visual dashboard, not a strategy. X positions are layout positions, not timestamps.
// Use a standard time-based chart. Panel timeframes may be below, equal to,
// or above the chart timeframe.
// Based on the user-supplied BeSight Multi Candle With PA source.
// Day Trade Setup visual edition. Pattern rules and timeframe snapshots retained.
// Live candles can change. This is a visual tool, not an entry/exit system.
string G_BRAND = "00 · Day Trade Setup"
bool showDashboard = input.bool(true, "Show MTF summary", group = G_BRAND)
string dashboardCorner = input.string("Top right", "Summary position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G_BRAND)
bool tintChartCandles = input.bool(false, "Apply DTS colors to chart candles", group = G_BRAND)
bool midnightBackground = input.bool(false, "Midnight chart background", tooltip = "Optional navy background matching the Day Trade Setup reference charts.", group = G_BRAND)
 
string G_TF = "01 · Timeframes"
bool enabled1 = input.bool(true, "Panel 1", inline = "tf1", group = G_TF)
string tf1 = input.timeframe("5", "", inline = "tf1", group = G_TF)
bool enabled2 = input.bool(true, "Panel 2", inline = "tf2", group = G_TF)
string tf2 = input.timeframe("15", "", inline = "tf2", group = G_TF)
bool enabled3 = input.bool(true, "Panel 3", inline = "tf3", group = G_TF)
string tf3 = input.timeframe("30", "", inline = "tf3", group = G_TF)
int candleCount = input.int(10, "Candles per panel", minval = 3, maxval = 30, group = G_TF)
 
string G_LAYOUT = "02 · Layout"
int candleStep = input.int(4, "Candle spacing (chart bars)", minval = 3, maxval = 8, group = G_LAYOUT)
int panelGap = input.int(8, "Panel gap (chart bars)", minval = 4, maxval = 30, group = G_LAYOUT)
int quoteSpace = input.int(12, "Price label space (chart bars)", minval = 8, maxval = 16, tooltip = "Reserves space to the right of each candle group for its latest-price label. Increase this or zoom in if price text overlaps the next group.", group = G_LAYOUT)
int rightOffset = input.int(10, "Distance from latest bar (chart bars)", minval = 3, maxval = 100, tooltip = "Places the first panel to the right of the latest chart bar. Candle spacing is reduced automatically if needed to stay within TradingView's 500-bar drawing limit.", group = G_LAYOUT)
bool showPrice = input.bool(true, "Show latest price", group = G_LAYOUT)
bool showTimer = input.bool(true, "Show countdown", group = G_LAYOUT)
bool showRange = input.bool(false, "Show panel high / low", group = G_LAYOUT)
bool highlightLatest = input.bool(true, "Accent latest candle", group = G_LAYOUT)
bool alignHeaders = input.bool(true, "Align panel headers", group = G_LAYOUT)
bool showHeaderDivider = input.bool(true, "Thin header divider", group = G_LAYOUT)
float headerRowSpacing = input.float(1.2, "Header row spacing", minval = 0.5, maxval = 2.5, step = 0.1, tooltip = "Distance from each header row to the divider, relative to the displayed price range. Increase if text touches the divider when zoomed out.", group = G_LAYOUT)
bool showPanelFill = input.bool(false, "Subtle panel background", group = G_LAYOUT)
string panelTextSize = input.string("Small", "Panel text size", options = ["Tiny", "Small", "Normal"], group = G_LAYOUT)
string labelSize = panelTextSize == "Tiny" ? size.tiny : panelTextSize == "Normal" ? size.normal : size.small
 
string G_PA = "03 · Price Action"
bool showPA = input.bool(true, "Show PA labels", group = G_PA)
bool livePA = input.bool(false, "Include unclosed candle (marked *)", tooltip = "An unclosed candle can change pattern before it closes.", group = G_PA)
bool useEngulf = input.bool(true, "Engulfing", group = G_PA)
bool usePin = input.bool(true, "Pin Bar", group = G_PA)
bool useInside = input.bool(true, "Inside Bar", group = G_PA)
bool useOutside = input.bool(true, "Outside Bar", group = G_PA)
bool useDoji = input.bool(true, "Doji", group = G_PA)
float pinRatio = input.float(2.0, "Pin: minimum long wick / body", minval = 1.5, maxval = 5.0, step = 0.1, group = G_PA)
float dojiRatio = input.float(0.10, "Doji: maximum body / range", minval = 0.01, maxval = 0.30, step = 0.01, group = G_PA)
 
// Palette sampled by visual matching to the supplied Day Trade Setup reference.
string G_COLOR = "04 · DTS Palette"
color bullBody = input.color(#00D4FF, "Bullish candle / Cyan", group = G_COLOR)
color bearBody = input.color(#D82BFF, "Bearish candle / Magenta", group = G_COLOR)
bool directionalWicks = input.bool(true, "Match wicks to candle direction", group = G_COLOR)
color candleOutline = input.color(#7A88AC, "Neutral wicks / borders", group = G_COLOR)
bool autoTextColor = input.bool(true, "Match overlay text to chart theme", group = G_COLOR)
color customTextColor = input.color(#DCE5FA, "Custom overlay text", group = G_COLOR)
color textColor = autoTextColor ? chart.fg_color : customTextColor
color bullPAColor = input.color(#00D4FF, "Bullish PA", group = G_COLOR)
color bearPAColor = input.color(#D82BFF, "Bearish PA", group = G_COLOR)
color accent1 = input.color(#00D4FF, "Panel 1 / Cyan", group = G_COLOR)
color accent2 = input.color(#5368FF, "Panel 2 / Electric blue", group = G_COLOR)
color accent3 = input.color(#D82BFF, "Panel 3 / Magenta", group = G_COLOR)
color midnight = input.color(#050A1F, "Midnight background", group = G_COLOR)
color dashboardInk = #E7ECFA
color mutedInk = #94A3C5
string dashboardPosition = dashboardCorner == "Top left" ? position.top_left : dashboardCorner == "Bottom left" ? position.bottom_left : dashboardCorner == "Bottom right" ? position.bottom_right : position.top_right
var table dashboard = table.new(dashboardPosition, 3, 7, bgcolor = midnight, frame_color = #253354, frame_width = 1, border_width = 0)
 
// Opt-in global chart styling. Overlay panels always use real OHLC prices.
barcolor(tintChartCandles ? (close >= open ? bullBody : bearBody) : na)
bgcolor(midnightBackground ? midnight : na)
 
type Candle
    float o
    float h
    float l
    float c
    int openedAt
    int closesAt
    string pattern
    int bias
 
var array<box> bodies = array.new<box>()
var array<line> strokes = array.new<line>()
var array<label> captions = array.new<label>()
 
// One label per candle, in priority order: engulfing, pin, inside, outside, doji.
// Pin direction describes wick rejection; it does not require a matching body color.
f_pattern(float o, float h, float l, float c, float po, float ph, float pl, float pc) =>
    float body = math.abs(c - o)
    float span = h - l
    float upper = h - math.max(o, c)
    float lower = math.min(o, c) - l
    bool previousValid = not na(po) and not na(ph) and not na(pl) and not na(pc)
    bool bullEngulf = previousValid and c > o and pc < po and o <= pc and c >= po and body > math.abs(pc - po)
    bool bearEngulf = previousValid and c < o and pc > po and o >= pc and c <= po and body > math.abs(pc - po)
    bool pinBody = span > 0 and body >= syminfo.mintick and body <= span * 0.35
    bool bullPin = pinBody and lower >= body * pinRatio and upper <= body and c >= l + span * 0.65
    bool bearPin = pinBody and upper >= body * pinRatio and lower <= body and c <= l + span * 0.35
    bool inside = previousValid and h < ph and l > pl
    bool outside = previousValid and h > ph and l < pl
    string name = ""
    int bias = 0
    if span > 0
        if useEngulf and bullEngulf
            name := "ENG+"
            bias := 1
        else if useEngulf and bearEngulf
            name := "ENG−"
            bias := -1
        else if usePin and bullPin
            name := "PIN+"
            bias := 1
        else if usePin and bearPin
            name := "PIN−"
            bias := -1
        else if useInside and inside
            name := "IB"
        else if useOutside and outside
            name := "OB"
        else if useDoji and body <= span * dojiRatio
            name := "DOJI"
    [name, bias]
 
// All history indexing happens INSIDE the requested timeframe. This avoids
// repeating one HTF candle once for every chart bar inside that candle.
// For LTF panels, request.security selects the last available intrabar's result.
// That result is already a complete N-candle snapshot from the panel timeframe,
// including candles before the current chart bar. Do not build this history by
// indexing the returned series in the chart context: that would skip LTF candles.
f_snapshot() =>
    array<Candle> result = array.new<Candle>()
    for i = 0 to candleCount - 1
        if not na(open[i]) and not na(high[i]) and not na(low[i]) and not na(close[i])
            [pattern, bias] = f_pattern(open[i], high[i], low[i], close[i], open[i + 1], high[i + 1], low[i + 1], close[i + 1])
            result.push(Candle.new(open[i], high[i], low[i], close[i], time[i], time_close[i], pattern, bias))
    result
 
f_bounds(array<Candle> data) =>
    float bottom = na
    float top = na
    if not na(data)
        for item in data
            bottom := na(bottom) ? item.l : math.min(bottom, item.l)
            top := na(top) ? item.h : math.max(top, item.h)
    [bottom, top]
 
f_min(float a, float b) =>
    na(a) ? b : na(b) ? a : math.min(a, b)
 
f_max(float a, float b) =>
    na(a) ? b : na(b) ? a : math.max(a, b)
 
f_caption(int x, float y, string txt, color ink, string fontSize, string tip) =>
    label item = label.new(x, y, txt, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_none, color = na, textcolor = ink, size = fontSize, tooltip = tip)
    captions.push(item)
    item
 
// Transparent, left-anchored text: the label extends right from its x coordinate.
f_left_caption(int x, float y, string txt, color ink, string fontSize, string tip) =>
    label item = label.new(x, y, txt, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = na, textcolor = ink, textalign = text.align_left, size = fontSize, tooltip = tip)
    captions.push(item)
    item
 
f_timeframe_name(string tf) =>
    float minutes = str.tonumber(tf)
    string result = tf
    if not na(minutes)
        result := minutes >= 60 and minutes % 60 == 0 ? str.tostring(minutes / 60, "#") + " H" : str.tostring(minutes, "#") + " MIN"
    result
 
f_countdown(int closesAt) =>
    int remaining = int(math.max(0, math.ceil((closesAt - timenow) / 1000.0)))
    int days = int(remaining / 86400)
    int hours = int(remaining % 86400 / 3600)
    int minutes = int(remaining % 3600 / 60)
    int seconds = remaining % 60
    string clockText = str.tostring(minutes, "00") + ":" + str.tostring(seconds, "00")
    if hours > 0 or days > 0
        clockText := str.tostring(hours, "00") + ":" + clockText
    if days > 0
        clockText := str.tostring(days) + "d " + clockText
    clockText
 
f_clear() =>
    while bodies.size() > 0
        box.delete(bodies.pop())
    while strokes.size() > 0
        line.delete(strokes.pop())
    while captions.size() > 0
        label.delete(captions.pop())
 
// Two transparent text rows with a one-pixel rule between them. No header box.
f_header(int left, int right, float y, float padding, string heading, string status, color accent, string tip) =>
    if showHeaderDivider
        strokes.push(line.new(left, y, right, y, color = color.new(accent, 55), width = 1))
    f_left_caption(left, y + padding * headerRowSpacing, heading, accent, labelSize, tip)
    f_left_caption(left, y - padding * headerRowSpacing, status, color.new(accent, 15), size.tiny, tip)
 
f_draw(array<Candle> data, string tf, color accent, int left, int spacing, float sharedBottom, float sharedTop) =>
    int width = (candleCount - 1) * spacing + 2
    int center = left + int(width / 2)
    [localBottom, localTop] = f_bounds(data)
    float bottom = na(localBottom) ? close : localBottom
    float top = na(localTop) ? close : localTop
    float sharedSpan = na(sharedTop) or na(sharedBottom) ? syminfo.mintick : sharedTop - sharedBottom
    float padding = math.max(sharedSpan * 0.05, syminfo.mintick * 3)
    float headerY = (alignHeaders and not na(sharedTop) ? sharedTop : top) + padding * 5
    string heading = "DTS  /  " + f_timeframe_name(tf)
    int panelRight = left + width + quoteSpace - 1
    float panelBottom = (alignHeaders and not na(sharedBottom) ? sharedBottom : bottom) - padding * 4
    // Optional fill belongs to the candle area, leaving the header frameless.
    if showPanelFill
        bodies.push(box.new(left - 2, top + padding * 2, panelRight, panelBottom, border_color = color.new(accent, 88), bgcolor = color.new(midnight, 15)))
    if na(data)
        f_header(left, panelRight, headerY, padding, heading, "NO DATA", accent, "Symbol: " + syminfo.ticker + "\nTimeframe: " + tf)
        f_caption(center, (top + bottom) / 2, "NO DATA", textColor, size.small, "No candles were returned for this timeframe.")
    else if data.size() == 0
        f_header(left, panelRight, headerY, padding, heading, "NO DATA", accent, "Symbol: " + syminfo.ticker + "\nTimeframe: " + tf)
        f_caption(center, (top + bottom) / 2, "NO DATA", textColor, size.small, "No candles were returned for this timeframe.")
    else
        Candle latest = data.get(0)
        int referenceTime = barstate.isrealtime ? timenow : time_close
        bool isLive = barstate.isrealtime and not na(latest.closesAt) and latest.closesAt > timenow
        string stateText = isLive ? "LIVE" : (barstate.isrealtime or timenow >= latest.closesAt ? "CLOSED" : "HISTORY")
        string timer = isLive and showTimer ? " · " + f_countdown(latest.closesAt) : ""
        string statusText = stateText + timer + " · " + str.tostring(data.size()) + " bars"
        f_header(left, panelRight, headerY, padding, heading, statusText, accent, "Symbol: " + syminfo.ticker + "\nCountdown updates when the chart receives a price update.\nHistorical / Replay HTF candles become available at their close.")
        for i = 0 to data.size() - 1
            Candle item = data.get(i)
            int x = left + (candleCount - 1 - i) * spacing + 1
            // Use actual OHLC prices so all panels align with the main chart's scale.
            float yOpen = item.o
            float yClose = item.c
            float yHigh = item.h
            float yLow = item.l
            float bodyTop = math.max(yOpen, yClose)
            float bodyBottom = math.min(yOpen, yClose)
            color fill = item.c >= item.o ? bullBody : bearBody
            color outline = directionalWicks ? fill : candleOutline
            outline := i == 0 and highlightLatest ? accent : outline
            if i == 0 and highlightLatest
                bodies.push(box.new(x - 1, yHigh, x + 1, yLow, border_color = na, bgcolor = color.new(fill, 90)))
            strokes.push(line.new(x, yHigh, x, yLow, color = outline))
            // An exact doji has a zero-height body with a horizontal border.
            bodies.push(box.new(x - 1, bodyTop, x + 1, bodyBottom, border_color = outline, border_width = i == 0 and highlightLatest ? 2 : 1, bgcolor = fill))
            bool confirmed = not na(item.closesAt) and not na(referenceTime) and item.closesAt <= referenceTime
            if showPA and item.pattern != "" and (confirmed or livePA)
                color ink = item.bias > 0 ? bullPAColor : item.bias < 0 ? bearPAColor : textColor
                string mark = item.pattern + (confirmed ? "" : "*")
                float labelY = item.bias < 0 ? yHigh + padding : yLow - padding
                string tip = item.pattern + (confirmed ? " · Closed candle" : " · Provisional") + "\n" + str.format_time(item.openedAt, "yyyy-MM-dd HH:mm", syminfo.timezone) + " (" + syminfo.timezone + ")\nO " + str.tostring(item.o, format.mintick) + "  H " + str.tostring(item.h, format.mintick) + "\nL " + str.tostring(item.l, format.mintick) + "  C " + str.tostring(item.c, format.mintick)
                f_caption(x, labelY, mark, ink, size.tiny, tip)
        if showPrice
            int lastX = left + width - 1
            strokes.push(line.new(lastX + 1, latest.c, lastX + 4, latest.c, color = accent, style = line.style_dotted))
            f_left_caption(lastX + 4, latest.c, str.tostring(latest.c, format.mintick), accent, labelSize, "Latest price · " + f_timeframe_name(tf) + "\nThe dotted connector is at the actual close price; live while its candle is open.")
        if showRange
            f_left_caption(left, bottom - padding * 3, "RANGE  " + str.tostring(localBottom, format.mintick) + " — " + str.tostring(localTop, format.mintick), color.new(textColor, 25), size.tiny, "Low / high of the displayed candles.")
 
// The summary uses the latest CLOSED candle in each available snapshot.
// Candle direction and PA bias are distinct: a bullish body may have a bearish pin.
f_summary_row(array<Candle> data, string tf, int row, color accent, bool enabled) =>
    string direction = enabled ? "NO DATA" : "OFF"
    string pa = "—"
    color directionInk = mutedInk
    color paInk = mutedInk
    int referenceTime = barstate.isrealtime ? timenow : time_close
    string tip = "Latest available closed candle. Body direction is not a trend signal."
    if enabled and not na(data)
        for item in data
            if not na(item.closesAt) and not na(referenceTime) and item.closesAt <= referenceTime
                direction := item.c > item.o ? "BULL" : item.c < item.o ? "BEAR" : "FLAT"
                directionInk := item.c > item.o ? bullBody : item.c < item.o ? bearBody : mutedInk
                pa := item.pattern == "" ? "—" : item.pattern
                paInk := item.bias > 0 ? bullPAColor : item.bias < 0 ? bearPAColor : dashboardInk
                tip := "Closed candle · " + str.format_time(item.openedAt, "yyyy-MM-dd HH:mm", syminfo.timezone) + " (" + syminfo.timezone + ")\nO " + str.tostring(item.o, format.mintick) + "  C " + str.tostring(item.c, format.mintick)
                break
    table.cell(dashboard, 0, row, f_timeframe_name(tf), text_color = enabled ? accent : mutedInk, text_size = labelSize, text_halign = text.align_left, bgcolor = color.new(accent, 92))
    table.cell(dashboard, 1, row, direction, text_color = directionInk, text_size = labelSize, tooltip = tip)
    table.cell(dashboard, 2, row, pa, text_color = paInk, text_size = labelSize, tooltip = tip)
 
f_dashboard(array<Candle> data1, array<Candle> data2, array<Candle> data3) =>
    if showDashboard
        table.cell(dashboard, 0, 0, "DAY TRADE SETUP", text_color = #00D4FF, bgcolor = #101A36, text_size = labelSize, text_halign = text.align_left)
        table.cell(dashboard, 0, 1, "MULTI TIMEFRAME CANDLES  /  " + syminfo.ticker, text_color = dashboardInk, text_size = size.tiny, text_halign = text.align_left)
        table.cell(dashboard, 0, 2, "TIMEFRAME", text_color = mutedInk, text_size = size.tiny)
        table.cell(dashboard, 1, 2, "CLOSED BODY", text_color = mutedInk, text_size = size.tiny)
        table.cell(dashboard, 2, 2, "PA", text_color = mutedInk, text_size = size.tiny)
        f_summary_row(data1, tf1, 3, accent1, enabled1)
        f_summary_row(data2, tf2, 4, accent2, enabled2)
        f_summary_row(data3, tf3, 5, accent3, enabled3)
        table.cell(dashboard, 0, 6, "daytradesetup.com  ·  * = provisional PA", text_color = mutedInk, text_size = size.tiny, text_halign = text.align_left)
    else
        table.clear(dashboard, 0, 0, 2, 6)
 
if barstate.isfirst
    table.merge_cells(dashboard, 0, 0, 2, 0)
    table.merge_cells(dashboard, 0, 1, 2, 1)
    table.merge_cells(dashboard, 0, 6, 2, 6)
    if not enabled1 and not enabled2 and not enabled3
        runtime.error("Enable at least one timeframe panel.")
    if not chart.is_standard
        runtime.error("Use a standard time-based Candles or Bars chart (not Heikin Ashi, Renko, Range, etc.).")
 
// Prewarm the SAME request contexts on the last confirmed historical bar before
// realtime begins. Only the dashboard's last bars receive collection snapshots.
// This avoids copying arrays into the main context over the entire chart history.
// lookahead_off selects the last intrabar snapshot on historical LTF requests;
// realtime requests return the latest available snapshot. Only the latest panel
// state is needed, so we intentionally do not collect every intrabar snapshot.
if barstate.islastconfirmedhistory or barstate.islast
    array<Candle> data1 = na
    array<Candle> data2 = na
    array<Candle> data3 = na
    if enabled1
        data1 := request.security(syminfo.tickerid, tf1, f_snapshot(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 80)
    if enabled2
        data2 := request.security(syminfo.tickerid, tf2, f_snapshot(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 80)
    if enabled3
        data3 := request.security(syminfo.tickerid, tf3, f_snapshot(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 80)
    if barstate.islast
        f_clear()
        f_dashboard(data1, data2, data3)
        [low1, high1] = f_bounds(data1)
        [low2, high2] = f_bounds(data2)
        [low3, high3] = f_bounds(data3)
        float sharedBottom = f_min(f_min(low1, low2), low3)
        float sharedTop = f_max(f_max(high1, high2), high3)
        int panels = (enabled1 ? 1 : 0) + (enabled2 ? 1 : 0) + (enabled3 ? 1 : 0)
        // Reserve a quote column per group, including the final group. Even at
        // maximum inputs, spacing remains >= 3 and all drawing anchors <= +500.
        int maxSpacing = int((499 - rightOffset - (panels - 1) * panelGap - panels * (2 + quoteSpace)) / (panels * (candleCount - 1)))
        int spacing = math.min(candleStep, maxSpacing)
        int panelWidth = (candleCount - 1) * spacing + 2 + quoteSpace
        int left = bar_index + rightOffset
        if enabled1
            f_draw(data1, tf1, accent1, left, spacing, sharedBottom, sharedTop)
            left += panelWidth + panelGap
        if enabled2
            f_draw(data2, tf2, accent2, left, spacing, sharedBottom, sharedTop)
            left += panelWidth + panelGap
        if enabled3
            f_draw(data3, tf3, accent3, left, spacing, sharedBottom, sharedTop)

← 返回列表