SPY bull call spread as one order
Once a day at a set time, if SPY is above its 20-day average, buys the at-the-money call and sells the call a few strikes higher as ONE combo at a limit built from each leg's mid price. An unfilled combo is cancelled whole after a few minutes; a filled one is squared off whole if SPY closes a 15-minute bar below the long strike.
Once a day at a set time, if SPY is above its 20-day average, buys the at-the-money call and sells the call a few strikes higher as ONE combo at a limit built from each leg's mid price. An unfilled combo is cancelled whole after a few minutes; a filled one is squared off whole if SPY closes a 15-minute bar below the long strike.
Shows: option(), leg(..., price=), combo(order_type="LMT", name=, tag=), combo_id, cancel(combo_id), orders.square_off(combo_id), SQUARE_OFF events, subscribe() without a handler, quotes().
"""SPY bull call spread as one order
Once a day at a set time, if SPY is above its 20-day average, buys the
at-the-money call and sells the call a few strikes higher as ONE combo at a
limit built from each leg's mid price. An unfilled combo is cancelled whole
after a few minutes; a filled one is squared off whole if SPY closes a
15-minute bar below the long strike.
Shows: option(), leg(..., price=), combo(order_type="LMT", name=, tag=), combo_id, cancel(combo_id), orders.square_off(combo_id), SQUARE_OFF events, subscribe() without a handler, quotes().
"""
import time
from datetime import datetime
from decimal import Decimal
from zoneinfo import ZoneInfo
import while25
from while25 import Bars, Strategy, on
from while25.inputs import Int, Str
SPY = "EQ:US:SPY"
NY = ZoneInfo("America/New_York")
TAG = "spy_bcs"
def mid(inst, quote):
"""The bid/ask midpoint on the contract's tick, or None without both sides."""
if not quote or quote["bid"] is None or quote["ask"] is None:
return None
return inst.snap((quote["bid"] + quote["ask"]) / 2)
def net_debit(buy_price, sell_price):
"""What one spread costs per share: the bought leg's limit less the sold one's."""
return Decimal(buy_price) - Decimal(sell_price)
class BullCallSpread(Strategy):
id = "spy_bull_call_spread"
label = "SPY bull call spread"
inputs = [Str("expiry", default="2027-01-15", label="Expiry (YYYY-MM-DD)"),
Int("width", default=5, minimum=1, maximum=30, label="Short call, strikes above ATM"),
Int("lots", default=1, minimum=1, maximum=50),
Int("hour", default=10, minimum=9, maximum=15),
Int("fill_wait_s", default=180, minimum=30, maximum=1800)]
daily = Bars(SPY, "1D", keep=30)
bars = Bars(SPY, "15m", keep=10)
def on_start(self, ctx):
self.combo_id, self.placed_at, self.long_strike = None, None, None
self.filled, self.done_on = False, None
@on.schedule(every="30s")
def open_or_tidy(self, ctx):
now = datetime.now(NY)
if self.combo_id and not self.filled and time.monotonic() - self.placed_at > \
while25.params["fill_wait_s"]:
while25.orders.cancel(self.combo_id) # every leg still working, whole
self.combo_id = None
return
if self.combo_id or self.done_on == now.date() or now.hour != while25.params["hour"]:
return
closes = self.daily.closes
if len(closes) < 20 or closes[-1] <= sum(closes[-20:]) / 20:
return
self.done_on = now.date()
self.open_spread()
def open_spread(self):
p = while25.params
long_c = while25.option("SPY", p["expiry"], "CALL", "ATM")
short_c = while25.option("SPY", p["expiry"], "CALL", f"ATM+{p['width']}")
keys = [long_c["instrument_key"], short_c["instrument_key"]]
for k in keys:
while25.subscribe(k) # prices only, no handler
time.sleep(2) # let the first quotes land
q_long, q_short = while25.quotes(keys)
buy_px = mid(while25.data.instrument(keys[0]), q_long)
sell_px = mid(while25.data.instrument(keys[1]), q_short)
if buy_px is None or sell_px is None:
while25.log("no two-sided quote on a leg: no spread today", "warn")
return
legs = [while25.leg(long_c, "BUY", price=buy_px),
while25.leg(short_c, "SELL", price=sell_px)]
res = while25.combo(legs, lots=p["lots"], order_type="LMT",
name="SPY bull call", tag=TAG)
self.combo_id, self.placed_at = res["combo_id"], time.monotonic()
self.long_strike = long_c["strike"]
while25.log(f"spread {long_c['strike']}/{short_c['strike']} for "
f"{net_debit(buy_px, sell_px)} debit, as one order: {res['one_order']}")
@on.bar(bars)
def guard(self, ctx, bar):
if self.filled and self.combo_id and bar["close"] < self.long_strike:
while25.orders.square_off(self.combo_id) # the whole spread, at market
@on.fill(tag=TAG)
def on_fill(self, ctx, ev):
if ev["combo_id"] == self.combo_id:
self.filled = True
while25.log(f"{ev['symbol']} {ev['side']} {ev['last_fill_quantity']} "
f"@ {ev['last_fill_price']}")
@on.order(tag=TAG)
def on_order(self, ctx, ev):
if ev["event"] == "SQUARE_OFF" and ev["combo_id"] == self.combo_id:
while25.log(f"square off {ev['status']}: {ev['reason']}")
if ev["status"] in ("SENT", "DONE"):
self.combo_id, self.filled = None, FalseMoving-average trend on a Bars line
Holds MSFT while its fast average is above its slow one and is flat otherwise, deciding on each closed hourly bar. The `Bars` line arrives warmed up, so the first decision already has its history; exits are sized from what this strategy holds, never from the account.
Daily breakout with a trailing-stop exit
Buys AAPL when a daily bar closes above the highest high of the bars before it, and on the fill puts a trailing stop under the position, a few average true ranges away. The stop can be held by While25 or, where the broker holds trailing stops (IBKR), by the broker, so it works while the computer sleeps.