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.
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.
Shows: idempotency_key=, While25Error.code / .idempotency_key, TIMEOUT, DUPLICATE_ORDER, BUSY, @on.schedule, orders.mine().
"""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.
Shows: idempotency_key=, While25Error.code / .idempotency_key, TIMEOUT, DUPLICATE_ORDER, BUSY, @on.schedule, orders.mine().
"""
import time
from datetime import datetime
from zoneinfo import ZoneInfo
import while25
from while25 import Strategy, on
from while25.inputs import Int
KEY = "EQ:US:MSFT"
NY = ZoneInfo("America/New_York")
TAG = "msft_daily"
def place_once(send, key, *, tries=3, pause_s=1.0, sleep=time.sleep):
"""Call `send(idempotency_key)` until While25 answers for certain.
Returns the placement's answer, or None when DUPLICATE_ORDER says an
earlier attempt under this key was already accepted (watch @on.order for
it). TIMEOUT retries under the key the error carries; BUSY waits and
retries; every other refusal raises."""
for attempt in range(tries):
try:
return send(key)
except while25.While25Error as e:
if e.code == "DUPLICATE_ORDER":
return None
if e.code == "TIMEOUT":
key = e.idempotency_key or key # the key it really went out with
elif e.code != "BUSY":
raise
if attempt == tries - 1:
raise
sleep(pause_s * (attempt + 1))
return None
def order_key(day, strategy_id=TAG):
"""One key per trading day: a second run the same day cannot buy again."""
return f"{strategy_id}-{day.isoformat()}"
class OnceADay(Strategy):
id = "msft_once_a_day"
label = "MSFT once a day, exactly once"
inputs = [Int("shares", default=5, minimum=1, maximum=10_000),
Int("hour", default=10, minimum=9, maximum=15, label="Buy at this hour (New York)")]
def on_start(self, ctx):
self.bought_on = None
@on.schedule(every="1m")
def tick(self, ctx):
now = datetime.now(NY)
if now.hour != while25.params["hour"] or self.bought_on == now.date():
return
if while25.market.is_open(KEY) is not True:
return
qty = while25.params["shares"]
res = place_once(lambda k: while25.buy(KEY, qty, tag=TAG, idempotency_key=k),
order_key(now.date()))
self.bought_on = now.date()
if res is None:
working = [o["order_id"] for o in while25.orders.mine(KEY) if o["tag"] == TAG]
while25.log(f"already placed today; working: {working or 'none'}")
else:
while25.log(f"placed {res['order_id']}")
@on.order(tag=TAG)
def on_order(self, ctx, ev):
if ev["event"] in ("FILL", "REJECT", "CANCEL"):
while25.log(f"{ev['event']} {ev['order_id']}: {ev['reason'] or ''}")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=...)`.
Index futures trend with a manual roll
Trades one S&P 500 or Nasdaq-100 futures contract (ES, MES, NQ or MNQ) with the hourly trend: long above the 20-hour average, flat below, always with a bracket stop a few average true ranges away. `future()` names the contract the chart's continuous line is on now; when that moves to the next month, the strategy closes the old contract and opens the new one itself. A redeploy picks its bracket back up from `my_positions()`.