filtrix-cli 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/PKG-INFO +3 -1
  2. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/README.md +2 -0
  3. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/pyproject.toml +1 -1
  4. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/AGENTS.md +19 -0
  5. filtrix_cli-0.4.0/src/filtrix_cli/__init__.py +1 -0
  6. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/__main__.py +3 -0
  7. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/client.py +7 -2
  8. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/_helpers.py +55 -44
  9. filtrix_cli-0.4.0/src/filtrix_cli/commands/live.py +370 -0
  10. filtrix_cli-0.4.0/tests/test_cmd_live.py +185 -0
  11. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_smoke.py +1 -1
  12. filtrix_cli-0.3.0/src/filtrix_cli/__init__.py +0 -1
  13. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/.gitignore +0 -0
  14. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/LICENSE +0 -0
  15. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/auth.py +0 -0
  16. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/__init__.py +0 -0
  17. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/account.py +0 -0
  18. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/authcmd.py +0 -0
  19. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/backtest.py +0 -0
  20. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/configcmd.py +0 -0
  21. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/filters.py +0 -0
  22. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/keys.py +0 -0
  23. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/llms.py +0 -0
  24. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/market.py +0 -0
  25. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/research.py +0 -0
  26. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/screen.py +0 -0
  27. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/commands/ticker.py +0 -0
  28. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/config.py +0 -0
  29. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/filters.py +0 -0
  30. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/output.py +0 -0
  31. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/render.py +0 -0
  32. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/src/filtrix_cli/state.py +0 -0
  33. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/__init__.py +0 -0
  34. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_auth.py +0 -0
  35. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_client.py +0 -0
  36. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_client_register.py +0 -0
  37. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_auth.py +0 -0
  38. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_backtest_screen.py +0 -0
  39. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_config.py +0 -0
  40. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_keys.py +0 -0
  41. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_llms.py +0 -0
  42. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_market.py +0 -0
  43. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_profile.py +0 -0
  44. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_read.py +0 -0
  45. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_register.py +0 -0
  46. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_cmd_research.py +0 -0
  47. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_config.py +0 -0
  48. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_filters.py +0 -0
  49. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_helpers.py +0 -0
  50. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_output.py +0 -0
  51. {filtrix_cli-0.3.0 → filtrix_cli-0.4.0}/tests/test_render.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: filtrix-cli
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Agent-first command-line interface for the FILTRIX backtest engine.
5
5
  Project-URL: Homepage, https://filtrix.net
6
6
  Project-URL: Documentation, https://pypi.org/project/filtrix-cli/
@@ -75,6 +75,8 @@ filtrix runs list
75
75
  filtrix simulate --run-id 42 --entry open_at_0930 --exit stop_loss_take_profit --sl 0.03 --tp 0.06 --wait
76
76
  filtrix runs context 42 ABCD 2025-03-14 # daily + minute bars of one event
77
77
  filtrix jobs get JOB_ID
78
+ filtrix scanner query -f "gap_gup>=10" --order-by gap_gup --desc # live market now (Pro, once enabled)
79
+ filtrix paper account # paper trading account (Pro, once enabled)
78
80
  filtrix keys create --name laptop
79
81
  filtrix llms # machine-readable usage guide for AI agents
80
82
  ```
@@ -43,6 +43,8 @@ filtrix runs list
43
43
  filtrix simulate --run-id 42 --entry open_at_0930 --exit stop_loss_take_profit --sl 0.03 --tp 0.06 --wait
44
44
  filtrix runs context 42 ABCD 2025-03-14 # daily + minute bars of one event
45
45
  filtrix jobs get JOB_ID
46
+ filtrix scanner query -f "gap_gup>=10" --order-by gap_gup --desc # live market now (Pro, once enabled)
47
+ filtrix paper account # paper trading account (Pro, once enabled)
46
48
  filtrix keys create --name laptop
47
49
  filtrix llms # machine-readable usage guide for AI agents
48
50
  ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "filtrix-cli"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Agent-first command-line interface for the FILTRIX backtest engine."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -59,6 +59,25 @@ Structured command-line access to the FILTRIX historical backtest engine.
59
59
 
60
60
  Note: global flags like `--json` go BEFORE the subcommand (e.g. `filtrix --json backtest ...`).
61
61
 
62
+ ## Live Scanner and Paper Trading (Pro)
63
+ Available once FILTRIX enables the live API (until then: exit 3, "not available through the API yet").
64
+ - filtrix scanner status (free) session, freshness, allowed + reason
65
+ - filtrix scanner columns [--search Q] live columns (not the historical `filtrix filters`)
66
+ - filtrix scanner query --filter ... [--field COL ...] [--order-by COL --desc] [--limit 25 (max 100)] [--monitor-id N]
67
+ - filtrix scanner matches [--field COL ...] [--rows 25] what your running windows match now
68
+ - filtrix scanner chart SYMBOL
69
+ - filtrix scanner monitors list | save [--id N] [--name X] [--filter ...] [--telegram/--no-telegram] [--run/--stop]
70
+ | delete ID --yes
71
+ - filtrix paper status (free) | catalog | validate --spec-json JSON|- | account | list KIND [--after C] [--limit N]
72
+ (KIND: strategies, orders, positions, trades, events, epochs)
73
+ - filtrix paper create-account --limits-json JSON [--capital 100000] | limits --limits-json JSON
74
+ | reset --capital X --limits-json JSON --yes | close-all --yes
75
+ - filtrix paper strategy save --spec-json JSON [--id N] [--monitor-id N] | strategy archive ID --yes
76
+ - filtrix paper start STRATEGY_ID | pause RUN_ID | resume RUN_ID | close RUN_ID --yes
77
+ Paper money is simulated. Every paper write sends an Idempotency-Key (--idempotency-key, else a new one);
78
+ versions (--version, --account-version, --draft-version) are fetched from `filtrix paper account` when omitted.
79
+ A 409 version_conflict carries current_version. Run ids are UUIDs.
80
+
62
81
  ## Background jobs
63
82
  `runs save` and `simulate` print {"job_id","status":"queued","poll"}. Add `--wait` to poll until the job ends
64
83
  (prints the finished job; a failed job exits 1, `--timeout` seconds without an end exits 6), or poll with
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
@@ -13,6 +13,7 @@ from filtrix_cli.commands import configcmd
13
13
  from filtrix_cli.commands import llms as llms_cmd
14
14
  from filtrix_cli.commands import market as market_cmd
15
15
  from filtrix_cli.commands import research as research_cmd
16
+ from filtrix_cli.commands import live as live_cmd
16
17
 
17
18
  app = typer.Typer(
18
19
  add_completion=False,
@@ -61,6 +62,8 @@ app.command("premarket")(market_cmd.premarket)
61
62
  app.add_typer(research_cmd.runs_app, name="runs")
62
63
  app.command("simulate")(research_cmd.simulate)
63
64
  app.add_typer(research_cmd.jobs_app, name="jobs")
65
+ app.add_typer(live_cmd.scanner_app, name="scanner")
66
+ app.add_typer(live_cmd.paper_app, name="paper")
64
67
 
65
68
 
66
69
  def main() -> None:
@@ -54,9 +54,9 @@ class FiltrixClient:
54
54
  return headers
55
55
 
56
56
  def _request(self, method: str, path: str, *, json_body: Any = None, auth: str = "any",
57
- params: Optional[dict] = None) -> Any:
57
+ params: Optional[dict] = None, headers: Optional[dict] = None) -> Any:
58
58
  url = f"{self.base_url}{path}"
59
- headers = self._headers(auth)
59
+ headers = {**self._headers(auth), **(headers or {})}
60
60
  clean_params = {k: v for k, v in (params or {}).items() if v is not None} or None
61
61
  try:
62
62
  with httpx.Client(timeout=self.timeout) as client:
@@ -137,6 +137,11 @@ class FiltrixClient:
137
137
  def premarket_gappers(self) -> Any:
138
138
  return self._request("GET", "/api/v1/premarket/gappers")
139
139
 
140
+ def call(self, method: str, path: str, *, json_body: Any = None, params: Optional[dict] = None,
141
+ headers: Optional[dict] = None) -> Any:
142
+ """Any Public API v1 call with the configured credential (live scanner / paper commands)."""
143
+ return self._request(method, path, json_body=json_body, params=params, headers=headers)
144
+
140
145
  # ---- Saved runs, simulations, jobs (v1) ----
141
146
  def runs_list(self, limit: int = 20, offset: int = 0) -> Any:
142
147
  return self._request("GET", "/api/v1/runs", params={"limit": limit, "offset": offset})
@@ -1,44 +1,55 @@
1
- """Shared plumbing for Typer commands: error handling, client construction, output."""
2
- import functools
3
- from typing import Any, Callable, Tuple
4
-
5
- import typer
6
-
7
- from filtrix_cli import config as config_mod
8
- from filtrix_cli.client import FiltrixClient
9
- from filtrix_cli.output import CLIError, emit_error, emit_json, is_json_mode
10
- from filtrix_cli.render import render_human
11
- from filtrix_cli.state import get_state
12
-
13
-
14
- def command(func: Callable) -> Callable:
15
- """Wrap a Typer command: catch CLIError, emit it, exit with its code.
16
- functools.wraps keeps the original signature so Typer still sees the params."""
17
- @functools.wraps(func)
18
- def wrapper(*args, **kwargs):
19
- json_mode = is_json_mode(get_state().json)
20
- try:
21
- return func(*args, **kwargs)
22
- except CLIError as err:
23
- emit_error(err, json_mode)
24
- raise typer.Exit(err.exit_code)
25
- return wrapper
26
-
27
-
28
- def build_client() -> Tuple[FiltrixClient, dict]:
29
- state = get_state()
30
- settings = config_mod.resolve_settings(
31
- profile=state.profile, api_key=state.api_key, base_url=state.base_url
32
- )
33
- client = FiltrixClient(
34
- base_url=settings["base_url"], api_key=settings["api_key"], jwt=settings["jwt"]
35
- )
36
- return client, settings
37
-
38
-
39
- def output_result(result: Any, *, kind: str) -> None:
40
- state = get_state()
41
- if is_json_mode(state.json):
42
- emit_json(result)
43
- else:
44
- render_human(result, kind=kind, quiet=state.quiet, no_color=state.no_color)
1
+ """Shared plumbing for Typer commands: error handling, client construction, output."""
2
+ import functools
3
+ from typing import Any, Callable, Tuple
4
+
5
+ import typer
6
+
7
+ from filtrix_cli import config as config_mod
8
+ from filtrix_cli.client import FiltrixClient
9
+ from filtrix_cli.output import CLIError, emit_error, emit_json, is_json_mode
10
+ from filtrix_cli.render import render_human
11
+ from filtrix_cli.state import get_state
12
+
13
+
14
+ def command(func: Callable) -> Callable:
15
+ """Wrap a Typer command: catch CLIError, emit it, exit with its code.
16
+ functools.wraps keeps the original signature so Typer still sees the params."""
17
+ @functools.wraps(func)
18
+ def wrapper(*args, **kwargs):
19
+ json_mode = is_json_mode(get_state().json)
20
+ try:
21
+ return func(*args, **kwargs)
22
+ except CLIError as err:
23
+ emit_error(err, json_mode)
24
+ raise typer.Exit(err.exit_code)
25
+ return wrapper
26
+
27
+
28
+ def require_yes(yes: bool, message: str, suggestion: str) -> None:
29
+ """Destructive commands: --yes, or an interactive confirmation. Never silently in scripts."""
30
+ import sys
31
+
32
+ if yes:
33
+ return
34
+ if is_json_mode(get_state().json) or not sys.stdin.isatty():
35
+ raise CLIError("invalid_request", f"{message}; pass --yes to confirm.", suggestion=suggestion, exit_code=2)
36
+ typer.confirm(f"{message}. Continue?", abort=True)
37
+
38
+
39
+ def build_client() -> Tuple[FiltrixClient, dict]:
40
+ state = get_state()
41
+ settings = config_mod.resolve_settings(
42
+ profile=state.profile, api_key=state.api_key, base_url=state.base_url
43
+ )
44
+ client = FiltrixClient(
45
+ base_url=settings["base_url"], api_key=settings["api_key"], jwt=settings["jwt"]
46
+ )
47
+ return client, settings
48
+
49
+
50
+ def output_result(result: Any, *, kind: str) -> None:
51
+ state = get_state()
52
+ if is_json_mode(state.json):
53
+ emit_json(result)
54
+ else:
55
+ render_human(result, kind=kind, quiet=state.quiet, no_color=state.no_color)
@@ -0,0 +1,370 @@
1
+ """Live Scanner and Paper Trading over the Public API v1 (Pro).
2
+
3
+ They answer "not available through the API yet" until FILTRIX enables the live API.
4
+ Paper money is simulated; nothing here places a real order. Paper writes send an
5
+ Idempotency-Key (--idempotency-key, or a new one per run) and fill in the account and
6
+ draft versions from `filtrix paper account` when you leave them out.
7
+ """
8
+ import json
9
+ import sys
10
+ import uuid
11
+ from enum import Enum
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ import typer
15
+
16
+ from filtrix_cli.commands._helpers import build_client, command, output_result, require_yes
17
+ from filtrix_cli.filters import resolve_filters
18
+ from filtrix_cli.output import CLIError
19
+
20
+ scanner_app = typer.Typer(help="Live Scanner (Pro).", no_args_is_help=True)
21
+ monitors_app = typer.Typer(help="Your scanner windows (saved live filter sets).", no_args_is_help=True)
22
+ paper_app = typer.Typer(help="Paper trading on the live feed (simulated money).", no_args_is_help=True)
23
+ strategy_app = typer.Typer(help="Paper strategies.", no_args_is_help=True)
24
+ scanner_app.add_typer(monitors_app, name="monitors")
25
+ paper_app.add_typer(strategy_app, name="strategy")
26
+
27
+ FILTER_HELP = 'Filter "COL OP VAL" (repeatable); columns from `filtrix scanner columns`.'
28
+ KEY_HELP = "Idempotency-Key for this command (a retry with the same key does not act twice)."
29
+
30
+
31
+ class Kind(str, Enum):
32
+ strategies = "strategies"
33
+ orders = "orders"
34
+ positions = "positions"
35
+ trades = "trades"
36
+ events = "events"
37
+ epochs = "epochs"
38
+
39
+
40
+ def _drop_none(d: Dict[str, Any]) -> Dict[str, Any]:
41
+ return {k: v for k, v in d.items() if v is not None}
42
+
43
+
44
+ def _json_arg(value: str, name: str) -> Any:
45
+ raw = sys.stdin.read() if value == "-" else value
46
+ try:
47
+ return json.loads(raw)
48
+ except ValueError as exc:
49
+ raise CLIError("invalid_request", f"{name} is not valid JSON: {exc}", exit_code=2)
50
+
51
+
52
+ def _versions(client, strategy_id: Optional[int] = None) -> Tuple[Any, Any]:
53
+ overview = client.call("GET", "/api/v1/paper/account")
54
+ account = overview.get("account")
55
+ if not account:
56
+ raise CLIError("not_found", "No paper account yet.", suggestion="filtrix paper create-account --limits-json ...",
57
+ exit_code=3)
58
+ draft = None
59
+ if strategy_id is not None:
60
+ match = next((s for s in overview.get("strategies") or [] if s.get("id") == strategy_id), None)
61
+ if match is None:
62
+ raise CLIError("not_found", f"Strategy {strategy_id} is not one of your active strategies.",
63
+ suggestion="filtrix paper list strategies", exit_code=3)
64
+ draft = match.get("draft_version")
65
+ return account.get("version"), draft
66
+
67
+
68
+ def _command(client, method: str, path: str, key: Optional[str], *, body: Any = None,
69
+ params: Optional[dict] = None) -> Any:
70
+ return client.call(method, path, json_body=body, params=params,
71
+ headers={"Idempotency-Key": key or f"cli-{uuid.uuid4()}"})
72
+
73
+
74
+ # ---- scanner ------------------------------------------------------------------------
75
+ @scanner_app.command("status")
76
+ @command
77
+ def scanner_status() -> None:
78
+ """Session, data freshness and whether you may use the scanner (free)."""
79
+ client, _ = build_client()
80
+ output_result(client.call("GET", "/api/v1/scanner/status"), kind="scanner")
81
+
82
+
83
+ @scanner_app.command("columns")
84
+ @command
85
+ def scanner_columns(search: Optional[str] = typer.Option(None, "--search", help="Keyword, e.g. gap or volume."),
86
+ limit: int = typer.Option(50, "--limit", min=1, max=300)) -> None:
87
+ """Live scanner columns (differ from the historical `filtrix filters`)."""
88
+ client, _ = build_client()
89
+ output_result(client.call("GET", "/api/v1/scanner/columns", params={"q": search, "limit": limit}), kind="scanner")
90
+
91
+
92
+ @scanner_app.command("query")
93
+ @command
94
+ def scanner_query(
95
+ filter: Optional[List[str]] = typer.Option(None, "--filter", "-f", help=FILTER_HELP),
96
+ filters_json: Optional[str] = typer.Option(None, "--filters-json", help="JSON array of filters, or '-'."),
97
+ field: Optional[List[str]] = typer.Option(None, "--field", help="Column to return per row (repeatable)."),
98
+ limit: int = typer.Option(25, "--limit", min=1, max=100),
99
+ offset: int = typer.Option(0, "--offset", min=0),
100
+ order_by: str = typer.Option("symbol", "--order-by"),
101
+ desc: bool = typer.Option(False, "--desc", help="Sort descending."),
102
+ monitor_id: Optional[int] = typer.Option(None, "--monitor-id", help="Use the filters of one of your windows."),
103
+ ) -> None:
104
+ """Run filters over the live market now."""
105
+ filters = resolve_filters(filter, filters_json) if (filter or filters_json is not None) else []
106
+ body: Dict[str, Any] = {"filters": filters, "limit": limit, "offset": offset, "order_by": order_by,
107
+ "order_direction": "DESC" if desc else "ASC"}
108
+ if field:
109
+ body["fields"] = list(field)
110
+ if monitor_id is not None:
111
+ body["monitor_id"] = monitor_id
112
+ client, _ = build_client()
113
+ output_result(client.call("POST", "/api/v1/scanner/query", json_body=body), kind="scanner")
114
+
115
+
116
+ @scanner_app.command("matches")
117
+ @command
118
+ def scanner_matches(field: Optional[List[str]] = typer.Option(None, "--field"),
119
+ rows: int = typer.Option(25, "--rows", min=1, max=100, help="Rows per window.")) -> None:
120
+ """What each of your running windows matches now."""
121
+ client, _ = build_client()
122
+ output_result(client.call("GET", "/api/v1/scanner/matches",
123
+ params={"fields": list(field) if field else None, "rows_per_window": rows}),
124
+ kind="scanner")
125
+
126
+
127
+ @scanner_app.command("chart")
128
+ @command
129
+ def scanner_chart(symbol: str = typer.Argument(...)) -> None:
130
+ """Today's minute bars and recent daily bars of one symbol."""
131
+ client, _ = build_client()
132
+ output_result(client.call("GET", "/api/v1/scanner/chart", params={"symbol": symbol.upper()}), kind="scanner")
133
+
134
+
135
+ @monitors_app.command("list")
136
+ @command
137
+ def monitors_list() -> None:
138
+ """Your scanner windows."""
139
+ client, _ = build_client()
140
+ output_result(client.call("GET", "/api/v1/scanner/monitors"), kind="scanner")
141
+
142
+
143
+ @monitors_app.command("save")
144
+ @command
145
+ def monitors_save(
146
+ monitor_id: Optional[int] = typer.Option(None, "--id", help="Change this window; omit to create one."),
147
+ name: Optional[str] = typer.Option(None, "--name"),
148
+ filter: Optional[List[str]] = typer.Option(None, "--filter", "-f", help=FILTER_HELP),
149
+ filters_json: Optional[str] = typer.Option(None, "--filters-json"),
150
+ telegram: Optional[bool] = typer.Option(None, "--telegram/--no-telegram", help="Telegram alerts on or off."),
151
+ running: Optional[bool] = typer.Option(None, "--run/--stop", help="Start or stop the window."),
152
+ ) -> None:
153
+ """Create a window or change yours (only the options you pass change)."""
154
+ body = _drop_none({"id": monitor_id, "name": name, "channel_telegram": telegram, "is_running": running})
155
+ if filter or filters_json is not None:
156
+ body["filters"] = resolve_filters(filter, filters_json)
157
+ client, _ = build_client()
158
+ output_result(client.call("PUT", "/api/v1/scanner/monitors", json_body=body), kind="scanner")
159
+
160
+
161
+ @monitors_app.command("delete")
162
+ @command
163
+ def monitors_delete(monitor_id: int = typer.Argument(...), yes: bool = typer.Option(False, "--yes", "-y")) -> None:
164
+ """Delete one of your windows."""
165
+ require_yes(yes, f"Deleting scanner window {monitor_id}", f"filtrix scanner monitors delete {monitor_id} --yes")
166
+ client, _ = build_client()
167
+ output_result(client.call("DELETE", f"/api/v1/scanner/monitors/{monitor_id}"), kind="scanner")
168
+
169
+
170
+ # ---- paper: reads --------------------------------------------------------------------
171
+ @paper_app.command("status")
172
+ @command
173
+ def paper_status() -> None:
174
+ """Enabled, can start, has account, feed ready (free)."""
175
+ client, _ = build_client()
176
+ output_result(client.call("GET", "/api/v1/paper/meta"), kind="paper")
177
+
178
+
179
+ @paper_app.command("catalog")
180
+ @command
181
+ def paper_catalog() -> None:
182
+ """Strategy building blocks."""
183
+ client, _ = build_client()
184
+ output_result(client.call("GET", "/api/v1/paper/catalog"), kind="paper")
185
+
186
+
187
+ @paper_app.command("validate")
188
+ @command
189
+ def paper_validate(spec_json: str = typer.Option(..., "--spec-json", help="Strategy spec as JSON, or '-'.")) -> None:
190
+ """Check a strategy spec without saving it."""
191
+ spec = _json_arg(spec_json, "--spec-json")
192
+ client, _ = build_client()
193
+ output_result(client.call("POST", "/api/v1/paper/validate", json_body={"spec": spec}), kind="paper")
194
+
195
+
196
+ @paper_app.command("account")
197
+ @command
198
+ def paper_account() -> None:
199
+ """Your paper account: version, summary, runs, positions, orders, strategies."""
200
+ client, _ = build_client()
201
+ output_result(client.call("GET", "/api/v1/paper/account"), kind="paper")
202
+
203
+
204
+ @paper_app.command("list")
205
+ @command
206
+ def paper_list(kind: Kind = typer.Argument(...), after: Optional[str] = typer.Option(None, "--after"),
207
+ limit: int = typer.Option(50, "--limit", min=1, max=100),
208
+ epoch_id: Optional[str] = typer.Option(None, "--epoch-id"),
209
+ run_id: Optional[str] = typer.Option(None, "--run-id")) -> None:
210
+ """A page of strategies, orders, positions, trades, events or epochs."""
211
+ client, _ = build_client()
212
+ output_result(client.call("GET", f"/api/v1/paper/{kind.value}",
213
+ params={"after": after, "limit": limit, "epoch_id": epoch_id, "run_id": run_id}),
214
+ kind="paper")
215
+
216
+
217
+ # ---- paper: commands -----------------------------------------------------------------
218
+ @paper_app.command("create-account")
219
+ @command
220
+ def paper_create_account(limits_json: str = typer.Option(..., "--limits-json", help="Risk limits as JSON."),
221
+ capital: str = typer.Option("100000", "--capital", help="Simulated USD."),
222
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP)) -> None:
223
+ """Open your paper account."""
224
+ limits = _json_arg(limits_json, "--limits-json")
225
+ client, _ = build_client()
226
+ output_result(_command(client, "POST", "/api/v1/paper/account", key, body={"capital": capital, "limits": limits}),
227
+ kind="paper")
228
+
229
+
230
+ @paper_app.command("limits")
231
+ @command
232
+ def paper_limits(limits_json: str = typer.Option(..., "--limits-json"),
233
+ version: Optional[int] = typer.Option(None, "--version", help="Account version (fetched if omitted)."),
234
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP)) -> None:
235
+ """Change the account's risk limits."""
236
+ limits = _json_arg(limits_json, "--limits-json")
237
+ client, _ = build_client()
238
+ version = version or _versions(client)[0]
239
+ output_result(_command(client, "PATCH", "/api/v1/paper/account/limits", key,
240
+ body={"expected_version": version, "limits": limits}), kind="paper")
241
+
242
+
243
+ @paper_app.command("reset")
244
+ @command
245
+ def paper_reset(capital: str = typer.Option(..., "--capital"), limits_json: str = typer.Option(..., "--limits-json"),
246
+ version: Optional[int] = typer.Option(None, "--version"),
247
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP),
248
+ yes: bool = typer.Option(False, "--yes", "-y")) -> None:
249
+ """Start a new epoch with fresh capital (closes every run and position)."""
250
+ limits = _json_arg(limits_json, "--limits-json")
251
+ require_yes(yes, "Resetting the paper account closes every run and position", "filtrix paper reset ... --yes")
252
+ client, _ = build_client()
253
+ version = version or _versions(client)[0]
254
+ output_result(_command(client, "POST", "/api/v1/paper/account/reset", key,
255
+ body={"expected_version": version, "capital": capital, "limits": limits}), kind="paper")
256
+
257
+
258
+ @paper_app.command("close-all")
259
+ @command
260
+ def paper_close_all(version: Optional[int] = typer.Option(None, "--version"),
261
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP),
262
+ yes: bool = typer.Option(False, "--yes", "-y")) -> None:
263
+ """Close every open paper position and run."""
264
+ require_yes(yes, "Closing every paper position and run", "filtrix paper close-all --yes")
265
+ client, _ = build_client()
266
+ version = version or _versions(client)[0]
267
+ output_result(_command(client, "POST", "/api/v1/paper/account/close-all", key,
268
+ body={"expected_version": version}), kind="paper")
269
+
270
+
271
+ @strategy_app.command("save")
272
+ @command
273
+ def strategy_save(spec_json: str = typer.Option(..., "--spec-json", help="Strategy spec as JSON, or '-'."),
274
+ strategy_id: Optional[int] = typer.Option(None, "--id", help="Edit this strategy; omit to create."),
275
+ monitor_id: Optional[int] = typer.Option(None, "--monitor-id", help="Take a scanner window's filters."),
276
+ account_version: Optional[int] = typer.Option(None, "--account-version"),
277
+ draft_version: Optional[int] = typer.Option(None, "--draft-version"),
278
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP)) -> None:
279
+ """Save a strategy draft."""
280
+ spec = _json_arg(spec_json, "--spec-json")
281
+ client, _ = build_client()
282
+ if account_version is None or (strategy_id is not None and draft_version is None):
283
+ fetched_account, fetched_draft = _versions(client, strategy_id)
284
+ account_version = account_version or fetched_account
285
+ draft_version = draft_version or fetched_draft
286
+ body = _drop_none({"spec": spec, "account_version": account_version,
287
+ "draft_version": draft_version if strategy_id is not None else None,
288
+ "source_monitor_id": monitor_id})
289
+ if strategy_id is None:
290
+ result = _command(client, "POST", "/api/v1/paper/strategies", key, body=body)
291
+ else:
292
+ result = _command(client, "PATCH", f"/api/v1/paper/strategies/{strategy_id}", key, body=body)
293
+ output_result(result, kind="paper")
294
+
295
+
296
+ @strategy_app.command("archive")
297
+ @command
298
+ def strategy_archive(strategy_id: int = typer.Argument(...),
299
+ draft_version: Optional[int] = typer.Option(None, "--draft-version"),
300
+ version: Optional[int] = typer.Option(None, "--version"),
301
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP),
302
+ yes: bool = typer.Option(False, "--yes", "-y")) -> None:
303
+ """Archive a strategy (it must have no open run)."""
304
+ require_yes(yes, f"Archiving paper strategy {strategy_id}", f"filtrix paper strategy archive {strategy_id} --yes")
305
+ client, _ = build_client()
306
+ if version is None or draft_version is None:
307
+ fetched_account, fetched_draft = _versions(client, strategy_id)
308
+ version = version or fetched_account
309
+ draft_version = draft_version or fetched_draft
310
+ output_result(_command(client, "DELETE", f"/api/v1/paper/strategies/{strategy_id}", key,
311
+ params={"draft_version": draft_version, "expected_version": version}), kind="paper")
312
+
313
+
314
+ @paper_app.command("start")
315
+ @command
316
+ def paper_start(strategy_id: int = typer.Argument(...),
317
+ account_version: Optional[int] = typer.Option(None, "--account-version"),
318
+ draft_version: Optional[int] = typer.Option(None, "--draft-version"),
319
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP)) -> None:
320
+ """Start a paper run of a strategy on the live feed."""
321
+ client, _ = build_client()
322
+ if account_version is None or draft_version is None:
323
+ fetched_account, fetched_draft = _versions(client, strategy_id)
324
+ account_version = account_version or fetched_account
325
+ draft_version = draft_version or fetched_draft
326
+ output_result(_command(client, "POST", f"/api/v1/paper/strategies/{strategy_id}/start", key,
327
+ body={"account_version": account_version, "draft_version": draft_version}), kind="paper")
328
+
329
+
330
+ def _run_id(value: str) -> str:
331
+ """Run ids are UUIDs; anything else could point the request at another endpoint."""
332
+ try:
333
+ return str(uuid.UUID(value))
334
+ except ValueError:
335
+ raise CLIError("invalid_request", f"Not a run id: {value!r} (expected a UUID from `filtrix paper account`).",
336
+ exit_code=2)
337
+
338
+
339
+ def _run_action(action: str, run_id: str, version: Optional[int], key: Optional[str]) -> None:
340
+ run_id = _run_id(run_id)
341
+ client, _ = build_client()
342
+ version = version or _versions(client)[0]
343
+ output_result(_command(client, "POST", f"/api/v1/paper/runs/{run_id}/{action}", key,
344
+ body={"expected_version": version}), kind="paper")
345
+
346
+
347
+ @paper_app.command("pause")
348
+ @command
349
+ def paper_pause(run_id: str = typer.Argument(...), version: Optional[int] = typer.Option(None, "--version"),
350
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP)) -> None:
351
+ """Pause a run (no new entries)."""
352
+ _run_action("pause", run_id, version, key)
353
+
354
+
355
+ @paper_app.command("resume")
356
+ @command
357
+ def paper_resume(run_id: str = typer.Argument(...), version: Optional[int] = typer.Option(None, "--version"),
358
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP)) -> None:
359
+ """Resume a paused run."""
360
+ _run_action("resume", run_id, version, key)
361
+
362
+
363
+ @paper_app.command("close")
364
+ @command
365
+ def paper_close(run_id: str = typer.Argument(...), version: Optional[int] = typer.Option(None, "--version"),
366
+ key: Optional[str] = typer.Option(None, "--idempotency-key", help=KEY_HELP),
367
+ yes: bool = typer.Option(False, "--yes", "-y")) -> None:
368
+ """Close a run and its open positions."""
369
+ require_yes(yes, f"Closing paper run {run_id}", f"filtrix paper close {run_id} --yes")
370
+ _run_action("close", run_id, version, key)
@@ -0,0 +1,185 @@
1
+ """filtrix scanner / filtrix paper: paths, bodies, headers, versions, --yes, exit codes."""
2
+ import json
3
+
4
+ import pytest
5
+ import respx
6
+ from httpx import Response
7
+ from typer.testing import CliRunner
8
+
9
+ from filtrix_cli.__main__ import app
10
+ from filtrix_cli.state import reset_state
11
+
12
+ runner = CliRunner()
13
+ BASE = "https://api.test"
14
+ RUN = "6f1b2c3d-0000-4000-8000-000000000001"
15
+ LIMITS = {"max_open_risk": "500", "daily_loss_limit": "500", "max_symbols": 10}
16
+ ACCOUNT = {"account": {"account_id": "a1", "version": 4}, "strategies": [{"id": 5, "draft_version": 3}]}
17
+
18
+
19
+ def setup_function():
20
+ reset_state()
21
+
22
+
23
+ @pytest.fixture(autouse=True)
24
+ def _env(monkeypatch):
25
+ monkeypatch.setenv("FILTRIX_API_KEY", "flt_x")
26
+ monkeypatch.setenv("FILTRIX_BASE_URL", BASE)
27
+
28
+
29
+ def _body(route):
30
+ return json.loads(route.calls.last.request.content)
31
+
32
+
33
+ @respx.mock
34
+ def test_scanner_reads():
35
+ status = respx.get(f"{BASE}/api/v1/scanner/status").mock(return_value=Response(200, json={"allowed": True}))
36
+ cols = respx.get(f"{BASE}/api/v1/scanner/columns").mock(return_value=Response(200, json={"columns": []}))
37
+ matches = respx.get(f"{BASE}/api/v1/scanner/matches").mock(return_value=Response(200, json={"windows": []}))
38
+ chart = respx.get(f"{BASE}/api/v1/scanner/chart").mock(return_value=Response(200, json={"bars": []}))
39
+ monitors = respx.get(f"{BASE}/api/v1/scanner/monitors").mock(return_value=Response(200, json={"monitors": []}))
40
+
41
+ assert runner.invoke(app, ["scanner", "status"]).exit_code == 0
42
+ assert runner.invoke(app, ["scanner", "columns", "--search", "gap", "--limit", "5"]).exit_code == 0
43
+ assert runner.invoke(app, ["scanner", "matches", "--field", "gap_gup", "--field", "price_price",
44
+ "--rows", "5"]).exit_code == 0
45
+ assert runner.invoke(app, ["scanner", "chart", "amd"]).exit_code == 0
46
+ assert runner.invoke(app, ["scanner", "monitors", "list"]).exit_code == 0
47
+
48
+ assert status.call_count == monitors.call_count == 1
49
+ assert dict(cols.calls.last.request.url.params) == {"q": "gap", "limit": "5"}
50
+ assert matches.calls.last.request.url.params.get_list("fields") == ["gap_gup", "price_price"]
51
+ assert chart.calls.last.request.url.params["symbol"] == "AMD"
52
+
53
+
54
+ @respx.mock
55
+ def test_scanner_query_body():
56
+ route = respx.post(f"{BASE}/api/v1/scanner/query").mock(return_value=Response(200, json={"data": []}))
57
+
58
+ result = runner.invoke(app, ["scanner", "query", "-f", "gap_gup>=10", "--field", "price_price",
59
+ "--order-by", "gap_gup", "--desc", "--limit", "10"])
60
+
61
+ assert result.exit_code == 0, result.stdout
62
+ body = _body(route)
63
+ assert body["filters"][0]["column"] == "gap_gup" and body["fields"] == ["price_price"]
64
+ assert body["order_by"] == "gap_gup" and body["order_direction"] == "DESC" and body["limit"] == 10
65
+
66
+
67
+ @respx.mock
68
+ def test_scanner_query_on_a_monitor_needs_no_filters():
69
+ route = respx.post(f"{BASE}/api/v1/scanner/query").mock(return_value=Response(200, json={"data": []}))
70
+
71
+ assert runner.invoke(app, ["scanner", "query", "--monitor-id", "3"]).exit_code == 0
72
+ assert _body(route)["monitor_id"] == 3 and _body(route)["filters"] == []
73
+
74
+
75
+ @respx.mock
76
+ def test_monitor_save_and_delete_needs_yes():
77
+ put = respx.put(f"{BASE}/api/v1/scanner/monitors").mock(return_value=Response(200, json={"id": 3}))
78
+ delete = respx.delete(f"{BASE}/api/v1/scanner/monitors/3").mock(return_value=Response(200, json={"ok": True}))
79
+
80
+ assert runner.invoke(app, ["scanner", "monitors", "save", "--name", "Gappers", "-f", "gap_gup>=10",
81
+ "--no-telegram"]).exit_code == 0
82
+ refused = runner.invoke(app, ["scanner", "monitors", "delete", "3"])
83
+ assert refused.exit_code == 2 and delete.call_count == 0
84
+ assert runner.invoke(app, ["scanner", "monitors", "delete", "3", "--yes"]).exit_code == 0
85
+
86
+ body = _body(put)
87
+ assert body["name"] == "Gappers" and body["channel_telegram"] is False and body["filters"][0]["column"] == "gap_gup"
88
+ assert "is_running" not in body and "id" not in body
89
+
90
+
91
+ @respx.mock
92
+ def test_paper_reads():
93
+ meta = respx.get(f"{BASE}/api/v1/paper/meta").mock(return_value=Response(200, json={"enabled": True}))
94
+ account = respx.get(f"{BASE}/api/v1/paper/account").mock(return_value=Response(200, json=ACCOUNT))
95
+ orders = respx.get(f"{BASE}/api/v1/paper/orders").mock(return_value=Response(200, json={"items": []}))
96
+ catalog = respx.get(f"{BASE}/api/v1/paper/catalog").mock(return_value=Response(200, json={}))
97
+
98
+ for args in (["paper", "status"], ["paper", "account"], ["paper", "catalog"],
99
+ ["paper", "list", "orders", "--limit", "10", "--after", "c1"]):
100
+ assert runner.invoke(app, args).exit_code == 0, args
101
+
102
+ assert meta.call_count == account.call_count == catalog.call_count == 1
103
+ assert dict(orders.calls.last.request.url.params) == {"limit": "10", "after": "c1"}
104
+
105
+
106
+ @respx.mock
107
+ def test_create_account_sends_body_and_given_key():
108
+ route = respx.post(f"{BASE}/api/v1/paper/account").mock(return_value=Response(201, json={"version": 1}))
109
+
110
+ result = runner.invoke(app, ["paper", "create-account", "--limits-json", json.dumps(LIMITS),
111
+ "--capital", "25000", "--idempotency-key", "k1"])
112
+
113
+ assert result.exit_code == 0, result.stdout
114
+ assert _body(route) == {"capital": "25000", "limits": LIMITS}
115
+ assert route.calls.last.request.headers["Idempotency-Key"] == "k1"
116
+
117
+
118
+ @respx.mock
119
+ def test_reset_needs_yes_and_fetches_the_version():
120
+ respx.get(f"{BASE}/api/v1/paper/account").mock(return_value=Response(200, json=ACCOUNT))
121
+ reset = respx.post(f"{BASE}/api/v1/paper/account/reset").mock(return_value=Response(202, json={}))
122
+
123
+ refused = runner.invoke(app, ["paper", "reset", "--capital", "50000", "--limits-json", json.dumps(LIMITS)])
124
+ ok = runner.invoke(app, ["paper", "reset", "--capital", "50000", "--limits-json", json.dumps(LIMITS), "--yes"])
125
+
126
+ assert refused.exit_code == 2 and ok.exit_code == 0
127
+ assert _body(reset) == {"expected_version": 4, "capital": "50000", "limits": LIMITS}
128
+ assert len(reset.calls.last.request.headers["Idempotency-Key"]) >= 8
129
+
130
+
131
+ @respx.mock
132
+ def test_strategy_save_archive_start_and_run_actions():
133
+ respx.get(f"{BASE}/api/v1/paper/account").mock(return_value=Response(200, json=ACCOUNT))
134
+ create = respx.post(f"{BASE}/api/v1/paper/strategies").mock(return_value=Response(201, json={}))
135
+ archive = respx.delete(f"{BASE}/api/v1/paper/strategies/5").mock(return_value=Response(202, json={}))
136
+ start = respx.post(f"{BASE}/api/v1/paper/strategies/5/start").mock(return_value=Response(202, json={}))
137
+ pause = respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/pause").mock(return_value=Response(202, json={}))
138
+ close = respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/close").mock(return_value=Response(202, json={}))
139
+
140
+ assert runner.invoke(app, ["paper", "strategy", "save", "--spec-json", '{"name": "x"}']).exit_code == 0
141
+ assert runner.invoke(app, ["paper", "strategy", "archive", "5", "--yes"]).exit_code == 0
142
+ assert runner.invoke(app, ["paper", "start", "5"]).exit_code == 0
143
+ assert runner.invoke(app, ["paper", "pause", RUN, "--version", "7"]).exit_code == 0
144
+ assert runner.invoke(app, ["paper", "close", RUN]).exit_code == 2
145
+ assert runner.invoke(app, ["paper", "close", RUN, "--yes"]).exit_code == 0
146
+
147
+ assert _body(create) == {"spec": {"name": "x"}, "account_version": 4}
148
+ assert dict(archive.calls.last.request.url.params) == {"draft_version": "3", "expected_version": "4"}
149
+ assert _body(start) == {"account_version": 4, "draft_version": 3}
150
+ assert _body(pause) == {"expected_version": 7}
151
+ assert close.call_count == 1
152
+
153
+
154
+ @respx.mock
155
+ def test_no_paper_account_exits_3_with_the_next_step():
156
+ respx.get(f"{BASE}/api/v1/paper/account").mock(return_value=Response(200, json={"account": None}))
157
+
158
+ result = runner.invoke(app, ["paper", "close-all", "--yes"])
159
+
160
+ assert result.exit_code == 3 and "filtrix paper create-account" in result.stderr
161
+
162
+
163
+ def test_bad_json_argument_exits_2():
164
+ result = runner.invoke(app, ["paper", "validate", "--spec-json", "{not json"])
165
+
166
+ assert result.exit_code == 2
167
+
168
+
169
+ @respx.mock
170
+ def test_live_api_off_is_not_found():
171
+ respx.get(f"{BASE}/api/v1/scanner/status").mock(return_value=Response(404, json={
172
+ "detail": "Live Scanner and Paper Trading are not available through the API yet."}))
173
+
174
+ result = runner.invoke(app, ["scanner", "status"])
175
+
176
+ assert result.exit_code == 3 and "not available through the API yet" in result.stderr
177
+
178
+
179
+ @respx.mock
180
+ def test_run_id_must_be_a_uuid_and_no_request_is_made():
181
+ close_all = respx.post(f"{BASE}/api/v1/paper/account/close-all").mock(return_value=Response(202, json={}))
182
+
183
+ result = runner.invoke(app, ["paper", "pause", "../account/close-all#", "--version", "4"])
184
+
185
+ assert result.exit_code == 2 and close_all.call_count == 0
@@ -8,7 +8,7 @@ runner = CliRunner()
8
8
  def test_version_prints_semver():
9
9
  result = runner.invoke(app, ["version"])
10
10
  assert result.exit_code == 0
11
- assert "filtrix-cli 0.3.0" in result.stdout
11
+ assert "filtrix-cli 0.4.0" in result.stdout
12
12
 
13
13
 
14
14
  def test_no_args_shows_help():
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"
File without changes
File without changes