Skip to content

cointoss.cli

cli

The cointoss command: set up an instance, sweep by hand, check on it, and back it up.

cointoss init     [--data-dir D] [--systemd [--unit NAME]] [--port N] [--schedule CRON]
                                               create the instance, idempotently
cointoss sweep    [--data-dir D] [--force]
cointoss backfill [--data-dir D] [--days N]    fill dates with no stored bar, stocks too
cointoss sweep-stocks [--data-dir D] [--force] evaluate yahoo-industries for the last session
cointoss status   [--data-dir D]
cointoss token    [--data-dir D]               print the JSON-RPC bearer token
cointoss backup   [--data-dir D] DEST          copy the database and configs into DEST
cointoss restore  [--data-dir D] SRC           copy a backup into a stopped instance
cointoss portfolio create NAME [--kind K] [--custodian C]       [--url U] [--token=T]
cointoss trade add PORTFOLIO INSTRUMENT QUANTITY [--cost USD] [--at TIME] [--kind K]
                   [--note N] [--source S] [--coingecko-id ID]  [--url U] [--token=T]
cointoss trade void TRADE                                       [--url U] [--token=T]

The data directory is --data-dir, else $COINTOSS_HOME, else ~/.local/share/cointoss (cointoss.config.resolve_data_dir). It holds cointoss.db, cointoss.yaml, woodglue.yaml and woodglue's own stores (auth.db, mounts/, and wgl.log when not under systemd).

init writes each config only when it is missing, so an edited one is never overwritten, then validates both, so a re-run doubles as a config check. The woodglue.yaml it writes does not name the data directory: the fragment takes woodglue's own (wgl --data D), so wgl --data D start from a shell serves the same store the unit does, and a copied instance serves its own. The unit also sets COINTOSS_HOME, for any cointoss command run under it.

When Streamlit is installed (the ui extra), a new woodglue.yaml also serves the Dataset explorer as uis.explore, naming the absolute path of cointoss/explorer_app.py in this install, since woodglue resolves a relative app against the data directory. woodglue runs it with its own Python, which is this environment's. A kept woodglue.yaml without it is reported with the entry to add, as a differing port is.

JupyterLab (cointoss.notebook, the notebook extra) is never added: when it is installed and woodglue.yaml has no uis.notebook, init prints the entry to add by hand; when it is configured, init warns of a Role other than admin that may view it, or auth turned off.

A second instance on the same host, such as a dev checkout beside an installed one, takes its own --data-dir, --unit and --port. Each unit names its own virtualenv's bin, which is why it is a plain unit per instance rather than a cointoss@.service template.

A sweep missed while the server was down is caught up by lythonic when the server starts: a schedule trigger that missed its last firing fires once on start, so the unit needs no catch-up step of its own.

sweep calls the fragment's own sweep node, so a manual run follows exactly the scheduled run's idempotency rule and takes the same lock, but without waiting for it. It records CoinGecko's current listing for today (UTC), so it has no date to choose; a missed past day is history backfill: backfill calls the fragment's backfill node, waiting for the sweep lock before each write as the scheduled one does, and fills stock bars as the stock sweep does. sweep-stocks calls the fragment's stock_sweep node the same way: it evaluates yahoo-industries for the latest US session closed and fetches the stocks' bars, and waits for the sweep lock before its writes. init reports a kept woodglue.yaml that lacks the backfill or stock_sweep trigger, with the entry to add.

backup and restore are described in cointoss.backup. backup runs beside a serving instance and waits for a sweep in progress; restore refuses while the server for its data directory runs, and checks the backup's configs as init checks an instance's before writing anything. It leaves auth.db alone: cointoss init afterwards creates a token if there is none.

portfolio and trade are JSON-RPC clients of a running server rather than writers of the local store, so they work the same from another machine on the tailnet, calling int, and run as whoever the token names: that User owns what they create. They call the fragment's create_portfolio, add_trade and void_trade (see cointoss.app for the Role they need). The server is --url, else $COINTOSS_URL, else the local instance's own woodglue.yaml; the token is --token, else $COINTOSS_TOKEN, else the local instance's admin token when calling it, else the one wgl login URL stored. init writes the portfolio Role into a new woodglue.yaml, and reports a kept one that lacks it.

Expected failures -- a config that does not load, a sweep already running, a missing store -- are turned into CliError where they arise and reported as one line. Anything else is a bug and keeps its traceback.

The CLI uses argparse rather than lythonic's ActionTree, which derives option names from Python parameter names (--data_dir) and takes root options only before the subcommand.

CliError

Bases: Exception

A failure reported as one line on stderr, with a non-zero exit.

Source code in src/cointoss/cli.py
class CliError(Exception):
    """A failure reported as one line on stderr, with a non-zero exit."""

Endpoint

Bases: NamedTuple

A server's base URL, and the bearer token to send it; None for what wgl login stored.

Source code in src/cointoss/cli.py
class Endpoint(NamedTuple):
    """A server's base URL, and the bearer token to send it; None for what `wgl login` stored."""

    url: str
    token: str | None

user_unit_dir()

Where systemd --user looks for units the user installed.

Source code in src/cointoss/cli.py
def user_unit_dir() -> Path:
    """Where `systemd --user` looks for units the user installed."""
    config_home = os.environ.get("XDG_CONFIG_HOME")
    base = Path(config_home) if config_home else Path.home() / ".config"
    return base / "systemd" / "user"

render_unit(*, bin_dir, data_dir, unit=DEFAULT_UNIT)

The shipped cointoss.service template with this install's paths and unit name filled in.

systemd splits Exec*= lines on whitespace, so a path containing any is refused rather than quoted into a unit that might still be misread. A % is doubled, since systemd would read it as the start of a specifier.

Source code in src/cointoss/cli.py
def render_unit(*, bin_dir: Path, data_dir: Path, unit: str = DEFAULT_UNIT) -> str:
    """The shipped `cointoss.service` template with this install's paths and unit name filled in.

    systemd splits `Exec*=` lines on whitespace, so a path containing any is refused rather than
    quoted into a unit that might still be misread. A `%` is doubled, since systemd would read
    it as the start of a specifier.
    """
    paths = {"bin_dir": bin_dir, "data_dir": data_dir}
    for path in paths.values():
        if any(c.isspace() for c in str(path)):
            raise ValueError(f"path contains whitespace, not supported in the unit: {path}")
    template = files("cointoss").joinpath(UNIT_TEMPLATE).read_text()
    # The template's header explains the placeholders, which are gone once filled in.
    body = template[template.index("\n[Unit]") + 1 :]
    header = (
        "# Written by `cointoss init --systemd` from the template cointoss/cointoss.service.\n\n"
    )
    escaped = {name: str(path).replace("%", "%%") for name, path in paths.items()}
    return header + Template(body).substitute(escaped, unit=unit)

check_unit_name(name)

Refuse a unit name that is not a plain one, installed as NAME.service.

>>> check_unit_name("cointoss-dev")
>>> check_unit_name("x.service")
Traceback (most recent call last):
...
cointoss.cli.CliError: --unit 'x.service': give the name without .service
Source code in src/cointoss/cli.py
def check_unit_name(name: str) -> None:
    """Refuse a unit name that is not a plain one, installed as `NAME.service`.

    >>> check_unit_name("cointoss-dev")
    >>> check_unit_name("x.service")
    Traceback (most recent call last):
    ...
    cointoss.cli.CliError: --unit 'x.service': give the name without .service
    """
    if not name or not set(name) <= UNIT_NAME_CHARS:
        raise CliError(f"--unit {name!r}: use only letters, digits, '_', '.' and '-'")
    if name.endswith(".service"):
        raise CliError(f"--unit {name!r}: give the name without .service")

check_schedule(schedule)

Refuse anything but a 5-field cron expression, read as UTC by lythonic's trigger, that fires.

>>> check_schedule("0 0 30 2 *")
Traceback (most recent call last):
...
cointoss.cli.CliError: --schedule '0 0 30 2 *': never fires
Source code in src/cointoss/cli.py
def check_schedule(schedule: str) -> None:
    """Refuse anything but a 5-field cron expression, read as UTC by lythonic's trigger, that fires.

    >>> check_schedule("0 0 30 2 *")
    Traceback (most recent call last):
    ...
    cointoss.cli.CliError: --schedule '0 0 30 2 *': never fires
    """
    if len(schedule.split()) != 5 or not croniter.is_valid(schedule):
        raise CliError(f"--schedule {schedule!r}: not a 5-field cron expression")
    # A valid expression can still name no real day, such as 30 February.
    try:
        first_daily_firing(schedule)
    except CroniterError as exc:
        raise CliError(f"--schedule {schedule!r}: never fires") from exc

first_daily_firing(schedule)

How long after 00:00 UTC a cron schedule first fires on a day it fires at all.

The hour and minute fields do not depend on the day, so any day's first firing will do.

>>> first_daily_firing("5 0 * * *")
datetime.timedelta(seconds=300)
>>> first_daily_firing("30 1,12 * * 1")
datetime.timedelta(seconds=5400)
Source code in src/cointoss/cli.py
def first_daily_firing(schedule: str) -> dt.timedelta:
    """How long after 00:00 UTC a cron schedule first fires on a day it fires at all.

    The hour and minute fields do not depend on the day, so any day's first firing will do.

    >>> first_daily_firing("5 0 * * *")
    datetime.timedelta(seconds=300)
    >>> first_daily_firing("30 1,12 * * 1")
    datetime.timedelta(seconds=5400)
    """
    fired = croniter(schedule, -1).get_next(float)
    return dt.timedelta(seconds=fired % 86400)

streamlit_installed()

Whether this environment, the one woodglue runs a Streamlit UI with, has Streamlit.

Source code in src/cointoss/cli.py
def streamlit_installed() -> bool:
    """Whether this environment, the one woodglue runs a Streamlit UI with, has Streamlit."""
    return importlib.util.find_spec("streamlit") is not None

explorer_ui()

The uis.explore entry serving this install's Dataset explorer.

Its only Grant is call on the cointoss namespace, so whoever views it, the app can do no more than call cointoss's read nodes: woodglue exposes only api nodes over JSON-RPC, so the sweep is not callable, and firing its trigger needs a trigger Grant. The portfolio writes are api nodes but require cointoss.app.WRITE_ACTION, which no call Grant reaches.

Source code in src/cointoss/cli.py
def explorer_ui() -> dict[str, Any]:
    """The `uis.explore` entry serving this install's Dataset explorer.

    Its only Grant is `call` on the cointoss namespace, so whoever views it, the app can do no
    more than call cointoss's read nodes: woodglue exposes only `api` nodes over JSON-RPC, so
    the sweep is not callable, and firing its trigger needs a `trigger` Grant. The portfolio
    writes are `api` nodes but require `cointoss.app.WRITE_ACTION`, which no `call` Grant
    reaches.
    """
    return {
        "kind": "streamlit",
        "app": str(EXPLORER_SCRIPT),
        "label": "Explore",
        "grants": [f"call {NAMESPACE}"],
    }

auth_roles()

The Roles a new woodglue.yaml defines: portfolio, for Users who record their trades.

The built-in admin Role, whose token cointoss token prints, needs no definition. Only a write cointoss Grant reaches the portfolio writes, so a reader's Role may use any call pattern.

Source code in src/cointoss/cli.py
def auth_roles() -> dict[str, list[str]]:
    """The Roles a new `woodglue.yaml` defines: `portfolio`, for Users who record their trades.

    The built-in `admin` Role, whose token `cointoss token` prints, needs no definition. Only a
    `write cointoss` Grant reaches the portfolio writes, so a reader's Role may use any `call`
    pattern.
    """
    return {PORTFOLIO_ROLE: list(PORTFOLIO_GRANTS)}

woodglue_config(*, port=DEFAULT_PORT, schedule=DEFAULT_SWEEP_SCHEDULE, explorer=False)

The woodglue.yaml a new instance starts from: the cointoss namespace, local, with auth.

With explorer, it also serves the Dataset explorer at /ui/explore/.

Source code in src/cointoss/cli.py
def woodglue_config(
    *, port: int = DEFAULT_PORT, schedule: str = DEFAULT_SWEEP_SCHEDULE, explorer: bool = False
) -> dict[str, Any]:
    """The `woodglue.yaml` a new instance starts from: the cointoss namespace, local, with auth.

    With `explorer`, it also serves the Dataset explorer at `/ui/explore/`.
    """
    config: dict[str, Any] = {
        "host": "127.0.0.1",
        "port": port,
        "auth": {"enabled": True, "roles": auth_roles()},
        "namespaces": {
            NAMESPACE: {
                "expose_api": True,
                "run_engine": True,
                "entries": [fragment_entry(schedule=schedule)],
            }
        },
    }
    if explorer:
        config["uis"] = {EXPLORE_UI: explorer_ui()}
    return config

cointoss_config()

The cointoss.yaml a new instance starts from: the default universes and listing width.

Source code in src/cointoss/cli.py
def cointoss_config() -> dict[str, Any]:
    """The `cointoss.yaml` a new instance starts from: the default universes and listing width."""
    defaults = Settings(data_dir=Path("."))
    return {
        "top_n": defaults.top_n,
        "bar_window_hours": defaults.bar_window_hours,
        "universes": [declared.model_dump() for declared in defaults.universes],
    }

cmd_init(data_dir, systemd, *, unit=None, port=None, schedule=None)

Create or check the instance; port and schedule apply to a new woodglue.yaml only.

Every option is checked before anything is written.

Source code in src/cointoss/cli.py
def cmd_init(
    data_dir: Path,
    systemd: bool,
    *,
    unit: str | None = None,
    port: int | None = None,
    schedule: str | None = None,
) -> None:
    """Create or check the instance; `port` and `schedule` apply to a new `woodglue.yaml` only.

    Every option is checked before anything is written.
    """
    if unit is not None:
        if not systemd:
            raise CliError("--unit names the systemd unit; give it with --systemd")
        check_unit_name(unit)
    if port is not None and not 0 < port < 65536:
        raise CliError(f"--port {port}: not a TCP port")
    if schedule is not None:
        check_schedule(schedule)

    data_dir.mkdir(parents=True, exist_ok=True)
    print(f"data dir: {data_dir}")

    written = _write_new(
        data_dir / CONFIG_FILENAME,
        _yaml(
            "# cointoss: declared universes and how wide a listing each sweep fetches.\n",
            cointoss_config(),
        ),
    )
    print(f"{CONFIG_FILENAME}: {'created' if written else 'kept'}")
    settings = _settings(data_dir)

    explorer = streamlit_installed()
    written = _write_new(
        data_dir / WOODGLUE_CONFIG,
        _yaml(
            "# woodglue: serves the cointoss namespace and runs its sweep, backfill and stock "
            "sweep triggers.\n",
            woodglue_config(
                port=DEFAULT_PORT if port is None else port,
                schedule=schedule or DEFAULT_SWEEP_SCHEDULE,
                explorer=explorer,
            ),
        ),
    )
    print(f"{WOODGLUE_CONFIG}: {'created' if written else 'kept'}")
    config = _load_woodglue(data_dir)
    auth = _auth_store(data_dir, config)
    if not written:
        _report_differences(config, port=port, schedule=schedule)
    elif schedule is not None:
        _warn_after_bar_window(schedule, settings.bar_window)
    _report_trigger(
        config, BACKFILL_NODE, BACKFILL_TRIGGER, DEFAULT_BACKFILL_SCHEDULE, "backfill daily"
    )
    _report_trigger(
        config,
        STOCK_SWEEP_NODE,
        STOCK_SWEEP_TRIGGER,
        DEFAULT_STOCK_SWEEP_SCHEDULE,
        "sweep stocks after each US close",
    )
    _report_explorer(data_dir, config, installed=explorer)
    _report_notebook(config, installed=jupyterlab_installed())
    _report_portfolio_role(config)

    with Store(settings.db_path) as store:
        for reconciled in ensure_universes(store, settings.universes, utc_today()):
            print(f"universe {reconciled.name}: {reconciled.outcome} (rev {reconciled.revision})")
    print(f"database: {settings.db_path}")

    if auth is None:
        print("auth: disabled in woodglue.yaml")
    else:
        created = not auth.admin_tokens()
        auth.ensure_admin_token()
        print(f"auth token: {'created' if created else 'exists'}; `cointoss token` prints it")

    if systemd:
        _install_unit(data_dir, unit or DEFAULT_UNIT)

resolve_endpoint(data_dir, url, token)

Where the portfolio commands and cointoss.client send their calls, and as whom.

The URL is --url, else $COINTOSS_URL, else the local instance's woodglue.yaml. The token is --token, else $COINTOSS_TOKEN, else the local instance's admin token when calling that instance, else whatever wgl login stored for the URL.

Source code in src/cointoss/cli.py
def resolve_endpoint(data_dir: Path, url: str | None, token: str | None) -> Endpoint:
    """Where the portfolio commands and `cointoss.client` send their calls, and as whom.

    The URL is `--url`, else `$COINTOSS_URL`, else the local instance's `woodglue.yaml`. The
    token is `--token`, else `$COINTOSS_TOKEN`, else the local instance's admin token when
    calling that instance, else whatever `wgl login` stored for the URL.
    """
    url = url or os.environ.get(URL_ENV)
    token = token or os.environ.get(TOKEN_ENV)
    if url:
        return Endpoint(url, token)
    try:
        config = load_config(data_dir)
    except FileNotFoundError:
        raise CliError(
            f"no instance at {data_dir}; give --url (or ${URL_ENV}) to reach one elsewhere"
        ) from None
    except (ValidationError, WoodglueYAMLError) as exc:
        raise CliError(f"{data_dir / WOODGLUE_CONFIG}: {one_line(exc, whole='config')}") from exc
    # A server listening on every interface is reached locally on loopback.
    host = "127.0.0.1" if config.host in ("0.0.0.0", "::", "") else config.host
    if token is None and (auth := _auth_store(data_dir, config)) is not None:
        tokens = auth.admin_tokens()
        token = tokens[0] if len(tokens) == 1 else None
    return Endpoint(f"http://{host}:{config.port}", token)