Skip to Content
While25SDK docs
ExamplesStrategies

Patient 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.

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.

Shows: @on.tick, tick bid/ask, Instrument.offset()/ticks_between()/check(), order_type="LMT", orders.modify(), orders.cancel(), @on.order (NEW, FILL, MODIFY_REJECT, CANCEL, CANCEL_REJECT, REJECT).

View on GitHub

strategies/limit_entry_modify_cancel.py
"""Patient 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.

Shows: @on.tick, tick bid/ask, Instrument.offset()/ticks_between()/check(), order_type="LMT", orders.modify(), orders.cancel(), @on.order (NEW, FILL, MODIFY_REJECT, CANCEL, CANCEL_REJECT, REJECT).
"""
import time

import while25
from while25 import Strategy, on
from while25.inputs import Int

KEY = "EQ:US:AAPL"
TAG = "aapl_limit"


def peg_price(inst, bid, ticks_under):
    """The price `ticks_under` ticks below the bid, on the tick grid."""
    return inst.offset(bid, -ticks_under)


def needs_repeg(inst, working, wanted, tolerance):
    """True when the order's price is more than `tolerance` ticks from where
    it should now rest. A price pair the venue cannot count (no tick, or a
    band edge between them) is left alone."""
    apart = inst.ticks_between(working, wanted)
    return apart is not None and abs(apart) > tolerance


def timed_out(placed_at, now, max_wait_s):
    return placed_at is not None and now - placed_at >= max_wait_s


class LimitEntry(Strategy):
    id = "aapl_limit_entry"
    label = "AAPL patient limit entry"
    inputs = [Int("shares", default=10, minimum=1, maximum=10_000),
              Int("ticks_under", default=2, minimum=0, maximum=50,
                  label="Rest this many ticks under the bid"),
              Int("tolerance", default=3, minimum=1, maximum=50,
                  label="Move the order once the bid is this many ticks away"),
              Int("max_wait_s", default=300, minimum=10, maximum=3600)]

    def on_start(self, ctx):
        self.inst = while25.data.instrument(KEY)
        self.order_id = None
        self.price = None
        self.placed_at = None
        self.done = False           # filled, or given up: one attempt per run

    @on.tick(KEY)
    def on_tick(self, ctx, tick):
        if self.done or tick["bid"] is None:    # IBKR sends bid and ask apart
            return
        p = while25.params
        wanted = peg_price(self.inst, tick["bid"], p["ticks_under"])
        if wanted is None:
            return                              # the venue states no tick
        if self.order_id is None:
            self.place(wanted)
        elif timed_out(self.placed_at, time.monotonic(), p["max_wait_s"]):
            while25.orders.cancel(self.order_id)
            self.done = True
        elif needs_repeg(self.inst, self.price, wanted, p["tolerance"]):
            while25.orders.modify(self.order_id, price=wanted)
            self.price = wanted

    def place(self, price):
        qty = while25.params["shares"]
        problem = self.inst.check(quantity=qty, price=price, side="BUY")
        if problem:
            while25.log(f"not placed: {problem}", "warn")
            self.done = True
            return
        res = while25.buy(KEY, qty, order_type="LMT", price=price, tag=TAG)
        self.order_id, self.price, self.placed_at = res["order_id"], price, time.monotonic()

    @on.order(tag=TAG)
    def on_order(self, ctx, ev):
        kind = ev["event"]
        if kind == "NEW":
            while25.log(f"resting {ev['quantity']} at {ev['price']}")
        elif kind == "FILL":
            while25.log(f"filled {ev['last_fill_quantity']} at {ev['last_fill_price']}")
            if ev["status"] == "COMPLETE":
                self.done = True
        elif kind == "MODIFY_REJECT":
            while25.log(f"not moved, still at {self.price}: {ev['reason']}", "warn")
        elif kind == "CANCEL_REJECT":
            while25.log(f"cancel refused, the order still works: {ev['reason']}", "warn")
        elif kind in ("CANCEL", "REJECT"):
            while25.log(f"order ended ({kind}): {ev['reason']}")
            self.done = True