From 65ad2b534e209b7d9132baaded5dcd3dbc312f03 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Oct 2026 14:41:51 +0000 Subject: [PATCH 1/6] dsh adapter: install the desk skill and register the MCP server for the DeepSeek Harness adapters/dsh/install-dsh.sh: skill copy, merge-safe MCP entry (--mcp-file), --doctor with a real MCP handshake, --uninstall. Interpreter order matches bin/register-mcp.sh (PY, .venv, python with mcp, else uvx); bash 3.2 safe; probes scrub PYTHONPATH. Tests, README section, CHANGELOG, CI syntax check. Rebased on v1.1.0. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GLsbckEp88WEwC41dfyMeS --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 4 + README.md | 19 +++ adapters/dsh/install-dsh.sh | 199 ++++++++++++++++++++++ console/backend/tests/test_dsh_adapter.py | 73 ++++++++ 5 files changed, 296 insertions(+), 1 deletion(-) create mode 100755 adapters/dsh/install-dsh.sh create mode 100644 console/backend/tests/test_dsh_adapter.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 32a5672..3d760d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,7 +47,7 @@ jobs: - run: pip install ruff && ruff check --select F,E9 console tools # Every first-party script must at least parse. - run: for f in console/frontend/*.js traders-desk/desktop/plugin.js; do node --check "$f"; done - - run: for f in install.sh console/start.sh tools/sync-live.sh bin/is-enabled.sh; do bash -n "$f"; done + - run: for f in install.sh adapters/dsh/install-dsh.sh console/start.sh tools/sync-live.sh bin/is-enabled.sh; do bash -n "$f"; done # The vendored bundles are what was recorded (a hand edit or a half-applied upgrade fails here), and the # generated preload list follows the module graph. - run: python tools/vendor-sums.py --check diff --git a/CHANGELOG.md b/CHANGELOG.md index cbd8f4b..c20fbaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ All notable changes to this project are documented here. Format: [Keep a Changel `console/service-macos.sh` behind launchd), so the OS row, the service section and the platform bullet now say Linux + macOS, name the launchd counterpart of the systemd unit, and link the Mac setup. Windows stays out of scope, and `docs/HANDOFF.md`'s operator line now names both machines. +- **DeepSeek Harness adapter** (`adapters/dsh/install-dsh.sh`): installs the desk skill and registers the `traders-chart` MCP server for + dsh. `--mcp-file` merges the entry into a JSON file you name (other servers kept, backup made, invalid JSON refused), `--doctor` + runs a real MCP handshake (56 tools) and checks the console, `--uninstall` undoes it. The Hermes pane stays Hermes-only. Not yet + tried against a real dsh install. ### Changed diff --git a/README.md b/README.md index b4f82da..b5fc7db 100644 --- a/README.md +++ b/README.md @@ -318,6 +318,25 @@ tick — measured 37-156 ms on the wire for `add` / `market` / `apply`, ~65-80 m healthy, 2 s if it drops) and the file bridge is untouched, so an older view still works. The bridge is still not a headless renderer: with no view attached, commands fail fast and say so. +### Using it from the DeepSeek Harness (dsh) + +The chart pane is Hermes-only, but the desk is not: the same MCP server (56 tools) and the same skill work from dsh, +and the agent drives the console's chart exactly as it does from Hermes. Open `http://127.0.0.1:8787/` in a browser tab +to watch it. + +```bash +./console/start.sh # the console must be running +./adapters/dsh/install-dsh.sh --mcp-file PATH # PATH: the JSON file where your dsh lists MCP servers +./adapters/dsh/install-dsh.sh --doctor # skill, launcher, a real MCP handshake, the console +``` + +It copies the skill to `~/.agents/skills/trader-desk` (`--skills-dir` or `DSH_SKILLS_DIR` to change it) and writes a +stdio entry into the file you name (it runs `console/mcp/server.py` with `PY`, the repo's `.venv` or a python that has the `mcp` client, same order as `bin/register-mcp.sh`; else `uvx fastmcp run`; `--venv` forces a private venv), +keeping your other servers and a `.bak-traders` copy. Without `--mcp-file` it prints the entry for you to paste. +`PORT=9000` points the entry at a console on another port. It reads nothing from dsh itself and writes nowhere else, so +check your dsh's own docs for the config path. Not verified against a real dsh install yet: the handshake is tested with +the MCP client, and dsh's skill and config locations are as reported by third-party dsh plugins. + ## Screenshots | | | diff --git a/adapters/dsh/install-dsh.sh b/adapters/dsh/install-dsh.sh new file mode 100755 index 0000000..1dc8a3d --- /dev/null +++ b/adapters/dsh/install-dsh.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# Install the Trader's Agent desk into the DeepSeek Harness (dsh): the skill and the MCP server. +# +# ./adapters/dsh/install-dsh.sh copy the desk skill, build/choose the MCP launcher, print the MCP entry +# ./adapters/dsh/install-dsh.sh --mcp-file PATH also merge the entry into that JSON file ({"mcpServers": {...}}); a backup is kept +# ./adapters/dsh/install-dsh.sh --skills-dir DIR skill folder (default $DSH_SKILLS_DIR, else ~/.agents/skills) +# ./adapters/dsh/install-dsh.sh --venv always use a private venv with fastmcp (default: PY, .venv or a python with `mcp`, else uvx) +# ./adapters/dsh/install-dsh.sh --doctor check skill, launcher, a real MCP handshake and the console +# ./adapters/dsh/install-dsh.sh --uninstall remove the skill (and the entry from --mcp-file) +# ./adapters/dsh/install-dsh.sh --help this text +# PORT=9000 ./adapters/dsh/install-dsh.sh the console is not on 8787 (written into the MCP entry as LUXALGO_CONSOLE) +# +# What dsh gets: the `trader-desk` skill and the 56-tool `traders-chart` MCP server. What it does not +# get: the Hermes sidebar pane (plugin/plugin.js is Hermes Desktop only). In dsh, open the console in a +# browser tab at http://127.0.0.1:$PORT/ and the agent drives that same chart through the tools. +# The console itself must be running: ./console/start.sh +# +# dsh's config locations are not read from dsh itself, so nothing is written outside --skills-dir and +# --mcp-file. If your dsh keeps MCP servers elsewhere, use the printed entry as-is. +# Written for bash 3.2 (macOS /bin/bash): no mapfile, no associative arrays. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO="$(cd "$HERE/../.." && pwd)" +SERVER="$REPO/console/mcp/server.py" +SKILL_SRC="$REPO/skills/trader-desk/SKILL.md" +SKILLS_DIR="${DSH_SKILLS_DIR:-$HOME/.agents/skills}" +PORT="${PORT:-8787}" +CONSOLE_URL="${LUXALGO_CONSOLE:-http://127.0.0.1:$PORT}" +VENV="${TRADERS_MCP_VENV:-$HOME/.local/share/traders-agent/mcp-venv}" +NAME="traders-chart" + +usage() { awk 'NR>1 && /^set -euo/{exit} NR>1{sub(/^# ?/,""); print}' "$0"; } + +DOCTOR=0 UNINSTALL=0 USE_VENV=0 MCP_FILE="" +while [[ $# -gt 0 ]]; do + case "$1" in + -h|--help) usage; exit 0 ;; + --doctor) DOCTOR=1 ;; + --uninstall) UNINSTALL=1 ;; + --venv) USE_VENV=1 ;; + --skills-dir) [[ $# -ge 2 ]] || { echo "install-dsh: --skills-dir needs a folder" >&2; exit 2; }; SKILLS_DIR="$2"; shift ;; + --mcp-file) [[ $# -ge 2 ]] || { echo "install-dsh: --mcp-file needs a path" >&2; exit 2; }; MCP_FILE="$2"; shift ;; + *) echo "install-dsh: unknown option '$1'" >&2; usage >&2; exit 2 ;; + esac + shift +done +[[ "$PORT" =~ ^[0-9]{1,5}$ ]] || { echo "install-dsh: PORT must be a number, got '$PORT'" >&2; exit 2; } +SKILL_DST="$SKILLS_DIR/trader-desk" + +# PYTHONPATH/PYTHONHOME are scrubbed for the probe: an agent session can export one that shadows the probe's own packages. +has_mcp() { env -u PYTHONPATH -u PYTHONHOME "$1" -c 'import mcp' >/dev/null 2>&1; } + +# The interpreter dsh will run, in the order bin/register-mcp.sh and start.sh use: PY (an explicit +# choice), the repo's .venv, a python3.11+ on PATH that has the `mcp` client. server.py runs on the +# plain `mcp` SDK (it falls back to mcp.server.fastmcp), so no extra package is needed for these. +find_python() { + local cand + if [[ -n "${PY:-}" && -x "${PY:-/nonexistent}" ]] && has_mcp "$PY"; then echo "$PY"; return 0; fi + if [[ -x "$REPO/.venv/bin/python" ]] && has_mcp "$REPO/.venv/bin/python"; then echo "$REPO/.venv/bin/python"; return 0; fi + for cand in python3.13 python3.12 python3.11 python3; do + if command -v "$cand" >/dev/null 2>&1 && has_mcp "$(command -v "$cand")"; then command -v "$cand"; return 0; fi + done + return 1 +} + +# The command dsh will run, one element per line, command first. Order: an interpreter that already has +# the mcp client; else uvx (fetches fastmcp on first use); else a private venv holding fastmcp. +# --venv skips straight to the private venv. +launcher() { + local py + if [[ $USE_VENV -eq 0 ]] && py="$(find_python)"; then + printf '%s\n' "$py" "$SERVER" + elif [[ $USE_VENV -eq 0 ]] && command -v uvx >/dev/null 2>&1; then + printf '%s\n' "$(command -v uvx)" fastmcp run "$SERVER" + else + printf '%s\n' "$VENV/bin/python" "$SERVER" + fi +} + +ensure_venv() { + if [[ $USE_VENV -eq 0 ]] && { find_python >/dev/null || command -v uvx >/dev/null 2>&1; }; then return 0; fi + if [[ -x "$VENV/bin/python" ]] && "$VENV/bin/python" -c 'import fastmcp' >/dev/null 2>&1; then return 0; fi + command -v python3 >/dev/null 2>&1 || { echo "install-dsh: python3 is needed to build the MCP environment" >&2; exit 1; } + echo "building the MCP environment (fastmcp) in $VENV — needs the network once" + rm -rf "$VENV" + python3 -m venv "$VENV" + "$VENV/bin/pip" install --quiet --upgrade pip + "$VENV/bin/pip" install --quiet fastmcp +} + +# Writes/prints {"mcpServers": {NAME: {...}}} for the chosen launcher. $1 = "print" or a file to merge into. +entry_json() { + local target="$1"; local L=() line + while IFS= read -r line; do L+=("$line"); done < <(launcher) + python3 - "$target" "$NAME" "$CONSOLE_URL" "${L[@]}" <<'PY' +import json, os, shutil, sys +target, name, console, cmd, *args = sys.argv[1:] +entry = {"type": "stdio", "command": cmd, "args": args, "env": {"LUXALGO_CONSOLE": console}} +if target == "print": + print(json.dumps({"mcpServers": {name: entry}}, indent=2)); sys.exit(0) +doc = {} +if os.path.exists(target): + try: + doc = json.load(open(target)) + except ValueError as e: + sys.exit(f"install-dsh: {target} is not valid JSON ({e}); fix or move it, nothing was changed") + if not isinstance(doc, dict): + sys.exit(f"install-dsh: {target} is not a JSON object; nothing was changed") + shutil.copy2(target, target + ".bak-traders") +servers = doc.setdefault("mcpServers", {}) +if not isinstance(servers, dict): + sys.exit(f"install-dsh: 'mcpServers' in {target} is not an object; nothing was changed") +servers[name] = entry +os.makedirs(os.path.dirname(os.path.abspath(target)), exist_ok=True) +tmp = target + ".tmp" +with open(tmp, "w") as f: + json.dump(doc, f, indent=2); f.write("\n") +os.replace(tmp, target) +PY +} + +remove_entry() { + python3 - "$1" "$NAME" <<'PY' +import json, os, shutil, sys +target, name = sys.argv[1:] +if not os.path.exists(target): print(f"no {target}; nothing to remove"); sys.exit(0) +doc = json.load(open(target)); s = doc.get("mcpServers", {}) +if name in s: + shutil.copy2(target, target + ".bak-traders"); del s[name] + json.dump(doc, open(target, "w"), indent=2); print(f"removed '{name}' from {target}") +else: print(f"'{name}' not in {target}") +PY +} + +if [[ $UNINSTALL -eq 1 ]]; then + rm -rf "$SKILL_DST"; echo "removed $SKILL_DST" + if [[ -n "$MCP_FILE" ]]; then remove_entry "$MCP_FILE"; fi + echo "still yours: the MCP entry if you added it by hand, $VENV, ~/.local/state/traders-agent/" + exit 0 +fi + +if [[ $DOCTOR -eq 1 ]]; then + fail=0 + ok() { echo " ok $1"; } + bad() { echo " FAIL $1"; fail=1; } + echo "Trader's Agent — dsh doctor" + if command -v dsh >/dev/null 2>&1; then ok "dsh on PATH ($(command -v dsh))"; else echo " -- dsh not on PATH (not required for this check)"; fi + [[ -f "$SKILL_DST/SKILL.md" ]] && ok "skill at $SKILL_DST" || bad "skill missing at $SKILL_DST (run without --doctor)" + [[ -f "$SERVER" ]] && ok "MCP server in repo" || bad "MCP server missing: $SERVER" + L=(); while IFS= read -r line; do L+=("$line"); done < <(launcher) + if [[ "${L[0]}" == */uvx ]]; then ok "launcher: uvx fastmcp run" + elif [[ -x "${L[0]}" ]] && has_mcp "${L[0]}"; then ok "launcher: ${L[0]} (has the mcp client)" + else bad "no interpreter with the mcp client (pip install mcp, or run without --doctor to build a venv, or install uv)"; fi + # A real handshake: start the server the way dsh will and count its tools. + n="$(python3 - "$CONSOLE_URL" "${L[@]}" <<'PY' 2>/dev/null || true +import asyncio, sys +console, cmd, *args = sys.argv[1:] +try: + from mcp import ClientSession, StdioServerParameters + from mcp.client.stdio import stdio_client +except Exception: + print("noclient"); sys.exit(0) +async def go(): + p = StdioServerParameters(command=cmd, args=args, env={"LUXALGO_CONSOLE": console, "PATH": __import__("os").environ.get("PATH", "")}) + async with stdio_client(p) as (r, w): + async with ClientSession(r, w) as s: + await asyncio.wait_for(s.initialize(), 60) + print(len((await s.list_tools()).tools)) +asyncio.run(go()) +PY +)" + case "$n" in + ''|*[!0-9]*) if [[ "$n" == "noclient" ]]; then echo " -- python 'mcp' client not installed here; handshake skipped"; else bad "MCP handshake failed: run the launcher by hand to see the error"; fi ;; + *) ok "MCP handshake: $n tools" ;; + esac + if curl -fsS --max-time 3 "$CONSOLE_URL/api/health" >/dev/null 2>&1; then ok "console answering on $CONSOLE_URL"; else bad "console not answering on $CONSOLE_URL (./console/start.sh)"; fi + [[ $fail -eq 0 ]] && { echo "all checks passed"; exit 0; } || { echo "one or more checks failed"; exit 1; } +fi + +[[ -f "$SKILL_SRC" ]] || { echo "install-dsh: $SKILL_SRC not found" >&2; exit 1; } +mkdir -p "$SKILL_DST" +cp "$SKILL_SRC" "$SKILL_DST/SKILL.md" +echo "desk skill -> $SKILL_DST" +ensure_venv +if [[ -n "$MCP_FILE" ]]; then + entry_json "$MCP_FILE" + echo "MCP entry -> $MCP_FILE (previous copy: $MCP_FILE.bak-traders, if it existed)" +else + echo; echo "Add this to your dsh MCP servers (or re-run with --mcp-file PATH):"; entry_json print +fi +cat < Date: Thu, 15 Oct 2026 04:54:49 +0000 Subject: [PATCH 2/6] install: ./install.sh --all, uv-first python setup, Linux service helper bin/setup-python.sh makes /.venv with the mcp client (uv when present: 5.6 s vs 286 s for pip in the same sandbox; else python3.11+ venv + pip; an existing python with mcp is left alone). It asks for Python 3.12/3.13/3.11, never the newest: a bare >=3.11 picked a 3.14 release candidate whose pydantic could not import. console/service-linux.sh is the systemd counterpart of service-macos.sh, with a detached fallback that does not hold the caller's pipe. install.sh --all chains plugin, python, service, MCP registration and a health wait; a plain ./install.sh is unchanged. Tests (test_fast_install), README, CHANGELOG, MACOS.md, CI syntax check. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GLsbckEp88WEwC41dfyMeS --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 8 + README.md | 21 ++- bin/setup-python.sh | 112 +++++++++++++ console/backend/tests/test_fast_install.py | 136 +++++++++++++++ console/service-linux.sh | 183 +++++++++++++++++++++ docs/MACOS.md | 3 + install.sh | 63 ++++++- 8 files changed, 520 insertions(+), 8 deletions(-) create mode 100755 bin/setup-python.sh create mode 100644 console/backend/tests/test_fast_install.py create mode 100755 console/service-linux.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d760d0..1cce2a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,7 +47,7 @@ jobs: - run: pip install ruff && ruff check --select F,E9 console tools # Every first-party script must at least parse. - run: for f in console/frontend/*.js traders-desk/desktop/plugin.js; do node --check "$f"; done - - run: for f in install.sh adapters/dsh/install-dsh.sh console/start.sh tools/sync-live.sh bin/is-enabled.sh; do bash -n "$f"; done + - run: for f in install.sh adapters/dsh/install-dsh.sh console/start.sh console/service-linux.sh bin/setup-python.sh tools/sync-live.sh bin/is-enabled.sh bin/register-mcp.sh; do bash -n "$f"; done # The vendored bundles are what was recorded (a hand edit or a half-applied upgrade fails here), and the # generated preload list follows the module graph. - run: python tools/vendor-sums.py --check diff --git a/CHANGELOG.md b/CHANGELOG.md index c20fbaa..229262c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,14 @@ All notable changes to this project are documented here. Format: [Keep a Changel `console/service-macos.sh` behind launchd), so the OS row, the service section and the platform bullet now say Linux + macOS, name the launchd counterpart of the systemd unit, and link the Mac setup. Windows stays out of scope, and `docs/HANDOFF.md`'s operator line now names both machines. +- **`./install.sh --all`, the one-command install**, plus the two pieces it is made of. `bin/setup-python.sh` gives the console and the + agent a python with the `mcp` client: `uv` when it is on PATH (5.6 s against 286 s for pip in the same slow sandbox), else + `python3.11+ -m venv` + pip; a python you already have that imports `mcp` is left alone. It asks for Python 3.12, then 3.13, then + 3.11, never "the newest": a bare `>=3.11` once made uv choose a 3.14 release candidate whose pydantic could not import (found by + running it, held by a test). `console/service-linux.sh` is the systemd counterpart of `service-macos.sh` (user unit + `traders-agent.service`; a detached console where there is no systemd user session, said plainly; an already-running console, or the + developer's `luxalgo-web.service`, is left alone). `--setup-python` and `--service` run each step alone. Nothing about what the + plugin does changes; a plain `./install.sh` behaves as before. Tests: `test_fast_install`. - **DeepSeek Harness adapter** (`adapters/dsh/install-dsh.sh`): installs the desk skill and registers the `traders-chart` MCP server for dsh. `--mcp-file` merges the entry into a JSON file you name (other servers kept, backup made, invalid JSON refused), `--doctor` runs a real MCP handshake (56 tools) and checks the console, `--uninstall` undoes it. The Hermes pane stays Hermes-only. Not yet diff --git a/README.md b/README.md index b5fc7db..47adf93 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ MCP server) in one local web app — your chat session is left exactly where it | | | |---|---| | **Hermes Desktop** | v0.21.3 or newer (the plugin uses the `sidebar.nav` + `routes` contribution areas) | -| **Python** | 3.11+ with the `mcp` client: `pip install mcp` (a venv is fine — point `PY=` at it) | +| **Python** | 3.11+ with the `mcp` client. `./install.sh --all` (or `./bin/setup-python.sh`) makes a `.venv` with it; or `pip install mcp` yourself and point `PY=` at it | | **Network** | for LuxAlgo's MCP endpoint and the Binance data feed; with no market feed the chart stays empty (`chart_state` says `bars None`). The chart engine and Pine runtime are served locally | | **Node 20+** *(optional)* | only for [Edge Stats](#edge-stats--how-often-did-it-actually-happen) — `./install.sh --with-edge` installs LuxAlgo's engine (~300 MB with its dependencies) next to the console. Without it everything else works and the sheet explains what is missing | | **Preview resizer** *(optional)* | `libvips` (or ImageMagick, or `ffmpeg`) — see [Catalogue previews](#catalogue-previews-are-kept-on-your-machine). With none of them the console still shows every preview, just at the catalogue's original size | @@ -53,6 +53,25 @@ MCP server) in one local web app — your chat session is left exactly where it ## Install +**One command** (Linux and macOS; about a minute with [uv](https://docs.astral.sh/uv/), a few without it): + +```bash +git clone --depth 1 https://github.com/godzillacode0000/tradersagent-plugin +cd tradersagent-plugin +./install.sh --all +``` + +`--all` installs the plugin and the desk skill, makes a python with the `mcp` client (`bin/setup-python.sh`: uv when +it is on PATH, else `python3.11+ -m venv` + pip; it leaves a python you already have alone), installs the console as a +service (systemd user unit on Linux, LaunchAgent on macOS, a detached process where neither exists), registers the +chart's MCP server with Hermes, and waits until the console answers. Then, in Hermes Desktop: reload the plugins and +click the **Trader's Agent** row. Measured on a clean machine: clone 1.5 s, `./install.sh` 0.25 s, console up in 1.6 s; +the dependency step is the long one (`uv pip install mcp` 5.6 s against 286 s for pip in the same slow sandbox). +Optional extras stay separate: `--with-edge` (~300 MB), `--with-backtest` (~840 MB). Add `--no-mcp` to skip the +registration. Re-running is safe. + +The same steps by hand: + ```bash git clone https://github.com/godzillacode0000/tradersagent-plugin cd tradersagent-plugin diff --git a/bin/setup-python.sh b/bin/setup-python.sh new file mode 100755 index 0000000..289a652 --- /dev/null +++ b/bin/setup-python.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# bin/setup-python.sh — give the console and the agent a python with the `mcp` client, fast. +# +# ./bin/setup-python.sh make /.venv with `mcp` (skips if you already have a python that does) +# ./bin/setup-python.sh --print show what it would do and change nothing +# ./bin/setup-python.sh --force delete and rebuild the repo .venv even if `mcp` is already importable +# +# Why: `pip install mcp` is the slow step of a fresh install (measured 286 s against 5.6 s for +# `uv pip install mcp` in the same sandbox, 72 MB of packages either way). So: uv when it is on PATH +# (it can also fetch a python itself), else python3.11+ -m venv + pip. The python is 3.12, 3.13 or 3.11, in that +# order: the versions CI covers and that have final releases of every dependency. Plain `>=3.11` made uv pick a +# 3.14 release candidate once, whose pydantic could not import, so the newest is not chosen on purpose. Nothing else about the +# console changes: it stays stdlib-only apart from this one package, and start.sh / register-mcp.sh / +# service helpers all already prefer /.venv when it can import mcp. +# +# An interpreter you chose with PY=... that can import mcp is left alone, and so is a python3.11+ on +# PATH that already has it (nothing to install). Bash 3.2 safe (macOS /bin/bash): no arrays, no mapfile. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")/.." && pwd)" +VENV="$HERE/.venv" +REQ='mcp>=1,<3' # the same range console/requirements.txt pins +PRINT=0 FORCE=0 +for arg in "$@"; do + case "$arg" in + -h|--help) sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; exit 0 ;; + --print) PRINT=1 ;; + --force) FORCE=1 ;; + *) echo "setup-python.sh: unknown option '$arg'" >&2; exit 2 ;; + esac +done + +# PYTHONPATH/PYTHONHOME are scrubbed for every probe: an agent session can export a PYTHONPATH that +# shadows the probe's own packages and makes a healthy interpreter read as broken. +has_mcp() { [ -x "$1" ] && env -u PYTHONPATH -u PYTHONHOME "$1" -c 'import mcp' >/dev/null 2>&1; } +is_311() { env -u PYTHONPATH -u PYTHONHOME "$1" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' >/dev/null 2>&1; } + +find_ready_python() { # a python 3.11+ that can already import mcp, in start.sh's order + local cand p + if [ -n "${PY:-}" ] && has_mcp "$PY"; then echo "$PY"; return 0; fi + if has_mcp "$VENV/bin/python"; then echo "$VENV/bin/python"; return 0; fi + for cand in python3.14 python3.13 python3.12 python3.11 python3; do + p="$(command -v "$cand" 2>/dev/null || true)" + if [ -n "$p" ] && is_311 "$p" && has_mcp "$p"; then echo "$p"; return 0; fi + done + return 1 +} + +find_python311() { # a python 3.11+ (no mcp needed): the base for a pip-built venv, preferred order above + local cand p + for cand in python3.12 python3.13 python3.11 python3.14 python3; do + p="$(command -v "$cand" 2>/dev/null || true)" + if [ -n "$p" ] && is_311 "$p"; then echo "$p"; return 0; fi + done + return 1 +} + +if [ $FORCE -eq 0 ] && READY="$(find_ready_python)"; then + echo "ok a python with the mcp client is already available: $READY (nothing to install)" + exit 0 +fi + +UVPY="" +if command -v uv >/dev/null 2>&1; then + TOOL="uv" + for v in 3.12 3.13 3.11; do # an already-installed one first: no download + if uv python find "$v" >/dev/null 2>&1; then UVPY="$v"; break; fi + done + [ -n "$UVPY" ] || UVPY="3.12" # none installed: uv fetches a standalone 3.12 +elif BASE="$(find_python311)"; then + TOOL="pip" +else + echo "setup-python.sh: no uv and no python 3.11+ on PATH." >&2 + echo " Install uv (https://docs.astral.sh/uv/) — it can fetch python itself — or python 3.11+, then run this again." >&2 + exit 1 +fi + +if [ $PRINT -eq 1 ]; then + echo "# tool: $TOOL target: $VENV" + if [ "$TOOL" = "uv" ]; then + if [ $FORCE -eq 1 ] || [ ! -x "$VENV/bin/python" ]; then echo "uv venv --python $UVPY $VENV"; fi + echo "uv pip install --python $VENV/bin/python '$REQ'" + else + if [ $FORCE -eq 1 ] || [ ! -x "$VENV/bin/python" ]; then echo "$BASE -m venv $VENV"; fi + echo "$VENV/bin/python -m pip install '$REQ'" + fi + exit 0 +fi + +START="$(date +%s)" +if [ $FORCE -eq 1 ] && [ -d "$VENV" ]; then rm -rf "$VENV"; fi +if [ "$TOOL" = "uv" ]; then + if [ ! -x "$VENV/bin/python" ]; then + echo "creating $VENV with uv (python $UVPY)" + uv venv --quiet --python "$UVPY" "$VENV" + fi + echo "installing $REQ with uv" + uv pip install --quiet --python "$VENV/bin/python" "$REQ" +else + if [ ! -x "$VENV/bin/python" ]; then + echo "creating $VENV with $BASE (no uv found: this is the slower path)" + "$BASE" -m venv "$VENV" + fi + echo "installing $REQ with pip" + "$VENV/bin/python" -m pip install --quiet --disable-pip-version-check "$REQ" +fi + +if ! has_mcp "$VENV/bin/python"; then + echo "setup-python.sh: installed, but $VENV/bin/python still cannot import mcp" >&2 + exit 1 +fi +echo "ok $VENV is ready (mcp client importable) in $(( $(date +%s) - START ))s" diff --git a/console/backend/tests/test_fast_install.py b/console/backend/tests/test_fast_install.py new file mode 100644 index 0000000..5d9ba03 --- /dev/null +++ b/console/backend/tests/test_fast_install.py @@ -0,0 +1,136 @@ +"""bin/setup-python.sh (uv-first python setup), console/service-linux.sh and install.sh --all: plans, flags, unit text. + +Nothing here downloads anything or touches systemd: setup-python is driven with --print, and the unit is printed.""" +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +SETUP = ROOT / "bin" / "setup-python.sh" +SERVICE = ROOT / "console" / "service-linux.sh" +INSTALL = ROOT / "install.sh" +BASH = shutil.which("bash") or "bash" + + +def _has_mcp(): + try: + import mcp # noqa: F401 + return True + except ImportError: + return False + + +def _tools_dir(with_uv, uv_finds_python=True): + """A PATH with only the few coreutils the script needs, a python3.12 shim, and optionally a stub uv.""" + d = Path(tempfile.mkdtemp()) + for tool in ("env", "date", "dirname", "rm", "mkdir", "sed", "cat", "sleep"): + src = shutil.which(tool) + if src: + (d / tool).symlink_to(src) + (d / "python3.12").symlink_to(sys.executable) + if with_uv: + uv = d / "uv" + uv.write_text("#!/bin/sh\n" + ("" if uv_finds_python else '[ "$1 $2" = "python find" ] && exit 1\n') + "exit 0\n") + uv.chmod(0o755) + return d + + +def run_setup(*args, path_dir=None, **env): + e = {k: v for k, v in os.environ.items() if k not in ("PY", "PYTHONPATH", "PYTHONHOME")} + e.update(env) + if path_dir is not None: + e["PATH"] = str(path_dir) + return subprocess.run([BASH, str(SETUP), *args], capture_output=True, text=True, env=e, timeout=60) + + +class SetupPython(unittest.TestCase): + def test_syntax(self): + for f in (SETUP, SERVICE, INSTALL): + self.assertEqual(subprocess.run(["bash", "-n", str(f)]).returncode, 0, f) + + def test_uv_plan_pins_a_tested_python_and_the_mcp_range(self): + d = _tools_dir(with_uv=True) + r = run_setup("--force", "--print", path_dir=d) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("tool: uv", r.stdout) + self.assertIn("uv venv --python 3.12", r.stdout) + self.assertIn("'mcp>=1,<3'", r.stdout) + # a bare '>=3.11' once let uv pick a 3.14 release candidate whose pydantic could not import + self.assertNotIn(">=3.11", r.stdout) + + def test_uv_falls_back_to_a_fetched_312_when_none_is_installed(self): + d = _tools_dir(with_uv=True, uv_finds_python=False) + r = run_setup("--force", "--print", path_dir=d) + self.assertIn("uv venv --python 3.12", r.stdout) + + def test_without_uv_it_uses_venv_and_pip(self): + d = _tools_dir(with_uv=False) + r = run_setup("--force", "--print", path_dir=d) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("tool: pip", r.stdout) + self.assertIn("-m venv", r.stdout) + self.assertIn("-m pip install 'mcp>=1,<3'", r.stdout) + + def test_no_uv_and_no_python_is_a_sentence_not_a_traceback(self): + d = Path(tempfile.mkdtemp()) + for tool in ("env", "date", "dirname", "sed", "cat"): + src = shutil.which(tool) + if src: + (d / tool).symlink_to(src) + r = run_setup("--force", "--print", path_dir=d) + self.assertEqual(r.returncode, 1) + self.assertIn("no uv and no python 3.11+", r.stderr) + + @unittest.skipUnless(_has_mcp(), "needs the mcp client in this interpreter") + def test_an_existing_python_with_mcp_is_left_alone(self): + r = run_setup(PY=sys.executable) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("nothing to install", r.stdout) + + def test_unknown_flag(self): + self.assertEqual(run_setup("--nope").returncode, 2) + + +@unittest.skipUnless(sys.platform.startswith("linux"), "the systemd helper is Linux only") +class ServiceLinux(unittest.TestCase): + def test_unit_text(self): + r = subprocess.run(["bash", str(SERVICE), "print", "--port", "9123"], capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 0, r.stderr) + for needle in ('Environment="PORT=9123"', "Restart=always", "WantedBy=default.target", + 'ExecStart=/bin/bash "%s"' % (ROOT / "console" / "start.sh")): + self.assertIn(needle, r.stdout) + + def test_bad_port_and_unknown_command(self): + self.assertEqual(subprocess.run(["bash", str(SERVICE), "print", "--port", "abc"], capture_output=True, text=True).returncode, 2) + self.assertEqual(subprocess.run(["bash", str(SERVICE), "frobnicate"], capture_output=True, text=True).returncode, 2) + + def test_detached_start_does_not_hold_the_callers_pipe(self): + # the recorded pid must be the console itself, and no wrapper may keep the caller's stdout open + src = SERVICE.read_text() + self.assertIn('exec env PORT="$PORT"', src) + self.assertIn('echo $! > "$PIDFILE"', src) + + +class InstallAllFlag(unittest.TestCase): + def test_help_lists_the_one_command_install(self): + r = subprocess.run(["bash", str(INSTALL), "--help"], capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 0) + for flag in ("--all", "--setup-python", "--service"): + self.assertIn(flag, r.stdout) + + def test_unknown_flag_still_refuses(self): + r = subprocess.run(["bash", str(INSTALL), "--nope"], capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 2) + + def test_python_step_runs_before_registration_and_service(self): + src = INSTALL.read_text() + self.assertLess(src.index("bin/setup-python.sh"), src.index('"$HERE/bin/register-mcp.sh"')) + self.assertLess(src.index("bin/setup-python.sh"), src.index("SERVICE_SH=")) + + +if __name__ == "__main__": + unittest.main() diff --git a/console/service-linux.sh b/console/service-linux.sh new file mode 100755 index 0000000..cfa435f --- /dev/null +++ b/console/service-linux.sh @@ -0,0 +1,183 @@ +#!/usr/bin/env bash +# Linux service helper — the counterpart of service-macos.sh, so one command keeps the console running. +# +# ./console/service-linux.sh install [--port N] write the systemd user unit, enable it, wait until it answers +# ./console/service-linux.sh uninstall stop it and remove the unit (or stop the detached console) +# ./console/service-linux.sh status unit state, is the console answering, where are the logs +# ./console/service-linux.sh print print the unit file and change nothing +# +# Unit: ~/.config/systemd/user/traders-agent.service (the same name the README documents). +# Without a systemd user session (a container, WSL without systemd, an SSH-less box) it starts the +# console detached instead (nohup, pid file in the state dir) and says plainly that this does NOT +# survive a reboot. A console that is already answering and that this script did not start is left alone. +# Logs: ~/.local/state/traders-agent/console.log +# +# Bash 3.2 safe: no arrays, no mapfile. +set -euo pipefail + +[[ "$(uname -s)" == "Linux" ]] || { echo "service-linux.sh: Linux only (macOS uses ./console/service-macos.sh)" >&2; exit 2; } + +HERE="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$HERE/.." && pwd)" +UNIT_NAME="traders-agent.service" +UNIT_DIR="$HOME/.config/systemd/user" +UNIT="$UNIT_DIR/$UNIT_NAME" +STATE_DIR="$HOME/.local/state/traders-agent" +PIDFILE="$STATE_DIR/console.pid" +LOG="$STATE_DIR/console.log" +PORT="${PORT:-8787}" + +# Environment baked into the unit: a systemd user service gets a minimal PATH, but the console shells +# out (`node` drives the Edge Stats sidecar, `hermes` starts the in-app study bridge). +NODE_DIR="" +if command -v node >/dev/null 2>&1; then NODE_DIR="$(cd "$(dirname "$(command -v node)")" && pwd)"; fi +SVC_PATH="/usr/local/bin:/usr/bin:/bin:$HOME/.local/bin" +[[ -n "$NODE_DIR" ]] && SVC_PATH="$NODE_DIR:$SVC_PATH" + +# systemd specifiers: a literal % in a path must be written %%. Quoted args keep spaces intact. +unit_escape() { printf '%s' "$1" | sed -e 's/%/%%/g' -e 's/\\/\\\\/g' -e 's/"/\\"/g'; } + +has_mcp() { [[ -x "$1" ]] && env -u PYTHONPATH -u PYTHONHOME "$1" -c 'import mcp' >/dev/null 2>&1; } +resolve_py() { + local cand p + if [[ -n "${PY:-}" ]]; then echo "$PY"; return 0; fi + if has_mcp "$ROOT/.venv/bin/python"; then echo "$ROOT/.venv/bin/python"; return 0; fi + for cand in python3.14 python3.13 python3.12 python3.11 python3; do + p="$(command -v "$cand" 2>/dev/null || true)" + if [[ -n "$p" ]] && has_mcp "$p"; then echo "$p"; return 0; fi + done + return 1 +} + +health() { curl -fsS --max-time 2 "http://127.0.0.1:$PORT/api/health" >/dev/null 2>&1; } +wait_health() { + local i + for i in $(seq 1 40); do # 40 x 0.5 s: the console needs a few seconds to open its MCP session + if health; then return 0; fi + sleep 0.5 + done + return 1 +} + +have_user_systemd() { + command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1 +} + +unit_text() { # $1 = interpreter + cat </dev/null || true)" + if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then kill "$pid" 2>/dev/null || true; echo "stopped the detached console (pid $pid)"; fi + rm -f "$PIDFILE" + fi +} + +cmd_install() { + local PYR + if ! PYR="$(resolve_py)"; then + echo "service-linux.sh: no python with the 'mcp' client found. Run ./bin/setup-python.sh first." >&2 + exit 1 + fi + mkdir -p "$STATE_DIR" + + # A console somebody started themselves (a terminal, the developer's own unit): do not fight it for the port. + if health && [[ ! -f "$UNIT" ]] && [[ ! -f "$PIDFILE" ]]; then + echo "ok a console is already answering on port $PORT (not started by this script) — leaving it alone" + return 0 + fi + if command -v systemctl >/dev/null 2>&1 && systemctl --user is-active --quiet luxalgo-web.service 2>/dev/null; then + echo "ok luxalgo-web.service is already running the console — not installing a second unit" + return 0 + fi + + if have_user_systemd; then + stop_detached + mkdir -p "$UNIT_DIR" + unit_text "$PYR" > "$UNIT" + systemctl --user daemon-reload + systemctl --user enable --now "$UNIT_NAME" >/dev/null 2>&1 || { echo "service-linux.sh: could not enable $UNIT_NAME (journalctl --user -u $UNIT_NAME)" >&2; exit 1; } + systemctl --user restart "$UNIT_NAME" + if wait_health; then + echo "ok console running as $UNIT_NAME on port $PORT (starts at login; logs: journalctl --user -u $UNIT_NAME)" + else + echo "warning: $UNIT_NAME is enabled but the console is not answering after 20 s" >&2 + echo " check: journalctl --user -u $UNIT_NAME -n 30" >&2 + exit 1 + fi + else + stop_detached + echo "note: no systemd user session here — starting the console detached (it will NOT survive a reboot)" + # exec inside the subshell: the recorded pid is the console itself (not a wrapper), and nothing keeps + # the caller's stdout open (a lingering wrapper made `./install.sh --all | tee log` hang until the console died). + ( cd "$ROOT" && exec env PORT="$PORT" PY="$PYR" PATH="$SVC_PATH:$PATH" nohup bash "$ROOT/console/start.sh" >>"$LOG" 2>&1 < /dev/null ) & + echo $! > "$PIDFILE" + if wait_health; then + echo "ok console running detached on port $PORT (pid $(cat "$PIDFILE"); logs: $LOG)" + echo " to keep it across reboots, run ./console/start.sh from your own session manager" + else + echo "warning: the detached console is not answering after 20 s — see $LOG" >&2 + exit 1 + fi + fi +} + +cmd_uninstall() { + if have_user_systemd && [[ -f "$UNIT" ]]; then + systemctl --user disable --now "$UNIT_NAME" >/dev/null 2>&1 || true + rm -f "$UNIT" + systemctl --user daemon-reload + echo "removed $UNIT" + else + echo "no $UNIT_NAME to remove" + fi + stop_detached +} + +cmd_status() { + if have_user_systemd && [[ -f "$UNIT" ]]; then + echo "unit $UNIT_NAME: $(systemctl --user is-active "$UNIT_NAME" 2>/dev/null || true), enabled: $(systemctl --user is-enabled "$UNIT_NAME" 2>/dev/null || true)" + else + echo "unit none installed" + fi + if [[ -f "$PIDFILE" ]] && kill -0 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null; then echo "detached running, pid $(cat "$PIDFILE")"; fi + if health; then echo "console answering on http://127.0.0.1:$PORT/"; else echo "console NOT answering on port $PORT"; fi + echo "logs journalctl --user -u $UNIT_NAME | $LOG" +} + +cmd="${1:-}"; [[ $# -gt 0 ]] && shift || true +while [[ $# -gt 0 ]]; do + case "$1" in + --port) [[ $# -ge 2 ]] || { echo "service-linux.sh: --port needs a number" >&2; exit 2; }; PORT="$2"; shift ;; + *) echo "service-linux.sh: unknown option '$1'" >&2; exit 2 ;; + esac + shift +done +[[ "$PORT" =~ ^[0-9]{1,5}$ ]] || { echo "service-linux.sh: PORT must be a number, got '$PORT'" >&2; exit 2; } + +case "$cmd" in + install) cmd_install ;; + uninstall) cmd_uninstall ;; + status) cmd_status ;; + print) PYR="$(resolve_py || echo python3)"; unit_text "$PYR" ;; + -h|--help|"") sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; [[ -n "$cmd" ]] || exit 2 ;; + *) echo "service-linux.sh: unknown command '$cmd' (install | uninstall | status | print)" >&2; exit 2 ;; +esac diff --git a/docs/MACOS.md b/docs/MACOS.md index ce712ba..7f3850b 100644 --- a/docs/MACOS.md +++ b/docs/MACOS.md @@ -5,6 +5,9 @@ Linux README assumes differently: the interpreter and the service. ## One-time setup +Shortcut: `./install.sh --all` does this setup (with `uv` when installed, else a `python3.11+` venv + pip), the +LaunchAgent and the MCP registration in one go. The manual steps below are what it does. + The console needs Python 3.11+ with the `mcp` client. macOS's `/usr/bin/python3` is 3.9, so give the repo its own venv: diff --git a/install.sh b/install.sh index b08f370..7684cee 100755 --- a/install.sh +++ b/install.sh @@ -3,6 +3,12 @@ # # ./install.sh copy plugin/ -> $HERMES_HOME/desktop-plugins/traders-desk/, the desk # skill, and register the chart's MCP server with Hermes (idempotent) +# ./install.sh --all the one-command install: everything above, plus a python with the `mcp` +# client (uv when present: seconds, else pip), the console as a service +# (systemd user unit / launchd agent / detached fallback) and a wait until +# it answers. Afterwards you only reload the plugins in Hermes. +# ./install.sh --setup-python only the python step (same as ./bin/setup-python.sh) +# ./install.sh --service only the service step (./console/service-linux.sh | service-macos.sh) # ./install.sh --no-mcp skip the MCP registration (register it later: ./bin/register-mcp.sh) # ./install.sh --doctor check interpreter, console port, service, plugin folder, MCP server # ./install.sh --uninstall remove the installed plugin and the desk skill (prints what is left to undo) @@ -18,9 +24,10 @@ # Flags may be combined in any order. An unknown flag is an error: it never installs by accident. # To refresh the vendored Vela / PineTS builds see console/frontend/vendor/VENDORING.md. # -# This script does not start the console: the plugin only frames it, so the console must be -# listening on http://127.0.0.1:$PORT (see console/start.sh and the README's service section). +# Without --all / --service this script does not start the console: the plugin only frames it, so the +# console must be listening on http://127.0.0.1:$PORT (see console/start.sh and the README). set -euo pipefail +START_TS="$(date +%s)" HERE="$(cd "$(dirname "$0")" && pwd)" HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}" @@ -40,9 +47,9 @@ SKILL_DST="$HERMES_HOME/skills/trading/trader-desk" PORT="${PORT:-8787}" CONSOLE_URL="${LUXALGO_CONSOLE:-http://127.0.0.1:$PORT}" -usage() { sed -n '2,/^# listening on/p' "$0" | sed 's/^# \{0,1\}//'; } +usage() { sed -n '2,/^set -euo pipefail/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; } -DOCTOR=0 UNINSTALL=0 WITH_BT=0 WITH_EDGE=0 NO_MCP=0 +DOCTOR=0 UNINSTALL=0 WITH_BT=0 WITH_EDGE=0 NO_MCP=0 ALL=0 SETUP_PY=0 SERVICE=0 for arg in "$@"; do case "$arg" in -h|--help) usage; exit 0 ;; @@ -51,6 +58,9 @@ for arg in "$@"; do --with-backtest) WITH_BT=1 ;; --with-edge) WITH_EDGE=1 ;; --no-mcp) NO_MCP=1 ;; + --all) ALL=1; SETUP_PY=1; SERVICE=1 ;; + --setup-python) SETUP_PY=1 ;; + --service) SERVICE=1 ;; --vendor) echo "install.sh: --vendor was removed (it rewrote committed files without checking them); see console/frontend/vendor/VENDORING.md" >&2; exit 2 ;; *) echo "install.sh: unknown option '$arg'" >&2; usage >&2; exit 2 ;; esac @@ -84,6 +94,7 @@ if [[ $UNINSTALL -eq 1 ]]; then echo " hermes mcp remove traders-chart (the MCP registration)" echo " systemctl --user disable --now traders-agent.service (Linux: if you installed the unit)" echo " ./console/service-macos.sh uninstall (macOS: if you installed the LaunchAgent)" + echo " ./console/service-linux.sh uninstall (Linux: the unit ./install.sh --all wrote, or the detached console)" echo " ~/.local/state/traders-agent/ (token, paper account) ~/.local/share/traders-agent/ (caches, Edge Stats, backtest venv)" exit 0 fi @@ -163,6 +174,13 @@ mkdir -p "$SKILL_DST" cp "$HERE/skills/trader-desk/SKILL.md" "$SKILL_DST/SKILL.md" echo "desk skill -> $SKILL_DST" +# One python with the `mcp` client, made fast (uv if present). Must run before the MCP registration +# and the service step below: both look for /.venv first. +if [[ $SETUP_PY -eq 1 ]]; then + echo + "$HERE/bin/setup-python.sh" || { echo "install.sh: python setup failed — fix it and run ./bin/setup-python.sh, then ./install.sh --all again" >&2; exit 1; } +fi + if [[ $WITH_BT -eq 1 ]]; then # Optional, and never a default: vectorbt pulls pandas + numba (~840 MB) and needs the network # once. It lives in its own venv so the console stays stdlib-only, and it is plain `vectorbt` @@ -237,6 +255,22 @@ if [[ $WITH_EDGE -eq 1 ]]; then echo "next: open the pane, ⋯ -> Edge Stats, and load the demo data (or download BTCUSDT)" fi +# The console as a service (--all / --service): installs, starts and waits until it answers, so the +# restart block below must not bounce it a second time. +SERVICE_DONE=0 +if [[ $SERVICE -eq 1 ]]; then + echo + case "$(uname -s)" in + Darwin) SERVICE_SH="$HERE/console/service-macos.sh" ;; + *) SERVICE_SH="$HERE/console/service-linux.sh" ;; + esac + if env PORT="$PORT" "$SERVICE_SH" install; then + SERVICE_DONE=1 + else + echo "warning: the service step failed — start the console yourself with ./console/start.sh" >&2 + fi +fi + # Restart the console if a user unit is running it. # # A running console keeps its Python in memory: editing chart_bridge.py (or any backend module) and @@ -252,7 +286,9 @@ elif command -v systemctl >/dev/null 2>&1 && systemctl --user list-unit-files tr UNIT="traders-agent.service" fi -if [[ -n "$UNIT" ]] && systemctl --user is-active --quiet "$UNIT"; then +if [[ $SERVICE_DONE -eq 1 ]]; then + : # just installed and started above +elif [[ -n "$UNIT" ]] && systemctl --user is-active --quiet "$UNIT"; then systemctl --user restart "$UNIT" # Wait for it to actually answer before judging it. Measured on this machine: the console needs # ~7s to come up (it opens an MCP session with a remote server, then binds the port). An earlier @@ -271,7 +307,7 @@ if [[ -n "$UNIT" ]] && systemctl --user is-active --quiet "$UNIT"; then fi elif [[ -n "$UNIT" ]]; then echo "console not running -> $UNIT (start it before using the pane)" -else +elif [[ $SERVICE_DONE -eq 0 ]]; then echo "no user unit found — start the console yourself with ./console/start.sh" echo " macOS: keep it running across logins -> ./console/service-macos.sh install (docs/MACOS.md)" fi @@ -289,6 +325,21 @@ if [[ $NO_MCP -eq 0 ]]; then fi fi +if [[ $ALL -eq 1 ]]; then + READY="not answering yet" + curl -fsS --max-time 3 "$CONSOLE_URL/api/health" >/dev/null 2>&1 && READY="answering on $CONSOLE_URL" + cat < "Reload desktop plugins" + 2. click the row left sidebar -> "Trader's Agent" + (If the row is missing: Settings -> Plugins -> "Trader's Agent" -> on. New agent sessions get the chart tools.) +Check everything any time: ./install.sh --doctor +EOF_ALL + exit 0 +fi + cat <<'EOF' Next: From 863317c947c0e783ffe44290818c9bb04e087e5d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 17:06:36 +0000 Subject: [PATCH 3/6] one version everywhere, and say what the Host allowlist really grants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SERVER_VERSION was typed once at 1.0.0 and never touched, so /api/health, /api/build and the Server: header all answered 1.0.0 while the repo shipped 1.3.0; traders-desk/plugin.yaml had drifted the other way (1.2.0 against a v1.3.0 tag and a catalog entry claiming 1.3.0), so the manifest the catalog reads disagreed with the entry pointing at it. All three state 1.3.0 and test_docs_drift.OneVersionNumber fails while they disagree — the old drift test checked the manifest's name, never its version. TRADERS_AGENT_ALLOWED_HOSTS appeared in no document. Measured: an allowlisted Host from loopback is handed the POST token and POST /api/broker answers 200, so behind `tailscale serve` every device on the tailnet can approve paper orders with ALLOW_LAN unset, while the README's ALLOW_LAN row still promised LAN peers a read-only console. The README now carries the variable, calls each name a full-trust door and corrects that row; three live-socket tests pin the token, the write and the still-refused unknown name. No behaviour changed, only what the repo admits to. Also: the package README documented the pre---all install, and the test counts disagreed (README ~1,130, HANDOFF 1,166). Both now match a measured run: 1,188 tests, 9 skipped, 73 files. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01GLsbckEp88WEwC41dfyMeS --- CHANGELOG.md | 22 +++++ README.md | 11 ++- console/backend/server.py | 5 +- .../backend/tests/test_allowed_hosts_env.py | 96 +++++++++++++++++++ console/backend/tests/test_docs_drift.py | 36 +++++++ docs/HANDOFF.md | 2 +- traders-desk/README.md | 17 +++- traders-desk/plugin.yaml | 4 +- 8 files changed, 185 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 229262c..cf4c1d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,28 @@ All notable changes to this project are documented here. Format: [Keep a Changel ### Fixed +- **The console stopped reporting a version it had not been since September.** `SERVER_VERSION` was typed + once at `1.0.0` and never touched again, so `/api/health`, `/api/build` and the server's own `Server:` + header all answered **1.0.0** while the repo shipped 1.3.0 — a number the agent, a bug report and + `./install.sh --doctor` all read and believe. The manifest had drifted the other way (`traders-desk/plugin.yaml` + said 1.2.0 against a v1.3.0 tag and a catalog entry claiming 1.3.0), so the file the catalog actually reads + disagreed with the entry pointing at it. All three now state **1.3.0**, and + `test_docs_drift.OneVersionNumber` fails while they disagree — the old drift test checked the manifest's + *name* and never its version, which is why nothing caught either one. +- **`TRADERS_AGENT_ALLOWED_HOSTS` was an undocumented change to who can write.** Measured, not inferred: with a + name on the list, a request carrying it from loopback is handed the POST token and `POST /api/broker` answers + **200**. That is the intended trade (`tailscale serve` terminates here, so your phone arrives as 127.0.0.1), + but it means every device on that tailnet can approve paper orders, drive the chart and run Pine **with + `ALLOW_LAN` unset** — and the variable appeared in no document at all, while the README's `ALLOW_LAN` row + still promised "LAN peers get a read-only console", which stopped describing this path. The README now carries + the variable, says plainly that each name is a full-trust door, and corrects the `ALLOW_LAN` row; three live-socket + tests pin the token, the write and the still-refused unknown name (removing the name from the allowlist fails two + of them). No behaviour changed — only what the repository admits to. +- **The package README documented an install that is no longer the short one** (`./console/start.sh` + `./install.sh`, + with no mention of `--all`), and the test counts disagreed across files (README ~1,130, `HANDOFF` 1,166). Both now + match a measured run: **1,188 tests, 9 skipped, 73 files**. The dated measurement block further down `HANDOFF.md` + keeps its own older number, because it is a record of one run and not a claim about today. + - **The README still claimed Linux-only.** macOS support shipped on 13 Oct (`docs/MACOS.md`, the repo venv, `console/service-macos.sh` behind launchd), so the OS row, the service section and the platform bullet now say Linux + macOS, name the launchd counterpart of the systemd unit, and link the Mac setup. Windows stays diff --git a/README.md b/README.md index 47adf93..3f53668 100644 --- a/README.md +++ b/README.md @@ -410,7 +410,8 @@ bin/ register-mcp.sh (the MCP registration on its own) · is-enabl | `LUXALGO_CONSOLE` | `http://127.0.0.1:8787` | where the MCP server, `trader-chart` and `library-indicator` find the console (set it with `hermes mcp add … --env LUXALGO_CONSOLE=http://127.0.0.1:9000` when `PORT` is not 8787) | | `TRADER_CONSOLE_TOKEN_FILE` | `~/.local/state/traders-agent/console.token` | the POST token the console mints and the MCP server and CLI read | | `TRADERS_AGENT_WORKDIR` | `~/Projects/luxalgo-web` if it exists, else `console/agents` | the folder the in-app study bridge runs the agent CLI in (never taken from a request) | -| `TRADERS_AGENT_ALLOW_LAN` | unset | with `--host 0.0.0.0`, let LAN peers receive the POST token; without it they get a read-only console | +| `TRADERS_AGENT_ALLOW_LAN` | unset | with `--host 0.0.0.0`, let peers that reach the console **from their own address** receive the POST token; without it they get a read-only console. It does **not** govern a caller arriving through a local reverse proxy — see the row below | +| `TRADERS_AGENT_ALLOWED_HOSTS` | unset | comma-separated extra `Host` names this console answers to, for a local reverse proxy that forwards the public name (`tailscale serve` does). **Every name you add here is a full-trust door:** the proxy terminates on this machine, so the caller arrives on loopback, is handed the POST token and can write — approve paper orders, drive the chart, run Pine — with `ALLOW_LAN` unset. Only add names that resolve to this machine inside an access-controlled network, and read it as “everyone on that tailnet is me”. Any other name is still refused | | `TRADER_PAPER_FILE` | `~/.local/state/traders-agent/paper.json` | the paper account (use another path for a second test console) | | `LUXALGO_AGENTS_DIR` | `console/agents` | runtime state: chart bridge files, study threads, shots | | `HERMES_CLI` | `hermes` on `PATH` | CLI the in-app study bridge shells out to | @@ -454,6 +455,12 @@ it from `http://127.0.0.1:8787/api/library/thumb`: **~5 ms warm instead of ~2 s* - **The bridge is not a headless renderer.** `trader-chart` and the MCP tools only take effect while a chart view is mounted (the Hermes pane or a browser tab); with none attached they fail fast with "no chart view attached" rather than hanging. Commands are pushed, so a view answers in tens of ms. +- **Reaching the console through a proxy widens who can write.** The trust model is “a loopback caller is + the human at this machine”. A local reverse proxy (`tailscale serve`) makes every device on that network a + loopback caller, so `TRADERS_AGENT_ALLOWED_HOSTS` turns that network into the trusted set — the approve + brake on paper orders is then only as strong as the network's own access control. Pinned by + `console/backend/tests/test_allowed_hosts_env.py`, which asserts an allowlisted name both receives the token + and writes. - **One console per machine** on one port. No real orders and no brokerage account exist: the only trading is a **simulated Binance spot paper account** (`broker_*`), where the agent can only propose and you approve. The account and the journal its fills keep (win rate, profit factor, the realised curve) are one surface — ⋯ → **Trader's desk**. @@ -478,7 +485,7 @@ python3 -m compileall console/backend The suite is stdlib-only on purpose — the study store, the chat bridge, the chart bridge and the push channel are covered without a browser, a network, or the app — and the MCP tool layer runs against a -stub console. about 1,130 tests; the MCP ones skip themselves when `fastmcp` is absent (CI sets +stub console. about 1,188 tests (73 files, 9 skipped on 16 Oct); the MCP ones skip themselves when `fastmcp` is absent (CI sets `TRADER_CHART_REQUIRE_MCP=1` so they cannot silently skip there). CI (`.github/workflows/ci.yml`) has three jobs: the plugin harness (Node 20 — the real plugin first, diff --git a/console/backend/server.py b/console/backend/server.py index 2ab07f0..b3a9276 100755 --- a/console/backend/server.py +++ b/console/backend/server.py @@ -58,7 +58,10 @@ # Constants # -------------------------------------------------------------------------- -SERVER_VERSION = "1.0.0" +# Bump on release together with traders-desk/plugin.yaml and docs/plugin-catalog-entry.yaml: +# test_docs_drift.OneVersionNumber fails while the three disagree. It is reported on /api/health, +# in /api/build and in this server's own `Server:` header, so a stale value misinforms the agent. +SERVER_VERSION = "1.3.0" DEFAULT_MCP_URL = "https://mcp.luxalgo.com/mcp" # -------------------------------------------------------------------------- diff --git a/console/backend/tests/test_allowed_hosts_env.py b/console/backend/tests/test_allowed_hosts_env.py index ccd4d6c..fdd065c 100644 --- a/console/backend/tests/test_allowed_hosts_env.py +++ b/console/backend/tests/test_allowed_hosts_env.py @@ -6,11 +6,16 @@ import in a subprocess. """ +import json import os +import socket import subprocess import sys +import tempfile +import threading import unittest from pathlib import Path +from unittest import mock BACKEND = Path(__file__).resolve().parents[1] @@ -42,3 +47,94 @@ def test_empty_value_changes_nothing(self): if __name__ == "__main__": unittest.main() + + +class AllowedHostBehindAProxyIsATrustedPeer(unittest.TestCase): + """What an allowlisted Host actually BUYS the caller — pinned, because it is easy to misread. + + `tailscale serve` terminates on this machine and forwards the request to 127.0.0.1 carrying the + tailnet name as Host. So every device on that tailnet arrives as a LOOPBACK peer: `_peer_is_local()` + is true for all of them, and the Host gate is the only thing left that could say no — which is + exactly what TRADERS_AGENT_ALLOWED_HOSTS switches off for the names you list. + + The consequence, measured and asserted below: an allowlisted name gets the POST token and can WRITE + (the paper broker's approve path included) WITHOUT `TRADERS_AGENT_ALLOW_LAN=1`, because ALLOW_LAN + guards a non-loopback peer and a proxied caller is not one. That is the intended trade for reaching + your own console from your own phone; it is pinned here so nobody reads the README's ALLOW_LAN row + ("LAN peers get a read-only console") and concludes this path is read-only too. A name that is NOT + on the list is still refused, which is the half that must never regress. + """ + + PROXY = "macmini.tail1234.ts.net" + + @classmethod + def setUpClass(cls): + sys.path.insert(0, str(BACKEND)) + import server as srv # noqa: PLC0415 - the suite's usual late import + cls.srv = srv + cls.tmp = tempfile.TemporaryDirectory() + frontend = Path(cls.tmp.name) / "frontend" + frontend.mkdir(parents=True) + (frontend / "index.html").write_text("console", encoding="utf-8") + cls._orig_static = srv.Handler.static + srv.Handler.static = srv.StaticFiles(str(frontend)) + cls.token = "allowed-hosts-token-0123456789" + # LOCAL_HOSTS is what the gate consults per request; the env that fills it is read at import, + # so patch the resolved set rather than re-importing the module into this process. + cls.patches = [ + mock.patch.object(srv, "CONSOLE_TOKEN", cls.token), + mock.patch.object(srv, "LOCAL_HOSTS", srv.LOCAL_HOSTS | {cls.PROXY}), + mock.patch.object(srv, "AGENTS_ROOT", cls.tmp.name), + ] + for p in cls.patches: + p.start() + cls.httpd = srv.Server(("127.0.0.1", 0), srv.Handler) + cls.port = cls.httpd.server_address[1] + cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True) + cls.thread.start() + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + cls.srv.Handler.static = cls._orig_static + for p in cls.patches: + p.stop() + cls.tmp.cleanup() + + def call(self, path, method="GET", headers=None, body=None, host=None): + data = json.dumps(body).encode() if body is not None else b"" + head = {"Host": host or f"127.0.0.1:{self.port}", "Connection": "close"} + head.update(headers or {}) + if body is not None: + head.setdefault("Content-Type", "application/json") + head["Content-Length"] = str(len(data)) + with socket.create_connection(("127.0.0.1", self.port), timeout=10) as sock: + sock.sendall((f"{method} {path} HTTP/1.1\r\n" + + "".join(f"{k}: {v}\r\n" for k, v in head.items()) + + "\r\n").encode() + data) + reply = sock.makefile("rb").read() + top, _, payload = reply.partition(b"\r\n\r\n") + status = int(top.decode("latin-1").split("\r\n")[0].split()[1]) + try: + return status, json.loads(payload.decode() or "null") + except ValueError: + return status, payload + + def test_an_allowlisted_proxy_name_is_handed_the_post_token(self): + code, body = self.call("/api/session", host=self.PROXY) + self.assertEqual(code, 200) + self.assertEqual(body["data"]["token"], self.token, + "an allowlisted Host is a trusted peer: it receives the write token") + + def test_and_that_token_really_writes_without_allow_lan(self): + self.assertFalse(self.srv.ALLOW_LAN, "this test is only meaningful while ALLOW_LAN is off") + code, _ = self.call("/api/broker", "POST", { + "X-Trader-Token": self.token, + "Origin": f"http://{self.PROXY}", + }, {"op": "state"}, host=self.PROXY) + self.assertEqual(code, 200, "the proxied caller reaches a token-gated writer, not a 401/403") + + def test_a_name_that_is_not_on_the_list_is_still_refused(self): + code, _ = self.call("/api/session", host="evil.example.com") + self.assertEqual(code, 403, "the DNS-rebinding refusal must survive the allowlist") diff --git a/console/backend/tests/test_docs_drift.py b/console/backend/tests/test_docs_drift.py index 47fbe57..b969161 100644 --- a/console/backend/tests/test_docs_drift.py +++ b/console/backend/tests/test_docs_drift.py @@ -20,6 +20,7 @@ MCP_TOOLS_DOC = os.path.join(ROOT, "docs", "MCP-TOOLS.md") MANIFEST = os.path.join(ROOT, "traders-desk", "plugin.yaml") DESKTOP_ENTRY = os.path.join(ROOT, "traders-desk", "desktop", "plugin.js") +CONSOLE_SERVER = os.path.join(ROOT, "console", "backend", "server.py") TABLE_HEADER = "| Tool | What it does |" @@ -147,3 +148,38 @@ def test_mcp_tools_doc_heading_matches_the_count(self): if __name__ == "__main__": # pragma: no cover unittest.main() + + +class OneVersionNumber(unittest.TestCase): + """The three places that state a version must state the SAME one. + + They rotted apart exactly as you would expect, each for its own reason: `SERVER_VERSION` was + typed once at 1.0.0 and never touched again (nothing reads it back, so nothing complained), + while the manifest and the catalog entry are edited by different hands at release time. The + console then reported `"version": "1.0.0"` on `/api/health`, in `/api/build` and in its own + `Server:` header while the repo shipped 1.3.0 - a number an agent, a bug report and + `./install.sh --doctor` all read and believe. + + Deliberately three literals and one test, not one file read at runtime: the console is + stdlib-only and must not grow an import-time file read (and a fallback value would be the same + lie with extra steps). Bumping a release means editing all three; this fails loudly until you do. + """ + + def version_of(self, path: str, pattern: str) -> str: + found = re.search(pattern, _read(path), re.M) + self.assertIsNotNone(found, f"no version found in {os.path.relpath(path, ROOT)}") + return found.group(1) + + def test_manifest_catalog_entry_and_console_agree(self): + manifest = self.version_of(MANIFEST, r'^version:\s*"?([0-9]+\.[0-9]+\.[0-9]+)"?\s*$') + catalog = self.version_of(CATALOG, r'^version:\s*"?([0-9]+\.[0-9]+\.[0-9]+)"?\s*$') + console = self.version_of(CONSOLE_SERVER, r'^SERVER_VERSION\s*=\s*"([0-9]+\.[0-9]+\.[0-9]+)"') + self.assertEqual( + {"traders-desk/plugin.yaml": manifest, + "docs/plugin-catalog-entry.yaml": catalog, + "console/backend/server.py": console}, + {"traders-desk/plugin.yaml": manifest, + "docs/plugin-catalog-entry.yaml": manifest, + "console/backend/server.py": manifest}, + "the manifest, the catalog entry and the console must all state one version", + ) diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 5630f58..055b145 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -48,7 +48,7 @@ native tools. Versions: Hermes Desktop 0.21.5, console `SERVER_VERSION = 1.0.0`. CI was red from 28 Sep (`1f9d340`) to 2 Oct (`8df6e2e` — a stale MCP test only CI could see); green since `ab3708b`, and -green on every ship below. **about 1,166 backend tests** (skips depend on `fastmcp`, node and a real Edge Stats engine; run the suite for the exact count), 9 plugin contributions across 5 areas. +green on every ship below. **about 1,188 backend tests** (skips depend on `fastmcp`, node and a real Edge Stats engine; run the suite for the exact count), 9 plugin contributions across 5 areas. Shipped since this file was written: the paper broker (Phase 5), replay (6/6b), the top-bar one-door consolidation, the drawer as the single Library surface, and Phase 7 — three agent doors into Vela (`chart_drawing` 76 types / `chart_view` settings / `chart_marks`), 56 MCP tools (8 of them `edgestats_*`). 4 Oct: Edge Stats — the optional local engine, the sheet behind the `⋯` menu, the eight tools (see CHANGELOG; real Binance / Dukascopy downloads were never run from the build machine). Also 4 Oct: the top row diff --git a/traders-desk/README.md b/traders-desk/README.md index 55f111d..bf050df 100644 --- a/traders-desk/README.md +++ b/traders-desk/README.md @@ -18,10 +18,21 @@ local Python service that lives in the same repository (`console/`) and is start operator: ```shell -git clone https://github.com/godzillacode0000/tradersagent-plugin +git clone --depth 1 https://github.com/godzillacode0000/tradersagent-plugin cd tradersagent-plugin -./console/start.sh # terminal 1 — the console (macOS: see docs/MACOS.md) -./install.sh # the plugin + the desk skill + the MCP registration +./install.sh --all # the console's python + the service + the plugin + the skill + the MCP registration +``` + +`--all` is the whole install: it makes a python with the `mcp` client (`uv` when it is on PATH, +else a venv + pip), installs the console as a service (systemd user unit, launchd agent, or a +detached process where neither exists), registers the `traders-chart` MCP server and waits until +the console answers. The steps still exist on their own if you would rather drive them: + +```shell +./bin/setup-python.sh # just the interpreter +./console/start.sh # the console in the foreground (macOS notes: docs/MACOS.md) +./install.sh # just the plugin + the desk skill + the MCP registration +./install.sh --doctor # check all of it ``` Without the console the pane says so, in one line, instead of showing a blank page. The agent's diff --git a/traders-desk/plugin.yaml b/traders-desk/plugin.yaml index 39e2f69..3cc4840 100644 --- a/traders-desk/plugin.yaml +++ b/traders-desk/plugin.yaml @@ -8,7 +8,9 @@ # agent's chart tools come the same way — ./bin/register-mcp.sh registers the traders-chart MCP # server with Hermes; the plugin itself registers UI, not tools (so `provides_tools` stays empty). name: traders-desk -version: 1.2.0 +# Bump with docs/plugin-catalog-entry.yaml and console/backend/server.py (SERVER_VERSION): +# test_docs_drift.OneVersionNumber fails while the three disagree. +version: 1.3.0 description: >- A chart-first Trader's Agent for Hermes Desktop: one sidebar row docks a live Vela chart (the LuxAlgo engine this repo vendors) beside your conversation, with replay, 76 drawing tools, the From aca9d43b35fcb9fbabb854427153954f9d565f38 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 02:50:54 +0000 Subject: [PATCH 4/6] fix(data): full long windows from the tick store, a bounded cache, CI green - fxticks.bars sized its window from a 0.4x guess and grew it a day per pass, re-reading every hour each time and stopping after 60: on a two-year store 500 x 4h gave 404 bars (12 s) and 500 x D gave 186 (67 s), silently. The window is now sized once (1.5x the trading time + 4 days, one wider pass, never before the store's first day): 500 and 500 in 0.8 s and 4.9 s, identical bars elsewhere. - The LRU held raw ticks (gigabytes at 4,096 busy hours); hours are now packed minute bars, ~4 KB each. The docstring's on-disk bars-v1 cache never existed; the claim and the unused TRADERS_FX_BARS go. - A truncated hour raised inside bars() and sank the whole request to the network; it is now skipped and counted (unreadable_hours). fx-fetch writes via a .part file and rename so it leaves none. - fx-fetch walked to the current, unfinished hour and marked unpublished hours .empty for good; it now ends at the last complete hour and only marks 404s older than a day. - fxdata.status() dropped `ticks` when the network cache folder did not exist, so the Data tab sat on "Reading the tick store..." for an operator who only ran fx-fetch. One shape always, plus `yahoo`; the card's Yahoo line follows it and the card re-reads on every visit. - Unused `import json` in tools/fx-fetch.py, which failed the ruff gate on main. 15 new tests; full suite 1,293 OK. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GLsbckEp88WEwC41dfyMeS --- CHANGELOG.md | 25 ++++ README.md | 2 +- console/backend/fxdata.py | 21 +-- console/backend/fxticks.py | 156 ++++++++++++++--------- console/backend/tests/test_desk_sheet.py | 8 ++ console/backend/tests/test_fx_ticks.py | 60 +++++++++ console/backend/tests/test_fxdata.py | 17 ++- console/backend/tests/test_fxticks.py | 103 +++++++++++++++ console/frontend/desk.js | 8 +- docs/HANDOFF.md | 2 +- tools/fx-fetch.py | 26 +++- 11 files changed, 348 insertions(+), 80 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df385f2..e0dbeec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,31 @@ All notable changes to this project are documented here. Format: [Keep a Changel ## [Unreleased] +### Fixed + +- **Long tick-store windows came back short and slow** (30 Oct): `fxticks.bars` grew its window a day + per pass from a 0.4x guess, re-reading every hour on every pass and giving up after 60. On a two-year + store 500 x 4h returned 404 bars in 12 s and 500 x D returned 186 in 67 s, with no sign anything was + missing. The window is now sized once from the timeframe (1.5x the trading time plus a long weekend, + one wider pass for holidays, never before the store's first day): 500 and 500, in 0.8 s and 4.9 s. + Same bars as before wherever the old walk did reach. Weekends cost one stat instead of 24. +- **The hour cache held raw ticks**: 4,096 decoded hours of a busy pair ran to gigabytes. Each hour is + now packed as at most 60 minute bars (~4 KB), so 20,000 hours stay under ~80 MB. The docstring's + promise of an on-disk `fx/bars-v1` cache, which never existed, is gone, along with the unused + `TRADERS_FX_BARS`. +- **One truncated hour sank the whole request**: a download cut off mid-write left a half gzip that + raised inside `bars()`, so the provider dropped the store and went to the network. Unreadable hours + are now skipped and counted (`unreadable_hours` in the meta). `tools/fx-fetch.py` writes each hour to a + `.part` file and renames it, so it no longer leaves them. +- **`tools/fx-fetch.py` cached hours that were not final**: the walk ended at the current hour (cached + half-full for good), and a 404 the feed had simply not published yet became a permanent `.empty` hole. + It now stops at the last complete hour and marks a 404 empty only once it is a day old. +- **The Data tab could read "Reading the tick store…" forever**: `fxdata.status()` returned early when + the network cache folder did not exist and dropped the `ticks` block, which is exactly the case for an + operator who has only run `fx-fetch.py`. One shape always now, plus a `yahoo` flag. The card's Yahoo + line follows the server instead of a constant, and it re-reads the store on every visit. +- **CI was red on `main`**: an unused `import json` in `tools/fx-fetch.py` failed the ruff gate. + ### Added - **A Data tab in the desk sheet** (21 Oct), so the source is visible instead of inferred: it reads diff --git a/README.md b/README.md index d102317..fef5b54 100644 --- a/README.md +++ b/README.md @@ -567,7 +567,7 @@ python3 -m compileall console/backend The suite is stdlib-only on purpose — the study store, the chat bridge, the chart bridge and the push channel are covered without a browser, a network, or the app — and the MCP tool layer runs against a -stub console. about 1,188 tests (73 files, 9 skipped on 16 Oct); the MCP ones skip themselves when `fastmcp` is absent (CI sets +stub console. about 1,314 tests (81 files, 9 skipped on 30 Oct); the MCP ones skip themselves when `fastmcp` is absent (CI sets `TRADER_CHART_REQUIRE_MCP=1` so they cannot silently skip there). CI (`.github/workflows/ci.yml`) has three jobs: the plugin harness (Node 20 — the real plugin first, diff --git a/console/backend/fxdata.py b/console/backend/fxdata.py index ba20031..4a68d33 100644 --- a/console/backend/fxdata.py +++ b/console/backend/fxdata.py @@ -287,6 +287,10 @@ def _from_ticks(pair: str, tf: str, want: int, wanted_end: dt.datetime): return rows, meta +def _yahoo_allowed() -> bool: + return os.environ.get("TRADERS_FX_ALLOW_YAHOO", "").strip() in ("1", "true", "yes") + + def _fallback(pair: str, tf: str, want: int): """Yahoo is OFF unless TRADERS_FX_ALLOW_YAHOO=1: the operator ruled it out for backtests. @@ -294,7 +298,7 @@ def _fallback(pair: str, tf: str, want: int): answer silently: unset, the call fails with the reason instead of substituting mid prices that have no volume and no spread (and which once got labelled "dukascopy"). """ - if os.environ.get("TRADERS_FX_ALLOW_YAHOO", "").strip() not in ("1", "true", "yes"): + if not _yahoo_allowed(): raise FxError("no local ticks for this pair and the Dukascopy feed is unreachable; " "Yahoo is disabled (set TRADERS_FX_ALLOW_YAHOO=1 to allow the labelled fallback)", "no_local_ticks") @@ -385,15 +389,14 @@ def symbol_info(pair: str) -> dict: def status() -> dict: - """How much is cached, so a caller can say 'first load takes a minute' honestly.""" - if not CACHE.exists(): - # One shape always: the empty-cache branch used to omit `pairs_supported`/`feed`, and a test - # that read it passed or failed by whether this machine's cache dir happened to exist. - return {"home": str(CACHE), "pairs": {}, "hours": 0, "bytes": 0, - "feed": FEED, "pairs_supported": list(PAIRS)} + """How much is cached, so a caller can say 'first load takes a minute' honestly. + + One shape always, with or without a network cache: the empty-cache branch once returned early and + dropped `ticks`, so an operator who had only run tools/fx-fetch.py saw an endless "Reading…" card. + """ pairs: dict[str, dict] = {} total_h = total_b = 0 - for d in sorted(CACHE.iterdir()): + for d in (sorted(CACHE.iterdir()) if CACHE.exists() else ()): if not d.is_dir(): continue n = b = 0 @@ -404,7 +407,7 @@ def status() -> dict: total_h += n total_b += b out = {"home": str(CACHE), "pairs": pairs, "hours": total_h, "bytes": total_b, - "feed": FEED, "pairs_supported": list(PAIRS)} + "feed": FEED, "pairs_supported": list(PAIRS), "yahoo": _yahoo_allowed()} try: import fxticks out["ticks"] = fxticks.status() diff --git a/console/backend/fxticks.py b/console/backend/fxticks.py index 76070cf..ce25d0c 100644 --- a/console/backend/fxticks.py +++ b/console/backend/fxticks.py @@ -15,24 +15,25 @@ Storage read: `~/.local/share/traders-agent/fx/ticks-v1///.json.gz`, the shape `tools/fx-fetch.py` writes (v1 JSON, whole hour, cumulative deltas). `.empty` markers are shut hours. -Resampled bars are cached per symbol/timeframe/month under `fx/bars-v1/…` so a 500-bar request costs one -pass over the hours, not one pass per request. +Each hour is decoded once and kept in memory as at most 60 packed minute bars (~3 KB), keyed by path and +mtime, so a repeat request is a resample, not a re-read. There is no on-disk bar cache: the first daily or +4h request over a long window still decodes every hour in it once. """ from __future__ import annotations +import array import datetime as dt import gzip import json import os import statistics +import zlib from functools import lru_cache from pathlib import Path TICKS = Path(os.environ.get("TRADERS_FX_TICKS") or Path.home() / ".local/share/traders-agent/fx/ticks-v1") -BARS = Path(os.environ.get("TRADERS_FX_BARS") - or Path.home() / ".local/share/traders-agent/fx/bars-v1") SYMBOLS = ("GBPUSD", "EURUSD", "GBPJPY", "XAUUSD", "XAGUSD", "NAS100", "SP500") TIMEFRAMES = {"1": 1, "5": 5, "15": 15, "30": 30, "60": 60, "120": 120, "240": 240, "D": 1440} @@ -82,61 +83,97 @@ def _decode(doc: dict): return out -@lru_cache(maxsize=4096) -def _hour(path_str: str, mtime_ns: int): - """One instrument-hour, decoded and cached by (path, mtime) so a re-run sees fresh bytes.""" - with gzip.open(path_str, "rb") as fh: - return tuple(_decode(json.loads(fh.read()))) - +_FIELDS = 7 # epoch minute, open, high, low, close, ticks, median spread -def hour_ticks(symbol: str, when: dt.datetime) -> tuple: - path = TICKS / symbol / when.strftime("%Y-%m-%d") / f"{when.hour:02d}.json.gz" - if not path.exists() or path.stat().st_size == 0: - return () - return _hour(str(path), path.stat().st_mtime_ns) +@lru_cache(maxsize=20000) # ~2 years of one symbol's hours at ~3 KB each +def _hour(path_str: str, mtime_ns: int): + """One instrument-hour as packed minute bars, cached by (path, mtime) so a re-run sees fresh bytes. -def _minute_bars(symbol: str, start: dt.datetime, end: dt.datetime) -> dict[int, dict]: - """M1 bars keyed by epoch-minute, built from ticks.""" - out: dict[int, dict] = {} + Minute bars, not ticks: a busy hour is thousands of ticks, and holding thousands of hours of tick + tuples ran to gigabytes. None when the file cannot be read (a download cut off mid-write). + """ + try: + with gzip.open(path_str, "rb") as fh: + ticks = _decode(json.loads(fh.read())) + except (OSError, EOFError, ValueError, KeyError, TypeError, zlib.error): + return None + minutes: dict[int, list] = {} + for ms, bid, ask, _bv, _av in ticks: + mid = (bid + ask) / 2.0 + minute = ms // 60000 # epoch MINUTES + bar = minutes.get(minute) + if bar is None: + minutes[minute] = [mid, mid, mid, mid, 1, [ask - bid]] + else: + bar[1] = max(bar[1], mid) + bar[2] = min(bar[2], mid) + bar[3] = mid + bar[4] += 1 + bar[5].append(ask - bid) + packed = array.array("d") + for minute in sorted(minutes): + o, h, low, c, v, spreads = minutes[minute] + # Each minute keeps its MEDIAN spread, so one bad print cannot widen a 30m bar. + packed.extend((minute, o, h, low, c, v, statistics.median(spreads))) + return packed + + +def _hour_path(symbol: str, when: dt.datetime) -> Path: + return TICKS / symbol / when.strftime("%Y-%m-%d") / f"{when.hour:02d}.json.gz" + + +def _packed(symbol: str, when: dt.datetime): + """The hour's packed minutes; empty when the hour is not on disk, None when it is unreadable.""" + path = _hour_path(symbol, when) + try: + st = path.stat() + except OSError: + return array.array("d") + if st.st_size == 0: + return array.array("d") + return _hour(str(path), st.st_mtime_ns) + + +def hour_minutes(symbol: str, when: dt.datetime) -> list[tuple]: + """`(epoch_minute, open, high, low, close, ticks, median_spread)` per minute of one hour.""" + packed = _packed(clean_pair(symbol), when) or () + return [tuple(packed[i:i + _FIELDS]) for i in range(0, len(packed), _FIELDS)] + + +def _minute_bars(symbol: str, start: dt.datetime, end: dt.datetime) -> tuple[dict[int, tuple], int]: + """(M1 bars keyed by epoch-minute, hours that could not be read) between two hours, inclusive.""" + out: dict[int, tuple] = {} + unreadable = 0 cur = start.replace(minute=0, second=0, microsecond=0) while cur <= end: - for ms, bid, ask, _bv, _av in hour_ticks(symbol, cur): - mid = (bid + ask) / 2.0 - minute = ms // 60000 # epoch MINUTES - bar = out.get(minute) - spread = ask - bid - if bar is None: - out[minute] = {"t": minute * 60000, "o": mid, "h": mid, "l": mid, "c": mid, - "v": 1, "s": [spread]} - else: - bar["h"] = max(bar["h"], mid) - bar["l"] = min(bar["l"], mid) - bar["c"] = mid - bar["v"] += 1 - bar["s"].append(spread) + if not (TICKS / symbol / cur.strftime("%Y-%m-%d")).is_dir(): # a weekend: one stat, not 24 + cur = cur.replace(hour=0) + dt.timedelta(days=1) + continue + packed = _packed(symbol, cur) + if packed is None: + unreadable += 1 + else: + for i in range(0, len(packed), _FIELDS): + out[int(packed[i])] = tuple(packed[i + 1:i + _FIELDS]) cur += dt.timedelta(hours=1) - return out + return out, unreadable -def _resample(m1: dict[int, dict], minutes: int) -> list[dict]: +def _resample(m1: dict[int, tuple], minutes: int) -> list[dict]: buckets: dict[int, dict] = {} - order = sorted(m1) - for key in order: - bar = m1[key] + for key in sorted(m1): + o, h, low, c, v, minute_spread = m1[key] slot = key // minutes * minutes # epoch minutes, bucketed agg = buckets.get(slot) - # Each minute contributes its MEDIAN spread, so one bad print cannot widen a 30m bar. - minute_spread = statistics.median(bar["s"]) if bar["s"] else 0.0 if agg is None: - buckets[slot] = {"openTime": slot * 60000, "open": bar["o"], "high": bar["h"], - "low": bar["l"], "close": bar["c"], "volume": bar["v"], - "spread": minute_spread, "_n": 1} + buckets[slot] = {"openTime": slot * 60000, "open": o, "high": h, "low": low, "close": c, + "volume": int(v), "spread": minute_spread, "_n": 1} else: - agg["high"] = max(agg["high"], bar["h"]) - agg["low"] = min(agg["low"], bar["l"]) - agg["close"] = bar["c"] - agg["volume"] += bar["v"] + agg["high"] = max(agg["high"], h) + agg["low"] = min(agg["low"], low) + agg["close"] = c + agg["volume"] += int(v) agg["spread"] += minute_spread agg["_n"] += 1 rows = [] @@ -160,28 +197,28 @@ def bars(pair: str, timeframe: str = "30", limit: int = 500, tf = str(timeframe or "30").upper() if tf not in TIMEFRAMES: raise TickError(f"{timeframe!r} is not one of {', '.join(TIMEFRAMES)}") - if not has(symbol): - raise TickError(f"no local ticks for {symbol}") minutes = TIMEFRAMES[tf] wanted_end = (end or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc) wanted_end = wanted_end.replace(minute=0, second=0, microsecond=0) - cov = coverage(symbol) or {} - newest_day = cov.get("to") - if not newest_day: + cov = coverage(symbol) + if not cov: raise TickError(f"no local ticks for {symbol}") + first_day = dt.datetime.strptime(cov["from"], "%Y-%m-%d").replace(tzinfo=dt.timezone.utc) want = max(1, min(int(limit), 20000)) - # Walk back a day at a time until the resample yields enough bars; weekends/holidays cost ~40%. - span = dt.timedelta(days=1) + # Size the window from the timeframe once: markets trade about 5 days in 7, so read 1.5x the trading + # time plus a long weekend. A holiday or a gap in the store gets one wider pass. Never read before + # the store's first day — there is nothing there, and a short store answers with what it holds. + span = dt.timedelta(minutes=want * minutes) * 1.5 + dt.timedelta(days=4) rows: list[dict] = [] - start = wanted_end - for _ in range(60): - start = wanted_end - span - dt.timedelta(minutes=want * minutes * 0.4) - m1 = _minute_bars(symbol, start, wanted_end) + unreadable = 0 + for _ in range(2): + start = max(first_day, wanted_end - span) + m1, unreadable = _minute_bars(symbol, start, wanted_end) rows = _resample(m1, minutes) - if len(rows) >= want: + if len(rows) >= want or start == first_day: break - span += dt.timedelta(days=1) + span *= 3 rows = rows[-want:] if not rows: raise TickError(f"the tick store has no bars for {symbol} in that window") @@ -192,6 +229,7 @@ def bars(pair: str, timeframe: str = "30", limit: int = 500, "lag_hours": round((wanted_end - dt.datetime.fromtimestamp( rows[-1]["openTime"] / 1000, dt.timezone.utc)).total_seconds() / 3600.0, 1), "store": {"from": cov.get("from"), "to": cov.get("to"), "hours": cov.get("hours")}, + "unreadable_hours": unreadable, "spread_mean": round(sum(r["spread"] for r in rows) / len(rows), 8)} return rows, meta diff --git a/console/backend/tests/test_desk_sheet.py b/console/backend/tests/test_desk_sheet.py index 6bb831a..f4b21da 100644 --- a/console/backend/tests/test_desk_sheet.py +++ b/console/backend/tests/test_desk_sheet.py @@ -152,5 +152,13 @@ def test_it_says_yahoo_is_off(self): # the operator's ruling: no silent substitution, and the card has to say so self.assertIn("Yahoo off", self.js) + def test_the_yahoo_line_follows_the_server_not_a_constant(self): + # with TRADERS_FX_ALLOW_YAHOO=1 the card used to keep saying "Yahoo off" + self.assertIn("status.yahoo", self.js) + + def test_the_card_rereads_the_store_each_time_the_tab_opens(self): + # a download finished while the console ran was invisible until a page reload + self.assertNotIn("S.data.asked", self.js) + def test_symbols_are_escaped(self): self.assertIn("esc(sym)", self.js) diff --git a/console/backend/tests/test_fx_ticks.py b/console/backend/tests/test_fx_ticks.py index 20de977..083e898 100644 --- a/console/backend/tests/test_fx_ticks.py +++ b/console/backend/tests/test_fx_ticks.py @@ -72,3 +72,63 @@ def test_the_seven_instruments_have_feed_codes(self): def test_storage_layout_is_symbol_day_hour(self): path = fxf.hour_path("GBPUSD", dt.datetime(2026, 9, 24, 10, tzinfo=dt.timezone.utc)) self.assertTrue(str(path).endswith("GBPUSD/2026-09-24/10.json.gz")) + + +class TheWriteIsAtomic(unittest.TestCase): + """An interrupted walk must not leave a half-written hour that a resume then calls 'cached'.""" + + def setUp(self): + import tempfile + from unittest import mock + self.mock = mock + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + p = mock.patch.object(fxf, "HOME", Path(self.tmp.name)) + p.start() + self.addCleanup(p.stop) + self.when = dt.datetime(2026, 9, 24, 10, tzinfo=dt.timezone.utc) + + def test_a_failed_write_leaves_no_hour_behind(self): + with self.mock.patch.object(fxf, "_fetch", return_value=("ok", b'{"timestamp": 0}')), \ + self.mock.patch("os.replace", side_effect=KeyboardInterrupt): + with self.assertRaises(KeyboardInterrupt): + fxf.fetch_one("GBPUSD", "GBP-USD", self.when) + self.assertFalse(fxf.hour_path("GBPUSD", self.when).exists()) + + def test_a_good_write_lands_whole_with_no_temp_file(self): + with self.mock.patch.object(fxf, "_fetch", return_value=("ok", b'{"timestamp": 0}')): + self.assertEqual(fxf.fetch_one("GBPUSD", "GBP-USD", self.when)[0], "ok") + day = fxf.hour_path("GBPUSD", self.when).parent + self.assertEqual(sorted(p.name for p in day.iterdir()), ["10.json.gz"]) + + +class RecentHoursAreNotFinal(unittest.TestCase): + """The walk used to end at the CURRENT hour: a partial hour was then cached as whole, and an hour the + feed had not published yet got an `.empty` marker — a permanent hole a resume never re-asks.""" + + def setUp(self): + import tempfile + from unittest import mock + self.mock = mock + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + p = mock.patch.object(fxf, "HOME", Path(self.tmp.name)) + p.start() + self.addCleanup(p.stop) + + def test_the_walk_ends_at_the_last_complete_hour(self): + now = dt.datetime(2026, 10, 30, 14, 25, tzinfo=dt.timezone.utc) + self.assertEqual(fxf.last_complete_hour(now), dt.datetime(2026, 10, 30, 13, tzinfo=dt.timezone.utc)) + + def test_a_recent_404_is_not_marked_empty(self): + recent = dt.datetime.now(dt.timezone.utc).replace(minute=0, second=0, microsecond=0) \ + - dt.timedelta(hours=3) + with self.mock.patch.object(fxf, "_fetch", return_value=("empty", b"")): + fxf.fetch_one("GBPUSD", "GBP-USD", recent) + self.assertFalse(fxf.marker_path("GBPUSD", recent).exists()) + + def test_an_old_404_is_marked_empty(self): + old = dt.datetime(2026, 1, 1, 3, tzinfo=dt.timezone.utc) + with self.mock.patch.object(fxf, "_fetch", return_value=("empty", b"")): + fxf.fetch_one("GBPUSD", "GBP-USD", old) + self.assertTrue(fxf.marker_path("GBPUSD", old).exists()) diff --git a/console/backend/tests/test_fxdata.py b/console/backend/tests/test_fxdata.py index 37c14d5..1da26d9 100644 --- a/console/backend/tests/test_fxdata.py +++ b/console/backend/tests/test_fxdata.py @@ -122,9 +122,24 @@ def capture(req, timeout=0, **kw): def test_status_has_one_shape_with_or_without_a_cache(self): with mock.patch.object(fxdata, "CACHE", Path(self.tmp.name) / "absent"): empty = fxdata.status() - self.assertEqual(set(empty), {"home", "pairs", "hours", "bytes", "feed", "pairs_supported"}) + self.assertEqual(set(empty), {"home", "pairs", "hours", "bytes", "feed", "pairs_supported", + "ticks", "yahoo"}) self.assertIn("GBPUSD", empty["pairs_supported"]) + def test_status_reports_the_tick_store_even_without_a_network_cache(self): + # an operator who only ran tools/fx-fetch.py has no bi5 cache; the early return dropped `ticks` + # and the desk's Data tab sat on "Reading the tick store..." for good + with mock.patch.object(fxdata, "CACHE", Path(self.tmp.name) / "absent"): + out = fxdata.status() + self.assertIn("symbols", out["ticks"]) + + def test_status_says_whether_yahoo_may_answer(self): + with mock.patch.object(fxdata, "CACHE", Path(self.tmp.name) / "absent"): + with mock.patch.dict("os.environ", {"TRADERS_FX_ALLOW_YAHOO": "1"}): + self.assertTrue(fxdata.status()["yahoo"]) + with mock.patch.dict("os.environ", {"TRADERS_FX_ALLOW_YAHOO": ""}): + self.assertFalse(fxdata.status()["yahoo"]) + def test_a_404_is_an_answer_and_is_cached(self): when = dt.datetime(2026, 10, 15, 10, tzinfo=dt.timezone.utc) with mock.patch("urllib.request.urlopen", self.fake(code=404)): diff --git a/console/backend/tests/test_fxticks.py b/console/backend/tests/test_fxticks.py index 9fc60c2..6e4cfda 100644 --- a/console/backend/tests/test_fxticks.py +++ b/console/backend/tests/test_fxticks.py @@ -133,3 +133,106 @@ def test_fxdata_returns_ticks_before_touching_the_network(self): rows, meta = fxdata._bars("GBPUSD", "30", 10) self.assertEqual(meta["source"], "dukascopy-ticks") self.assertTrue(rows) + + +def _weekday_store(root: Path, symbol: str, last_day: dt.datetime, weekdays: int) -> int: + """`weekdays` trading days ending on `last_day`, two ticks an hour; returns the hour-files written.""" + n, day = 0, last_day + while n < weekdays * 24: + if day.weekday() < 5: + for hour in range(24): + write_hour(root, symbol, day.replace(hour=hour), + [(1_000, 1.30000, 1.30020), (2_000, 1.30010, 1.30030)]) + n += 1 + day -= dt.timedelta(days=1) + return n + + +class LongWindows(unittest.TestCase): + """A 4h or daily request covers months of calendar time. The window has to be sized from the + timeframe once — not grown a day at a time, which re-read every hour on every pass, gave up after + 60 passes and returned fewer bars than asked for without saying so (500 x 4h came back as ~400).""" + + WEEKDAYS = 230 + END = dt.datetime(2026, 10, 24, tzinfo=dt.timezone.utc) # a Saturday: Friday is the last day + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.root = Path(cls.tmp.name) + cls.files = _weekday_store(cls.root, "GBPUSD", dt.datetime(2026, 10, 23, tzinfo=dt.timezone.utc), + cls.WEEKDAYS) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def setUp(self): + self._old = fxticks.TICKS + fxticks.TICKS = self.root + fxticks._hour.cache_clear() + self.addCleanup(setattr, fxticks, "TICKS", self._old) + self.addCleanup(fxticks._hour.cache_clear) + self.passes = 0 + real = fxticks._minute_bars + + def counted(*a, **k): + self.passes += 1 + return real(*a, **k) + + fxticks._minute_bars = counted + self.addCleanup(setattr, fxticks, "_minute_bars", real) + + def test_500_four_hour_bars_are_500(self): + rows, meta = fxticks.bars("GBPUSD", "240", 500, self.END) + self.assertEqual(len(rows), 500) + self.assertEqual(meta["count"], 500) + + def test_150_daily_bars_are_150(self): + rows, _ = fxticks.bars("GBPUSD", "D", 150, self.END) + self.assertEqual(len(rows), 150) + + def test_the_hours_are_read_in_at_most_two_passes(self): + fxticks.bars("GBPUSD", "240", 500, self.END) + self.assertLessEqual(self.passes, 2) + + def test_asking_past_the_store_returns_the_store_and_stops_at_its_first_day(self): + rows, meta = fxticks.bars("GBPUSD", "D", 1000, self.END) + self.assertEqual(len(rows), self.WEEKDAYS) # every day there is, not a guess + self.assertEqual(meta["count"], self.WEEKDAYS) + self.assertLessEqual(self.passes, 2) # and no walking into years with no files + + +class TheHourCache(unittest.TestCase): + """The decoded-hour cache is what makes a second request cheap; it must not hold raw ticks. A busy + hour is thousands of ticks — at thousands of cached hours that was gigabytes of tuples.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self._old = fxticks.TICKS + fxticks.TICKS = self.root + fxticks._hour.cache_clear() + self.addCleanup(setattr, fxticks, "TICKS", self._old) + self.addCleanup(fxticks._hour.cache_clear) + + def test_an_hour_is_cached_as_at_most_sixty_minute_bars(self): + when = dt.datetime(2026, 10, 20, 10, tzinfo=dt.timezone.utc) + write_hour(self.root, "GBPUSD", when, + [(i * 100, 1.30000 + (i % 7) * 1e-5, 1.30020 + (i % 7) * 1e-5) for i in range(3000)]) + cached = fxticks.hour_minutes("GBPUSD", when) + self.assertLessEqual(len(cached), 60) + self.assertEqual(sum(m[5] for m in cached), 3000) # every tick still counted in volume + + def test_a_truncated_hour_is_skipped_not_fatal(self): + # tools/fx-fetch.py interrupted mid-write used to leave a half gzip that broke every window + # containing it — the provider then fell through to the network for the whole request + day = dt.datetime(2026, 10, 20, tzinfo=dt.timezone.utc) + write_hour(self.root, "GBPUSD", day.replace(hour=10), [(1_000, 1.30000, 1.30020)]) + write_hour(self.root, "GBPUSD", day.replace(hour=11), [(1_000, 1.30100, 1.30120)]) + bad = self.root / "GBPUSD" / "2026-10-20" / "11.json.gz" + bad.write_bytes(bad.read_bytes()[:12]) + rows, meta = fxticks.bars("GBPUSD", "60", 10, day.replace(hour=12)) + self.assertEqual(len(rows), 1) + self.assertEqual(meta["unreadable_hours"], 1) diff --git a/console/frontend/desk.js b/console/frontend/desk.js index 7cd03b1..4457561 100644 --- a/console/frontend/desk.js +++ b/console/frontend/desk.js @@ -44,7 +44,7 @@ tab: 'paper', open: false, busy: false, account: null, accountErr: null, firms: null, offers: null, propErr: null, propBusy: false, propAsked: false, firmsNote: '', - data: { status: null, err: null, busy: false, asked: false }, + data: { status: null, err: null, busy: false }, sim: { // the prop-firm simulator (19 Oct) stats: { winrate: 48, avg_win: 1.6, avg_loss: 1, risk: 1, trades_per_day: 4, paths: 10000, seed: 42 }, status: null, busy: false, err: null, result: null, target: null, @@ -359,7 +359,9 @@ if (!rows.length) return '

No ticks on disk yet. Run: python3 tools/fx-fetch.py --years 2

'; return `

Dukascopy ticks on disk · ${int(st.hours)} instrument-hours · ${size(st.bytes)} · - mid-price bars with real volume and median spread · Yahoo off, nothing substituted

+ mid-price bars with real volume and median spread · ${d.status.yahoo + ? 'Yahoo fallback ON (TRADERS_FX_ALLOW_YAHOO), its bars are labelled' + : 'Yahoo off, nothing substituted'}

@@ -494,7 +496,7 @@ if (TABS.some(([id]) => id === tab)) S.tab = tab; render(); if (S.tab === 'propfirms' && !S.propAsked) { S.propAsked = true; pullPropFirms(); } - if (S.tab === 'data' && !S.data.asked) { S.data.asked = true; pullData(); } + if (S.tab === 'data') pullData(); // every visit: a download may have finished since } function open(tab) { diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index bcbd34c..33cd506 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -48,7 +48,7 @@ native tools. Versions: Hermes Desktop 0.21.5, console `SERVER_VERSION = 1.0.0`. CI was red from 28 Sep (`1f9d340`) to 2 Oct (`8df6e2e` — a stale MCP test only CI could see); green since `ab3708b`, and -green on every ship below. **about 1,236 backend tests** (skips depend on `fastmcp`, node and a real Edge Stats engine; run the suite for the exact count), 9 plugin contributions across 5 areas. +green on every ship below. **about 1,314 backend tests** (skips depend on `fastmcp`, node and a real Edge Stats engine; run the suite for the exact count), 9 plugin contributions across 5 areas. Shipped since this file was written: the paper broker (Phase 5), replay (6/6b), the top-bar one-door consolidation, the drawer as the single Library surface, and Phase 7 — three agent doors into Vela (`chart_drawing` 76 types / `chart_view` settings / `chart_marks`), 56 MCP tools (8 of them `edgestats_*`). 4 Oct: Edge Stats — the optional local engine, the sheet behind the `⋯` menu, the eight tools (see CHANGELOG; real Binance / Dukascopy downloads were never run from the build machine). Also 4 Oct: the top row diff --git a/tools/fx-fetch.py b/tools/fx-fetch.py index 8754d36..c37ed41 100644 --- a/tools/fx-fetch.py +++ b/tools/fx-fetch.py @@ -21,7 +21,10 @@ Storage: one gzipped JSON per instrument-hour under `~/.local/share/traders-agent/fx/ticks-v1///.json.gz`, plus a small `.empty` marker for hours that answer 404 (market shut/holiday) so a resume does not re-ask. The raw payload is -kept, not a re-encoding: a decoder bug can always be re-run over the bytes. +kept, not a re-encoding: a decoder bug can always be re-run over the bytes. Each hour is written to a +`.part` file and renamed into place, so an interrupted walk never leaves a half hour that a resume would +call cached. The walk stops at the last COMPLETE hour, and a 404 younger than a day is not marked: the +feed may simply not have published it yet. Usage: python3 tools/fx-fetch.py --years 2 --workers 4 # the full walk @@ -34,7 +37,6 @@ import argparse import datetime as dt import gzip -import json import os import sys import threading @@ -58,6 +60,7 @@ "SP500": "USA500.IDX-USD", } HOURS_PER_DAY = 24 +SETTLE = dt.timedelta(hours=24) # a 404 younger than this may be publishing lag, not a shut market _print_lock = threading.Lock() @@ -70,6 +73,11 @@ def marker_path(symbol: str, when: dt.datetime) -> Path: return HOME / symbol / when.strftime("%Y-%m-%d") / f"{when.hour:02d}.empty" +def last_complete_hour(now: dt.datetime) -> dt.datetime: + """The newest hour that has ended — the current one is still being written by the feed.""" + return now.replace(minute=0, second=0, microsecond=0) - dt.timedelta(hours=1) + + def decode_hour(doc: dict) -> list[tuple[int, float, float, float, float]]: """Ticks as `(epoch_ms, bid, ask, bid_volume, ask_volume)` from Dukascopy's delta encoding. @@ -123,11 +131,17 @@ def fetch_one(symbol: str, code: str, when: dt.datetime) -> tuple[str, str, int] if not payload: marker_path(symbol, when).write_bytes(b"") return "empty", symbol, 0 - with gzip.open(path, "wb", compresslevel=6) as fh: - fh.write(payload) + part = path.with_name(path.name + ".part") + try: + with gzip.open(part, "wb", compresslevel=6) as fh: + fh.write(payload) + os.replace(part, path) + finally: + part.unlink(missing_ok=True) return "ok", symbol, len(payload) if status == "empty": - marker_path(symbol, when).write_bytes(b"") + if dt.datetime.now(dt.timezone.utc) - when >= SETTLE: + marker_path(symbol, when).write_bytes(b"") return "empty", symbol, 0 return status, symbol, 0 @@ -218,7 +232,7 @@ def main(argv: list[str]) -> int: if bad: print("unknown instruments:", ", ".join(bad), "· known:", ", ".join(INSTRUMENTS)) return 2 - end = dt.datetime.now(dt.timezone.utc).replace(minute=0, second=0, microsecond=0) + end = last_complete_hour(dt.datetime.now(dt.timezone.utc)) back = dt.timedelta(days=a.days) if a.days else dt.timedelta(days=365.25 * a.years) walk(symbols, end - back, end, a.workers) return 0 From cf2fe0c14d001e80fc818049e02ab0b5d944fc2a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 03:06:12 +0000 Subject: [PATCH 5/6] fix(chart): a dragged chart stays where the operator put it, in replay and out nudgeChart()'s repaint dispatched a window 'resize' and the resize handler called nudgeChart() again: an endless loop, 140 view resets in 10 idle seconds (measured in Chromium). Each reset re-applied getVisibleRange(), which Vela caps at the newest bar in whole bars, so a drag into the right-hand space sprang back to the edge and the zoom crept in. - onWindowResize ignores synthetic (untrusted) resize events, so the nudge no longer re-enters itself - the repaint is Vela's public panBy(0): same zoom and position, full redraw Verified: 0 resets idle; drags into empty space and into history hold, in replay too (step and play leave a panned view alone); the canvas still repaints after a panel flip and a window resize. Three new tests in test_escape_and_layout.py. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GLsbckEp88WEwC41dfyMeS --- CHANGELOG.md | 9 ++++++ .../backend/tests/test_escape_and_layout.py | 32 ++++++++++++++++++- console/frontend/app.js | 16 +++++++--- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0dbeec..6ad11af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ All notable changes to this project are documented here. Format: [Keep a Changel ### Fixed +- **The chart sprang back to its right edge after a drag, in replay and out** (30 Oct). Two faults in + `nudgeChart()` (app.js): its repaint dispatched a window `resize`, and the resize handler called + `nudgeChart()` again — an endless loop, measured at 140 view resets in 10 idle seconds; and each + reset re-applied `getVisibleRange()`, which Vela caps at the newest bar in whole bars, so the space + the operator had dragged in was thrown away and the zoom crept. The handler now ignores synthetic + resizes (`isTrusted`), and the repaint is Vela's `panBy(0)`: same zoom, same position, full redraw. + Verified in Chromium: 0 resets idle; a drag into empty space or history stays put, in replay too + (stepping or playing while looking at older candles leaves the view alone); the canvas still + repaints after a panel flip and a window resize. - **Long tick-store windows came back short and slow** (30 Oct): `fxticks.bars` grew its window a day per pass from a 0.4x guess, re-reading every hour on every pass and giving up after 60. On a two-year store 500 x 4h returned 404 bars in 12 s and 500 x D returned 186 in 67 s, with no sign anything was diff --git a/console/backend/tests/test_escape_and_layout.py b/console/backend/tests/test_escape_and_layout.py index aae60b7..a78a89b 100644 --- a/console/backend/tests/test_escape_and_layout.py +++ b/console/backend/tests/test_escape_and_layout.py @@ -60,7 +60,7 @@ def test_window_resize_nudges_the_chart(self): app = read(APP) self.assertIn("addEventListener('resize', onWindowResize)", app, "a window resize (the app's split being dragged) never nudges Vela") - self.assertRegex(app, re.escape("function onWindowResize()"), + self.assertRegex(app, r"function onWindowResize\(", "the debounced resize handler does not exist") def test_the_nudge_debounces_so_a_drag_does_not_thrash_vela(self): @@ -75,6 +75,36 @@ def test_the_nudge_debounces_so_a_drag_does_not_thrash_vela(self): self.assertIn("nudgeChart()", body[:1500], "the resize handler does not nudge the chart") +class TheNudgeLeavesTheViewWhereTheOperatorPutIt(unittest.TestCase): + """30 Oct — the operator: drag the candles (in replay or not) and the chart springs back to the + right edge. Measured in Chromium: 140 setVisibleRange calls in 10 idle seconds. nudgeChart()'s + kick dispatched a window 'resize', the resize handler called nudgeChart() again, forever; and each + pass re-applied getVisibleRange(), which Vela caps at the newest bar in whole bars — so every pass + dropped the right-hand space the operator had dragged in and crept the zoom.""" + + def nudge_body(self): + app = read(APP) + start = app.index("function nudgeChart()") + return app[start:app.index("\n}\n", start)] + + def resize_body(self): + app = read(APP) + start = app.index("function onWindowResize(") + return app[start:app.index("\n}\n", start)] + + def test_the_repaint_does_not_reapply_the_capped_visible_range(self): + self.assertNotIn("setVisibleRange(", self.nudge_body(), + "the nudge re-applies getVisibleRange(), which snaps the view to the newest bar") + + def test_the_repaint_is_a_zero_pan(self): + # Vela's public panBy keeps zoom and position and invalidates the whole plot + self.assertIn("panBy(0)", self.nudge_body()) + + def test_the_nudges_own_resize_event_does_not_nudge_again(self): + self.assertIn("isTrusted", self.resize_body(), + "a synthetic resize from the nudge re-enters the nudge: an endless loop") + + class TheLibraryIsASheetAtPaneWidths(unittest.TestCase): """2 Oct — the operator, looking at the pane: "Make the Velachart full screen or utilising 80% of the view". Stacked in the grid, the Library took ~45% of the pane's height and shrank the diff --git a/console/frontend/app.js b/console/frontend/app.js index 7c001cb..606b471 100644 --- a/console/frontend/app.js +++ b/console/frontend/app.js @@ -73,10 +73,13 @@ function nudgeChart() { if (c && typeof c.resize === 'function') { try { c.resize(); } catch { /* older Vela build */ } } - /* resize() alone leaves the canvas blank after the column changes (proved on the live page): - re-applying the SAME visible range forces a full redraw without moving the user's view. */ - if (c && typeof c.getVisibleRange === 'function' && typeof c.setVisibleRange === 'function') { - try { c.setVisibleRange(c.getVisibleRange()); } catch { /* older Vela build */ } + /* resize() alone leaves the canvas blank after the column changes (proved on the live page), so + force a full redraw. A zero pan does it without moving anything: same zoom, same right-hand + space. Re-applying getVisibleRange() (the old way) did move it — Vela caps that range at the + newest bar in whole bars, so every pass threw away the space the operator had dragged in and + crept the zoom, and the chart sprang back to its edge (30 Oct). */ + if (c && typeof c.panBy === 'function') { + try { c.panBy(0); } catch { /* older Vela build */ } } }; requestAnimationFrame(() => { kick(); setTimeout(kick, 90); setTimeout(kick, 320); setTimeout(kick, 700); }); @@ -510,7 +513,10 @@ function setBars(text, detail) { the pane top, re-fit the bars pill, then nudge Vela exactly as a panel flip does. Debounced because a drag fires dozens of times a second and nudgeChart() does repeat passes by design. */ let resizeTimer = null; -function onWindowResize() { +function onWindowResize(ev) { + /* Only a real resize. nudgeChart() dispatches a synthetic one for whoever else listens; taking it + here re-entered the nudge, forever — 140 view resets in 10 idle seconds, measured 30 Oct. */ + if (ev && ev.isTrusted === false) return; clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { setPaneTop(); From 5811de7cde9b208f39344cc41f075705dfea3bd2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 06:43:01 +0000 Subject: [PATCH 6/6] feat(replay): the strip becomes a glass capsule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The operator's pick of two designs ("A — Capsule"): one frosted pill whose top edge is the scrubber (white playhead; the range ends fade in on hover), Play as the one bright control (Pause while playing), back-to-start and next-bar as icons, the cursor time as date over clock (still opens the calendar), a ring beside "N bars left" that fills as this replay advances, and the speed as a chip. The speed menu and calendar wear the same glass. Behaviour is unchanged: seek on release, Start bar, drag handle and saved spot, the paper broker's replay price. Icon-only buttons are named, focus is visible, the count has a fixed width so the pill does not wobble during playback, and a narrow pane drops the words but keeps the number and ring. Verified in Chromium at 1150/620/420 px, dark and light, driving every control. 8 new tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GLsbckEp88WEwC41dfyMeS --- CHANGELOG.md | 14 +++ console/backend/tests/test_replay.py | 49 ++++++++ console/frontend/replay.js | 74 +++++++---- console/frontend/styles.css | 179 +++++++++++++++++---------- 4 files changed, 226 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ad11af..eca6351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to this project are documented here. Format: [Keep a Changel ## [Unreleased] +### Changed + +- **The replay strip is a glass capsule** (30 Oct), the operator's pick of two designs. One frosted + pill, about 430 px: the scrubber is its top edge (white playhead, the range's first and last bar fade + in on hover), Play is the one bright control and turns into Pause, back-to-start and next-bar flank + it as icons, the cursor time reads as date over clock (still the door to the calendar), a ring beside + "N bars left" fills as this replay advances, and the speed is a chip that opens the same menu. The + speed menu and the calendar take the same glass. Everything the strip did still works: seek on + release, Start bar, the drag handle and its saved spot, the paper broker's replay price. Icon-only + buttons carry names for screen readers; focus is visible; the count has a fixed width so the pill + does not wobble during playback. In a narrow Hermes pane the words "bars left" drop and the number + and ring stay. Verified in Chromium at 1150, 620 and 420 px, dark and light. Eight tests in + `test_replay.py`. + ### Fixed - **The chart sprang back to its right edge after a drag, in replay and out** (30 Oct). Two faults in diff --git a/console/backend/tests/test_replay.py b/console/backend/tests/test_replay.py index aa97653..085ef6b 100644 --- a/console/backend/tests/test_replay.py +++ b/console/backend/tests/test_replay.py @@ -266,6 +266,55 @@ def test_the_scrubber_fill_uses_the_console_accent(self): self.assertIn("--lx-accent", block) +class TheStripIsTheCapsule(unittest.TestCase): + """30 Oct, the operator picked "Capsule" over "Deck": one frosted-glass pill whose top edge is the + scrubber, Play as the one bright control, the time as date over clock, a ring that fills beside + the bars-left count, the speed as a chip. Everything the old strip did still works.""" + + js = _read(FRONT / "replay.js") + css = _read(FRONT / "styles.css") + + def rule(self, sel): + m = re.search(re.escape(sel) + r" \{(.*?)\}", self.css, re.S) + self.assertIsNotNone(m, f"{sel} has no rule") + return m.group(1) + + def test_the_pill_is_frosted_glass(self): + rule = self.rule(".ta-replay") + self.assertIn("var(--lx-radius-pill)", rule) + self.assertIn("backdrop-filter", rule) + # a solid background first, for a renderer without color-mix + self.assertLess(rule.index("background: var(--lx-surface-2)"), rule.index("color-mix(in srgb, var(--lx-surface-2)")) + + def test_the_scrubber_is_the_top_edge_and_its_ends_show_on_hover(self): + self.assertRegex(self.rule(".ta-replay__scrub"), r"position:\s*absolute") + self.assertRegex(self.rule(".ta-replay__scrub"), r"top:\s*-\d+px") + self.assertIn(".ta-replay__scrub:hover .ta-replay__ends", self.css) + + def test_play_is_the_accented_control_and_says_what_it_does(self): + self.assertIn("--lx-accent", self.rule(".ta-replay__btn--play")) + self.assertIn("playBtn.setAttribute('aria-label'", self.js) + + def test_icon_only_buttons_have_names(self): + for name in ('aria-label="Start bar"', 'aria-label="Next bar"', 'aria-label="Leave replay"'): + self.assertIn(name, self.js) + + def test_the_time_reads_as_date_over_clock(self): + self.assertIn("data-clock", self.js) + self.assertIn("fmtDate(state.cursorTime)", self.js) + + def test_the_ring_fills_from_where_this_replay_began(self): + self.assertIn("data-ring", self.js) + self.assertIn("(state.cursorTime - origin) / (b.last - origin)", self.js) + self.assertIn("stroke-dasharray", self.js) + + def test_a_narrow_pane_keeps_the_count_and_drops_the_words(self): + self.assertIn(".ta-replay__left small { display: none; }", self.css) + + def test_keyboard_focus_is_visible(self): + self.assertIn(".ta-replay__btn:focus-visible", self.css) + + class TheAgentDoor(unittest.TestCase): bridge = _read(FRONT / "chart-bridge.js") diff --git a/console/frontend/replay.js b/console/frontend/replay.js index 7679dc4..d594b00 100644 --- a/console/frontend/replay.js +++ b/console/frontend/replay.js @@ -8,7 +8,10 @@ N bars left | ✕, with a scrubber over the row. Asked for the rest of the graphic ("Nak"): the timestamp opens a CALENDAR (month nav + day grid, a date/time footer) that seeks to a picked day, and the row carries a drag handle (⠿) so the strip can be moved out of the way — the spot - persists across reloads. Vela ships the ENGINE and no such strip (no "Start bar" string anywhere + persists across reloads. + 30 Oct, the operator picked the "Capsule" redesign: one frosted-glass pill, the scrubber is its top + edge (the range ends show on hover), Play is the one bright control, the cursor time reads as date + over clock, and a ring beside "N bars left" fills as this replay advances. Vela ships the ENGINE and no such strip (no "Start bar" string anywhere in the vendored dist), so the design is ours to paint; the glyphs are inline SVGs because the row is rebuilt from a string. While replay is on, every paper fill uses the REPLAY cursor price: this file pushes it to the @@ -29,7 +32,7 @@ let speed = 1; let origin = null; // the earliest cursor of this replay — where "Start bar" lands let el = null, label = null, left = null, playBtn = null, speedBtn = null, speedText = null; - let timeBtn = null, dragBtn = null, dragPos = null; + let timeBtn = null, dragBtn = null, dragPos = null, clock = null, leftN = null, ring = null; let range = null, startLabel = null, endLabel = null, speedsMenu = null; let calPop = null, calMonth = null, calTitle = null, calGrid = null, calDate = null, calTime = null; let lastPush = ''; @@ -43,19 +46,22 @@ /* The row is built from a string, so the glyphs ride in it — Vela's icon registry paints ITS row, not ours. Shapes follow the release graphic: a 2×3 dot grip, skip-to-start (bar + left - triangle), play, pause, skip-forward (right triangle + bar), month chevrons, a chevron on the - speed control, a thin ✕. */ + triangle), play, pause, skip-forward (right triangle + bar), month chevrons, a thin ✕, and + the progress ring. */ const GLYPH = { grip: '', - start: '', - play: '', - pause: '', - step: '', - chev: '', + start: '', + play: '', + pause: '', + step: '', prev: '', next: '', - close: '', + close: '', + /* how far this replay has come: the second circle's dash is set from sync() */ + ring: '', }; + const RING = 2 * Math.PI * 7; + const fmtDate = (ms) => (ms ? new Date(ms).toLocaleString([], { month: 'short', day: 'numeric' }) : '—'); function engine() { const ws = (window.__wsApp || {}).ws; @@ -134,18 +140,20 @@
- - - + + + - + - - - + ${GLYPH.ring}— bars left + +
`; el.addEventListener('click', onClick); range = el.querySelector('[data-scrub]'); @@ -154,7 +162,10 @@ dragBtn.addEventListener('pointerdown', onDragDown); document.body.appendChild(el); label = el.querySelector('[data-label]'); + clock = el.querySelector('[data-clock]'); left = el.querySelector('[data-left]'); + leftN = el.querySelector('[data-left-word]'); + ring = el.querySelector('[data-ring]'); playBtn = el.querySelector('[data-act="play"]'); speedBtn = el.querySelector('[data-act="speed"]'); speedText = el.querySelector('[data-speed]'); @@ -209,11 +220,26 @@ (`start({from})` again; the changelog's own rule: calling start() while replaying jumps). */ if (state.cursorTime != null && (origin === null || state.cursorTime < origin)) origin = state.cursorTime; const px = await priceAtCursor(state.cursorTime); - label.textContent = fmtTime(state.cursorTime); - label.title = (px != null ? 'Cursor price ' + money(px) + ' — ' : '') + 'the bar a paper fill right now would use'; - left.textContent = state.remaining === 1 ? '1 bar left' : state.remaining + ' bars left'; + label.textContent = fmtDate(state.cursorTime); + clock.textContent = state.cursorTime != null ? fmtClock(state.cursorTime) : ''; + timeBtn.title = fmtTime(state.cursorTime) + (px != null ? ' · cursor price ' + money(px) : '') + + ' — the bar a paper fill right now would use. Click to jump to a date.'; + left.textContent = String(state.remaining); + leftN.textContent = state.remaining === 1 ? ' bar left' : ' bars left'; + left.parentElement.title = state.remaining + (state.remaining === 1 ? ' bar' : ' bars') + ' still hidden'; + /* the ring: how far THIS replay has come, from where it began to the newest loaded bar */ + let done = 0; + try { + const b = engine().bounds; + if (b && origin != null && state.cursorTime != null && b.last > origin) done = (state.cursorTime - origin) / (b.last - origin); + else if (state.remaining === 0) done = 1; + } catch (err) { done = 0; } + done = Math.max(0, Math.min(1, done)); + ring.setAttribute('stroke-dasharray', (RING * done).toFixed(2) + ' ' + RING.toFixed(2)); playBtn.innerHTML = state.playing ? GLYPH.pause : GLYPH.play; playBtn.title = state.playing ? 'Pause' : 'Play'; + playBtn.setAttribute('aria-label', playBtn.title); + playBtn.classList.toggle('is-playing', !!state.playing); speedText.textContent = speed + '×'; syncScrub(r); if (calPop) calMark(); @@ -381,7 +407,7 @@ } catch (err) { /* private mode: the drag still holds for this session */ } } - /* The speed control: a small menu (the release graphic's chevron), not a blind cycle. */ + /* The speed control: a chip that opens a small menu, not a blind cycle. */ const speedsAway = (ev) => { if (el && !el.contains(ev.target)) closeSpeeds(); }; const speedsKey = (ev) => { if (ev.key === 'Escape') { ev.stopPropagation(); closeSpeeds(); } }; function closeSpeeds() { diff --git a/console/frontend/styles.css b/console/frontend/styles.css index 378c7e5..3854b64 100644 --- a/console/frontend/styles.css +++ b/console/frontend/styles.css @@ -1405,97 +1405,144 @@ pre { @keyframes ta-order-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } } @media (prefers-reduced-motion: reduce) { .ta-order { animation: none; } .ta-order__btn { transition: none; } } -/* ── Replay (Phase 6, 3 Oct; restyled 4 Oct to Vela's v0.8.0 Bar-replay release graphic) ───────── +/* ── Replay (Phase 6, 3 Oct; the "Capsule" redesign, 30 Oct) ────────────────────────────────────── The operator's call: the strip lives IN the chart ("jalur kawalan dalam chart"), bottom-centre — above the date axis, clear of the order card and the account popover (both in the top band) and of the price axis (right). Nothing is on screen until replay is on, so the chart stays whole. - The row takes the release graphic's composition (⏮ Start bar · ▶ · ⏭ | 1× ⌄ | time | bars left | - ✕) with a scrubber over it; motion is opacity + transform only (a 2016 Pavilion renders those on - the GPU). */ + 30 Oct he picked "Capsule" from two designs: one frosted-glass pill. The scrubber is its top edge + (the range ends appear on hover), Play is the only bright control, the cursor time reads as date + over clock, a ring beside "N bars left" fills as the replay advances, the speed is a chip. + Motion is opacity + transform only (a 2016 Pavilion renders those on the GPU). */ .ta-replay { - position: fixed; bottom: 56px; left: 50%; transform: translateX(-50%); - z-index: 55; display: flex; flex-direction: column; gap: 3px; - padding: 7px 10px 5px; border-radius: var(--lx-radius-xl); - background: var(--lx-surface-2); border: 1px solid var(--lx-border-strong); - box-shadow: var(--lx-shadow-3); color: var(--lx-fg); font-size: var(--lx-fs-sm); + position: fixed; bottom: 58px; left: 50%; transform: translateX(-50%); + z-index: 55; display: flex; align-items: center; height: 48px; padding: 0 8px 0 6px; + border-radius: var(--lx-radius-pill); color: var(--lx-fg); font-size: var(--lx-fs-sm); + font-variant-numeric: tabular-nums; + background: var(--lx-surface-2); + background: color-mix(in srgb, var(--lx-surface-2) 88%, transparent); + -webkit-backdrop-filter: blur(16px) saturate(150%); backdrop-filter: blur(16px) saturate(150%); + border: 1px solid color-mix(in srgb, var(--lx-fg) 9%, transparent); + box-shadow: inset 0 1px 0 color-mix(in srgb, var(--lx-fg) 6%, transparent), + 0 10px 30px rgba(0, 0, 0, .38), 0 2px 6px rgba(0, 0, 0, .22); animation: ta-replay-in var(--lx-dur-fast) var(--lx-ease) both; } +:root[data-theme="light"] .ta-replay { box-shadow: inset 0 1px 0 rgba(255, 255, 255, .7), 0 10px 28px rgba(0, 0, 0, .14), 0 2px 6px rgba(0, 0, 0, .08); } .ta-replay[hidden] { display: none; } -.ta-replay__row { display: flex; align-items: center; gap: 2px; } -.ta-replay__sep { width: 1px; align-self: stretch; margin: 4px 6px; background: var(--lx-border); } -.ta-replay__label { font-family: var(--lx-font-mono); color: var(--lx-fg); white-space: nowrap; padding: 0 3px; } -.ta-replay__left { font-family: var(--lx-font-mono); color: var(--lx-fg-muted); white-space: nowrap; padding: 0 3px; } +.ta-replay__row { display: flex; align-items: center; gap: 4px; } +.ta-replay__sep { width: 1px; height: 22px; margin: 0 6px; background: color-mix(in srgb, var(--lx-fg) 12%, transparent); } .ta-replay__btn { - all: unset; box-sizing: border-box; cursor: pointer; min-width: 26px; text-align: center; - display: inline-flex; align-items: center; justify-content: center; gap: 5px; - padding: 3px 6px; border-radius: var(--lx-radius-md); color: var(--lx-fg); - transition: background var(--lx-dur-fast) var(--lx-ease); -} -.ta-replay__btn svg { width: 13px; height: 13px; display: block; fill: currentColor; } -.ta-replay__btn:hover, .ta-replay__btn:focus-visible { background: var(--lx-accent-soft); } -.ta-replay__btn--start { padding: 3px 8px 3px 5px; } -.ta-replay__btn--speed { padding: 3px 5px; color: var(--lx-fg-muted); } -.ta-replay__btn--x { color: var(--lx-fg-muted); } -/* The scrubber: full width of the pill, the filled part painted from --ta-fill (set in replay.js — - a range input's track cannot be styled from its value). */ -.ta-replay__scrub { display: flex; flex-direction: column; gap: 1px; min-width: 340px; } + all: unset; box-sizing: border-box; cursor: pointer; display: inline-grid; place-items: center; + color: var(--lx-fg); transition: background var(--lx-dur-fast) var(--lx-ease), transform var(--lx-dur-fast) var(--lx-ease); +} +.ta-replay__btn svg { width: 14px; height: 14px; display: block; fill: currentColor; } +.ta-replay__btn:hover { background: color-mix(in srgb, var(--lx-fg) 8%, transparent); } +.ta-replay__btn:focus-visible, .ta-replay__drag:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--lx-accent); } +.ta-replay__btn:active { transform: scale(.94); } +.ta-replay__btn--icon { width: 32px; height: 32px; border-radius: 50%; } +/* Play: the one bright control */ +.ta-replay__btn--play { + width: 36px; height: 36px; border-radius: 50%; color: #fff; + background: radial-gradient(120% 120% at 30% 20%, color-mix(in srgb, var(--lx-accent) 70%, #fff), var(--lx-accent) 60%); + box-shadow: 0 0 0 4px var(--lx-accent-soft), 0 4px 12px color-mix(in srgb, var(--lx-accent) 45%, transparent); +} +.ta-replay__btn--play:hover { background: radial-gradient(120% 120% at 30% 20%, color-mix(in srgb, var(--lx-accent) 60%, #fff), var(--lx-accent) 65%); } +.ta-replay__btn--play svg { margin-left: 2px; } +.ta-replay__btn--play.is-playing svg { margin-left: 0; } +.ta-replay__btn--play:focus-visible { box-shadow: 0 0 0 2px var(--lx-surface-2), 0 0 0 4px var(--lx-accent); } +/* the cursor time: date over clock — also the door to the calendar */ +.ta-replay__btn--time { display: inline-flex; flex-direction: column; align-items: flex-start; gap: 1px; padding: 4px 8px; border-radius: 10px; line-height: 1.1; } +.ta-replay__label { font-size: 13px; font-weight: 600; letter-spacing: -.01em; white-space: nowrap; color: var(--lx-fg); } +.ta-replay__clock { font-size: 11px; color: var(--lx-fg-muted); white-space: nowrap; } +/* bars left, with the ring that fills as this replay advances */ +.ta-replay__left { display: inline-flex; align-items: center; gap: 6px; padding: 0 6px; color: var(--lx-fg-muted); white-space: nowrap; } +.ta-replay__left b { color: var(--lx-fg); font-weight: 600; min-width: 3ch; line-height: 1; text-align: right; } /* fixed width: the pill must not wobble as 100 becomes 99 */ +.ta-replay__left small { font-size: inherit; line-height: 1; margin-left: -2px; } +.ta-replay__ring { width: 18px; height: 18px; flex: none; transform: rotate(-90deg); } +.ta-replay__ring circle { fill: none; stroke-width: 2.4; } +.ta-replay__ring circle:first-child { stroke: color-mix(in srgb, var(--lx-fg) 18%, transparent); } +.ta-replay__ring [data-ring] { stroke: var(--lx-accent); stroke-linecap: round; stroke-dasharray: 0 44; } +.ta-replay__btn--speed { height: 26px; padding: 0 9px; border-radius: var(--lx-radius-pill); font-weight: 600; background: color-mix(in srgb, var(--lx-fg) 8%, transparent); } +.ta-replay__btn--speed:hover { background: color-mix(in srgb, var(--lx-fg) 14%, transparent); } +.ta-replay__btn--x { width: 28px; height: 28px; border-radius: 50%; color: var(--lx-fg-muted); } +.ta-replay__btn--x svg { width: 13px; height: 13px; } +.ta-replay__btn--x:hover { color: var(--lx-fg); } +/* The scrubber is the pill's top edge: a 3px track, a white playhead ringed in the accent. The filled + part is painted from --ta-fill (set in replay.js — a range input's track cannot be styled from its + value). The range ends fade in above it on hover, so the pill stays quiet otherwise. */ +.ta-replay__scrub { position: absolute; left: 22px; right: 22px; top: -8px; height: 16px; } .ta-replay--flat .ta-replay__scrub { display: none; } -.ta-replay__range { -webkit-appearance: none; appearance: none; width: 100%; height: 14px; margin: 0; background: transparent; cursor: pointer; } +.ta-replay__range { -webkit-appearance: none; appearance: none; display: block; width: 100%; height: 16px; margin: 0; background: transparent; cursor: pointer; } +.ta-replay__range:focus-visible { outline: none; } .ta-replay__range::-webkit-slider-runnable-track { - height: 3px; border-radius: 2px; - background: linear-gradient(90deg, var(--lx-accent) var(--ta-fill, 0%), var(--lx-border-strong) var(--ta-fill, 0%)); + height: 3px; border-radius: 3px; + background: linear-gradient(90deg, color-mix(in srgb, var(--lx-accent) 55%, transparent), var(--lx-accent) var(--ta-fill, 0%), + color-mix(in srgb, var(--lx-fg) 14%, transparent) var(--ta-fill, 0%)); } .ta-replay__range::-webkit-slider-thumb { - -webkit-appearance: none; appearance: none; width: 11px; height: 11px; margin-top: -4px; - border-radius: 50%; background: var(--lx-accent); border: none; -} -.ta-replay__ends { display: flex; justify-content: space-between; gap: 12px; } -.ta-replay__end { font-size: 10px; font-family: var(--lx-font-mono); color: var(--lx-fg-muted); white-space: nowrap; } -.ta-replay__speeds { - position: absolute; bottom: calc(100% + 6px); z-index: 56; display: flex; flex-direction: column; - min-width: 64px; padding: 4px; border-radius: var(--lx-radius-md); - background: var(--lx-surface-2); border: 1px solid var(--lx-border-strong); box-shadow: var(--lx-shadow-3); -} + -webkit-appearance: none; appearance: none; width: 11px; height: 11px; margin-top: -4px; border-radius: 50%; + background: #fff; border: none; box-shadow: 0 0 0 3px var(--lx-accent), 0 2px 6px rgba(0, 0, 0, .4); + transition: transform var(--lx-dur-fast) var(--lx-ease); +} +.ta-replay__range:hover::-webkit-slider-thumb, .ta-replay__range:focus-visible::-webkit-slider-thumb { transform: scale(1.25); } +.ta-replay__ends { + position: absolute; left: 0; right: 0; bottom: calc(100% - 2px); display: flex; justify-content: space-between; gap: 12px; + opacity: 0; transform: translateY(3px); pointer-events: none; + transition: opacity var(--lx-dur-fast) var(--lx-ease), transform var(--lx-dur-fast) var(--lx-ease); +} +.ta-replay__scrub:hover .ta-replay__ends, .ta-replay__scrub:focus-within .ta-replay__ends { opacity: 1; transform: none; } +.ta-replay__end { + font-size: 10.5px; color: var(--lx-fg-muted); white-space: nowrap; padding: 1px 6px; border-radius: 6px; + background: color-mix(in srgb, var(--lx-surface-2) 92%, transparent); +} +/* the speed menu and the calendar: the same glass, opening upward */ +.ta-replay__speeds, .ta-replay__cal { + position: absolute; bottom: calc(100% + 10px); z-index: 56; border-radius: 14px; + background: var(--lx-surface-2); + background: color-mix(in srgb, var(--lx-surface-2) 94%, transparent); + -webkit-backdrop-filter: blur(16px) saturate(150%); backdrop-filter: blur(16px) saturate(150%); + border: 1px solid color-mix(in srgb, var(--lx-fg) 10%, transparent); box-shadow: var(--lx-shadow-3); +} +.ta-replay__speeds { display: flex; flex-direction: column; min-width: 72px; padding: 4px; } .ta-replay__speed { - all: unset; box-sizing: border-box; cursor: pointer; padding: 3px 10px; - border-radius: var(--lx-radius-sm); font-family: var(--lx-font-mono); color: var(--lx-fg); text-align: left; + all: unset; box-sizing: border-box; cursor: pointer; padding: 5px 12px; + border-radius: 9px; font-weight: 600; color: var(--lx-fg); text-align: left; } -.ta-replay__speed:hover, .ta-replay__speed:focus-visible { background: var(--lx-accent-soft); } +.ta-replay__speed:hover, .ta-replay__speed:focus-visible { background: color-mix(in srgb, var(--lx-fg) 8%, transparent); } .ta-replay__speed.is-on { background: var(--lx-accent-soft); color: var(--lx-accent); } -/* The drag handle (the graphic's ⠿) and the free spot it drops the strip into. */ -.ta-replay__drag { all: unset; box-sizing: border-box; cursor: grab; display: inline-flex; align-items: center; padding: 3px 3px 3px 1px; color: var(--lx-fg-muted); } +/* The drag handle (⠿) and the free spot it drops the strip into. */ +.ta-replay__drag { all: unset; box-sizing: border-box; cursor: grab; display: inline-flex; align-items: center; padding: 6px 2px; border-radius: 6px; color: var(--lx-fg-muted); opacity: .6; } .ta-replay__drag svg { width: 12px; height: 12px; display: block; fill: currentColor; } -.ta-replay__drag:hover, .ta-replay__drag:focus-visible { color: var(--lx-fg); } +.ta-replay__drag:hover { opacity: 1; } .ta-replay__drag:active { cursor: grabbing; } .ta-replay--free { left: auto; bottom: auto; transform: none; animation-name: ta-replay-in-free; } -/* The timestamp button and the calendar it opens (the graphic's top panel). */ -.ta-replay__btn--time { padding: 3px 7px; } -.ta-replay__cal { - position: absolute; bottom: calc(100% + 6px); z-index: 56; width: 236px; padding: 8px 9px 9px; - border-radius: var(--lx-radius-md); background: var(--lx-surface-2); - border: 1px solid var(--lx-border-strong); box-shadow: var(--lx-shadow-3); -} -.ta-replay__cal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px; } -.ta-replay__nav { all: unset; box-sizing: border-box; cursor: pointer; padding: 2px 7px; border-radius: var(--lx-radius-sm); color: var(--lx-fg-muted); } -.ta-replay__nav:hover, .ta-replay__nav:focus-visible { background: var(--lx-accent-soft); color: var(--lx-fg); } +/* The calendar the timestamp opens. */ +.ta-replay__cal { width: 244px; padding: 10px 10px 10px; } +.ta-replay__cal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; } +.ta-replay__nav { all: unset; box-sizing: border-box; cursor: pointer; padding: 4px 8px; border-radius: 8px; color: var(--lx-fg-muted); } +.ta-replay__nav:hover, .ta-replay__nav:focus-visible { background: color-mix(in srgb, var(--lx-fg) 8%, transparent); color: var(--lx-fg); } .ta-replay__nav svg { width: 11px; height: 11px; display: block; } .ta-replay__cal-head [data-cal-title] { font-weight: 600; } -.ta-replay__cal-week { display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; margin-bottom: 2px; } +.ta-replay__cal-week { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; margin-bottom: 2px; } .ta-replay__cal-week span { font-size: 10px; color: var(--lx-fg-muted); text-align: center; } -.ta-replay__cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; } -.ta-replay__day { all: unset; box-sizing: border-box; cursor: pointer; text-align: center; font-size: var(--lx-fs-sm); padding: 3px 0; border-radius: var(--lx-radius-sm); color: var(--lx-fg); } -.ta-replay__day:hover, .ta-replay__day:focus-visible { background: var(--lx-accent-soft); } -.ta-replay__day.is-on { background: var(--lx-accent-soft); color: var(--lx-accent); font-weight: 600; } +.ta-replay__cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; } +.ta-replay__day { all: unset; box-sizing: border-box; cursor: pointer; text-align: center; font-size: var(--lx-fs-sm); padding: 4px 0; border-radius: 50%; aspect-ratio: 1; display: grid; place-items: center; color: var(--lx-fg); } +.ta-replay__day:hover, .ta-replay__day:focus-visible { background: color-mix(in srgb, var(--lx-fg) 8%, transparent); } +.ta-replay__day.is-on { background: var(--lx-accent); color: #fff; font-weight: 600; } .ta-replay__day.is-dim { color: var(--lx-fg-muted); opacity: .4; cursor: default; } .ta-replay__day.is-dim:hover { background: none; } -.ta-replay__cal-foot { display: flex; align-items: center; gap: 6px; margin-top: 7px; } +.ta-replay__cal-foot { display: flex; align-items: center; gap: 6px; margin-top: 8px; } .ta-replay__chip { - font-family: var(--lx-font-mono); font-size: var(--lx-fs-sm); color: var(--lx-fg); - border: 1px solid var(--lx-border-strong); border-radius: var(--lx-radius-sm); - padding: 2px 8px; background: transparent; + font-size: var(--lx-fs-sm); color: var(--lx-fg); font-variant-numeric: tabular-nums; + border: 1px solid color-mix(in srgb, var(--lx-fg) 14%, transparent); border-radius: 8px; + padding: 3px 9px; background: transparent; } -.ta-replay__time { width: 84px; text-align: center; padding: 2px 4px; } +.ta-replay__time { width: 112px; text-align: center; padding: 3px 4px; font-family: inherit; } .ta-replay__time::-webkit-calendar-picker-indicator { opacity: .5; cursor: pointer; } +/* A Hermes pane is ~620px: the words "bars left" go, the number and the ring stay. */ +@media (max-width: 680px) { + .ta-replay__left small { display: none; } + .ta-replay__sep { margin: 0 3px; } +} @keyframes ta-replay-in { from { opacity: 0; transform: translateX(-50%) translateY(6px); } to { opacity: 1; transform: translateX(-50%); } } @keyframes ta-replay-in-free { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } } -@media (prefers-reduced-motion: reduce) { .ta-replay { animation: none; } .ta-replay__btn { transition: none; } } +@media (prefers-reduced-motion: reduce) { .ta-replay { animation: none; } .ta-replay__btn, .ta-replay__range::-webkit-slider-thumb, .ta-replay__ends { transition: none; } }
SymbolHoursFrom ToSize