Skip to Content
While25SDK docs
ExamplesStrategies

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().

View on GitHub

strategies/idempotent_retry.py
"""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 ''}")