本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// This Pine Script(R) code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rezdany76
indicator("Day & Week High/Low Scale Levels", shorttitle = "DW", overlay = true, max_lines_count = 20, max_labels_count = 20)
// Six reference levels shown as colored value labels inside the right price
// scale (Pine cannot recolor the scale's own tick marks), each with a small tag:
// PWH/PWL (S-1 Haut/Bas) : last completed week
// CWH/CWL (S Haut/Bas) : current week, adjusted at each new high or low
// PDH/PDL (J-1 Haut/Bas) : last completed trading day (Monday shows Friday,
// a holiday is skipped). While the market is closed
// after a session, that session is J-1.
// A J-1 or S-1 level is hidden once price trades at it after it became active
// (a wick is enough), until its period renews.
//
// Every level is computed in a fixed daily context, so the result does not
// depend on the chart timeframe. Prices come from the standard (non Heikin
// Ashi) chart with the chart's session, so they are real OHLC prices. No future
// data is used: on intraday charts the daily state is taken from the previous
// daily bar (offset [1] with lookahead_on, the documented non-repainting
// pattern) and completed with the chart bars of the current day; on daily and
// higher charts the daily state of the latest daily bar is read directly.
// ---------------------------------------------------------------- Inputs
string G_LVL = "Levels / Niveaux"
bool showPW = input.bool(true, "Previous week (S-1) / Semaine précédente", group = G_LVL)
bool showW = input.bool(true, "Current week (S) / Semaine en cours", group = G_LVL)
bool showD = input.bool(true, "Previous day (J-1) / Veille", group = G_LVL)
string G_COL = "Colors / Couleurs"
color pwLowCol = input.color(#FF3030, "PWL / PWH S-1", inline = "pw", group = G_COL)
color pwHighCol = input.color(#FF69B4, "", inline = "pw", group = G_COL)
color wLowCol = input.color(#0D47A1, "CWL / CWH S", inline = "w", group = G_COL)
color wHighCol = input.color(#64B5F6, "", inline = "w", group = G_COL)
color dLowCol = input.color(#1B5E20, "PDL / PDH J-1", inline = "d", group = G_COL)
color dHighCol = input.color(#81C784, "", inline = "d", group = G_COL)
string G_DSP = "Display / Affichage"
bool showLines = input.bool(false, "Horizontal lines / Lignes horizontales", group = G_DSP)
string lineStyleI = input.string("Dotted", "Line style / Style de ligne", options = ["Solid", "Dashed", "Dotted"], group = G_DSP, display = display.none)
int lineWidthI = input.int(1, "Line width / Épaisseur", minval = 1, maxval = 4, group = G_DSP, display = display.none)
string G_RUL = "Period rules / Règles de période"
bool hideTouched = input.bool(true, "Hide J-1 / S-1 once touched / Masquer J-1 / S-1 une fois touchés", group = G_RUL,
tooltip = "A J-1 level is hidden for the rest of the day, an S-1 level for the rest of the week, as soon as a trading day after its activation traded at its price (a wick is enough). / Un niveau J-1 est masqué jusqu'à la fin de la journée, un niveau S-1 jusqu'à la fin de la semaine, dès qu'une journée postérieure à son activation a coté son prix (une mèche suffit).")
bool rollover = input.bool(true, "Market closed: last session counts as completed / Marché fermé : dernière séance terminée", group = G_RUL,
tooltip = "When the market is closed and the last session has ended, that session becomes J-1 (and S-1 once the week has ended), instead of waiting for the first bar of the next session. / Marché fermé et séance finie : cette séance devient J-1 (et S-1 si la semaine est finie), sans attendre la séance suivante.")
// Declared last so that the ids of the inputs above do not change.
bool showTags = input.bool(true, "Level tags (PDH, PWL...) / Sigles", group = G_DSP,
tooltip = "Small text tags between the last bar and the price scale, no value, no box. Levels at the same price share one tag. / Petits sigles entre la dernière bougie et l'échelle, sans valeur ni cadre. Les niveaux au même prix partagent un sigle.")
int tagOffset = input.int(8, "Tag offset (bars) / Décalage des sigles (bougies)", minval = 0, maxval = 200, group = G_DSP, display = display.none,
tooltip = "Tags are right-aligned and end this many bars right of the last bar. Pine drawings are anchored to bars, not to the price scale: set it to your chart's right margin to put the tags against the scale. / Les sigles sont alignés à droite et se terminent à ce nombre de bougies après la dernière. Les dessins Pine sont ancrés aux bougies, pas à l'échelle : réglez-le sur la marge droite du graphique pour coller les sigles à l'échelle.")
// ---------------------------------------------------------------- Guards
if barstate.isfirst
if timeframe.isticks
runtime.error("Tick charts are not supported. / Graphiques en ticks non pris en charge.")
if not (chart.is_standard or chart.is_heikinashi)
runtime.error("Renko, Kagi, Point & Figure, Line Break and Range charts are not supported. / Types de graphique non pris en charge.")
// ---------------------------------------------------------------- Daily state
// Standard chart type, same session (regular/extended) as the chart.
string SRC = ticker.new(syminfo.prefix, syminfo.ticker, syminfo.session)
// True when a trading day whose range is [l, h] traded at `level`.
touches(float level, float h, float l) =>
not na(level) and l <= level and h >= level
// Weekly state after one more trading day with range [l, h].
// cH/cL: current week so far, pH/pL: last completed week,
// tH/tL: pH/pL traded at since the current week started.
nextDay(float cH, float cL, float pH, float pL, bool tH, bool tL, float h, float l, bool newWeek) =>
float npH = newWeek ? cH : pH
float npL = newWeek ? cL : pL
float ncH = newWeek ? h : math.max(cH, h)
float ncL = newWeek ? l : math.min(cL, l)
bool ntH = (not newWeek and tH) or touches(npH, h, l)
bool ntL = (not newWeek and tL) or touches(npL, h, l)
[ncH, ncL, npH, npL, ntH, ntL]
// Daily context: weekly state at the end of each daily bar (so far for the
// last one), the start and scheduled end of its week, and its own close time.
dailyState() =>
var float cH = na
var float cL = na
var float pH = na
var float pL = na
var bool tH = false
var bool tL = false
[ncH, ncL, npH, npL, ntH, ntL] = nextDay(cH, cL, pH, pL, tH, tL, high, low, timeframe.change("1W"))
cH := ncH
cL := ncL
pH := npH
pL := npL
tH := ntH
tL := ntL
[cH, cL, pH, pL, tH, tL, time("1W"), time_close("1W"), time_close]
// State including the latest daily bar, with J-1 = the daily bar before it,
// and whether that bar is the last one of a closed market.
dayNow() =>
[cH, cL, pH, pL, tH, tL, wT, wE, dE] = dailyState()
[cH, cL, pH, pL, tH, tL, wE, dE, high, low, high[1], low[1], touches(high[1], high, low), touches(low[1], high, low), barstate.islastconfirmedhistory]
// State at the end of the previous daily bar.
dayBefore() =>
[cH, cL, pH, pL, tH, tL, wT, wE, dE] = dailyState()
[cH[1], cL[1], pH[1], pL[1], tH[1], tL[1], wT[1], wE[1], high[1], low[1]]
// Daily and higher charts: the "1D" request is at or below the chart timeframe
// and returns the latest daily bar of each chart bar. Intraday realtime bars:
// it returns the live daily candle.
[nCH, nCL, nPH, nPL, nTH, nTL, nWE, nDE, nDH, nDL, nJ1H, nJ1L, nTJ1H, nTJ1L, nClosed] = request.security(SRC, "1D", dayNow(), currency = syminfo.currency)
// Intraday historical bars: state at the end of the previous trading day.
[bCH, bCL, bPH, bPL, bTH, bTL, bWT, bWE, bDH, bDL] = request.security(SRC, "1D", dayBefore(), lookahead = barmerge.lookahead_on, currency = syminfo.currency)
// Real OHLC of the chart's own bars (differs from the chart on Heikin Ashi).
[barH, barL] = request.security(SRC, timeframe.period, [high, low], currency = syminfo.currency)
// Current trading day accumulated from intraday chart bars. Marked incomplete
// when the chart history starts after the beginning of that day.
var float dayH = na
var float dayL = na
var bool dayFull = false
if barstate.isfirst or timeframe.change("1D")
dayH := barH
dayL := barL
dayFull := not barstate.isfirst or time == time("1D")
else
dayH := math.max(dayH, barH)
dayL := math.min(dayL, barL)
bool dailyOrMore = timeframe.in_seconds() >= 86400
bool useNow = dailyOrMore or barstate.isrealtime
bool newWeekBar = bWT != time("1W")
float tdH = dayFull ? dayH : na
float tdL = dayFull ? dayL : na
[iCH, iCL, iPH, iPL, iTH, iTL] = nextDay(bCH, bCL, bPH, bPL, bTH, bTL, tdH, tdL, newWeekBar)
// Same state whatever the chart timeframe.
bool known = useNow or dayFull
float curH = useNow ? nCH : iCH
float curL = useNow ? nCL : iCL
float prvH = useNow ? nPH : iPH
float prvL = useNow ? nPL : iPL
bool prvHT = useNow ? nTH : iTH
bool prvLT = useNow ? nTL : iTL
float todH = useNow ? nDH : tdH
float todL = useNow ? nDL : tdL
float yH = useNow ? nJ1H : bDH
float yL = useNow ? nJ1L : bDL
bool yHT = useNow ? nTJ1H : touches(bDH, tdH, tdL)
bool yLT = useNow ? nTJ1L : touches(bDL, tdH, tdL)
float weekEnd = useNow ? nWE : newWeekBar ? na : bWE
float dayEnd = dailyOrMore ? nDE : time_close("1D")
// Market closed after the end of the last session: that session is completed.
// "Market closed" is barstate.islastconfirmedhistory, which is false in Bar
// Replay, so a replayed session is never rolled before the next one starts.
// On daily and higher charts it is read in the daily context, because the
// chart's own value is false on monthly charts even with the market closed.
// No time tolerance is used. The end of the week comes from the daily context:
// on intraday charts time_close("1W") returns the next week's open.
bool marketClosed = dailyOrMore ? nClosed : barstate.islastconfirmedhistory
bool dayDone = rollover and barstate.islast and not barstate.isrealtime and marketClosed and not na(dayEnd) and timenow >= dayEnd
bool weekDone = dayDone and not na(weekEnd) and dayEnd >= weekEnd
// A level that has just become J-1 or S-1 has not been traded at since.
float s1H = weekDone ? curH : prvH
float s1L = weekDone ? curL : prvL
bool s1HT = weekDone ? false : prvHT
bool s1LT = weekDone ? false : prvLT
float sH = weekDone ? na : curH
float sL = weekDone ? na : curL
float j1H = dayDone ? todH : yH
float j1L = dayDone ? todL : yL
bool j1HT = dayDone ? false : yHT
bool j1LT = dayDone ? false : yLT
visible(bool enabled, bool touched) =>
known and enabled and not (hideTouched and touched)
bool vS1H = visible(showPW, s1HT)
bool vS1L = visible(showPW, s1LT)
bool vSH = visible(showW, false)
bool vSL = visible(showW, false)
bool vJ1H = visible(showD, j1HT)
bool vJ1L = visible(showD, j1LT)
// ---------------------------------------------------------------- Price scale
// Plotted on the last bar only: colored value labels in the price scale. The
// plot titles are the tags: with the chart's "indicator name labels" scale
// setting on, TradingView shows "DW:PDH" etc. inside the scale, attached to the
// value at any zoom or timeframe (the short title "DW" is the prefix). Values
// are listed in the Data Window.
bool onLast = barstate.islast
plot(onLast and vS1H ? s1H : na, "PWH", pwHighCol, display = display.price_scale + display.data_window, show_last = 1, editable = false)
plot(onLast and vS1L ? s1L : na, "PWL", pwLowCol, display = display.price_scale + display.data_window, show_last = 1, editable = false)
plot(onLast and vSH ? sH : na, "CWH", wHighCol, display = display.price_scale + display.data_window, show_last = 1, editable = false)
plot(onLast and vSL ? sL : na, "CWL", wLowCol, display = display.price_scale + display.data_window, show_last = 1, editable = false)
plot(onLast and vJ1H ? j1H : na, "PDH", dHighCol, display = display.price_scale + display.data_window, show_last = 1, editable = false)
plot(onLast and vJ1L ? j1L : na, "PDL", dLowCol, display = display.price_scale + display.data_window, show_last = 1, editable = false)
// ---------------------------------------------------------------- Optional lines
// Off by default.
var array<line> lines = array.new<line>()
drawLevel(bool enabled, float price, color c) =>
if enabled and not na(price)
string style = lineStyleI == "Solid" ? line.style_solid : lineStyleI == "Dashed" ? line.style_dashed : line.style_dotted
lines.push(line.new(bar_index - 1, price, bar_index, price, extend = extend.both, color = c, style = style, width = lineWidthI))
if barstate.islast
for ln in lines
ln.delete()
lines.clear()
if showLines
drawLevel(vS1H, s1H, pwHighCol)
drawLevel(vS1L, s1L, pwLowCol)
drawLevel(vSH, sH, wHighCol)
drawLevel(vSL, sL, wLowCol)
drawLevel(vJ1H, j1H, dHighCol)
drawLevel(vJ1L, j1L, dLowCol)
// ---------------------------------------------------------------- Tags
// One text-only tag per price (no value, transparent box), right-aligned so it
// ends `tagOffset` bars right of the last bar. Pine cannot anchor a drawing to
// the price scale: chart.right_visible_bar_time is the last bar, not the edge of
// the right margin. Visible levels at the
// same price share one tag such as "PWL/PDL"; its tooltip spells each one out.
var array<label> tags = array.new<label>()
addTag(array<float> prices, array<string> names, array<string> meanings, array<color> colors, bool enabled, float price, string name, string meaning, color c) =>
if enabled and not na(price)
prices.push(math.round_to_mintick(price))
names.push(name)
meanings.push(meaning)
colors.push(c)
if barstate.islast
for lb in tags
lb.delete()
tags.clear()
if showTags
array<float> prices = array.new<float>()
array<string> names = array.new<string>()
array<string> meanings = array.new<string>()
array<color> colors = array.new<color>()
addTag(prices, names, meanings, colors, vS1H, s1H, "PWH", "PWH = previous week high / S-1 Haut", pwHighCol)
addTag(prices, names, meanings, colors, vS1L, s1L, "PWL", "PWL = previous week low / S-1 Bas", pwLowCol)
addTag(prices, names, meanings, colors, vSH, sH, "CWH", "CWH = current week high / S Haut", wHighCol)
addTag(prices, names, meanings, colors, vSL, sL, "CWL", "CWL = current week low / S Bas", wLowCol)
addTag(prices, names, meanings, colors, vJ1H, j1H, "PDH", "PDH = previous day high / J-1 Haut", dHighCol)
addTag(prices, names, meanings, colors, vJ1L, j1L, "PDL", "PDL = previous day low / J-1 Bas", dLowCol)
array<bool> done = array.new<bool>(prices.size(), false)
for [i, p] in prices
if not done.get(i)
string txt = names.get(i)
string tip = meanings.get(i)
if i < prices.size() - 1
for j = i + 1 to prices.size() - 1
if not done.get(j) and prices.get(j) == p
txt += "/" + names.get(j)
tip += "\n" + meanings.get(j)
done.set(j, true)
tags.push(label.new(bar_index + tagOffset, p, txt, color = color.new(color.white, 100), textcolor = colors.get(i), style = label.style_label_right, size = size.small, tooltip = tip))