本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © IvanSetuper
//@version=6
// A day keeps one box and up to four lines and labels, so 125 boxes go back as far as 500 of the others do.
indicator("Opening Range Breakout", "ORB", overlay = true, max_lines_count = 500, max_boxes_count = 125, max_labels_count = 500)
// ————— Constants
const int BULL = 1
const int BEAR = -1
const int EXTEND = 4 // bars that the lines of a running day and of an open trade run past the newest bar
const int MAX_BACK = 5000 // furthest a drawing may start behind the newest bar; the most max_bars_back() takes
const string YES = "✔"
const string NO = "✖"
const color GREEN = #089981
const color RED = #F23645
const string G_MODEL = "Model"
const string G_DRIVE = "Opening drive"
const string G_RISK = "Risk"
const string G_TABLES = "Tables"
const string G_STYLE = "Style"
const string TT_MODEL = "Breakout: the first close beyond the range is the signal, and the trade enters at the open of the next bar. Retest: that close places a limit order at the broken edge instead. Opening drive: after a gap, a stop order one tick beyond the first candle. Each model places at most one order a day. Signals come from the closes of the chart's own bars, so the timeframe is part of the model. 5 minutes is the usual choice."
const string TT_SIDE = "Long only and Short only skip the days that point the other way. A first close beyond the range on the wrong side, or a gap in the wrong direction, ends the day without an order."
const string TT_RANGE = "Start of the range in the time zone below, and its length in minutes. The range is the high and low of the bars inside it. The chart's timeframe has to divide the length, and its bars have to begin at the start: an hourly bar that opens at 9:00 cannot hold a range from 9:30. The opening drive takes the start from here and the length from First candle, minutes. Write 9:30 or 0930."
const string TT_LAST = "A breakout or retest signal counts only on a bar that ends by this time, and the stop order of the opening drive waits until then. No order is placed at the time set under Close trades at or later. Write 15:45 or 1545."
const string TT_FLAT = "A trade still open at this time of day is closed at the close of the bar that ends then, or of the bar that runs through it, with whatever it has made or lost. An order that has not filled is cancelled. When the market is closed at this time, as on a half day, the last close before the break counts, but the script learns of the break only when trading resumes: on such a day close the trade yourself before the market does. The opening drive measures its gap from the previous day's close at this time. Write 16:00 or 1600."
const string TT_ZONE = "The range, every time in this group and the start of each day use this zone. Any IANA name works, for example America/New_York or Europe/London."
const string TT_STOP = "Breakout and Retest: the opposite edge of the range, or its midpoint, which is closer and gives a larger position. The opening drive always uses the far end of its first candle. A level between two ticks moves to the next tick away from the entry. Second value: ticks added beyond that price, in every model."
const string TT_TARGET = "Take profit as a multiple of the risk, measured from the fill. A level between two ticks moves to the next tick away from the entry. 0 leaves it out, and the trade runs until the stop loss or the time set under Close trades at."
const string TT_RETEST = "Retest model only. The limit order at the broken edge fills once a bar trades one tick through it, and is cancelled when no bar has done so by this time. Write 11:15 or 1115."
const string TT_GAP = "The gap is the open of the day's first bar against the previous day's close at the time set under Close trades at. A day trades only when the gap, up or down, is at least this share of that close. On a continuous futures chart the previous day is moved by the difference between the two contracts on the day they roll, so that difference does not count as a gap."
const string TT_OUTSIDE = "On: the day also has to open above the previous day's high after a gap up, or below its low after a gap down. That high and low count from the range start to the time set under Close trades at. Off: the open may lie anywhere."
const string TT_CANDLE = "The range of the opening drive is its first candle: the chart's bars over this many minutes from the range start, so the chart's timeframe has to divide it. A stop order waits one tick above its high after a gap up, or below its low after a gap down, until the time set under Entries until. The stop loss goes to its far end."
const string TT_WITH = "On: the first candle has to close in the direction of the gap, above its open after a gap up and below it after a gap down. Off: any first candle counts."
const string TT_RISK = "What you are willing to lose when the stop loss is hit, costs included, in the symbol's currency. The entry label shows the largest position that fits and what it loses at the stop loss. The size is set when the order appears. A breakout fills at the next open, and from then on the label shows what that size loses from the fill, a little more or less than before. When even the smallest position loses more than this amount, the label shows that larger amount and the checklist a cross. 0 leaves the size off the label and the row off the checklist."
const string TT_COSTS = "Spread, commission and slippage of a whole trade, entry plus exit, as a percentage of price. First value: every market except crypto. Second: crypto. For scale, 0.008% of 25,000 is 2 points. The position size allows for them, and the tooltip of the entry label gives them in R."
enum Model
breakout = "Breakout"
retest = "Retest"
drive = "Opening drive"
enum Direction
both = "Long and short"
longs = "Long only"
shorts = "Short only"
enum Stop
edge = "Opposite edge"
middle = "Range midpoint"
// ————— Inputs
Model modelInput = input.enum(Model.breakout, "Model", group = G_MODEL, tooltip = TT_MODEL)
Direction directionInput = input.enum(Direction.both, "Direction", group = G_MODEL, tooltip = TT_SIDE)
string startInput = input.string("09:30", "Opening range", inline = "range", group = G_MODEL, tooltip = TT_RANGE)
int lengthInput = input.int(15, "", minval = 1, inline = "range", group = G_MODEL)
string lastInput = input.string("15:45", "Entries until", group = G_MODEL, tooltip = TT_LAST)
string flatInput = input.string("16:00", "Close trades at", group = G_MODEL, tooltip = TT_FLAT)
string zoneInput = input.string("America/New_York", "Time zone", group = G_MODEL, tooltip = TT_ZONE)
Stop stopInput = input.enum(Stop.edge, "Stop loss", inline = "stop", group = G_MODEL, tooltip = TT_STOP)
int bufferInput = input.int(0, "", minval = 0, inline = "stop", group = G_MODEL)
float targetInput = input.float(2, "Target, R", minval = 0, step = 0.5, group = G_MODEL, tooltip = TT_TARGET)
string retestInput = input.string("11:15", "Retest until", group = G_MODEL, tooltip = TT_RETEST)
float gapInput = input.float(0.5, "Minimum gap, %", minval = 0, step = 0.1, group = G_DRIVE, tooltip = TT_GAP)
bool outsideInput = input.bool(true, "Open outside the previous day", group = G_DRIVE, tooltip = TT_OUTSIDE)
int candleInput = input.int(5, "First candle, minutes", minval = 1, group = G_DRIVE, tooltip = TT_CANDLE)
bool withGapInput = input.bool(true, "First candle with the gap", group = G_DRIVE, tooltip = TT_WITH)
float riskInput = input.float(500, "Risk per trade", minval = 0, group = G_RISK, tooltip = TT_RISK)
float costInput = input.float(0.008, "Costs per trade, % of price", minval = 0, step = 0.001, inline = "cost", group = G_RISK, tooltip = TT_COSTS)
float cryptoCostInput = input.float(0.07, "", minval = 0, step = 0.01, inline = "cost", group = G_RISK)
bool checklistInput = input.bool(true, "Checklist", group = G_TABLES)
bool watermarkInput = input.bool(true, "Watermark", group = G_TABLES)
color longColorInput = input.color(#2962FF, "Long and short", inline = "side", group = G_STYLE)
color shortColorInput = input.color(#DC143C, "", inline = "side", group = G_STYLE)
color lineColorInput = input.color(#787B86, "Lines and text", group = G_STYLE)
bool targetsInput = input.bool(true, "Stop loss and target lines", group = G_STYLE)
bool pricesInput = input.bool(false, "Prices on the labels", group = G_STYLE)
// Each model has one range. The opening drive builds its own from the first candle, and its stop loss always sits
// at the far end of it.
int rangeMinutes = modelInput == Model.drive ? candleInput : lengthInput
bool midStop = stopInput == Stop.middle and modelInput != Model.drive
// On a continuous futures chart the day a contract rolls opens on the next contract, and the step between the two
// would read as a gap. The same bars with back-adjustment on are free of that step, so the difference between the
// two series tells how far the prices before a roll have to move to compare with those after it.
float lift = request.security(ticker.modify(syminfo.tickerid, backadjustment = backadjustment.on), timeframe.period, close) - close
// ————— Types
// High and low of a day's bars from its first bar up to a moment, and the close of the last of them.
type Span
int until // the moment it ends
int left // its first bar
int right // its last bar, once it is complete
float hi
float lo
float cl
// The one order of a day, and the trade once it fills.
type Trade
int dir
float entry // the order's price, for a breakout the close of its signal; the fill price once filled
float stop
int until // the latest moment a bar that fills the order may end
float qty // position size, set when the order is placed
int bar // bar whose close placed the order
int fillBar
float exit
int endBar // bar that ended the trade, or the last bar on which the order could fill
array<line> lines // the entry first, then the stop loss, 1R and the target
array<label> labels // one at the right end of each line
// One day of the model, from the first bar at or after the range start to the next such bar.
type Day
Span opening // the opening range, for the opening drive its first candle
Span session // the day's bars up to the time trades are closed
Span prior // the session of the previous day, in this day's prices
int lastEntry
int retestEnd
float op // open of the day's first bar
float lift // what back-adjustment adds to the day's prices
int breakDir // side of the first close beyond the range
int breakEnd // the moment that bar ended
Trade trade
array<line> lines // the range lines
// What this bar did to an order or a trade, in words. One alert at the end of the script carries them all.
array<string> notices = array.new<string>()
// futures trade in whole contracts whatever the data feed reports
float lot = syminfo.type == "futures" or not (syminfo.mincontract > 0) ? 1 : syminfo.mincontract
// ————— Functions
//
// Pine may drop a call whose value is not used, along with what the function does to its arguments. A method that
// changes a day or a trade therefore either ends in a statement that returns nothing, and such a call is always
// kept, or returns a value that its caller uses.
// @function True when `a` lies beyond `b` in direction `dir`: above it for 1, below it for -1.
past(int dir, float a, float b) => dir * (a - b) > 0
// @function Same as past(), with touching allowed.
reached(int dir, float a, float b) => dir * (a - b) >= 0
// @function The bar's extreme in direction `dir`: its high for 1, its low for -1.
lead(int dir) => dir == BULL ? high : low
// @function `price` when it lies on the tick grid, else the next tick from it in direction `dir`. No order can
// rest between two ticks.
snap(float price, int dir) =>
float ticks = price / syminfo.mintick
// a millionth of a tick covers what the division leaves on a price that is on the grid
(dir == BULL ? math.ceil(ticks - 1e-6) : math.floor(ticks + 1e-6)) * syminfo.mintick
// @function The bar a drawing can start from: `bar`, or the furthest bar a drawing may reach when `bar` is older.
reachable(int bar) => math.max(bar, bar_index - MAX_BACK)
// @function True when the direction input lets the model trade in direction `dir`.
allowed(int dir) => directionInput == Direction.both or (directionInput == Direction.longs ? dir == BULL : dir == BEAR)
// @function Minutes after midnight for a clock time written as 16:00, 1600 or 9:30, na for any other text.
clock(string hhmm) =>
bool valid = str.match(hhmm, "[0-2]?[0-9]:?[0-5][0-9]") == hhmm
float n = valid ? str.tonumber(str.replace(hhmm, ":", "")) : na
n < 2400 ? int(n / 100) * 60 + int(n % 100) : na
// @function The moment the clock in the model's time zone shows minute `minuteOfDay` on the date of `t`, moved
// by `days` days.
moment(int t, int minuteOfDay, int days = 0) =>
timestamp(zoneInput, year(t, zoneInput), month(t, zoneInput), dayofmonth(t, zoneInput) + days, int(minuteOfDay / 60), minuteOfDay % 60, 0)
// @function The first moment after `t` at which the clock shows minute `minuteOfDay`.
after(int t, int minuteOfDay) =>
int m = moment(t, minuteOfDay)
m > t ? m : moment(t, minuteOfDay, 1)
// @function The clock time `hhmm` written as 09:30, whichever way it was typed.
tidy(string hhmm) =>
int m = clock(hhmm)
str.format("{0,number,00}:{1,number,00}", int(m / 60), m % 60)
// @function True when one more bar of the chart fits between `t` and `deadline`.
oneMoreBar(int t, int deadline) => t + 1000 * timeframe.in_seconds() <= deadline
// @function The latest moment, up to this bar's open, at which the clock showed the start of the range.
rangeStart() =>
var int minuteOfDay = clock(startInput)
int t = moment(time, minuteOfDay)
t <= time ? t : moment(time, minuteOfDay, -1)
// @function What a whole trade costs, entry plus exit, for each unit bought or sold at `price`.
fee(float price) => price * (syminfo.type == "crypto" ? cryptoCostInput : costInput) / 100
// @function How many of the smallest positions the symbol trades in fit the risk input when one unit loses
// `loss` at the stop loss. 0 when not even one does.
lots(float loss) =>
// a hair above the quotient, so that one that should be whole is not lost to rounding: 1.9999999999999982 is two contracts
math.floor(riskInput / (loss * syminfo.pointvalue) / lot * (1 + 1e-9))
// @function The largest position that loses no more than the risk input when one unit loses `loss` at the stop
// loss, never below the smallest position the symbol trades in.
quantity(float loss) => math.max(1, lots(loss)) * lot
// @function Amount of money as text, with cents unless it is a whole number: a dollar sign for US dollars, the
// currency code otherwise, and the bare number for a symbol that has no currency.
money(float amount) =>
string digits = str.tostring(amount, math.round(amount, 2) % 1 == 0 ? "#,##0" : "#,##0.00")
switch syminfo.currency
"USD" => "$" + digits
"NONE" => digits
=> digits + " " + syminfo.currency
// @function A position and what it loses at the stop loss, as text: 2 contracts, risk $486.
// @param loss What one unit loses at the stop loss: the distance to it plus the costs.
sized(float qty, float loss) =>
string unit = switch
syminfo.type == "futures" => qty == 1 ? " contract" : " contracts"
array.from("stock", "fund", "dr").includes(syminfo.type) => qty == 1 ? " share" : " shares"
=> qty == 1 ? " unit" : " units"
str.tostring(qty, "#,##0.########") + unit + ", risk " + money(qty * loss * syminfo.pointvalue)
// @function R multiple as text: +2R, -1R, +0.37R.
inR(float r) =>
float shown = math.round(r, 2)
shown == 0 ? "0R" : (shown > 0 ? "+" : "") + str.tostring(shown, "0.##") + "R"
// @function A text label without a body, anchored at its left edge.
textAt(int x, float y, string caption, color tint, string scale = size.tiny) =>
label.new(x, y, caption, style = label.style_label_left, color = color(na), textcolor = tint, size = scale)
method risk(Trade t) => math.abs(t.entry - t.stop)
method target(Trade t, float k) => snap(t.entry + t.dir * k * t.risk(), t.dir)
// @function What one unit of the trade loses at the stop loss, costs included.
method unitLoss(Trade t) => t.risk() + fee(t.entry)
// @function The trade's result in R before costs. A breakout that opened on its stop loss left at its entry and
// has no risk to measure a result in: 0.
method result(Trade t) => t.exit == t.entry ? 0.0 : t.dir * (t.exit - t.entry) / t.risk()
// @function Fills the order at `price` on this bar and says so in the alert, with the target when there is one
// and the fill left the trade room to its stop loss.
method enter(Trade t, float price) =>
t.entry := price
t.fillBar := bar_index
bool room = targetInput > 0 and past(t.dir, price, t.stop)
notices.push("entry filled at " + str.tostring(price, format.mintick) + (room ? ", TP " + str.tostring(t.target(targetInput), format.mintick) : ""))
// @function Closes the trade on bar `bar` at `price`, with its result in R before costs. `at` names what closed
// it: SL, TP or a time.
method settle(Trade t, int bar, float price, string at) =>
t.endBar := bar
t.exit := price
notices.push("trade closed at " + at + ", " + inR(t.result()))
// @function Cancels the order. `bar` is the last bar on which it could have filled.
method cancel(Trade t, int bar, string why) =>
t.endBar := bar
notices.push(why)
// @function One bar of the order and of the trade. A breakout fills at the open, wherever that is. A retest's
// limit order fills at its price once a bar trades one tick through it, the opening drive's stop order
// at its price or at the open of a bar that opens beyond it, and either is cancelled at the close of the
// last bar that could fill it. The stop loss fills like the stop order and is live from the entry bar
// on. The target fills at its price once a later bar trades one tick through it, and when a bar holds
// both, the stop loss goes first.
method follow(Trade t) =>
int dir = t.dir
if na(t.fillBar)
string expired = "no fill by " + tidy(modelInput == Model.retest ? retestInput : lastInput) + ", cancel the order"
if modelInput == Model.breakout
t.enter(open)
else if time_close > t.until
t.cancel(bar_index - 1, expired)
else if modelInput == Model.retest and reached(-dir, lead(-dir), t.entry - dir * syminfo.mintick)
t.enter(t.entry)
else if modelInput == Model.drive and reached(dir, lead(dir), t.entry)
t.enter(past(dir, open, t.entry) ? open : t.entry)
else if not oneMoreBar(time_close, t.until)
t.cancel(bar_index, expired)
if not na(t.fillBar) and na(t.endBar)
float goal = t.target(targetInput)
if reached(-dir, lead(-dir), t.stop)
t.settle(bar_index, past(-dir, open, t.stop) ? open : t.stop, "SL")
else if targetInput > 0 and bar_index > t.fillBar and reached(dir, lead(dir), goal + dir * syminfo.mintick)
t.settle(bar_index, goal, "TP")
// @function Adds this bar to the span.
method add(Span s) =>
s.left := nz(s.left, bar_index)
s.hi := math.max(nz(s.hi, high), high)
s.lo := math.min(nz(s.lo, low), low)
s.cl := close
// @function A copy of the span with its prices moved by `step`.
method moved(Span s, float step) => Span.new(s.until, s.left, s.right, s.hi + step, s.lo + step, s.cl + step)
// @function Adds this bar to the span while the span lasts. True on the bar that completes it: the bar that ends
// at its end or runs through it, or the first bar after it when the bars before stopped short.
method grow(Span s) =>
bool done = false
if na(s.right)
if time < s.until
s.add()
if time_close >= s.until
s.right := bar_index
done := true
else if not na(s.left)
s.right := bar_index - 1
done := true
done
// @function A new day that begins on this bar with a range from `start`. The day `before` hands on its session,
// moved by the step between two futures contracts when they rolled in between.
begin(Day before, int start) =>
Span prior = na(before) ? Span.new() : before.session.moved(before.lift - lift)
Day.new(Span.new(start + rangeMinutes * 60000), Span.new(after(start, clock(flatInput))), prior, after(start, clock(lastInput)), after(start, clock(retestInput)), open, lift, lines = array.new<line>())
// @function The stop loss of the day's order in direction `dir`: the far end of the range, or its midpoint when
// the stop loss input says so, moved by the buffer and then onto the tick grid.
method stopFor(Day d, int dir) =>
Span r = d.opening
float level = midStop ? (r.hi + r.lo) / 2 : dir == BULL ? r.lo : r.hi
snap(level - dir * bufferInput * syminfo.mintick, -dir)
// @function Direction of the day's gap from the previous day's close.
method gapDir(Day d) => d.op > d.prior.cl ? BULL : BEAR
// @function The day opened at least the minimum gap away from the previous day's close, on a side the direction
// input allows.
method gapped(Day d) =>
float gap = (d.op - d.prior.cl) / d.prior.cl
gap != 0 and math.abs(gap) >= gapInput / 100 and allowed(d.gapDir())
// @function The day opened above the previous day's high after a gap up, or below its low after a gap down.
method outside(Day d) => d.gapDir() == BULL ? d.op > d.prior.hi : d.op < d.prior.lo
// @function The first candle closed in the direction of the gap.
method withGap(Day d) => past(d.gapDir(), d.opening.cl, d.op)
// @function True when a signal on a bar that ends at `t` may still place the day's order: before the day's
// session ends, by the last entry time, and with a bar left for a limit or stop order to fill on.
method inTime(Day d, int t) =>
bool early = t < d.session.until
switch
modelInput == Model.breakout => early and t <= d.lastEntry
modelInput == Model.retest => early and t <= d.lastEntry and oneMoreBar(t, d.retestEnd)
=> early and oneMoreBar(t, d.lastEntry)
// @function Makes `t` the day's order, sizes it and says so in the alert.
// @returns `t`.
method place(Day d, Trade t) =>
d.trade := t
t.bar := bar_index
t.qty := quantity(t.unitLoss())
string price = str.tostring(t.entry, format.mintick)
string kind = switch
modelInput == Model.breakout => t.dir == BULL ? "buy at the open" : "sell at the open"
modelInput == Model.retest => (t.dir == BULL ? "buy limit " : "sell limit ") + price + " until " + tidy(retestInput)
=> (t.dir == BULL ? "buy stop " : "sell stop ") + price + " until " + tidy(lastInput)
notices.push((t.dir == BULL ? "long, " : "short, ") + kind + ", SL " + str.tostring(t.stop, format.mintick) + (riskInput > 0 ? ", " + sized(t.qty, t.unitLoss()) : ""))
t
// @function Ends the day's session with bar `bar`: the bar that closed at the flat time or ran through it, or the
// last bar before a break in trading that held the flat time. An order that has not filled is
// cancelled, a trade still open is closed at that bar's close.
// @returns The order or trade this ended, or na.
method closeOut(Day d, int bar) =>
d.session.right := bar
Trade t = d.trade
Trade done = na
if not na(t) and na(t.endBar)
if na(t.fillBar)
t.cancel(bar, "no fill by " + tidy(flatInput) + ", cancel the order")
else
t.settle(bar, d.session.cl, (bar < bar_index ? "the last close before " : "") + tidy(flatInput))
done := t
done
// @function The checklist of the day at this bar, a row per line, each starting with ✔ or ✖.
method checks(Day d) =>
Trade t = d.trade
bool drive = modelInput == Model.drive
bool got = not na(t) and not na(t.fillBar)
bool window = na(t) ? d.inTime(na(d.breakEnd) ? time_close : d.breakEnd) : got or na(t.endBar)
// what one unit loses at the stop loss: the order's once there is one, before that the least the range allows
Trade least = na(t) ? Trade.new(BULL, d.opening.hi + (drive ? syminfo.mintick : 0), d.stopFor(BULL)) : t
float loss = least.unitLoss()
string rows = (na(d.opening.right) ? NO : YES) + (drive ? " First candle set\n" : " Range set\n")
if drive
string way = directionInput == Direction.both ? "" : directionInput == Direction.longs ? " up" : " down"
rows += (d.gapped() ? YES : NO) + " Gap" + way + " of " + str.tostring(gapInput, "#.##") + "% or more\n"
if outsideInput
rows += (d.outside() ? YES : NO) + " Open outside the previous day\n"
if withGapInput
rows += (not na(d.opening.right) and d.withGap() ? YES : NO) + " First candle with the gap\n"
rows += (got ? YES : NO) + " Break of the first candle\n"
rows += (window ? YES : NO) + " Inside the entry window"
else
string wanted = directionInput == Direction.both ? "Close beyond" : directionInput == Direction.longs ? "First close above" : "First close below"
rows += (not na(d.breakDir) and allowed(d.breakDir) ? YES : NO) + " " + wanted + " the range\n"
if modelInput == Model.retest
rows += (got ? YES : NO) + " Retest of the broken edge\n"
rows += (window ? YES : NO) + " Inside the entry window\n"
// the day's one order is still to come, or it is alive
rows += (na(d.breakDir) or (not na(t) and na(t.endBar)) ? YES : NO) + " First order today"
if riskInput > 0 and not na(loss)
rows += "\n" + (lots(loss) >= 1 ? YES : NO) + " Position fits the risk"
rows
// @function True once the day's trade has filled and ended. Its exit is where the range lines stop.
method traded(Day d) => not na(d.trade) and not na(d.trade.fillBar) and not na(d.trade.endBar)
// @function Bar where the range lines end: where the day's trade ended, or else its session, never before the
// range does, and a little past the newest bar while neither has.
method rightEnd(Day d) =>
int end = d.traded() ? d.trade.endBar : d.session.right
na(end) ? bar_index + EXTEND : math.max(end, d.opening.right)
// @function Draws the completed range: a faint box over its bars, and lines at its high and low, and at its
// midpoint when the stop loss sits there.
method drawRange(Day d) =>
Span r = d.opening
int left = reachable(r.left)
int right = d.rightEnd()
box.new(left, r.hi, r.right, r.lo, border_color = color(na), bgcolor = color.new(lineColorInput, 90))
// the names go to the left end, because the trade's labels take the right one
label.new(left, r.hi, "OR.H", style = label.style_label_right, color = color(na), textcolor = lineColorInput, size = size.tiny)
label.new(left, r.lo, "OR.L", style = label.style_label_right, color = color(na), textcolor = lineColorInput, size = size.tiny)
d.lines.push(line.new(left, r.hi, right, r.hi, color = lineColorInput))
d.lines.push(line.new(left, r.lo, right, r.lo, color = lineColorInput))
if midStop
float mid = (r.hi + r.lo) / 2
label.new(left, mid, "OR.MID", style = label.style_label_right, color = color(na), textcolor = lineColorInput, size = size.tiny)
d.lines.push(line.new(left, mid, right, mid, color = lineColorInput, style = line.style_dotted))
// @function Moves the right end of a trade's lines and labels to bar `x`.
method reach(Trade t, int x) =>
for l in t.lines
l.set_x2(x)
for b in t.labels
b.set_x(x)
// @function Draws an order on the bar that places it, and again on the bar that fills it, where the entry may
// have moved: the entry line with the size and what it loses at the stop loss, then the stop loss, 1R
// and target lines, when the style input asks for them and the target input leaves them a place.
method draw(Trade t) =>
if not na(t.lines)
for l in t.lines
l.delete()
for b in t.labels
b.delete()
int left = reachable(t.bar)
int right = bar_index + EXTEND
color tint = t.dir == BULL ? longColorInput : shortColorInput
float goal = t.target(targetInput)
string stop = str.tostring(t.stop, format.mintick)
string oneR = str.tostring(t.target(1), format.mintick)
string tp = str.tostring(goal, format.mintick)
label note = textAt(right, t.entry, (t.dir == BULL ? "LONG" : "SHORT") + (riskInput > 0 ? " " + sized(t.qty, t.unitLoss()) : ""), tint)
note.set_tooltip("Entry " + str.tostring(t.entry, format.mintick) + "\nSL " + stop + "\n1R " + oneR + (targetInput > 0 ? "\nTP " + tp : "") + (t.risk() > 0 ? "\nCosts " + inR(-fee(t.entry) / t.risk()) : ""))
t.lines := array.from(line.new(left, t.entry, right, t.entry, color = tint, width = 2))
t.labels := array.from(note)
if targetsInput
t.lines.push(line.new(left, t.stop, right, t.stop, color = lineColorInput, style = line.style_dotted))
t.labels.push(textAt(right, t.stop, pricesInput ? "SL " + stop : "SL", lineColorInput, size.small))
if targetInput == 0 or targetInput > 1
t.lines.push(line.new(left, t.target(1), right, t.target(1), color = lineColorInput, style = line.style_dotted))
t.labels.push(textAt(right, t.target(1), pricesInput ? "1R " + oneR : "1R", lineColorInput, size.small))
if targetInput > 0
t.lines.push(line.new(left, goal, right, goal, color = lineColorInput, style = line.style_dotted))
t.labels.push(textAt(right, goal, pricesInput ? "TP " + tp : "TP", lineColorInput, size.small))
// @function Takes an order or a trade that ended off the active drawing: the stop loss and target lines go, the
// entry line stops where it ended, and its label keeps the side and the outcome.
method finish(Trade t) =>
while t.lines.size() > 1
line.delete(t.lines.pop())
label.delete(t.labels.pop())
t.reach(t.endBar)
t.labels.first().set_text((t.dir == BULL ? "LONG " : "SHORT ") + (na(t.fillBar) ? "no fill" : inR(t.result())))
// ————— Calculations
if not chart.is_standard
runtime.error("Use standard candles. On Heikin Ashi, Renko and similar charts the entry and stop loss prices do not exist in the market.")
if syminfo.mintick * 1e10 < 2
runtime.error("Prices on this symbol are too small: Pine Script treats numbers 0.0000000001 apart or closer as equal. Use a pair quoted per thousand or per million coins.")
if barstate.isfirst
if na(clock(startInput))
runtime.error("Opening range: write the start as 9:30 or 0930.")
if na(clock(lastInput))
runtime.error("Entries until: write the time as 15:45 or 1545.")
if na(clock(retestInput))
runtime.error("Retest until: write the time as 11:15 or 1115.")
if na(clock(flatInput))
runtime.error("Close trades at: write the time as 16:00 or 1600.")
// The range has to be a whole number of the chart's bars.
bool fits = timeframe.isintraday and rangeMinutes * 60 % timeframe.in_seconds() == 0
// A day begins with the first bar at or after the range start, provided it opens before the time trades are
// closed: futures that reopen on a Sunday evening begin Monday at the range start, not at the reopen. A first bar
// that opens after the range has ended begins a day without a range. Such a day takes no trade, but it is the
// previous day of the next one. When the bar before runs through the start, as an hourly bar from 9:00 does with
// a range from 9:30, the range would lack its first minutes, and no day begins.
int start = rangeStart()
bool first = start > time[1] and time < after(start, clock(flatInput))
var bool aligned = true
if first
aligned := time_close[1] <= start
bool newDay = first and aligned
var Day today = na
// What this bar did, for the drawings and the alerts further down.
Day opened = na // day that began
Day formed = na // day whose range completed
Day finished = na // day whose range lines stop here
Trade placed = na // order that was placed
Trade filled = na // order that filled
Trade ended = na // order or trade that ended
// The model runs on closed bars only, so no signal or level depends on a bar that is still forming.
if barstate.isconfirmed and fits
// A flat time that fell into a break in trading ends the day at the last bar before the break.
if not na(today) and na(today.session.right) and time >= today.session.until
if not today.traded()
finished := today
ended := today.closeOut(bar_index - 1)
if newDay
today := begin(today, start)
opened := today
if not na(today)
if na(today.session.right)
today.session.add()
// The order and the trade see this bar first: a signal on its close places an order for the next bar.
Trade t = today.trade
if not na(t) and na(t.endBar)
bool waiting = na(t.fillBar)
t.follow()
if waiting and not na(t.fillBar)
filled := t
if not na(t.endBar)
ended := t
if not na(t.fillBar)
finished := today
Span r = today.opening
if r.grow()
formed := today
if modelInput == Model.drive
if not na(formed) and today.gapped() and (today.outside() or not outsideInput) and (today.withGap() or not withGapInput) and today.inTime(time_close)
int dir = today.gapDir()
placed := today.place(Trade.new(dir, snap((dir == BULL ? r.hi : r.lo) + dir * syminfo.mintick, dir), today.stopFor(dir), today.lastEntry))
else if not na(r.right) and time >= r.until and na(today.breakDir) and na(today.session.right)
int dir = close > r.hi ? BULL : close < r.lo ? BEAR : 0
if dir != 0
today.breakDir := dir
today.breakEnd := time_close
float entry = modelInput == Model.breakout ? close : snap(dir == BULL ? r.hi : r.lo, -dir)
float stop = today.stopFor(dir)
// a range without width leaves a retest no room for its stop loss
if allowed(dir) and today.inTime(time_close) and past(dir, entry, stop)
placed := today.place(Trade.new(dir, entry, stop, modelInput == Model.retest ? today.retestEnd : na))
// The bar that ends at the flat time, or runs through it, ends the day at its close.
if na(today.session.right) and time_close >= today.session.until
if not today.traded()
finished := today
Trade done = today.closeOut(bar_index)
ended := na(done) ? ended : done
// ————— Visuals
// A drawing placed by bar number looks up that bar's time, and Pine settles how much history of `time` it keeps
// while the chart loads. On a live bar that buffer no longer grows, so a line reaching further back than any
// line did in history would stop the script. Reserving the full depth here rules that out.
max_bars_back(time, MAX_BACK)
// The close the opening drive measures its gap from.
if not na(opened) and modelInput == Model.drive and not na(opened.prior.right)
float pdc = opened.prior.cl
line.new(reachable(opened.prior.right), pdc, bar_index, pdc, color = lineColorInput, style = line.style_dotted)
textAt(bar_index, pdc, "PDC", lineColorInput)
if not na(formed)
formed.drawRange()
// An order shows from the close of the bar that places it. A breakout enters at the next open, which is known
// once that bar has closed, so the entry and the targets measured from it may move a little there.
if not na(placed)
placed.draw()
if not na(filled)
filled.draw()
if not na(ended)
ended.finish()
if not na(finished)
for l in finished.lines
l.set_x2(finished.rightEnd())
// The lines of a running day and of its order or open trade reach a little past the newest bar. An end that lies
// behind was set on its own bar and is left alone: a bar far back cannot be reached from here.
if barstate.islast and not na(today)
int end = today.rightEnd()
if end > bar_index
for l in today.lines
l.set_x2(end)
Trade t = today.trade
if not na(t) and na(t.endBar)
t.reach(bar_index + EXTEND)
// The tables take their colours from the chart, so they read on a light background and on a dark one.
color tableText = chart.fg_color
color headColor = color.new(chart.fg_color, 80)
color cellColor = color.new(chart.fg_color, 92)
var table checkTable = table.new(position.bottom_right, 2, 8)
if barstate.islast and checklistInput
checkTable.clear(0, 0, 1, 7)
string status = NO + " Use a " + (clock(startInput) % 5 == 0 and rangeMinutes % 5 == 0 ? "5" : "1") + " minute chart"
if fits and aligned
// While the first bar of a day is still forming, the checklist already shows that day. A chart on which
// no day has begun has no bar between the range start and the time trades are closed.
Day shown = newDay and not barstate.isconfirmed ? begin(today, start) : today
status := na(shown) ? NO + " No bars from " + tidy(startInput) + " to " + tidy(flatInput) + " " + zoneInput : shown.checks()
array<string> rows = str.split(status, "\n")
checkTable.cell(0, 0, "Checklist", text_color = tableText, bgcolor = headColor, text_size = size.tiny, text_halign = text.align_left, text_formatting = text.format_bold)
checkTable.cell(1, 0, "Status", text_color = tableText, bgcolor = headColor, text_size = size.tiny, text_formatting = text.format_bold)
for [k, row] in rows
bool pass = str.startswith(row, YES)
checkTable.cell(0, k + 1, str.substring(row, 2), text_color = tableText, bgcolor = cellColor, text_size = size.tiny, text_halign = text.align_left, text_formatting = text.format_bold)
checkTable.cell(1, k + 1, pass ? YES : NO, text_color = pass ? GREEN : RED, bgcolor = cellColor, text_size = size.tiny)
var table watermark = table.new(position.bottom_center, 1, 1)
if barstate.islast and watermarkInput and fits and aligned
string frame = timeframe.isseconds ? str.tostring(timeframe.multiplier) + "s" : timeframe.multiplier % 60 == 0 ? str.tostring(timeframe.multiplier / 60) + "h" : str.tostring(timeframe.multiplier) + "m"
watermark.cell(0, 0, "ORB(" + frame + ")\n" + syminfo.ticker + "\n" + str.format_time(time, "dd MMM yyyy", zoneInput), text_color = color.new(chart.fg_color, 45), text_size = size.normal, text_font_family = font.family_monospace)
// ————— Alerts
if notices.size() > 0
alert(syminfo.ticker + ": " + notices.join("; "), alert.freq_once_per_bar_close)
alertcondition(not na(placed) and placed.dir == BULL, "Long signal", "{{ticker}}: opening range long signal")
alertcondition(not na(placed) and placed.dir == BEAR, "Short signal", "{{ticker}}: opening range short signal")
alertcondition(not na(ended) and not na(ended.fillBar), "Trade closed", "{{ticker}}: opening range trade closed")