Macro Candles+ (M1D)

mayb1dayy · study · 295 行 · 点赞 66 · TradingView 原页

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

Pine Script

//@version=6
// © mayb1dayy
indicator("Macro Candles+ (M1D)", shorttitle = "Macro Candles+ (M1D)", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
// Colours every candle that prints inside an ICT macro window (XX:50 to XX+1:10, New York) and
// marks each window with one dotted vertical line at its open and a dot carrying its bias. A
// macro is bullish when it opens above the previous macro's high and bearish when it opens below
// its low, and it is re-graded once if a candle closes back through the level it opened beyond. A
// macro opening inside the previous range is consolidation and paints grey until a candle closes
// outside that range, which grades it the way it broke. Outside a window the chart's own candles
// show untouched.
// Spacing picks a macro every N hours counted from midnight New York (an engineering choice, not
// doctrine), and each clock hour can be switched off on its own. Works on every timeframe below
// one hour; on 1H and above a twenty-minute window has no candle to colour, so nothing draws.
 
const string TZ       = "America/New_York"
const color  C_INK    = #000000
const color  C_CLEAR  = #FFFFFF
const int    DAY_MS   = 24 * 60 * 60 * 1000
const int    MAX_OBJ  = 480
const int    LIFT_BARS = 15
 
// ═════════════════════════════════════════════════════════════════════════════
//  INPUTS
// ═════════════════════════════════════════════════════════════════════════════
 
string G_CANDLE = "Macro candles"
string colMode  = input.string("Vs previous macro", "Colour by", options = ["Vs previous macro", "Per candle", "One colour"], group = G_CANDLE, tooltip = "Vs previous macro: bullish when this macro opens above the previous macro's high, bearish when it opens below its low, grey (consolidation) when it opens inside that range. A macro can be re-graded once on a close through the range, and then holds to the close. Per candle: each candle's own up or down. One colour: every macro candle takes the bullish colour.")
color  upCol    = input.color(#1E88E5, "Bullish",  group = G_CANDLE, inline = "c", tooltip = "Body, wick and border all take this colour.")
color  dnCol    = input.color(#E53935, "Bearish",  group = G_CANDLE, inline = "c")
color  flatCol  = input.color(#5C5C5C, "Consolidation", group = G_CANDLE, inline = "c")
bool   flipOn   = input.bool(true, "Re-grade on a close through the range", group = G_CANDLE, tooltip = "A macro that opened above the previous high turns bearish on the first close back below that high, and one that opened below the previous low turns bullish on the first close back above it. A consolidation macro turns bearish on the first close below the previous low, bullish on the first close above its high. One change per macro.")
bool   paintOn  = input.bool(true, "Colour the candles", group = G_CANDLE)
bool   wickBody = input.bool(true, "Wick takes the macro colour", group = G_CANDLE, inline = "w", tooltip = "On: wick, body and border all take the macro colour, so the candle reads at any zoom. Off: the wick takes the colour beside it, which only reads when the chart is zoomed in enough to show bodies.")
color  wickCol  = input.color(#000000, "", group = G_CANDLE, inline = "w")
 
string G_LINES  = "Macro lines"
bool   linesOn  = input.bool(true, "Open line", group = G_LINES, tooltip = "One dotted vertical at the macro open (XX:50). The colour stopping is the close.")
color  lineCol  = input.color(#787B86, "Colour", group = G_LINES, inline = "l")
int    lineW    = input.int(1, "Width", minval = 1, maxval = 3, group = G_LINES, inline = "l")
bool   tagsOn   = input.bool(true, "Bias dot", group = G_LINES, tooltip = "A dot on the open line in the macro's colour: above price for a bearish macro, below for a bullish one, above for consolidation. Hover it for the reading.")
float  cushion  = input.float(1.0, "Dot cushion (× ATR14)", minval = 0.25, maxval = 1.5, step = 0.25, group = G_LINES, tooltip = "How far clear of the surrounding candles the dot sits. Kept at or under 1.5 so the dots do not stretch the price scale.")
int    dotPts   = input.int(5, "Dot size (points)", minval = 2, maxval = 20, group = G_LINES)
 
string G_WHICH  = "Which macros"
int    spacing  = input.int(1, "Spacing (hours)", minval = 1, maxval = 12, group = G_WHICH, tooltip = "H1 shows every hour's macro. H2 every second hour, H3 every third, and so on up to H12. Spacing counts from midnight New York, so H4 shows the 00:50, 04:50, 08:50 and 20:50 windows.")
int    daysBack = input.int(5, "History (days)", minval = 1, maxval = 60, group = G_WHICH, tooltip = "How many days of macro lines and tags stay on the chart. Candle colour is not limited by this.")
 
string G_HOURS  = "Hours (New York, the hour the macro opens in)"
bool h00 = input.bool(true, "00", group = G_HOURS, inline = "r1")
bool h01 = input.bool(true, "01", group = G_HOURS, inline = "r1")
bool h02 = input.bool(true, "02", group = G_HOURS, inline = "r1")
bool h03 = input.bool(true, "03", group = G_HOURS, inline = "r1")
bool h04 = input.bool(true, "04", group = G_HOURS, inline = "r1")
bool h05 = input.bool(true, "05", group = G_HOURS, inline = "r1")
bool h06 = input.bool(true, "06", group = G_HOURS, inline = "r2")
bool h07 = input.bool(true, "07", group = G_HOURS, inline = "r2")
bool h08 = input.bool(true, "08", group = G_HOURS, inline = "r2")
bool h09 = input.bool(true, "09", group = G_HOURS, inline = "r2")
bool h10 = input.bool(true, "10", group = G_HOURS, inline = "r2")
bool h11 = input.bool(true, "11", group = G_HOURS, inline = "r2")
bool h12 = input.bool(true, "12", group = G_HOURS, inline = "r3")
bool h13 = input.bool(true, "13", group = G_HOURS, inline = "r3")
bool h14 = input.bool(true, "14", group = G_HOURS, inline = "r3")
bool h15 = input.bool(true, "15", group = G_HOURS, inline = "r3")
bool h16 = input.bool(true, "16", group = G_HOURS, inline = "r3")
bool h17 = input.bool(true, "17", group = G_HOURS, inline = "r3")
bool h18 = input.bool(true, "18", group = G_HOURS, inline = "r4")
bool h19 = input.bool(true, "19", group = G_HOURS, inline = "r4")
bool h20 = input.bool(true, "20", group = G_HOURS, inline = "r4")
bool h21 = input.bool(true, "21", group = G_HOURS, inline = "r4")
bool h22 = input.bool(true, "22", group = G_HOURS, inline = "r4")
bool h23 = input.bool(true, "23", group = G_HOURS, inline = "r4")
 
// ═════════════════════════════════════════════════════════════════════════════
//  HELPERS
// ═════════════════════════════════════════════════════════════════════════════
 
//@function Whether the macro opening in a given New York hour is switched on.
//@param h (int) The hour, 0 to 23.
//@returns (bool) True when that hour's toggle is on and it lands on the spacing grid.
f_hourOn(int h) =>
    bool toggled = switch h
        0  => h00
        1  => h01
        2  => h02
        3  => h03
        4  => h04
        5  => h05
        6  => h06
        7  => h07
        8  => h08
        9  => h09
        10 => h10
        11 => h11
        12 => h12
        13 => h13
        14 => h14
        15 => h15
        16 => h16
        17 => h17
        18 => h18
        19 => h19
        20 => h20
        21 => h21
        22 => h22
        =>    h23
    toggled and h % spacing == 0
 
//@function Drops the oldest line while a store is over its cap.
//@param store (array<line>) The store.
f_pruneLines(array<line> store) =>
    while store.size() > MAX_OBJ
        line.delete(store.shift())
 
//@function Drops the oldest label while a store is over its cap.
//@param store (array<label>) The store.
f_pruneLabels(array<label> store) =>
    while store.size() > MAX_OBJ
        label.delete(store.shift())
 
// ═════════════════════════════════════════════════════════════════════════════
//  THE MACRO CLOCK
// ═════════════════════════════════════════════════════════════════════════════
 
bool   tfOk    = timeframe.isintraday and timeframe.in_seconds() < 60 * 60
int    nyHour  = hour(time, TZ)
int    nyMin   = minute(time, TZ)
 
// The hour whose macro this bar sits in: the :50–:59 part belongs to this clock hour, the
// :00–:09 part to the hour before it. A candle is named by its open, so the :09 candle is the
// last one inside: it closes at :10.
bool   tail     = nyMin >= 50
bool   head     = nyMin < 10
int    macroHr  = tail ? nyHour : head ? (nyHour + 23) % 24 : -1
bool   onClock  = tfOk and macroHr >= 0 and f_hourOn(macroHr)
 
// The window's own timestamps. Stepping the bar time back ten minutes lands every macro bar
// inside the clock hour the macro opened in, so the calendar day and hour read straight off it.
int    ref        = time - 10 * 60 * 1000
int    macroOpen  = onClock ? timestamp(TZ, year(ref, TZ), month(ref, TZ), dayofmonth(ref, TZ), hour(ref, TZ), 50, 0) : na
 
// A macro exists only if its opening bar printed. Around a session close (CME 17:00) the :50 bars
// of one hour run straight into the :00 bars of a later one with no candle between them; those
// head bars belong to a window that never opened and are left alone.
var int liveOpen = na
if onClock and (na(liveOpen) or macroOpen != liveOpen)
    liveOpen := tail ? macroOpen : na
bool   inMacro  = onClock and not na(liveOpen) and macroOpen == liveOpen
 
// ═════════════════════════════════════════════════════════════════════════════
//  CANDLES
// ═════════════════════════════════════════════════════════════════════════════
 
// The previous macro's range is what this one opens against.
var float prevHi   = na
var float prevLo   = na
var float curHi    = na
var float curLo    = na
var color  macroCol  = na
var int    bias      = 0       // 1 bullish · -1 bearish · 0 consolidation
var bool   flipped   = false
var bool   readable  = false   // false only when there is no previous macro to read against
var string biasNote  = ""
var float  openHi    = na      // the previous range this macro opened against
var float  openLo    = na
bool  newMacro = inMacro and (not inMacro[1] or macroOpen != macroOpen[1])
bool  flipNow  = false
 
if newMacro
    openHi   := prevHi
    openLo   := prevLo
    flipped  := false
    readable := not na(prevHi)
    if readable and open > prevHi
        bias     := 1
        biasNote := "Bullish: opened above the previous macro's high"
    else if readable and open < prevLo
        bias     := -1
        biasNote := "Bearish: opened below the previous macro's low"
    else
        bias     := 0
        biasNote := readable ? "Consolidation: opened inside the previous macro's range" : "No previous macro to read against"
    curHi := high
    curLo := low
else if inMacro
    curHi := math.max(curHi, high)
    curLo := math.min(curLo, low)
    if flipOn and not flipped and barstate.isconfirmed
        if bias == 1 and close < openHi
            bias     := -1
            flipped  := true
            flipNow  := true
            biasNote := "Bearish: opened above the previous macro's high, then closed back below it"
        else if bias == -1 and close > openLo
            bias     := 1
            flipped  := true
            flipNow  := true
            biasNote := "Bullish: opened below the previous macro's low, then closed back above it"
        else if bias == 0 and readable and close < openLo
            bias     := -1
            flipped  := true
            flipNow  := true
            biasNote := "Bearish: opened inside the previous macro's range, then closed below its low"
        else if bias == 0 and readable and close > openHi
            bias     := 1
            flipped  := true
            flipNow  := true
            biasNote := "Bullish: opened inside the previous macro's range, then closed above its high"
else if inMacro[1]
    prevHi := curHi
    prevLo := curLo
 
macroCol := not inMacro or not readable ? na : bias == 1 ? upCol : bias == -1 ? dnCol : flatCol
 
color candleCol = switch
    not paintOn or not inMacro   => na
    colMode == "Per candle"      => close > open ? upCol : dnCol
    colMode == "One colour"      => upCol
    =>                              macroCol
// Two layers: barcolor recolours the chart's own candle, and a filled candle is drawn over it so a
// hollow up candle still shows its colour.
bool  paintBar = not na(candleCol)
barcolor(candleCol, title = "Macro candle colour")
plotcandle(paintBar ? open : na, paintBar ? high : na, paintBar ? low : na, paintBar ? close : na, title = "Macro candles", color = candleCol, wickcolor = wickBody ? candleCol : wickCol, bordercolor = candleCol)
 
// ═════════════════════════════════════════════════════════════════════════════
//  OPEN LINE AND BIAS DOT — created once per window; the dot follows one flip
// ═════════════════════════════════════════════════════════════════════════════
 
var array<line>  lineStore = array.new<line>(0)
var array<label> tagStore  = array.new<label>(0)
var array<int>   tagBorn   = array.new<int>(0)
var array<bool>  tagSide   = array.new<bool>(0)
var int          lastOpen  = na
 
float atr     = ta.atr(14)
float hi15    = ta.highest(high, 15)
float lo15    = ta.lowest(low, 15)
bool  recent  = time >= last_bar_time - daysBack * DAY_MS
 
if inMacro and recent and (na(lastOpen) or macroOpen != lastOpen)
    lastOpen := macroOpen
    if linesOn
        lineStore.push(line.new(macroOpen, low, macroOpen, high, xloc = xloc.bar_time, extend = extend.both, color = lineCol, style = line.style_dotted, width = lineW))
        f_pruneLines(lineStore)
    if tagsOn
        bool  above = bias != 1
        float pad   = atr * cushion
        float dotY  = above ? hi15 + pad : lo15 - pad
        color dotC  = na(macroCol) ? lineCol : macroCol
        label dot = label.new(macroOpen, dotY, "", xloc = xloc.bar_time, style = label.style_circle, color = dotC, size = dotPts, tooltip = biasNote)
        tagStore.push(dot)
        tagBorn.push(bar_index)
        tagSide.push(above)
        f_pruneLabels(tagStore)
        while tagBorn.size() > tagStore.size()
            tagBorn.shift()
            tagSide.shift()
 
// A flip recolours the live dot, rewrites its reading and moves it to the other side of price.
if flipNow and tagsOn and tagStore.size() > 0
    int   last  = tagStore.size() - 1
    label dot   = tagStore.get(last)
    bool  above = bias != 1
    float pad   = atr * cushion
    label.set_color(dot, macroCol)
    label.set_tooltip(dot, biasNote)
    label.set_y(dot, above ? hi15 + pad : lo15 - pad)
    tagSide.set(last, above)
    tagBorn.set(last, bar_index)
 
// Self-lift: a fresh dot moves away from any candle that reaches it, then freezes as history.
if tagStore.size() > 0
    float pad = atr * cushion
    for i = tagStore.size() - 1 to 0
        if bar_index - tagBorn.get(i) > LIFT_BARS
            break
        label dot   = tagStore.get(i)
        bool  above = tagSide.get(i)
        float y     = label.get_y(dot)
        if above and high + pad > y
            label.set_y(dot, high + pad)
        else if not above and low - pad < y
            label.set_y(dot, low - pad)
 
// ═════════════════════════════════════════════════════════════════════════════
//  TIMEFRAME NOTE
// ═════════════════════════════════════════════════════════════════════════════
 
var table note = na
if barstate.islast and not tfOk
    if na(note)
        note := table.new(position.bottom_right, 1, 1, bgcolor = C_CLEAR, frame_color = C_INK, frame_width = 1)
    table.cell(note, 0, 0, " Macro Candles+ draws below 1H only ", text_color = C_INK, text_size = size.small, text_font_family = font.family_monospace)

← 返回列表