A strategy with its own desk
A SPY pullback strategy (buy a 5-minute close back above the 20-bar average after a bar that dipped below it, in an uptrend) whose panel is its desk: the platform's reconciled figures for the strategy, each entry rule met or not, the price against the stop and target, what happened today, and the bars it decides on. The strategy sends its state after each bar; the desk only shows.
A SPY pullback strategy (buy a 5-minute close back above the 20-bar average after a bar that dipped below it, in an uptrend) whose panel is its desk: the platform's reconciled figures for the strategy, each entry rule met or not, the price against the stop and target, what happened today, and the bars it decides on. The strategy sends its state after each bar; the desk only shows.
Shows: Strategy with desk = App, @on.signal(name, sender=""), ui.strategy_block(capital=), ui.conditions(need=3) / ui.rule (crosses_above with prev=, near=), ui.levels / ui.level, ui.timeline, ui.chart_block, ui.custom, emit().
"""A strategy with its own desk
A SPY pullback strategy (buy a 5-minute close back above the 20-bar average
after a bar that dipped below it, in an uptrend) whose panel is its desk: the
platform's reconciled figures for the strategy, each entry rule met or not,
the price against the stop and target, what happened today, and the bars it
decides on. The strategy sends its state after each bar; the desk only shows.
Shows: Strategy with desk = App, @on.signal(name, sender="<strategy id>"), ui.strategy_block(capital=), ui.conditions(need=3) / ui.rule (crosses_above with prev=, near=), ui.levels / ui.level, ui.timeline, ui.chart_block, ui.custom, emit().
"""
from types import SimpleNamespace
import while25
from while25 import App, Bars, Strategy, on, ui
KEY = "EQ:US:SPY"
TAG = "spy_pullback"
ui.panel("spy_pullback_desk", "SPY pullback")
ui.layout(ui.view("main"))
def sma(values, n):
return None if len(values) < n else sum(values[-n:]) / n
def signals(rows, n=20, trend_n=60):
"""The figures the rules are judged on, from closed bars only. Each is
None while there are too few bars."""
closes = [r["close"] for r in rows]
return {"close": closes[-1] if closes else None,
"prev_close": closes[-2] if len(closes) > 1 else None,
"avg": sma(closes, n), "prev_avg": sma(closes[:-1], n),
"trend": sma(closes, trend_n),
"dipped": len(rows) > 1 and sma(closes[:-1], n) is not None
and rows[-2]["low"] < sma(closes[:-1], n)}
def entry_rules(s):
"""The desk's entry rules, judged by the platform from these figures. A
rule whose figures are not known yet is left out; the block asks for all
three by count, so a left-out rule means "not met", never an error."""
rules = []
if None not in (s["close"], s["prev_close"], s["avg"]):
rules.append(ui.rule("Close vs 20-bar average", s["close"], "crosses_above", s["avg"],
prev=s["prev_close"], near=1.0, unit="pts"))
if None not in (s["avg"], s["trend"]):
rules.append(ui.rule("20-bar vs 60-bar average", s["avg"], ">", s["trend"],
near=2.0, unit="pts"))
rules.append(ui.rule("Previous bar dipped below the average", 1 if s["dipped"] else 0, "==", 1))
return rules
def wants_entry(s):
return (None not in (s["close"], s["prev_close"], s["avg"], s["prev_avg"], s["trend"])
and s["prev_close"] <= s["prev_avg"] and s["close"] > s["avg"]
and s["avg"] > s["trend"] and s["dipped"])
class PullbackDesk(App):
id = "spy_pullback_desk"
label = "SPY pullback desk"
@on.signal("spy_pullback_state", sender="spy_pullback")
def state(self, ctx, payload):
s = SimpleNamespace(**payload)
levels = [ui.level("Stop", s.stop, tone="loss"), ui.level("Target", s.target, tone="profit")] \
if s.stop is not None else [ui.level("20-bar average", s.figures["avg"])]
while25.ui.push("main", {"blocks": [
ui.strategy_block(capital=25_000),
ui.conditions("Entry", entry_rules(s.figures), need=3),
ui.levels(price=s.figures["close"], levels=levels),
ui.timeline([tuple(e) for e in s.events], title="Today"),
ui.chart_block({"kind": "line", "rows": s.chart, "x": "time", "y": ["close", "avg"]},
title="SPY 5m"),
ui.custom("How it works", html="<p>Buys 20 shares when a close crosses back above "
"the 20-bar average after a dip below it, while that average is above "
"the 60-bar one. A bracket holds the stop and target.</p>"),
]})
class SpyPullback(Strategy):
id = "spy_pullback"
label = "SPY pullback"
desk = PullbackDesk
spy = Bars(KEY, "5m", keep=120)
def on_start(self, ctx):
self.inst = while25.data.instrument(KEY)
self.events, self.stop, self.target = [], None, None
@on.bar(spy)
def on_bar(self, ctx, bar):
rows = self.spy.rows
s = signals(rows)
mine = while25.portfolio.my_position(KEY)
if wants_entry(s) and not (mine and mine["brackets"]):
risk = s["close"] - min(r["low"] for r in rows[-3:])
self.stop = self.inst.snap(s["close"] - risk, mode="down")
self.target = self.inst.snap(s["close"] + 2 * risk, mode="up")
while25.bracket(KEY, "BUY", 20, stop_loss=self.stop, take_profit=self.target, tag=TAG)
self.events.append((bar["time_ms"], f"bought 20 near {s['close']}", "active"))
closes = [r["close"] for r in rows]
chart = [{"time": r["time_ms"], "close": r["close"], "avg": sma(closes[:i + 1], 20)}
for i, r in enumerate(rows)][-60:]
while25.emit("spy_pullback_state", {
"figures": s, "events": self.events[-20:], "chart": chart,
"stop": None if self.stop is None else float(self.stop),
"target": None if self.target is None else float(self.target)})
@on.order(tag=TAG)
def on_order(self, ctx, ev):
if ev["event"] == "FILL" and ev["status"] == "COMPLETE" and ev["side"] == "SELL":
self.events.append((ev["timestamp_ms"], f"out at {ev['average_price']}", "attention"))
self.stop = self.target = NoneQuote recorder: a long-running loop that writes a CSV
Samples the quotes of a few ETFs once a second during regular hours and appends them to a CSV in the workspace, one file per day, with a small panel that shows how many rows it has written. A `run()` loop is the escape hatch for work the decorators do not cover; it checks `alive()` every pass so it stops the moment it is asked to.
One strategy, two fill assumptions, side by side
A dip-buying limit order on AAPL (buy 1% under the previous close, sell at that day's close) is very sensitive to whether a limit fills when the price merely touches it or only when it trades through. This runs the same logic under both and pushes the two sealed results into one panel, so the gap between them is the first thing you see.