Skip to Content
While25SDK docs
ExamplesStrategies

Scale-in strategy that survives a restart

Buys SPY in up to three equal tranches, each a set percent below the first entry, and sells everything once the price is back a set percent above the average cost. Its plan (the first entry and how many tranches are in) is saved in a file on every change and on stop; on start it reads the file back and checks it against what the platform says this strategy holds, which wins.

Buys SPY in up to three equal tranches, each a set percent below the first entry, and sells everything once the price is back a set percent above the average cost. Its plan (the first entry and how many tranches are in) is saved in a file on every change and on stop; on start it reads the file back and checks it against what the platform says this strategy holds, which wins.

Shows: on_start / on_stop, a JSON state file in data/, portfolio.my_position() kept across a restart, orders.mine() in on_stop, while25.alive(), @on.tick ltp.

View on GitHub

strategies/scale_in_with_restart.py
"""Scale-in strategy that survives a restart

Buys SPY in up to three equal tranches, each a set percent below the first
entry, and sells everything once the price is back a set percent above the
average cost. Its plan (the first entry and how many tranches are in) is saved
in a file on every change and on stop; on start it reads the file back and
checks it against what the platform says this strategy holds, which wins.

Shows: on_start / on_stop, a JSON state file in data/, portfolio.my_position() kept across a restart, orders.mine() in on_stop, while25.alive(), @on.tick ltp.
"""
import json
from decimal import Decimal
from pathlib import Path

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

KEY = "EQ:US:SPY"
TAG = "spy_scale_in"
STATE = Path("data/scale_in_state.json")


def next_action(state, held, price, step_pct, exit_pct, tranches):
    """"buy", "sell" or None for this price, given the saved plan and the
    shares this strategy holds."""
    first, done = state.get("first"), state.get("done", 0)
    if held == 0:
        return "buy" if first is None else None
    avg = state.get("avg")
    if avg and price >= avg * (1 + exit_pct / 100):
        return "sell"
    if first and done < tranches and price <= first * (1 - step_pct * done / 100):
        return "buy"
    return None


def reconcile(state, held):
    """The plan as the platform's count allows: holding nothing means no plan.
    A file from before a square off, or from another run, cannot buy again."""
    return {} if held == 0 else state


def load(path=STATE):
    try:
        return json.loads(path.read_text())
    except (FileNotFoundError, ValueError):
        return {}


def save(state, path=STATE):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(state))


class ScaleIn(Strategy):
    id = "spy_scale_in"
    label = "SPY scale-in, restart-safe"
    inputs = [Int("shares", default=10, minimum=1, maximum=10_000, label="Shares per tranche"),
              Int("tranches", default=3, minimum=1, maximum=10),
              Float("step_pct", default=1.0, minimum=0.1, maximum=20.0, step=0.1),
              Float("exit_pct", default=1.0, minimum=0.1, maximum=20.0, step=0.1)]

    def held(self):
        mine = while25.portfolio.my_position(KEY)
        return mine["quantity"] if mine else Decimal(0)

    def on_start(self, ctx):
        self.state = reconcile(load(), self.held())
        self.busy = False                   # an order is out: wait for its fill
        while25.log(f"starting with {self.held()} held, plan {self.state or 'empty'}")

    @on.tick(KEY)
    def on_tick(self, ctx, tick):
        if self.busy or tick["ltp"] is None or not while25.alive():
            return
        p = while25.params
        held = self.held()
        act = next_action(self.state, held, tick["ltp"], p["step_pct"], p["exit_pct"], p["tranches"])
        if act == "buy":
            while25.buy(KEY, p["shares"], tag=TAG)
            self.busy = True
        elif act == "sell":
            while25.sell(KEY, held, tag=TAG)
            self.busy = True

    @on.fill(tag=TAG)
    def on_fill(self, ctx, ev):
        if ev["status"] != "COMPLETE":
            return
        self.busy = False
        if ev["side"] == "SELL":
            self.state = {}
        else:
            mine = while25.portfolio.my_position(KEY)
            self.state.setdefault("first", float(ev["average_price"]))
            self.state["done"] = self.state.get("done", 0) + 1
            self.state["avg"] = float(mine["average_price"]) if mine and mine["average_price"] else None
        save(self.state)

    @on.order(tag=TAG)
    def on_order(self, ctx, ev):
        if ev["event"] in ("REJECT", "CANCEL"):
            self.busy = False
        elif ev["event"] == "POSITION_SQUARED_OFF":
            self.state = reconcile(self.state, self.held())
            save(self.state)

    def on_stop(self, ctx):
        # Two seconds, no orders: save, and say what is still working.
        save(self.state)
        working = [f"{o['side']} {o['quantity']} {o['order_type']}" for o in while25.orders.mine(KEY)]
        while25.log(f"stopped holding {self.held()}; working: {working or 'nothing'}")