Skip to Content
While25SDK docs
ExamplesMonitors

Nasdaq-100 opening-gap scanner

Turns on live prices for every Nasdaq-100 member, and in the first minutes after the open lists the biggest gaps from yesterday's close, then sends one notice with the top names. Members come from the platform's dated index list, whose date it logs: the list is as of that day, not today.

Turns on live prices for every Nasdaq-100 member, and in the first minutes after the open lists the biggest gaps from yesterday's close, then sends one notice with the top names. Members come from the platform's dated index list, whose date it logs: the list is as of that day, not today.

Shows: universe("ndx100"), universe_info(), subscribe(key) with no handler, quotes([...]) with None entries, prev_close / open, market.is_open(), @on.schedule, notify().

View on GitHub

monitors/gap_scanner.py
"""Nasdaq-100 opening-gap scanner

Turns on live prices for every Nasdaq-100 member, and in the first minutes
after the open lists the biggest gaps from yesterday's close, then sends one
notice with the top names. Members come from the platform's dated index list,
whose date it logs: the list is as of that day, not today.

Shows: universe("ndx100"), universe_info(), subscribe(key) with no handler, quotes([...]) with None entries, prev_close / open, market.is_open(), @on.schedule, notify().
"""
from datetime import datetime
from zoneinfo import ZoneInfo

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

NY = ZoneInfo("America/New_York")


def gap_pct(quote):
    """The open's gap from the previous close in percent, or None when the
    quote is missing either figure (never a 0 for "not known")."""
    if not quote or quote["open"] is None or not quote["prev_close"]:
        return None
    return (quote["open"] - quote["prev_close"]) / quote["prev_close"] * 100


def biggest_gaps(members, quotes, min_abs, top):
    """[(symbol, gap)] of the `top` largest gaps by size, at least `min_abs`."""
    gaps = [(m["symbol"], g) for m, q in zip(members, quotes)
            if (g := gap_pct(q)) is not None and abs(g) >= min_abs]
    return sorted(gaps, key=lambda x: -abs(x[1]))[:top]


class GapScanner(Monitor):
    id = "ndx_gap_scanner"
    label = "Nasdaq-100 gap scanner"
    inputs = [Float("min_gap", default=2.0, minimum=0.1, maximum=50.0, step=0.1,
                    label="Smallest gap to list (%)"),
              Int("top", default=8, minimum=1, maximum=30)]

    def on_start(self, ctx):
        info = while25.universe_info("ndx100")
        self.members = while25.universe("ndx100")
        self.keys = [m["canonical_id"] for m in self.members]
        while25.log(f"{info['name']}: {info['count']} members as of {info['as_of']}")
        for k in self.keys:
            # A refusal over the plan's limit is a warning on the module,
            # not a raise: the scan runs on the keys it did get.
            while25.subscribe(k)
        self.sent_on = None

    @on.schedule(every="1m")
    def scan(self, ctx):
        now = datetime.now(NY)
        if self.sent_on == now.date() or not (9 * 60 + 32 <= now.hour * 60 + now.minute <= 10 * 60):
            return
        if while25.market.is_open(self.keys[0]) is not True:
            return                          # a holiday, or the platform cannot say
        quotes = while25.quotes(self.keys)
        gaps = biggest_gaps(self.members, quotes, while25.params["min_gap"], while25.params["top"])
        missing = sum(1 for q in quotes if q is None)
        self.sent_on = now.date()
        if not gaps:
            while25.log(f"no gap of {while25.params['min_gap']}% or more ({missing} without data)")
            return
        text = ", ".join(f"{s} {g:+.1f}%" for s, g in gaps)
        while25.notify(text, title="Nasdaq-100 opening gaps", level="info")
        while25.log(f"{text} ({missing} members without data)")