Weekly dollar-amount buys
Buys a fixed dollar amount of one ETF (SPY by default) once a week, on the weekday you pick, during regular hours. The order is sized by `amount=`, so the broker decides the shares; where the broker takes no amount for that instrument it falls back to whole shares from the last price. The week it last bought is kept in a file, so a restart never buys twice.
Buys a fixed dollar amount of one ETF (SPY by default) once a week, on the weekday you pick, during regular hours. The order is sized by amount=, so the broker decides the shares; where the broker takes no amount for that instrument it falls back to whole shares from the last price. The week it last bought is kept in a file, so a restart never buys twice.
Shows: Symbol, Float and Enum inputs, @on.schedule, market.is_open(), amount=, AMOUNT_NOT_TAKEN, quote(), the COMPLETE event, a state file in data/.
"""Weekly dollar-amount buys
Buys a fixed dollar amount of one ETF (SPY by default) once a week, on the
weekday you pick, during regular hours. The order is sized by `amount=`, so
the broker decides the shares; where the broker takes no amount for that
instrument it falls back to whole shares from the last price. The week it last
bought is kept in a file, so a restart never buys twice.
Shows: Symbol, Float and Enum inputs, @on.schedule, market.is_open(), amount=, AMOUNT_NOT_TAKEN, quote(), the COMPLETE event, a state file in data/.
"""
import json
from datetime import datetime
from decimal import ROUND_FLOOR, Decimal
from pathlib import Path
from zoneinfo import ZoneInfo
import while25
from while25 import Strategy, on
from while25.inputs import Enum, Float, Symbol
NY = ZoneInfo("America/New_York")
TAG = "weekly_buy"
STATE = Path("data/weekly_cash_buys.json")
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
def week_of(day):
"""An ISO week label such as "2026-W48": one buy per label."""
y, w, _ = day.isocalendar()
return f"{y}-W{w:02d}"
def due(now, weekday, last_week):
"""True on the chosen weekday of a week with no buy yet."""
return now.strftime("%A") == weekday and week_of(now.date()) != last_week
def whole_shares(dollars, last_price, step):
"""Whole steps of shares that `dollars` buys at `last_price` (0 if none)."""
if not last_price or last_price <= 0:
return Decimal(0)
step = step or Decimal(1)
raw = Decimal(str(dollars)) / Decimal(str(last_price))
return (raw / step).to_integral_value(rounding=ROUND_FLOOR) * step
def load_state(path=STATE):
try:
return json.loads(path.read_text())
except (FileNotFoundError, ValueError):
return {}
def save_state(state, path=STATE):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(state, indent=2))
class WeeklyCashBuys(Strategy):
id = "weekly_cash_buys"
label = "Weekly dollar-amount buys"
inputs = [Symbol("symbol", default="EQ:US:SPY", label="What to buy"),
Float("dollars", default=500.0, minimum=1.0, label="Dollars per week"),
Enum("weekday", choices=DAYS, default="Monday")]
def on_start(self, ctx):
self.key = while25.params["symbol"]
self.state = load_state()
@on.schedule(every="15m")
def check(self, ctx):
p = while25.params
now = datetime.now(NY)
if not due(now, p["weekday"], self.state.get("last_week")):
return
if while25.market.is_open(self.key) is not True:
return # closed, or cannot tell: try next pass
try:
while25.buy(self.key, amount=p["dollars"], tag=TAG)
except while25.While25Error as e:
if e.code != "AMOUNT_NOT_TAKEN":
raise
self.buy_whole_shares(p["dollars"])
# Written as soon as the order is accepted: a restart this week
# finds the week done and buys nothing more.
self.state["last_week"] = week_of(now.date())
save_state(self.state)
def buy_whole_shares(self, dollars):
q = while25.quote(self.key)
step = while25.data.instrument(self.key).step
qty = whole_shares(dollars, q and q["ltp"], step)
if qty > 0:
while25.buy(self.key, qty, tag=TAG)
else:
while25.log(f"${dollars} buys no whole share at {q and q['ltp']}", "warn")
@on.order(tag=TAG)
def on_order(self, ctx, ev):
# An order by amount always ends on COMPLETE, after its last FILL.
if ev["event"] == "COMPLETE" or (ev["event"] == "FILL" and ev["status"] == "COMPLETE"):
while25.log(f"bought {ev['filled_quantity']} {ev['symbol']} at "
f"{ev['average_price']} on average")
elif ev["event"] == "REJECT":
while25.log(f"buy refused: {ev['reason']}", "error")Two strategies on one instrument, one account
A slow trend strategy and a fast mean-reversion strategy both trade NVDA. The broker nets their fills into one position, but each strategy keeps its own part: each tags its orders, listens only to its own tag, and sizes every exit from `my_position()`, never from the account's `position()`. Each also reads its part again when the whole position is squared off.
Keltner channel: an average with a band of average true ranges
An exponential average of the close, with an upper and a lower line a multiple of the average true range away, the space between them shaded. It draws on the price itself, and the breakout strategy in `strategies/keltner_breakout.py` reads the same numbers from its own bars.