Monitors
Code that watches the market and notifies you, including asking the AI.
A Monitor watches and tells you. It reads everything a strategy reads and
is woken the same way, and it can never place, change or cancel an order:
every order call raises OrderRightsError.
import while25
from while25 import Monitor, on
class BreakoutWatch(Monitor):
id = "breakout_watch"
label = "Breakout watch"
def on_start(self, ctx):
self.rows = list(while25.warmup("EQ:US:SPY", "5m", 20)) # the 20 bars before now
@on.bar("EQ:US:SPY", "5m")
def bar(self, ctx, bar):
high = max(r["high"] for r in self.rows) # the 20 bars before this one
self.rows = (self.rows + [bar])[-20:]
if bar["close"] > high:
while25.notify(f"closed at {bar['close']}, above the 20-bar high {high}",
title="SPY breakout", level="warn", symbol="EQ:US:SPY")It keeps its own window of bars, started from warmup() (see "Warm-up"): the
live series may hold no bars from before the module started.
Press Start on the file in the Code Editor, or on its row in the Monitors panel; Stop is in the same two places. There is no Deploy window, because nothing it does can trade. The Monitors panel lists every monitor, whether it runs, and what scripts have said. The AI chat can write a monitor and stop one; it cannot start one. You press Start.
Every notice and every AI question with its answer is also kept on this computer, in full and with its time, one CSV file a day: Open log folder in the Monitors panel. The data sent with a question is not kept.
One monitor can watch many symbols: several @on.bar or @on.tick lines, or
while25.subscribe(key, on_tick=self.method) for symbols known only while
running. Each running module is its own process, so write one monitor over
twenty symbols, not twenty monitors. A monitor is not started again when the
app restarts: start it by hand.
Asking the AI: while25.ai.ask
A monitor can ask the AI one question about what it found, and act on the answer:
@on.bar("EQ:US:SPY", "5m")
def bar(self, ctx, bar):
high = max(r["high"] for r in self.rows)
self.rows = (self.rows + [bar])[-20:]
if bar["close"] <= high:
return # the free check: most bars end here
verdict = while25.ai.ask(
"Is this a clean breakout or a likely fakeout? The last row is the breakout bar.",
data=self.rows, choices=["breakout", "fakeout"])
if verdict == "breakout":
while25.notify("clean breakout above the 20-bar high", title="SPY",
level="warn", symbol="EQ:US:SPY")while25.ai.ask(question, *, data=None, choices=None, timeout=60, then=None, tag=None)
question: at most 4,000 characters.data: what the AI should read with it: text, or rows and figures (sent as JSON), at most 32 KiB. The AI sees only the question and this. It has no tools and cannot look anything up, so send what it needs.choices: two to ten words. The answer is then exactly one of them, as written here.timeout: seconds an answer may take, 5 to 120.then: one of the monitor's own methods, to ask and carry on (below).tag: withthen, comes back with the answer: text, a number, or a list or dict of them, at most 1,000 characters as JSON.
Ask and wait (no then, as above): returns the answer as text, or None
when there is none. It blocks: the monitor's other handlers wait until it
returns. Right for a monitor that watches one symbol.
Ask and carry on (then=self.method): returns at once, True when the
question was asked and False when it could not be. The answer comes later
as one call of method(ctx, answer, tag), with answer None when there
was none. Right for a monitor over many symbols: each one that fires asks
without waiting for the one before.
SYMBOLS = ["EQ:US:AAPL", "EQ:US:MSFT", "EQ:US:NVDA"]
class BreakoutWatch(Monitor):
id = "breakout_watch"
def on_start(self, ctx):
self.rows = {s: list(while25.warmup(s, "5m", 20)) for s in SYMBOLS}
@on.bar("EQ:US:AAPL", "5m")
@on.bar("EQ:US:MSFT", "5m")
@on.bar("EQ:US:NVDA", "5m")
def bar(self, ctx, bar):
key = bar["symbol"]
high = max(r["high"] for r in self.rows[key])
self.rows[key] = (self.rows[key] + [bar])[-20:]
if bar["close"] <= high:
return
while25.ai.ask("Is this a clean breakout or a likely fakeout? The last row is the breakout bar.",
data=self.rows[key], choices=["breakout", "fakeout"],
then=self.judged, tag=key)
def judged(self, ctx, answer, tag):
if answer == "breakout": # the market has moved since the question: check again here if it matters
while25.notify("clean breakout above the 20-bar high", title=tag, level="warn", symbol=tag)A monitor may have 20 questions out at once; the app sends three at a time and the rest wait their turn. When a monitor is stopped, answers still on the way are dropped.
No answer (None, or False when the question never left) is never a raise,
and the console says why: the allowance for monitor questions is used up, the
AI is off or cannot be reached, too many questions are out, or no answer came
in time. A call that could never work raises ValueError or TypeError (no
question, too much data, bad choices, a then that is not one of the
monitor's own methods, a tag without then).
Only a Monitor may ask. From a Strategy, an App or an Indicator it
raises While25Error (code AI_NOT_ALLOWED), and a one-off Run cannot ask:
a module that may trade never asks the AI.
The app asks for the monitor, with your sign-in, apart from the AI chat: a question never interrupts the chat, and it is counted on the monitors' own share of your plan's AI limits (its cost is also part of the day's total). The app tells you when 80% of the day's allowance is gone and again when it is used up; from then until the next day's starts (midnight UTC) a question gets no answer. Decide whether to ask in Python, as above: that check costs nothing. The Monitors panel's AI questions list shows each question and its answer.
A monitor inside a strategy
A strategy never asks the AI. A monitor asks, and sends the strategy a signal. The strategy lists the monitor as its own:
import while25
from while25 import Bars, Monitor, Strategy, on
class DipWatch(Monitor):
id = "dip_watch"
aapl = Bars("EQ:US:AAPL", "5m", keep=20)
@on.bar(aapl)
def bar(self, ctx, bar):
if bar["close"] > 0.97 * self.aapl.rows[0]["close"]:
return # your own condition: most bars end here
while25.ai.ask("Is this fall a steady slide or one sharp drop? The rows are 5-minute bars.",
data=self.aapl.rows, choices=["slide", "drop"], then=self.judged)
def judged(self, ctx, answer, tag):
if answer == "drop": # None (no answer) sends nothing
while25.emit("dip_ok", {"close": self.aapl.last["close"]})
class DipBuyer(Strategy):
id = "dip_buyer"
monitors = [DipWatch] # its own: starts and stops with it
@on.signal("dip_ok", sender=DipWatch) # hears DipWatch, and nobody else
def go(self, ctx, payload):
while25.buy("EQ:US:AAPL", 10)Give it its panel in the same file too: see "A strategy's panel: its desk".
monitors lists Monitor classes, so the monitor is written (or imported)
above the strategy. Which file a monitor sits in decides nothing: one that no
strategy lists is nobody's. Only a Strategy or a trading App may list
any, and anything in the list that is not a Monitor class with an id is
refused when the file is saved.
- Deploy starts both, Stop stops both. Deploying the strategy starts the monitors it lists, on the same code; when the strategy stops or halts, they stop. A trading App has the monitors its own class lists and those its Strategy classes list.
- The Deploy window has a box to tick: the AI can be wrong, may give no answer, sees only what the monitor sends, and an order placed on its signal is a real order. A strategy that lists a monitor is not deployed until the box is ticked. It is asked at every deploy.
- Its signals reach its own strategy and no other module that trades.
- Settings: the monitor starts with the strategy's value for every input the two declare under the same name; its other inputs keep their defaults.
- If the monitor stops on an error, the strategy keeps running and no signal comes. The app says so; start the monitor again from the Monitors panel, where it is listed as part of its strategy.
- A backtest starts no monitor: no signal arrives there, and nothing asks the AI.
A monitor no strategy lists can signal a strategy too: only one deployed
with the box ticked, which the Deploy window offers when the strategy has an
@on.signal. Not ticked, the strategy deploys and no monitor's signal
reaches it. You start and stop such a monitor yourself.