Opening-range breakout with a bracket order
Buys NVDA when a 5-minute bar closes above the first 30 minutes' high, with a stop at the range's low and a target two ranges up, moves the stop to break-even once the trade is one range in profit, and squares off at 15:55 New York time. Use it as the template for any intraday bracket strategy.
Buys NVDA when a 5-minute bar closes above the first 30 minutes' high, with a stop at the range's low and a target two ranges up, moves the stop to break-even once the trade is one range in profit, and squares off at 15:55 New York time. Use it as the template for any intraday bracket strategy.
Shows: @on.bar, warmup(), data.instrument() snap/step, bracket(), the "-SL" stop id, orders.modify(), @on.order (HELD, MODIFY, FILL, SQUARE_OFF), @on.schedule, orders.square_off().
"""Opening-range breakout with a bracket order
Buys NVDA when a 5-minute bar closes above the first 30 minutes' high, with a
stop at the range's low and a target two ranges up, moves the stop to
break-even once the trade is one range in profit, and squares off at 15:55
New York time. Use it as the template for any intraday bracket strategy.
Shows: @on.bar, warmup(), data.instrument() snap/step, bracket(), the "-SL" stop id, orders.modify(), @on.order (HELD, MODIFY, FILL, SQUARE_OFF), @on.schedule, orders.square_off().
"""
from datetime import datetime, time
from decimal import ROUND_FLOOR, Decimal
from zoneinfo import ZoneInfo
import while25
from while25 import Strategy, on
from while25.inputs import Float, Int
KEY = "EQ:US:NVDA"
NY = ZoneInfo("America/New_York")
OPEN, FLAT_AT = time(9, 30), time(15, 55)
TAG = "orb"
def ny_time(t_ms):
return datetime.fromtimestamp(t_ms / 1000, NY)
def todays_bars(bars, day):
"""The regular-session bars whose start falls on New York date `day`."""
return [b for b in bars if ny_time(b["time_ms"]).date() == day]
def opening_range(bars, minutes):
"""(high, low) of the bars that start in the first `minutes` after 9:30,
or None until a bar past that window has closed (the range is not done)."""
end = OPEN.hour * 60 + OPEN.minute + minutes
inside = [b for b in bars if _minute(b) < end]
if not inside or not any(_minute(b) >= end for b in bars):
return None
return max(b["high"] for b in inside), min(b["low"] for b in inside)
def _minute(bar):
t = ny_time(bar["time_ms"])
return t.hour * 60 + t.minute
def bracket_levels(inst, entry, high, low, reward):
"""(stop, target) on the venue's tick grid: the stop at the range's low
(rounded down), the target `reward` ranges above the entry (rounded up)."""
stop = inst.snap(low, mode="down")
target = inst.snap(entry + reward * (high - low), mode="up")
return stop, target
def shares_for(risk_usd, entry, stop, step):
"""Whole steps of shares whose loss at the stop is at most `risk_usd`."""
per_share = Decimal(str(entry)) - Decimal(stop)
if per_share <= 0:
return Decimal(0)
raw = Decimal(str(risk_usd)) / per_share
step = step or Decimal(1)
return (raw / step).to_integral_value(rounding=ROUND_FLOOR) * step
class OpeningRangeBreakout(Strategy):
id = "nvda_orb"
label = "NVDA opening-range breakout"
inputs = [Int("range_minutes", default=30, minimum=5, maximum=120, step=5),
Float("risk_usd", default=200.0, minimum=10.0, label="Risk per trade ($)"),
Float("reward", default=2.0, minimum=0.5, maximum=10.0, step=0.5)]
def on_start(self, ctx):
self.inst = while25.data.instrument(KEY)
# Today's bars so far, in case the strategy starts after the open.
# 78 five-minute bars are one regular session.
self.bars = list(while25.warmup(KEY, "5m", 78))
self.day = None
self.entry_id = None # the bracket's id: also its square-off id
self.entry_price = None # the entry's average fill
self.range = None
self.at_break_even = False
@on.bar(KEY, "5m")
def on_bar(self, ctx, bar):
day = ny_time(bar["time_ms"]).date()
if day != self.day: # a new session: forget yesterday
self.day, self.entry_id, self.entry_price = day, None, None
self.at_break_even = False
self.bars = todays_bars(self.bars + [bar], day)
p = while25.params
rng = opening_range(self.bars, p["range_minutes"])
if rng is None:
return
high, low = rng
if self.entry_id is None and bar["close"] > high and ny_time(bar["time_ms"]).time() < FLAT_AT:
self.enter(bar["close"], high, low)
elif self.entry_price is not None and not self.at_break_even \
and bar["close"] >= self.entry_price + (Decimal(str(high)) - Decimal(str(low))):
# One range in profit: the stop goes to the entry price.
while25.orders.modify(self.entry_id + "-SL", trigger_price=self.entry_price)
self.at_break_even = True
def enter(self, close, high, low):
stop, target = bracket_levels(self.inst, close, high, low, while25.params["reward"])
qty = shares_for(while25.params["risk_usd"], close, stop, self.inst.step)
problem = self.inst.check(quantity=qty) if qty > 0 else "the risk buys no share"
if problem:
while25.log(f"no entry: {problem}", "warn")
self.entry_id = "skipped"
return
res = while25.bracket(KEY, "BUY", qty, stop_loss=stop, take_profit=target, tag=TAG)
self.entry_id = res["order_id"]
while25.log(f"entered {qty} above {high}: stop {stop}, target {target}")
@on.order(tag=TAG)
def on_order(self, ctx, ev):
if ev["order_id"] == self.entry_id and ev["event"] == "FILL":
self.entry_price = ev["average_price"]
elif ev["event"] == "HELD":
while25.log(f"stop set at {ev['trigger_price']} for {ev['quantity']}")
elif ev["event"] == "MODIFY":
while25.log(f"stop now at {ev['trigger_price']}")
elif ev["event"] == "MODIFY_REJECT":
while25.log(f"stop not moved: {ev['reason']}", "warn")
self.at_break_even = False
elif ev["event"] == "SQUARE_OFF":
while25.log(f"square off {ev['status']}: {ev['reason']}")
@on.schedule(every="1m")
def flat_by_close(self, ctx):
now = datetime.now(NY)
if self.entry_price is not None and now.time() >= FLAT_AT and self.day == now.date():
try:
while25.orders.square_off(self.entry_id)
except while25.While25Error as e:
if e.code not in ("NO_BRACKET", "NOTHING_HELD"): # already out: nothing to do
raise
self.entry_price = NonePatient limit entry: work a bid, follow it, give up in time
Rests a limit buy for AAPL a few ticks under the bid, moves it when the bid walks away by more than a set number of ticks, and cancels it if it has not filled within a time limit. Every price is put on the venue's tick grid before it is sent, so nothing is refused for an off-grid price.
Risk-sized stop-limit entry from the account's buying power
Each day MSFT closes above its 50-day average, rests a stop-limit buy just above that day's high, with a protective stop under its low. The share count risks a fixed fraction of the money the broker says is available for a new trade, and is checked against the venue's size and tick rules before anything is sent. When the broker states no such figure, it does not trade.