filtrix-cli 0.4.0__tar.gz → 0.5.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 (52) hide show
  1. filtrix_cli-0.5.0/CHANGELOG.md +16 -0
  2. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/PKG-INFO +3 -3
  3. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/README.md +2 -2
  4. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/pyproject.toml +1 -1
  5. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/AGENTS.md +9 -2
  6. filtrix_cli-0.5.0/src/filtrix_cli/__init__.py +1 -0
  7. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/client.py +276 -204
  8. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/live.py +21 -3
  9. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_live.py +129 -0
  10. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_smoke.py +9 -1
  11. filtrix_cli-0.4.0/src/filtrix_cli/__init__.py +0 -1
  12. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/.gitignore +0 -0
  13. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/LICENSE +0 -0
  14. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/__main__.py +0 -0
  15. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/auth.py +0 -0
  16. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/__init__.py +0 -0
  17. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/_helpers.py +0 -0
  18. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/account.py +0 -0
  19. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/authcmd.py +0 -0
  20. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/backtest.py +0 -0
  21. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/configcmd.py +0 -0
  22. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/filters.py +0 -0
  23. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/keys.py +0 -0
  24. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/llms.py +0 -0
  25. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/market.py +0 -0
  26. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/research.py +0 -0
  27. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/screen.py +0 -0
  28. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/commands/ticker.py +0 -0
  29. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/config.py +0 -0
  30. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/filters.py +0 -0
  31. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/output.py +0 -0
  32. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/render.py +0 -0
  33. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/src/filtrix_cli/state.py +0 -0
  34. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/__init__.py +0 -0
  35. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_auth.py +0 -0
  36. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_client.py +0 -0
  37. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_client_register.py +0 -0
  38. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_auth.py +0 -0
  39. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_backtest_screen.py +0 -0
  40. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_config.py +0 -0
  41. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_keys.py +0 -0
  42. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_llms.py +0 -0
  43. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_market.py +0 -0
  44. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_profile.py +0 -0
  45. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_read.py +0 -0
  46. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_register.py +0 -0
  47. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_cmd_research.py +0 -0
  48. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_config.py +0 -0
  49. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_filters.py +0 -0
  50. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_helpers.py +0 -0
  51. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_output.py +0 -0
  52. {filtrix_cli-0.4.0 → filtrix_cli-0.5.0}/tests/test_render.py +0 -0
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.5.0 (2026-11-11)
4
+
5
+ - A paper write the account worker has not answered within the server's 10 s wait comes back
6
+ `{"status": "pending", "event_id"}`. The CLI now reads its outcome for about 12 s more, with the same
7
+ Idempotency-Key, and prints the result.
8
+ - Still no answer: it prints `{"status": "pending", "event_id", "idempotency_key"}` and exits 6. The command
9
+ may still apply. Read it later with the new `filtrix paper command EVENT_ID`, and resend only with the same
10
+ `--idempotency-key`.
11
+ - A command refused while pending (for example 409 `version_conflict`) exits as a direct refusal would.
12
+ - A 500 `internal_error` on a paper write is retried once with the same key and body.
13
+
14
+ ## 0.4.0 (2026-11-08)
15
+
16
+ - `filtrix scanner` and `filtrix paper` commands (Pro), available once FILTRIX enables the live API.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: filtrix-cli
3
- Version: 0.4.0
3
+ Version: 0.5.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/
@@ -85,8 +85,8 @@ filtrix llms # machine-readable usage guide for AI agents
85
85
 
86
86
  Output is human-readable in a terminal and JSON when piped or with the global `--json` flag.
87
87
  Global flags (`--json`, `--quiet`, `--profile`, `--api-key`, `--base-url`) go BEFORE the subcommand.
88
- Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network or `--wait` timeout, 1 server
89
- or failed job.
88
+ Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network, `--wait` timeout or a paper
89
+ command still pending (`filtrix paper command EVENT_ID` reads it later), 1 server or failed job.
90
90
 
91
91
  `runs save` and `simulate` start background jobs; `--wait` polls until they finish. `runs delete` needs
92
92
  `--yes` when not interactive.
@@ -53,8 +53,8 @@ filtrix llms # machine-readable usage guide for AI agents
53
53
 
54
54
  Output is human-readable in a terminal and JSON when piped or with the global `--json` flag.
55
55
  Global flags (`--json`, `--quiet`, `--profile`, `--api-key`, `--base-url`) go BEFORE the subcommand.
56
- Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network or `--wait` timeout, 1 server
57
- or failed job.
56
+ Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network, `--wait` timeout or a paper
57
+ command still pending (`filtrix paper command EVENT_ID` reads it later), 1 server or failed job.
58
58
 
59
59
  `runs save` and `simulate` start background jobs; `--wait` polls until they finish. `runs delete` needs
60
60
  `--yes` when not interactive.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "filtrix-cli"
7
- version = "0.4.0"
7
+ version = "0.5.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"
@@ -14,7 +14,8 @@ Structured command-line access to the FILTRIX historical backtest engine.
14
14
  - 3 not found
15
15
  - 4 authentication required/failed
16
16
  - 5 rate limited (retryable)
17
- - 6 network/timeout, incl. `--wait` giving up on a job that is still running (retryable)
17
+ - 6 network/timeout, incl. `--wait` giving up on a job that is still running (retryable), or a paper command
18
+ still pending (see Live Scanner and Paper Trading)
18
19
 
19
20
  ## Auth
20
21
  - Reads/backtests: set env FILTRIX_API_KEY=flt_... (or `filtrix config set api_key ...`).
@@ -74,9 +75,15 @@ Available once FILTRIX enables the live API (until then: exit 3, "not available
74
75
  | reset --capital X --limits-json JSON --yes | close-all --yes
75
76
  - filtrix paper strategy save --spec-json JSON [--id N] [--monitor-id N] | strategy archive ID --yes
76
77
  - filtrix paper start STRATEGY_ID | pause RUN_ID | resume RUN_ID | close RUN_ID --yes
78
+ - filtrix paper command EVENT_ID outcome of a write that exited 6 "pending": its result, or still pending
77
79
  Paper money is simulated. Every paper write sends an Idempotency-Key (--idempotency-key, else a new one);
78
80
  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.
81
+ A 409 version_conflict carries current_version. Run ids are UUIDs.
82
+ A write waits for the account worker (up to ~10 s on the server, then ~12 s of status reads). Still no
83
+ answer: stdout {"status":"pending","event_id","idempotency_key"}, exit 6; it may still apply, so read it with
84
+ `filtrix paper command EVENT_ID` and resend only with the same --idempotency-key. A refusal read there exits as
85
+ a direct one would (e.g. 409 version_conflict, exit 2). A 500 internal_error is
86
+ retried once with the same key and body.
80
87
 
81
88
  ## Background jobs
82
89
  `runs save` and `simulate` print {"job_id","status":"queued","poll"}. Add `--wait` to poll until the job ends
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
@@ -1,204 +1,276 @@
1
- """Synchronous httpx client for the FILTRIX API, with error -> CLIError mapping."""
2
- import json
3
- from typing import Any, List, Optional
4
- from urllib.parse import quote
5
-
6
- import httpx
7
-
8
- from filtrix_cli import __version__
9
- from filtrix_cli.output import CLIError
10
-
11
-
12
- def _safe_detail(resp: httpx.Response) -> str:
13
- try:
14
- data = resp.json()
15
- except Exception:
16
- return resp.text or f"HTTP {resp.status_code}"
17
- if isinstance(data, dict) and "detail" in data:
18
- detail = data["detail"]
19
- return detail if isinstance(detail, str) else json.dumps(detail)
20
- return json.dumps(data)
21
-
22
-
23
- class FiltrixClient:
24
- def __init__(self, base_url: str, api_key: Optional[str] = None,
25
- jwt: Optional[str] = None, timeout: float = 60.0):
26
- self.base_url = base_url.rstrip("/")
27
- self.api_key = api_key
28
- self.jwt = jwt
29
- self.timeout = timeout
30
-
31
- def _headers(self, auth: str) -> dict:
32
- """auth in {'any', 'jwt', 'none'}."""
33
- headers = {
34
- "User-Agent": f"filtrix-cli/{__version__}",
35
- "X-Agent-Request": "true",
36
- "Content-Type": "application/json",
37
- }
38
- if auth == "none":
39
- return headers
40
- if auth == "jwt":
41
- if not self.jwt:
42
- raise CLIError("auth_failed", "This command requires login. Run `filtrix auth login`.",
43
- suggestion="filtrix auth login", exit_code=4)
44
- headers["Authorization"] = f"Bearer {self.jwt}"
45
- return headers
46
- # auth == "any"
47
- if self.api_key:
48
- headers["X-API-Key"] = self.api_key
49
- elif self.jwt:
50
- headers["Authorization"] = f"Bearer {self.jwt}"
51
- else:
52
- raise CLIError("auth_failed", "No credentials. Set FILTRIX_API_KEY or run `filtrix auth login`.",
53
- suggestion="filtrix auth login", exit_code=4)
54
- return headers
55
-
56
- def _request(self, method: str, path: str, *, json_body: Any = None, auth: str = "any",
57
- params: Optional[dict] = None, headers: Optional[dict] = None) -> Any:
58
- url = f"{self.base_url}{path}"
59
- headers = {**self._headers(auth), **(headers or {})}
60
- clean_params = {k: v for k, v in (params or {}).items() if v is not None} or None
61
- try:
62
- with httpx.Client(timeout=self.timeout) as client:
63
- resp = client.request(method, url, headers=headers, json=json_body, params=clean_params)
64
- except httpx.TimeoutException as e:
65
- raise CLIError("network", f"Request timed out: {e}", retryable=True, exit_code=6)
66
- except httpx.HTTPError as e:
67
- raise CLIError("network", f"Network error: {e}", retryable=True, exit_code=6)
68
- return self._handle_response(resp)
69
-
70
- def _handle_response(self, resp: httpx.Response) -> Any:
71
- if resp.status_code < 400:
72
- return resp.json() if resp.content else {}
73
- detail = _safe_detail(resp)
74
- code = resp.status_code
75
- if code in (401, 403):
76
- raise CLIError("auth_failed", detail, status=code,
77
- suggestion="Run `filtrix auth login` or check your API key.", exit_code=4)
78
- if code == 404:
79
- raise CLIError("not_found", detail, status=404, exit_code=3)
80
- if code == 429:
81
- raise CLIError("rate_limited", detail, status=429, retryable=True,
82
- suggestion="Run `filtrix account` to see your quota.", exit_code=5)
83
- if 400 <= code < 500:
84
- raise CLIError("invalid_request", detail, status=code, exit_code=2)
85
- raise CLIError("server_error", detail, status=code, retryable=True, exit_code=1)
86
-
87
- # ---- Public API v1 ----
88
- def backtest(self, filters: List[dict], outcome: str = "day_close_position",
89
- flat_threshold: float = 0.002, start_date: Optional[str] = None,
90
- end_date: Optional[str] = None, threshold: float = 0.0,
91
- pos_min: Optional[float] = None, pos_max: Optional[float] = None,
92
- sample_limit: int = 0) -> Any:
93
- body: dict = {"filters": filters, "outcome": outcome, "flat_threshold": flat_threshold,
94
- "threshold": threshold, "sample_limit": sample_limit}
95
- for key, value in (("start_date", start_date), ("end_date", end_date),
96
- ("pos_min", pos_min), ("pos_max", pos_max)):
97
- if value is not None:
98
- body[key] = value
99
- return self._request("POST", "/api/v1/backtest", json_body=body)
100
-
101
- def screen(self, filters: List[dict], limit: int = 50, offset: int = 0,
102
- fields: Optional[List[str]] = None) -> Any:
103
- body: dict = {"filters": filters, "limit": limit, "offset": offset}
104
- if fields:
105
- body["fields"] = list(fields)
106
- return self._request("POST", "/api/v1/screen", json_body=body)
107
-
108
- def ticker_info(self, symbol: str) -> Any:
109
- return self._request("GET", f"/api/v1/ticker/{symbol.upper()}")
110
-
111
- def list_filters(self, q: Optional[str] = None, value_type: Optional[str] = None,
112
- limit: Optional[int] = None) -> Any:
113
- return self._request("GET", "/api/v1/filters", auth="none",
114
- params={"q": q, "type": value_type, "limit": limit})
115
-
116
- def account(self) -> Any:
117
- return self._request("GET", "/api/v1/account")
118
-
119
- def meta(self) -> Any:
120
- return self._request("GET", "/api/v1/meta")
121
-
122
- def coverage(self, symbol: Optional[str] = None) -> Any:
123
- return self._request("GET", "/api/v1/coverage",
124
- params={"symbol": symbol.upper() if symbol else None})
125
-
126
- def ticker_overview(self, symbol: str) -> Any:
127
- return self._request("GET", f"/api/v1/ticker/{symbol.upper()}/overview")
128
-
129
- def ticker_gap_stats(self, symbol: str, gap_threshold: float = 10.0,
130
- direction: str = "up", stat: str = "avg") -> Any:
131
- return self._request("GET", f"/api/v1/ticker/{symbol.upper()}/gap-stats",
132
- params={"gap_threshold": gap_threshold, "direction": direction, "stat": stat})
133
-
134
- def ticker_daily(self, symbol: str, limit: int = 250) -> Any:
135
- return self._request("GET", f"/api/v1/ticker/{symbol.upper()}/daily", params={"limit": limit})
136
-
137
- def premarket_gappers(self) -> Any:
138
- return self._request("GET", "/api/v1/premarket/gappers")
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
-
145
- # ---- Saved runs, simulations, jobs (v1) ----
146
- def runs_list(self, limit: int = 20, offset: int = 0) -> Any:
147
- return self._request("GET", "/api/v1/runs", params={"limit": limit, "offset": offset})
148
-
149
- def run_get(self, run_id: int) -> Any:
150
- return self._request("GET", f"/api/v1/runs/{int(run_id)}")
151
-
152
- def run_rows(self, run_id: int, limit: int = 100, offset: int = 0) -> Any:
153
- return self._request("GET", f"/api/v1/runs/{int(run_id)}/rows", params={"limit": limit, "offset": offset})
154
-
155
- def run_save(self, body: dict) -> Any:
156
- return self._request("POST", "/api/v1/runs", json_body=body)
157
-
158
- def run_share(self, run_id: int) -> Any:
159
- return self._request("POST", f"/api/v1/runs/{int(run_id)}/share")
160
-
161
- def run_unshare(self, run_id: int) -> Any:
162
- return self._request("DELETE", f"/api/v1/runs/{int(run_id)}/share")
163
-
164
- def run_delete(self, run_id: int) -> Any:
165
- return self._request("DELETE", f"/api/v1/runs/{int(run_id)}")
166
-
167
- def trade_context(self, run_id: int, symbol: str, date: str, daily_lookback: int = 120) -> Any:
168
- return self._request("GET", f"/api/v1/runs/{int(run_id)}/trade-context",
169
- params={"symbol": symbol.upper(), "date": date, "daily_lookback": daily_lookback})
170
-
171
- def simulate(self, body: dict) -> Any:
172
- return self._request("POST", "/api/v1/simulations", json_body=body)
173
-
174
- def job_get(self, job_id: str) -> Any:
175
- return self._request("GET", f"/api/v1/jobs/{quote(job_id, safe='')}")
176
-
177
- def job_cancel(self, job_id: str) -> Any:
178
- return self._request("POST", f"/api/v1/jobs/{quote(job_id, safe='')}/cancel")
179
-
180
- # ---- Key management (JWT) ----
181
- def keys_list(self) -> Any:
182
- return self._request("GET", "/api/keys", auth="jwt")
183
-
184
- def keys_create(self, name: str = "default") -> Any:
185
- return self._request("POST", "/api/keys", json_body={"name": name}, auth="jwt")
186
-
187
- def keys_revoke(self, key_id: int) -> Any:
188
- return self._request("DELETE", f"/api/keys/{key_id}", auth="jwt")
189
-
190
- # ---- Registration (pre-auth) ----
191
- def register(self, email: str, password: str, delivery: str = "code",
192
- ref_source: Optional[str] = None) -> Any:
193
- body: dict = {"email": email, "password": password, "delivery": delivery}
194
- if ref_source:
195
- body["ref_data"] = {"ref_source": ref_source}
196
- return self._request("POST", "/api/auth/register", json_body=body, auth="none")
197
-
198
- def verify_email_code(self, email: str, code: str) -> Any:
199
- return self._request("POST", "/api/auth/verify-email-code",
200
- json_body={"email": email, "code": code}, auth="none")
201
-
202
- def resend_code(self, email: str) -> Any:
203
- return self._request("POST", "/api/auth/resend-code",
204
- json_body={"email": email}, auth="none")
1
+ """Synchronous httpx client for the FILTRIX API, with error -> CLIError mapping."""
2
+ import json
3
+ import time
4
+ from typing import Any, List, Optional
5
+ from urllib.parse import quote
6
+
7
+ import httpx
8
+
9
+ from filtrix_cli import __version__
10
+ from filtrix_cli.output import CLIError
11
+
12
+ # Paper commands: after the server's own 10 s wait, a pending command's result is read about 12 s more
13
+ # (1 quota each), as the MCP server does.
14
+ PENDING_POLL_DELAYS = (1.0, 1.0, 2.0, 2.0, 3.0, 3.0)
15
+ COMMAND_STATUS_PATH = "/api/v1/paper/commands"
16
+ INTERNAL_RETRY_DELAY = 1.0
17
+ _sleep = time.sleep
18
+
19
+
20
+ def _is_pending(body: Any) -> bool:
21
+ return isinstance(body, dict) and body.get("status") == "pending"
22
+
23
+
24
+ def _paper_code(resp: httpx.Response) -> Optional[str]:
25
+ """The code of a paper error body {"detail": {"code": ...}}, else None (plain or list detail)."""
26
+ try:
27
+ detail = resp.json().get("detail")
28
+ except Exception:
29
+ return None
30
+ code = detail.get("code") if isinstance(detail, dict) else None
31
+ return code if isinstance(code, str) and code else None
32
+
33
+
34
+ def _internal_error(resp: httpx.Response) -> bool:
35
+ """A 500 internal_error: the server asks for a retry with the same Idempotency-Key and body."""
36
+ return resp.status_code == 500 and _paper_code(resp) == "internal_error"
37
+
38
+
39
+ def _is_refusal(resp: httpx.Response) -> bool:
40
+ """The command's own answer from the status read: a 4xx (not 429) with a paper error code. A plain
41
+ detail (an old backend's 404 Not Found, an expired token, a revoked scope) or a validation list
42
+ is a failed read."""
43
+ return 400 <= resp.status_code < 500 and resp.status_code != 429 and _paper_code(resp) is not None
44
+
45
+
46
+ def _safe_detail(resp: httpx.Response) -> str:
47
+ try:
48
+ data = resp.json()
49
+ except Exception:
50
+ return resp.text or f"HTTP {resp.status_code}"
51
+ if isinstance(data, dict) and "detail" in data:
52
+ detail = data["detail"]
53
+ return detail if isinstance(detail, str) else json.dumps(detail)
54
+ return json.dumps(data)
55
+
56
+
57
+ class FiltrixClient:
58
+ def __init__(self, base_url: str, api_key: Optional[str] = None,
59
+ jwt: Optional[str] = None, timeout: float = 60.0):
60
+ self.base_url = base_url.rstrip("/")
61
+ self.api_key = api_key
62
+ self.jwt = jwt
63
+ self.timeout = timeout
64
+
65
+ def _headers(self, auth: str) -> dict:
66
+ """auth in {'any', 'jwt', 'none'}."""
67
+ headers = {
68
+ "User-Agent": f"filtrix-cli/{__version__}",
69
+ "X-Agent-Request": "true",
70
+ "Content-Type": "application/json",
71
+ }
72
+ if auth == "none":
73
+ return headers
74
+ if auth == "jwt":
75
+ if not self.jwt:
76
+ raise CLIError("auth_failed", "This command requires login. Run `filtrix auth login`.",
77
+ suggestion="filtrix auth login", exit_code=4)
78
+ headers["Authorization"] = f"Bearer {self.jwt}"
79
+ return headers
80
+ # auth == "any"
81
+ if self.api_key:
82
+ headers["X-API-Key"] = self.api_key
83
+ elif self.jwt:
84
+ headers["Authorization"] = f"Bearer {self.jwt}"
85
+ else:
86
+ raise CLIError("auth_failed", "No credentials. Set FILTRIX_API_KEY or run `filtrix auth login`.",
87
+ suggestion="filtrix auth login", exit_code=4)
88
+ return headers
89
+
90
+ def _send(self, method: str, path: str, *, json_body: Any = None, auth: str = "any",
91
+ params: Optional[dict] = None, headers: Optional[dict] = None) -> httpx.Response:
92
+ url = f"{self.base_url}{path}"
93
+ headers = {**self._headers(auth), **(headers or {})}
94
+ clean_params = {k: v for k, v in (params or {}).items() if v is not None} or None
95
+ try:
96
+ with httpx.Client(timeout=self.timeout) as client:
97
+ return client.request(method, url, headers=headers, json=json_body, params=clean_params)
98
+ except httpx.TimeoutException as e:
99
+ raise CLIError("network", f"Request timed out: {e}", retryable=True, exit_code=6)
100
+ except httpx.HTTPError as e:
101
+ raise CLIError("network", f"Network error: {e}", retryable=True, exit_code=6)
102
+
103
+ def _request(self, method: str, path: str, *, json_body: Any = None, auth: str = "any",
104
+ params: Optional[dict] = None, headers: Optional[dict] = None) -> Any:
105
+ return self._handle_response(self._send(method, path, json_body=json_body, auth=auth,
106
+ params=params, headers=headers))
107
+
108
+ def _handle_response(self, resp: httpx.Response) -> Any:
109
+ if resp.status_code < 400:
110
+ return resp.json() if resp.content else {}
111
+ detail = _safe_detail(resp)
112
+ code = resp.status_code
113
+ if code in (401, 403):
114
+ raise CLIError("auth_failed", detail, status=code,
115
+ suggestion="Run `filtrix auth login` or check your API key.", exit_code=4)
116
+ if code == 404:
117
+ raise CLIError("not_found", detail, status=404, exit_code=3)
118
+ if code == 429:
119
+ raise CLIError("rate_limited", detail, status=429, retryable=True,
120
+ suggestion="Run `filtrix account` to see your quota.", exit_code=5)
121
+ if 400 <= code < 500:
122
+ raise CLIError("invalid_request", detail, status=code, exit_code=2)
123
+ raise CLIError("server_error", detail, status=code, retryable=True, exit_code=1)
124
+
125
+ # ---- Public API v1 ----
126
+ def backtest(self, filters: List[dict], outcome: str = "day_close_position",
127
+ flat_threshold: float = 0.002, start_date: Optional[str] = None,
128
+ end_date: Optional[str] = None, threshold: float = 0.0,
129
+ pos_min: Optional[float] = None, pos_max: Optional[float] = None,
130
+ sample_limit: int = 0) -> Any:
131
+ body: dict = {"filters": filters, "outcome": outcome, "flat_threshold": flat_threshold,
132
+ "threshold": threshold, "sample_limit": sample_limit}
133
+ for key, value in (("start_date", start_date), ("end_date", end_date),
134
+ ("pos_min", pos_min), ("pos_max", pos_max)):
135
+ if value is not None:
136
+ body[key] = value
137
+ return self._request("POST", "/api/v1/backtest", json_body=body)
138
+
139
+ def screen(self, filters: List[dict], limit: int = 50, offset: int = 0,
140
+ fields: Optional[List[str]] = None) -> Any:
141
+ body: dict = {"filters": filters, "limit": limit, "offset": offset}
142
+ if fields:
143
+ body["fields"] = list(fields)
144
+ return self._request("POST", "/api/v1/screen", json_body=body)
145
+
146
+ def ticker_info(self, symbol: str) -> Any:
147
+ return self._request("GET", f"/api/v1/ticker/{symbol.upper()}")
148
+
149
+ def list_filters(self, q: Optional[str] = None, value_type: Optional[str] = None,
150
+ limit: Optional[int] = None) -> Any:
151
+ return self._request("GET", "/api/v1/filters", auth="none",
152
+ params={"q": q, "type": value_type, "limit": limit})
153
+
154
+ def account(self) -> Any:
155
+ return self._request("GET", "/api/v1/account")
156
+
157
+ def meta(self) -> Any:
158
+ return self._request("GET", "/api/v1/meta")
159
+
160
+ def coverage(self, symbol: Optional[str] = None) -> Any:
161
+ return self._request("GET", "/api/v1/coverage",
162
+ params={"symbol": symbol.upper() if symbol else None})
163
+
164
+ def ticker_overview(self, symbol: str) -> Any:
165
+ return self._request("GET", f"/api/v1/ticker/{symbol.upper()}/overview")
166
+
167
+ def ticker_gap_stats(self, symbol: str, gap_threshold: float = 10.0,
168
+ direction: str = "up", stat: str = "avg") -> Any:
169
+ return self._request("GET", f"/api/v1/ticker/{symbol.upper()}/gap-stats",
170
+ params={"gap_threshold": gap_threshold, "direction": direction, "stat": stat})
171
+
172
+ def ticker_daily(self, symbol: str, limit: int = 250) -> Any:
173
+ return self._request("GET", f"/api/v1/ticker/{symbol.upper()}/daily", params={"limit": limit})
174
+
175
+ def premarket_gappers(self) -> Any:
176
+ return self._request("GET", "/api/v1/premarket/gappers")
177
+
178
+ def call(self, method: str, path: str, *, json_body: Any = None, params: Optional[dict] = None,
179
+ headers: Optional[dict] = None) -> Any:
180
+ """Any Public API v1 call with the configured credential (live scanner / paper reads)."""
181
+ return self._request(method, path, json_body=json_body, params=params, headers=headers)
182
+
183
+ def paper_command(self, method: str, path: str, key: str, *, json_body: Any = None,
184
+ params: Optional[dict] = None) -> Any:
185
+ """A paper write with its Idempotency-Key. A 500 internal_error was not applied and is retried
186
+ once with the same key and body. A pending answer (the account worker had not answered within
187
+ the server's wait) is followed on /paper/commands?event_id= for about 12 s more; still pending,
188
+ it returns {"status": "pending", "event_id", "idempotency_key"} (and "status_error" when a
189
+ status read failed)."""
190
+ headers = {"Idempotency-Key": key}
191
+ resp = self._send(method, path, json_body=json_body, params=params, headers=headers)
192
+ if _internal_error(resp):
193
+ _sleep(INTERNAL_RETRY_DELAY)
194
+ resp = self._send(method, path, json_body=json_body, params=params, headers=headers)
195
+ result = self._handle_response(resp)
196
+ if not (_is_pending(result) and result.get("event_id")):
197
+ return result
198
+ pending = {"status": "pending", "event_id": str(result["event_id"]), "idempotency_key": key}
199
+ for delay in PENDING_POLL_DELAYS:
200
+ _sleep(delay)
201
+ try:
202
+ resp = self._send("GET", COMMAND_STATUS_PATH, params={"event_id": pending["event_id"]})
203
+ except CLIError as err: # network
204
+ return {**pending, "status_error": err.message}
205
+ if resp.status_code >= 400 and not _is_refusal(resp):
206
+ return {**pending, "status_error": f"HTTP {resp.status_code}: {_safe_detail(resp)}"}
207
+ status = self._handle_response(resp) # a refusal raises as a direct answer would
208
+ if not _is_pending(status):
209
+ return status
210
+ return pending
211
+
212
+ def paper_command_status(self, event_id: str) -> Any:
213
+ """A paper command that answered pending: its result, its refusal as an error, or
214
+ {"status": "pending"}. The id goes in the query, where no proxy decodes a "/" of the key."""
215
+ return self._request("GET", COMMAND_STATUS_PATH, params={"event_id": event_id})
216
+
217
+ # ---- Saved runs, simulations, jobs (v1) ----
218
+ def runs_list(self, limit: int = 20, offset: int = 0) -> Any:
219
+ return self._request("GET", "/api/v1/runs", params={"limit": limit, "offset": offset})
220
+
221
+ def run_get(self, run_id: int) -> Any:
222
+ return self._request("GET", f"/api/v1/runs/{int(run_id)}")
223
+
224
+ def run_rows(self, run_id: int, limit: int = 100, offset: int = 0) -> Any:
225
+ return self._request("GET", f"/api/v1/runs/{int(run_id)}/rows", params={"limit": limit, "offset": offset})
226
+
227
+ def run_save(self, body: dict) -> Any:
228
+ return self._request("POST", "/api/v1/runs", json_body=body)
229
+
230
+ def run_share(self, run_id: int) -> Any:
231
+ return self._request("POST", f"/api/v1/runs/{int(run_id)}/share")
232
+
233
+ def run_unshare(self, run_id: int) -> Any:
234
+ return self._request("DELETE", f"/api/v1/runs/{int(run_id)}/share")
235
+
236
+ def run_delete(self, run_id: int) -> Any:
237
+ return self._request("DELETE", f"/api/v1/runs/{int(run_id)}")
238
+
239
+ def trade_context(self, run_id: int, symbol: str, date: str, daily_lookback: int = 120) -> Any:
240
+ return self._request("GET", f"/api/v1/runs/{int(run_id)}/trade-context",
241
+ params={"symbol": symbol.upper(), "date": date, "daily_lookback": daily_lookback})
242
+
243
+ def simulate(self, body: dict) -> Any:
244
+ return self._request("POST", "/api/v1/simulations", json_body=body)
245
+
246
+ def job_get(self, job_id: str) -> Any:
247
+ return self._request("GET", f"/api/v1/jobs/{quote(job_id, safe='')}")
248
+
249
+ def job_cancel(self, job_id: str) -> Any:
250
+ return self._request("POST", f"/api/v1/jobs/{quote(job_id, safe='')}/cancel")
251
+
252
+ # ---- Key management (JWT) ----
253
+ def keys_list(self) -> Any:
254
+ return self._request("GET", "/api/keys", auth="jwt")
255
+
256
+ def keys_create(self, name: str = "default") -> Any:
257
+ return self._request("POST", "/api/keys", json_body={"name": name}, auth="jwt")
258
+
259
+ def keys_revoke(self, key_id: int) -> Any:
260
+ return self._request("DELETE", f"/api/keys/{key_id}", auth="jwt")
261
+
262
+ # ---- Registration (pre-auth) ----
263
+ def register(self, email: str, password: str, delivery: str = "code",
264
+ ref_source: Optional[str] = None) -> Any:
265
+ body: dict = {"email": email, "password": password, "delivery": delivery}
266
+ if ref_source:
267
+ body["ref_data"] = {"ref_source": ref_source}
268
+ return self._request("POST", "/api/auth/register", json_body=body, auth="none")
269
+
270
+ def verify_email_code(self, email: str, code: str) -> Any:
271
+ return self._request("POST", "/api/auth/verify-email-code",
272
+ json_body={"email": email, "code": code}, auth="none")
273
+
274
+ def resend_code(self, email: str) -> Any:
275
+ return self._request("POST", "/api/auth/resend-code",
276
+ json_body={"email": email}, auth="none")
@@ -3,9 +3,11 @@
3
3
  They answer "not available through the API yet" until FILTRIX enables the live API.
4
4
  Paper money is simulated; nothing here places a real order. Paper writes send an
5
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.
6
+ draft versions from `filtrix paper account` when you leave them out. A write that is still
7
+ pending after the wait exits 6 with its event_id; `filtrix paper command EVENT_ID` reads it.
7
8
  """
8
9
  import json
10
+ import shlex
9
11
  import sys
10
12
  import uuid
11
13
  from enum import Enum
@@ -67,8 +69,16 @@ def _versions(client, strategy_id: Optional[int] = None) -> Tuple[Any, Any]:
67
69
 
68
70
  def _command(client, method: str, path: str, key: Optional[str], *, body: Any = None,
69
71
  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
+ """A paper write. Still pending after the wait: print it (event_id, idempotency_key) and exit 6."""
73
+ key = key or f"cli-{uuid.uuid4()}"
74
+ result = client.paper_command(method, path, key, json_body=body, params=params)
75
+ if isinstance(result, dict) and result.get("status") == "pending" and result.get("event_id"):
76
+ output_result(result, kind="paper")
77
+ event_id = result["event_id"]
78
+ raise CLIError("pending", f"Paper command {event_id} has no answer yet; it may still apply.",
79
+ suggestion=f"filtrix paper command {shlex.quote(event_id)} (to send it again, keep "
80
+ f"--idempotency-key {shlex.quote(key)})", exit_code=6)
81
+ return result
72
82
 
73
83
 
74
84
  # ---- scanner ------------------------------------------------------------------------
@@ -214,6 +224,14 @@ def paper_list(kind: Kind = typer.Argument(...), after: Optional[str] = typer.Op
214
224
  kind="paper")
215
225
 
216
226
 
227
+ @paper_app.command("command")
228
+ @command
229
+ def paper_command_status(event_id: str = typer.Argument(..., help="event_id of a command that exited pending.")) -> None:
230
+ """The outcome of a paper command that was still pending: its result, or still pending."""
231
+ client, _ = build_client()
232
+ output_result(client.paper_command_status(event_id), kind="paper")
233
+
234
+
217
235
  # ---- paper: commands -----------------------------------------------------------------
218
236
  @paper_app.command("create-account")
219
237
  @command
@@ -183,3 +183,132 @@ def test_run_id_must_be_a_uuid_and_no_request_is_made():
183
183
  result = runner.invoke(app, ["paper", "pause", "../account/close-all#", "--version", "4"])
184
184
 
185
185
  assert result.exit_code == 2 and close_all.call_count == 0
186
+
187
+
188
+ # --- PAPER_SOURCE=derived: 202 pending, `paper command`, internal_error retry ----------------
189
+ KEY = "a//b/../c"
190
+ EVENT = f"command:7:pause:{KEY}"
191
+ COMMANDS = f"{BASE}/api/v1/paper/commands"
192
+ PENDING = {"status": "pending", "event_id": EVENT}
193
+ INTERNAL = {"detail": {"code": "internal_error",
194
+ "message": "The command could not be applied. Retry with the same Idempotency-Key and body."}}
195
+
196
+
197
+ @pytest.fixture
198
+ def sleeps(monkeypatch):
199
+ from filtrix_cli import client
200
+
201
+ slept = []
202
+ monkeypatch.setattr(client, "_sleep", slept.append)
203
+ return slept
204
+
205
+
206
+ @respx.mock
207
+ def test_pending_command_prints_its_result_once_applied(sleeps):
208
+ pause = respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/pause").mock(return_value=Response(202, json=PENDING))
209
+ status = respx.get(COMMANDS, params={"event_id": EVENT}).mock(side_effect=[
210
+ Response(200, json={"status": "pending"}), Response(200, json={"account": {"version": 5}})])
211
+
212
+ result = runner.invoke(app, ["--json", "paper", "pause", RUN, "--version", "4", "--idempotency-key", KEY])
213
+
214
+ url = status.calls.last.request.url
215
+ assert result.exit_code == 0, result.stderr
216
+ assert json.loads(result.stdout) == {"account": {"version": 5}}
217
+ assert pause.call_count == 1 and status.call_count == 2 and sleeps == [1.0, 1.0]
218
+ assert pause.calls.last.request.headers["Idempotency-Key"] == KEY
219
+ assert url.path == "/api/v1/paper/commands" and url.params["event_id"] == EVENT
220
+
221
+
222
+ @respx.mock
223
+ def test_still_pending_exits_6_with_the_event_id_and_key(sleeps):
224
+ from filtrix_cli.client import PENDING_POLL_DELAYS
225
+
226
+ respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/pause").mock(return_value=Response(202, json=PENDING))
227
+ status = respx.get(COMMANDS, params={"event_id": EVENT}).mock(return_value=Response(200, json={"status": "pending"}))
228
+
229
+ result = runner.invoke(app, ["--json", "paper", "pause", RUN, "--version", "4", "--idempotency-key", KEY])
230
+
231
+ out, err = json.loads(result.stdout), json.loads(result.stderr)["error"]
232
+ assert result.exit_code == 6
233
+ assert out == {"status": "pending", "event_id": EVENT, "idempotency_key": KEY}
234
+ assert err["type"] == "pending" and "filtrix paper command" in err["suggestion"] and KEY in err["suggestion"]
235
+ assert status.call_count == len(PENDING_POLL_DELAYS) and sum(sleeps) <= 15
236
+
237
+
238
+ # A failed status read (no paper code in detail) is not the command's answer: still pending.
239
+ READ_FAILURES = [
240
+ (503, {"code": "storage_unavailable", "message": "Paper account storage is unavailable."}, "storage_unavailable"),
241
+ (429, "Rate limit exceeded, retry in a few seconds", "Rate limit"),
242
+ (404, "Not Found", "Not Found"), # a backend without ?event_id= (/{kind})
243
+ (401, "Invalid or expired token", "expired token"),
244
+ (403, "insufficient_scope: read access was revoked", "insufficient_scope"),
245
+ (422, [{"loc": ["query", "event_id"], "msg": "Field required"}], "Field required"),
246
+ ]
247
+ # A refusal of the command itself: a 4xx whose detail is a paper error object with a code.
248
+ REFUSALS = [
249
+ (409, {"code": "version_conflict", "path": "", "message": "version conflict"}, "version_conflict", 2),
250
+ (403, {"code": "forbidden", "path": "", "message": "Paper trading entries need Pro"}, "forbidden", 4),
251
+ (404, {"code": "not_found", "path": "run_id", "message": "not found"}, "not_found", 3),
252
+ ]
253
+
254
+
255
+ @pytest.mark.parametrize("code,detail,text", READ_FAILURES)
256
+ @respx.mock
257
+ def test_a_failed_status_read_still_reports_pending(sleeps, code, detail, text):
258
+ respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/pause").mock(return_value=Response(202, json=PENDING))
259
+ status = respx.get(COMMANDS, params={"event_id": EVENT}).mock(return_value=Response(code, json={"detail": detail}))
260
+
261
+ result = runner.invoke(app, ["--json", "paper", "pause", RUN, "--version", "4", "--idempotency-key", KEY])
262
+
263
+ out = json.loads(result.stdout)
264
+ assert result.exit_code == 6 and out["event_id"] == EVENT and text in out["status_error"]
265
+ assert status.call_count == 1
266
+
267
+
268
+ @pytest.mark.parametrize("code,detail,text,exit_code", REFUSALS)
269
+ @respx.mock
270
+ def test_a_refusal_read_from_the_status_route_exits_like_a_direct_refusal(sleeps, code, detail, text, exit_code):
271
+ respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/pause").mock(return_value=Response(202, json=PENDING))
272
+ status = respx.get(COMMANDS, params={"event_id": EVENT}).mock(side_effect=[
273
+ Response(200, json={"status": "pending"}), Response(code, json={"detail": detail})])
274
+
275
+ result = runner.invoke(app, ["--json", "paper", "pause", RUN, "--version", "4", "--idempotency-key", KEY])
276
+
277
+ assert result.exit_code == exit_code and text in result.stderr and status.call_count == 2
278
+ assert result.stdout == ""
279
+
280
+
281
+ @respx.mock
282
+ def test_internal_error_is_retried_once_with_the_same_key_and_body(sleeps):
283
+ reset = respx.post(f"{BASE}/api/v1/paper/account/reset").mock(side_effect=[
284
+ Response(500, json=INTERNAL), Response(202, json={"account": {"version": 5}})])
285
+
286
+ result = runner.invoke(app, ["--json", "paper", "reset", "--capital", "50000", "--limits-json",
287
+ json.dumps(LIMITS), "--version", "4", "--yes"])
288
+
289
+ first, second = reset.calls
290
+ assert result.exit_code == 0, result.stderr
291
+ assert first.request.headers["Idempotency-Key"] == second.request.headers["Idempotency-Key"]
292
+ assert first.request.content == second.request.content and sleeps == [1.0]
293
+
294
+
295
+ @respx.mock
296
+ def test_a_second_internal_error_exits_1_and_other_errors_are_not_retried(sleeps):
297
+ close_all = respx.post(f"{BASE}/api/v1/paper/account/close-all").mock(return_value=Response(500, json=INTERNAL))
298
+ pause = respx.post(f"{BASE}/api/v1/paper/runs/{RUN}/pause").mock(return_value=Response(503, json={
299
+ "detail": {"code": "feed_unavailable", "message": "The live feed is not ready."}}))
300
+
301
+ failed = runner.invoke(app, ["paper", "close-all", "--version", "4", "--yes"])
302
+ refused = runner.invoke(app, ["paper", "pause", RUN, "--version", "4"])
303
+
304
+ assert failed.exit_code == 1 and "internal_error" in failed.stderr and close_all.call_count == 2
305
+ assert refused.exit_code == 1 and pause.call_count == 1
306
+
307
+
308
+ @respx.mock
309
+ def test_paper_command_sends_the_event_id_as_a_query():
310
+ status = respx.get(COMMANDS, params={"event_id": EVENT}).mock(return_value=Response(200, json={"status": "pending"}))
311
+
312
+ result = runner.invoke(app, ["--json", "paper", "command", EVENT])
313
+
314
+ assert result.exit_code == 0 and json.loads(result.stdout) == {"status": "pending"} and status.call_count == 1
@@ -1,5 +1,6 @@
1
1
  from typer.testing import CliRunner
2
2
 
3
+ from filtrix_cli import __version__
3
4
  from filtrix_cli.__main__ import app
4
5
 
5
6
  runner = CliRunner()
@@ -8,10 +9,17 @@ runner = CliRunner()
8
9
  def test_version_prints_semver():
9
10
  result = runner.invoke(app, ["version"])
10
11
  assert result.exit_code == 0
11
- assert "filtrix-cli 0.4.0" in result.stdout
12
+ assert "filtrix-cli 0.5.0" in result.stdout
12
13
 
13
14
 
14
15
  def test_no_args_shows_help():
15
16
  result = runner.invoke(app, [])
16
17
  assert result.exit_code == 0
17
18
  assert "FILTRIX CLI" in result.stdout
19
+
20
+
21
+ def test_changelog_has_an_entry_for_the_package_version():
22
+ import pathlib
23
+
24
+ changelog = pathlib.Path(__file__).resolve().parents[1] / "CHANGELOG.md"
25
+ assert f"\n## {__version__} " in changelog.read_text(encoding="utf-8")
@@ -1 +0,0 @@
1
- __version__ = "0.4.0"
File without changes
File without changes