Buy an at-the-money call on a breakout, manage it on its own ticks
When a 15-minute AAPL bar closes above the high of the day's earlier bars, buys the call the description names (ATM by default) for the expiry you set, then follows that contract's own prices to take a profit or cut a loss as a percentage of what was paid. The contract is only known at run time, so its prices are turned on with `subscribe(on_tick=...)`.
When a 15-minute AAPL bar closes above the high of the day's earlier bars, buys the call the description names (ATM by default) for the expiry you set, then follows that contract's own prices to take a profit or cut a loss as a percentage of what was paid. The contract is only known at run time, so its prices are turned on with subscribe(on_tick=...).
Shows: option() from a description, Str input, lot_size, subscribe(on_tick=self.method)/unsubscribe(), SubscriptionError, my_position() average_price, While25Error codes from option().
"""Buy an at-the-money call on a breakout, manage it on its own ticks
When a 15-minute AAPL bar closes above the high of the day's earlier bars,
buys the call the description names (ATM by default) for the expiry you set,
then follows that contract's own prices to take a profit or cut a loss as a
percentage of what was paid. The contract is only known at run time, so its
prices are turned on with `subscribe(on_tick=...)`.
Shows: option() from a description, Str input, lot_size, subscribe(on_tick=self.method)/unsubscribe(), SubscriptionError, my_position() average_price, While25Error codes from option().
"""
from datetime import datetime
from decimal import Decimal
from zoneinfo import ZoneInfo
import while25
from while25 import Bars, Strategy, on
from while25.inputs import Float, Int, Str
UNDERLYING = "EQ:US:AAPL"
NY = ZoneInfo("America/New_York")
TAG = "aapl_call"
def new_session_high(bars):
"""True when the last bar closed above every earlier bar of its New York day."""
if not bars:
return False
day = datetime.fromtimestamp(bars[-1]["time_ms"] / 1000, NY).date()
earlier = [b for b in bars[:-1]
if datetime.fromtimestamp(b["time_ms"] / 1000, NY).date() == day]
return bool(earlier) and bars[-1]["close"] > max(b["high"] for b in earlier)
def exit_reason(paid, last, take_pct, stop_pct):
""""take" at `take_pct` percent over what was paid, "stop" at `stop_pct`
under it, else None. None too while either price is unknown."""
if paid is None or last is None or paid <= 0:
return None
change = (Decimal(str(last)) - Decimal(paid)) / Decimal(paid) * 100
if change >= Decimal(str(take_pct)):
return "take"
if change <= -Decimal(str(stop_pct)):
return "stop"
return None
class AtmCallBreakout(Strategy):
id = "aapl_atm_call"
label = "AAPL call on a breakout"
inputs = [Str("expiry", default="2027-01-15", label="Expiry (YYYY-MM-DD)"),
Str("strike", default="ATM", label="Strike: a price, ATM, ATM+N or ATM-N"),
Int("lots", default=1, minimum=1, maximum=50),
Float("take_pct", default=50.0, minimum=1.0, maximum=500.0),
Float("stop_pct", default=30.0, minimum=1.0, maximum=100.0)]
aapl = Bars(UNDERLYING, "15m", keep=60)
def on_start(self, ctx):
self.contract = None
self.exiting = False
@on.bar(aapl)
def on_bar(self, ctx, bar):
if self.contract is not None or not new_session_high(self.aapl.rows):
return
p = while25.params
try:
c = while25.option("AAPL", expiry=p["expiry"], right="CALL", strike=p["strike"])
except while25.While25Error as e:
# NO_EXPIRY / NO_STRIKE / OFF_THE_LIST name the nearest listed ones.
while25.log(f"no contract ({e.code}): {e.message}", "warn")
return
while25.buy(c["instrument_key"], c["lot_size"] * p["lots"], tag=TAG)
self.contract = c["instrument_key"]
try:
while25.subscribe(self.contract, on_tick=self.on_option)
except while25.SubscriptionError as e:
while25.log(f"cannot follow {c['symbol']}: {e.code}", "error")
while25.log(f"bought {p['lots']} x {c['symbol']} (strike {c['strike']}, "
f"ATM was {c.get('atm_strike')})")
def on_option(self, ctx, tick):
if self.exiting:
return
mine = while25.portfolio.my_position(self.contract)
if not mine or mine["quantity"] <= 0:
return # the entry has not filled yet
p = while25.params
why = exit_reason(mine["average_price"], tick["bid"], p["take_pct"], p["stop_pct"])
if why:
while25.sell(self.contract, mine["quantity"], tag=TAG)
self.exiting = True
while25.log(f"{why}: sold {mine['quantity']} near {tick['bid']}")
@on.order(tag=TAG)
def on_order(self, ctx, ev):
if ev["event"] == "FILL" and ev["side"] == "SELL" and ev["status"] == "COMPLETE":
while25.unsubscribe(self.contract) # its prices and the calls end together
while25.log("out of the call; done for this run")
elif ev["event"] == "REJECT":
while25.log(f"{ev['side']} refused: {ev['reason']}", "error")
self.exiting = FalseDip buyer with an AI second opinion
A monitor watches QQQ's 5-minute bars for a fall of more than a set percent from the window's first close, asks the AI whether it reads as a steady slide or one sharp drop, and signals its strategy only on "drop". The strategy then buys with a bracket. The strategy never asks the AI itself: only a monitor may, and the strategy lists it as its own, so both start and stop together.
Placing an order exactly once, even when the call times out
A TIMEOUT means the order may or may not have been placed. This strategy buys MSFT once a day at a set time and routes the call through `place_once`, which retries a timed-out order under the same idempotency key: if the first attempt went through, the platform answers DUPLICATE_ORDER and nothing is placed twice.