Skip to Content
While25SDK docs
ExamplesMonitors

Price alerts on symbols picked in the settings

Three symbol settings and a percent: whichever symbols are filled in, the monitor turns their prices on while it runs and sends a notice the first time each moves more than that percent from where it was when the monitor started. A symbol a setting names cannot go in a decorator, so its ticks are turned on with `subscribe(on_tick=...)`.

Three symbol settings and a percent: whichever symbols are filled in, the monitor turns their prices on while it runs and sends a notice the first time each moves more than that percent from where it was when the monitor started. A symbol a setting names cannot go in a decorator, so its ticks are turned on with subscribe(on_tick=...).

Shows: Symbol inputs (default ""), subscribe(key, on_tick=self.method), SubscriptionError (NOT_RUNNING / BAD_REQUEST), quote() as the starting price, notify().

View on GitHub

monitors/watchlist_from_settings.py
"""Price alerts on symbols picked in the settings

Three symbol settings and a percent: whichever symbols are filled in, the
monitor turns their prices on while it runs and sends a notice the first time
each moves more than that percent from where it was when the monitor started.
A symbol a setting names cannot go in a decorator, so its ticks are turned on
with `subscribe(on_tick=...)`.

Shows: Symbol inputs (default ""), subscribe(key, on_tick=self.method), SubscriptionError (NOT_RUNNING / BAD_REQUEST), quote() as the starting price, notify().
"""
import while25
from while25 import Monitor
from while25.inputs import Float, Symbol


def key_for(symbol, keys):
    """The watched key a tick's `symbol` names: the key itself, or the key
    whose last part it is."""
    if symbol in keys:
        return symbol
    return next((k for k in keys if k.rsplit(":", 1)[-1] == symbol), None)


def moved_pct(start, price):
    if not start or price is None:
        return None
    return (price - start) / start * 100


class SettingsWatchlist(Monitor):
    id = "settings_watchlist"
    label = "Watchlist from settings"
    inputs = [Symbol("first", default="EQ:US:AAPL"),
              Symbol("second", default=""),
              Symbol("third", default=""),
              Float("move_pct", default=3.0, minimum=0.1, maximum=50.0, step=0.1)]

    def on_start(self, ctx):
        p = while25.params
        self.start, self.told = {}, set()
        for key in filter(None, (p["first"], p["second"], p["third"])):
            q = while25.quote(key)
            self.start[key] = q["ltp"] if q else None    # None: the first tick sets it
            try:
                while25.subscribe(key, on_tick=self.on_price)
            except while25.SubscriptionError as e:
                while25.log(f"{key} not watched: {e.code}", "warn")
        while25.log(f"watching {', '.join(self.start) or 'nothing: fill in a symbol'}")

    def on_price(self, ctx, tick):
        key = key_for(tick["symbol"], self.start)
        if key is None or key in self.told or tick["ltp"] is None:
            return
        if self.start.get(key) is None:
            self.start[key] = tick["ltp"]
            return
        m = moved_pct(self.start[key], tick["ltp"])
        if m is not None and abs(m) >= while25.params["move_pct"]:
            self.told.add(key)
            while25.notify(f"{m:+.1f}% since the start, at {tick['ltp']}",
                           title=key.split(":")[-1], level="warn", symbol=key)