filtrix-cli 0.2.0__tar.gz → 0.3.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 (49) hide show
  1. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/PKG-INFO +11 -2
  2. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/README.md +10 -1
  3. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/pyproject.toml +1 -1
  4. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/AGENTS.md +26 -2
  5. filtrix_cli-0.3.0/src/filtrix_cli/__init__.py +1 -0
  6. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/__main__.py +4 -0
  7. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/client.py +36 -0
  8. filtrix_cli-0.3.0/src/filtrix_cli/commands/research.py +240 -0
  9. filtrix_cli-0.3.0/tests/test_cmd_research.py +195 -0
  10. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_smoke.py +1 -1
  11. filtrix_cli-0.2.0/src/filtrix_cli/__init__.py +0 -1
  12. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/.gitignore +0 -0
  13. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/LICENSE +0 -0
  14. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/auth.py +0 -0
  15. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/__init__.py +0 -0
  16. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/_helpers.py +0 -0
  17. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/account.py +0 -0
  18. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/authcmd.py +0 -0
  19. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/backtest.py +0 -0
  20. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/configcmd.py +0 -0
  21. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/filters.py +0 -0
  22. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/keys.py +0 -0
  23. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/llms.py +0 -0
  24. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/market.py +0 -0
  25. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/screen.py +0 -0
  26. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/commands/ticker.py +0 -0
  27. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/config.py +0 -0
  28. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/filters.py +0 -0
  29. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/output.py +0 -0
  30. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/render.py +0 -0
  31. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/src/filtrix_cli/state.py +0 -0
  32. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/__init__.py +0 -0
  33. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_auth.py +0 -0
  34. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_client.py +0 -0
  35. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_client_register.py +0 -0
  36. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_auth.py +0 -0
  37. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_backtest_screen.py +0 -0
  38. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_config.py +0 -0
  39. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_keys.py +0 -0
  40. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_llms.py +0 -0
  41. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_market.py +0 -0
  42. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_profile.py +0 -0
  43. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_read.py +0 -0
  44. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_cmd_register.py +0 -0
  45. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_config.py +0 -0
  46. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_filters.py +0 -0
  47. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_helpers.py +0 -0
  48. {filtrix_cli-0.2.0 → filtrix_cli-0.3.0}/tests/test_output.py +0 -0
  49. {filtrix_cli-0.2.0 → filtrix_cli-0.3.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.2.0
3
+ Version: 0.3.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/
@@ -70,6 +70,11 @@ filtrix daily AAPL --limit 60 # daily OHLCV bars
70
70
  filtrix coverage TSLA # how much history
71
71
  filtrix premarket # today's premarket gappers (free)
72
72
  filtrix account
73
+ filtrix runs save -f "gap_gup>=20" -f "price_price<10" --name "Small gappers" --wait
74
+ filtrix runs list
75
+ filtrix simulate --run-id 42 --entry open_at_0930 --exit stop_loss_take_profit --sl 0.03 --tp 0.06 --wait
76
+ filtrix runs context 42 ABCD 2025-03-14 # daily + minute bars of one event
77
+ filtrix jobs get JOB_ID
73
78
  filtrix keys create --name laptop
74
79
  filtrix llms # machine-readable usage guide for AI agents
75
80
  ```
@@ -78,7 +83,11 @@ filtrix llms # machine-readable usage guide for AI agents
78
83
 
79
84
  Output is human-readable in a terminal and JSON when piped or with the global `--json` flag.
80
85
  Global flags (`--json`, `--quiet`, `--profile`, `--api-key`, `--base-url`) go BEFORE the subcommand.
81
- Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network, 1 server.
86
+ Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network or `--wait` timeout, 1 server
87
+ or failed job.
88
+
89
+ `runs save` and `simulate` start background jobs; `--wait` polls until they finish. `runs delete` needs
90
+ `--yes` when not interactive.
82
91
 
83
92
  ## Configuration
84
93
 
@@ -38,6 +38,11 @@ filtrix daily AAPL --limit 60 # daily OHLCV bars
38
38
  filtrix coverage TSLA # how much history
39
39
  filtrix premarket # today's premarket gappers (free)
40
40
  filtrix account
41
+ filtrix runs save -f "gap_gup>=20" -f "price_price<10" --name "Small gappers" --wait
42
+ filtrix runs list
43
+ filtrix simulate --run-id 42 --entry open_at_0930 --exit stop_loss_take_profit --sl 0.03 --tp 0.06 --wait
44
+ filtrix runs context 42 ABCD 2025-03-14 # daily + minute bars of one event
45
+ filtrix jobs get JOB_ID
41
46
  filtrix keys create --name laptop
42
47
  filtrix llms # machine-readable usage guide for AI agents
43
48
  ```
@@ -46,7 +51,11 @@ filtrix llms # machine-readable usage guide for AI agents
46
51
 
47
52
  Output is human-readable in a terminal and JSON when piped or with the global `--json` flag.
48
53
  Global flags (`--json`, `--quiet`, `--profile`, `--api-key`, `--base-url`) go BEFORE the subcommand.
49
- Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network, 1 server.
54
+ Exit codes: 0 ok, 2 usage, 3 not-found, 4 auth, 5 rate-limited, 6 network or `--wait` timeout, 1 server
55
+ or failed job.
56
+
57
+ `runs save` and `simulate` start background jobs; `--wait` polls until they finish. `runs delete` needs
58
+ `--yes` when not interactive.
50
59
 
51
60
  ## Configuration
52
61
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "filtrix-cli"
7
- version = "0.2.0"
7
+ version = "0.3.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,11 +14,13 @@ 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 (retryable)
17
+ - 6 network/timeout, incl. `--wait` giving up on a job that is still running (retryable)
18
18
 
19
19
  ## Auth
20
20
  - Reads/backtests: set env FILTRIX_API_KEY=flt_... (or `filtrix config set api_key ...`).
21
- - Quota: 50 requests/day free, 1000 Pro; meta, filters, account, premarket are free. Resets at midnight America/New_York.
21
+ - Quota: 50 requests/day free, 1000 Pro; meta, filters, account, premarket, jobs get are free. Resets at midnight America/New_York.
22
+ - Saved runs and simulations also have plan limits (`filtrix account`). `runs save`, `simulate`, `runs share|unshare|delete`
23
+ and `jobs cancel` change your account; an OAuth token granted read-only cannot run them.
22
24
  - Key management: `filtrix auth login` first (stores a JWT).
23
25
 
24
26
  ## Commands
@@ -34,6 +36,20 @@ Structured command-line access to the FILTRIX historical backtest engine.
34
36
  - filtrix coverage [SYMBOL] first/last event date and counts
35
37
  - filtrix premarket (free) today's premarket gappers with historical stats
36
38
  - filtrix account (free) tier, quota used/remaining, reset time, capabilities
39
+ - filtrix runs list [--limit 20] [--offset 0] your saved runs with summaries
40
+ - filtrix runs get RUN_ID filters, outcome, summary, share link
41
+ - filtrix runs rows RUN_ID [--limit 100] [--offset 0] the run's events with outcome values (max 500)
42
+ - filtrix runs save --filter ... [--name N] [--outcome ...] [--row-filter all|positive|negative|neutral|nonzero]
43
+ [backtest options] [--wait] [--timeout 600] saves a run (background job)
44
+ - filtrix runs share|unshare RUN_ID public read-only link on/off
45
+ - filtrix runs delete RUN_ID --yes permanent; --yes is required when not interactive
46
+ - filtrix runs context RUN_ID SYMBOL DATE [--lookback 120] daily + that day's minute bars for one event
47
+ - filtrix simulate (--run-id N | --filter ...) --entry open_at_0930|green_to_red|red_to_green|bar_break
48
+ [--within-minutes M] --exit close_1600|hold_minutes|stop_loss_take_profit
49
+ [--hold-minutes M] [--sl 0.02] [--tp 0.05] [--side long|short] [--bar-minutes 1..30]
50
+ [--limit-pairs 200] [--wait] [--timeout 600]
51
+ - filtrix jobs get JOB_ID (free) status, progress, result
52
+ - filtrix jobs cancel JOB_ID
37
53
  - filtrix keys list|create|revoke
38
54
  - filtrix auth login|logout|status
39
55
  - filtrix auth register --email E --password P --accept-tos (emails a 6-digit code, then prompts for it, then auto-logs-in)
@@ -43,6 +59,14 @@ Structured command-line access to the FILTRIX historical backtest engine.
43
59
 
44
60
  Note: global flags like `--json` go BEFORE the subcommand (e.g. `filtrix --json backtest ...`).
45
61
 
62
+ ## Background jobs
63
+ `runs save` and `simulate` print {"job_id","status":"queued","poll"}. Add `--wait` to poll until the job ends
64
+ (prints the finished job; a failed job exits 1, `--timeout` seconds without an end exits 6), or poll with
65
+ `filtrix jobs get JOB_ID`. At most 2 jobs run at a time per account (429 otherwise).
66
+ A simulation's result: summary (n_trades, win_rate 0..1, profit_factor, avg_pnl / total_pnl in USD per share,
67
+ avg_holding_min), up to 200 trades with pnl_pct, run_id. Definitions: `filtrix meta --json` -> "simulation".
68
+ --sl / --tp are fractions (0.02 = 2%).
69
+
46
70
  ## Filter DSL
47
71
  "COL OP VAL", operators: >= <= != = > < like in. Repeat --filter for AND.
48
72
  Examples: "gap_gup>=10", "price_price<5", "earnings_date_days_earningd=0.25", "sic_code in 7372,7389".
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -12,6 +12,7 @@ from filtrix_cli.commands import authcmd
12
12
  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
+ from filtrix_cli.commands import research as research_cmd
15
16
 
16
17
  app = typer.Typer(
17
18
  add_completion=False,
@@ -57,6 +58,9 @@ app.command("overview")(market_cmd.overview)
57
58
  app.command("gaps")(market_cmd.gaps)
58
59
  app.command("daily")(market_cmd.daily)
59
60
  app.command("premarket")(market_cmd.premarket)
61
+ app.add_typer(research_cmd.runs_app, name="runs")
62
+ app.command("simulate")(research_cmd.simulate)
63
+ app.add_typer(research_cmd.jobs_app, name="jobs")
60
64
 
61
65
 
62
66
  def main() -> None:
@@ -1,6 +1,7 @@
1
1
  """Synchronous httpx client for the FILTRIX API, with error -> CLIError mapping."""
2
2
  import json
3
3
  from typing import Any, List, Optional
4
+ from urllib.parse import quote
4
5
 
5
6
  import httpx
6
7
 
@@ -136,6 +137,41 @@ class FiltrixClient:
136
137
  def premarket_gappers(self) -> Any:
137
138
  return self._request("GET", "/api/v1/premarket/gappers")
138
139
 
140
+ # ---- Saved runs, simulations, jobs (v1) ----
141
+ def runs_list(self, limit: int = 20, offset: int = 0) -> Any:
142
+ return self._request("GET", "/api/v1/runs", params={"limit": limit, "offset": offset})
143
+
144
+ def run_get(self, run_id: int) -> Any:
145
+ return self._request("GET", f"/api/v1/runs/{int(run_id)}")
146
+
147
+ def run_rows(self, run_id: int, limit: int = 100, offset: int = 0) -> Any:
148
+ return self._request("GET", f"/api/v1/runs/{int(run_id)}/rows", params={"limit": limit, "offset": offset})
149
+
150
+ def run_save(self, body: dict) -> Any:
151
+ return self._request("POST", "/api/v1/runs", json_body=body)
152
+
153
+ def run_share(self, run_id: int) -> Any:
154
+ return self._request("POST", f"/api/v1/runs/{int(run_id)}/share")
155
+
156
+ def run_unshare(self, run_id: int) -> Any:
157
+ return self._request("DELETE", f"/api/v1/runs/{int(run_id)}/share")
158
+
159
+ def run_delete(self, run_id: int) -> Any:
160
+ return self._request("DELETE", f"/api/v1/runs/{int(run_id)}")
161
+
162
+ def trade_context(self, run_id: int, symbol: str, date: str, daily_lookback: int = 120) -> Any:
163
+ return self._request("GET", f"/api/v1/runs/{int(run_id)}/trade-context",
164
+ params={"symbol": symbol.upper(), "date": date, "daily_lookback": daily_lookback})
165
+
166
+ def simulate(self, body: dict) -> Any:
167
+ return self._request("POST", "/api/v1/simulations", json_body=body)
168
+
169
+ def job_get(self, job_id: str) -> Any:
170
+ return self._request("GET", f"/api/v1/jobs/{quote(job_id, safe='')}")
171
+
172
+ def job_cancel(self, job_id: str) -> Any:
173
+ return self._request("POST", f"/api/v1/jobs/{quote(job_id, safe='')}/cancel")
174
+
139
175
  # ---- Key management (JWT) ----
140
176
  def keys_list(self) -> Any:
141
177
  return self._request("GET", "/api/keys", auth="jwt")
@@ -0,0 +1,240 @@
1
+ """Saved runs, strategy simulations and background jobs over the Public API v1.
2
+
3
+ `runs save`, `runs share|unshare|delete` and `simulate` change your account; saving and
4
+ simulating run as background jobs (`--wait` polls until they end, `filtrix jobs get` later).
5
+ """
6
+ import sys
7
+ import time
8
+ from enum import Enum
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ import typer
12
+
13
+ from filtrix_cli.commands._helpers import build_client, command, output_result
14
+ from filtrix_cli.filters import resolve_filters
15
+ from filtrix_cli.output import CLIError, is_json_mode
16
+ from filtrix_cli.state import get_state
17
+
18
+ runs_app = typer.Typer(help="Your saved runs (the app's Context runs).", no_args_is_help=True)
19
+ jobs_app = typer.Typer(help="Background jobs started by `runs save` and `simulate`.", no_args_is_help=True)
20
+
21
+ # Module-level so tests can swap the clock.
22
+ _sleep = time.sleep
23
+ _clock = time.monotonic
24
+ POLL_SECONDS = 2.0
25
+ JOB_DONE = {"completed", "failed", "cancelled"}
26
+
27
+ FILTER_HELP = 'Filter "COL OP VAL" (repeatable). E.g. -f "gap_gup>=10".'
28
+ FILTERS_JSON_HELP = "JSON array of filter objects, or '-' to read from stdin."
29
+
30
+
31
+ class RowFilter(str, Enum):
32
+ all = "all"
33
+ positive = "positive"
34
+ negative = "negative"
35
+ neutral = "neutral"
36
+ nonzero = "nonzero"
37
+
38
+
39
+ class EntryType(str, Enum):
40
+ open_at_0930 = "open_at_0930"
41
+ green_to_red = "green_to_red"
42
+ red_to_green = "red_to_green"
43
+ bar_break = "bar_break"
44
+
45
+
46
+ class ExitType(str, Enum):
47
+ close_1600 = "close_1600"
48
+ hold_minutes = "hold_minutes"
49
+ stop_loss_take_profit = "stop_loss_take_profit"
50
+
51
+
52
+ class Side(str, Enum):
53
+ long = "long"
54
+ short = "short"
55
+
56
+
57
+ def _drop_none(d: Dict[str, Any]) -> Dict[str, Any]:
58
+ return {k: v for k, v in d.items() if v is not None}
59
+
60
+
61
+ def wait_for_job(client, job_id: str, timeout: float) -> Dict[str, Any]:
62
+ """Poll GET /api/v1/jobs/{id} (free) until the job ends or `timeout` seconds pass."""
63
+ deadline = _clock() + max(0.0, timeout)
64
+ while True:
65
+ job = client.job_get(job_id)
66
+ status = job.get("status")
67
+ if status == "failed":
68
+ raise CLIError("job_failed", job.get("error") or f"Job {job_id} failed.", exit_code=1)
69
+ if status in JOB_DONE:
70
+ return job
71
+ remaining = deadline - _clock()
72
+ if remaining <= 0:
73
+ raise CLIError("timeout", f"Job {job_id} is still {status} after {timeout:g}s.", retryable=True,
74
+ suggestion=f"filtrix jobs get {job_id}", exit_code=6)
75
+ _sleep(min(POLL_SECONDS, remaining))
76
+
77
+
78
+ def _started(client, started: Dict[str, Any], wait: bool, timeout: float, kind: str) -> None:
79
+ output_result(wait_for_job(client, started["job_id"], timeout) if wait else started, kind=kind)
80
+
81
+
82
+ # ---- runs -----------------------------------------------------------------------
83
+ @runs_app.command("list")
84
+ @command
85
+ def runs_list(
86
+ limit: int = typer.Option(20, "--limit", min=1, max=100, help="Runs per page."),
87
+ offset: int = typer.Option(0, "--offset", min=0),
88
+ ) -> None:
89
+ """Your saved runs, newest first, with their summaries."""
90
+ client, _ = build_client()
91
+ output_result(client.runs_list(limit=limit, offset=offset), kind="runs")
92
+
93
+
94
+ @runs_app.command("get")
95
+ @command
96
+ def runs_get(run_id: int = typer.Argument(..., help="Run id from `filtrix runs list`.")) -> None:
97
+ """One run: filters, outcome, summary statistics, share link."""
98
+ client, _ = build_client()
99
+ output_result(client.run_get(run_id), kind="run")
100
+
101
+
102
+ @runs_app.command("rows")
103
+ @command
104
+ def runs_rows(
105
+ run_id: int = typer.Argument(...),
106
+ limit: int = typer.Option(100, "--limit", min=1, max=500),
107
+ offset: int = typer.Option(0, "--offset", min=0),
108
+ ) -> None:
109
+ """A page of the run's events with their outcome values."""
110
+ client, _ = build_client()
111
+ output_result(client.run_rows(run_id, limit=limit, offset=offset), kind="run_rows")
112
+
113
+
114
+ @runs_app.command("save")
115
+ @command
116
+ def runs_save(
117
+ filter: Optional[List[str]] = typer.Option(None, "--filter", "-f", help=FILTER_HELP),
118
+ filters_json: Optional[str] = typer.Option(None, "--filters-json", help=FILTERS_JSON_HELP),
119
+ name: Optional[str] = typer.Option(None, "--name", help="Name shown in the app's Context runs."),
120
+ outcome: str = typer.Option("day_close_position", "--outcome", help="Outcome (see `filtrix meta`)."),
121
+ start: Optional[str] = typer.Option(None, "--start", help="Start date YYYY-MM-DD."),
122
+ end: Optional[str] = typer.Option(None, "--end", help="End date YYYY-MM-DD."),
123
+ threshold: float = typer.Option(0.0, "--threshold", help="In the outcome's unit, as for backtest."),
124
+ flat_threshold: float = typer.Option(0.002, "--flat-threshold"),
125
+ pos_min: Optional[float] = typer.Option(None, "--pos-min"),
126
+ pos_max: Optional[float] = typer.Option(None, "--pos-max"),
127
+ row_filter: RowFilter = typer.Option(RowFilter.all, "--row-filter", help="Which outcome rows to keep."),
128
+ wait: bool = typer.Option(False, "--wait", help="Poll until the save finishes."),
129
+ timeout: float = typer.Option(600, "--timeout", min=0, help="Seconds --wait polls before giving up."),
130
+ ) -> None:
131
+ """Save a backtest as a named run in your account (background job; plan limit on saved runs)."""
132
+ filters = resolve_filters(filter, filters_json)
133
+ body = _drop_none({"filters": filters, "name": name, "outcome": outcome, "start_date": start,
134
+ "end_date": end, "threshold": threshold, "flat_threshold": flat_threshold,
135
+ "pos_min": pos_min, "pos_max": pos_max, "row_filter": row_filter.value})
136
+ client, _ = build_client()
137
+ _started(client, client.run_save(body), wait, timeout, kind="job")
138
+
139
+
140
+ @runs_app.command("share")
141
+ @command
142
+ def runs_share(run_id: int = typer.Argument(...)) -> None:
143
+ """Turn on the run's public read-only link and print it."""
144
+ client, _ = build_client()
145
+ output_result(client.run_share(run_id), kind="share")
146
+
147
+
148
+ @runs_app.command("unshare")
149
+ @command
150
+ def runs_unshare(run_id: int = typer.Argument(...)) -> None:
151
+ """Turn the run's public link off."""
152
+ client, _ = build_client()
153
+ output_result(client.run_unshare(run_id), kind="share")
154
+
155
+
156
+ @runs_app.command("delete")
157
+ @command
158
+ def runs_delete(
159
+ run_id: int = typer.Argument(...),
160
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm; required when not interactive."),
161
+ ) -> None:
162
+ """Delete a run permanently (its events, rows and share link)."""
163
+ if not yes:
164
+ if is_json_mode(get_state().json) or not sys.stdin.isatty():
165
+ raise CLIError("invalid_request", "Deleting a run is permanent; pass --yes to confirm.",
166
+ suggestion=f"filtrix runs delete {run_id} --yes", exit_code=2)
167
+ typer.confirm(f"Delete run {run_id} permanently?", abort=True)
168
+ client, _ = build_client()
169
+ output_result(client.run_delete(run_id), kind="deleted")
170
+
171
+
172
+ @runs_app.command("context")
173
+ @command
174
+ def runs_context(
175
+ run_id: int = typer.Argument(...),
176
+ symbol: str = typer.Argument(..., help="Ticker of one of the run's events."),
177
+ date: str = typer.Argument(..., help="Event date YYYY-MM-DD."),
178
+ lookback: int = typer.Option(120, "--lookback", min=1, max=250, help="Daily bars up to the date."),
179
+ ) -> None:
180
+ """Daily bars and that day's minute bars for one event of the run."""
181
+ client, _ = build_client()
182
+ output_result(client.trade_context(run_id, symbol, date, daily_lookback=lookback), kind="trade_context")
183
+
184
+
185
+ # ---- simulate -------------------------------------------------------------------
186
+ @command
187
+ def simulate(
188
+ run_id: Optional[int] = typer.Option(None, "--run-id", help="Simulate the events of one of your runs."),
189
+ filter: Optional[List[str]] = typer.Option(None, "--filter", "-f", help=FILTER_HELP + " Saves a run first."),
190
+ filters_json: Optional[str] = typer.Option(None, "--filters-json", help=FILTERS_JSON_HELP),
191
+ entry: EntryType = typer.Option(..., "--entry", help="When the trade opens."),
192
+ within_minutes: Optional[int] = typer.Option(None, "--within-minutes", min=1, max=390,
193
+ help="Look for the entry only this many minutes after the open."),
194
+ exit: ExitType = typer.Option(..., "--exit", help="When the trade closes."),
195
+ hold_minutes: Optional[int] = typer.Option(None, "--hold-minutes", min=1, max=390, help="For --exit hold_minutes."),
196
+ sl: Optional[float] = typer.Option(None, "--sl", help="Stop loss as a fraction (0.02 = 2%)."),
197
+ tp: Optional[float] = typer.Option(None, "--tp", help="Take profit as a fraction (0.05 = 5%)."),
198
+ side: Side = typer.Option(Side.long, "--side"),
199
+ bar_minutes: int = typer.Option(1, "--bar-minutes", min=1, max=30, help="Bar size the strategy reads."),
200
+ limit_pairs: int = typer.Option(200, "--limit-pairs", min=1, max=500, help="How many events to simulate."),
201
+ outcome: str = typer.Option("day_close_position", "--outcome", help="Outcome of the run saved from filters."),
202
+ start: Optional[str] = typer.Option(None, "--start", help="Start date YYYY-MM-DD (with filters)."),
203
+ end: Optional[str] = typer.Option(None, "--end", help="End date YYYY-MM-DD (with filters)."),
204
+ name: Optional[str] = typer.Option(None, "--name", help="Name of the run saved from filters."),
205
+ wait: bool = typer.Option(False, "--wait", help="Poll until the simulation finishes."),
206
+ timeout: float = typer.Option(600, "--timeout", min=0, help="Seconds --wait polls before giving up."),
207
+ ) -> None:
208
+ """Simulate an intraday entry/exit strategy on a run's events (background job; simulation quota).
209
+ Result: win_rate, profit_factor, avg/total P&L in USD per share, holding time, up to 200 trades."""
210
+ has_filters = bool(filter) or filters_json is not None
211
+ if (run_id is None) == (not has_filters):
212
+ raise CLIError("invalid_request", "Pass exactly one of --run-id or --filter/--filters-json.", exit_code=2)
213
+ strategy = {"entry": _drop_none({"type": entry.value, "within_minutes": within_minutes}),
214
+ "exit": _drop_none({"type": exit.value, "hold_minutes": hold_minutes, "sl_pct": sl, "tp_pct": tp})}
215
+ body: Dict[str, Any] = {"strategy": strategy, "side": side.value, "bar_minutes": bar_minutes,
216
+ "limit_pairs": limit_pairs}
217
+ if run_id is not None:
218
+ body["run_id"] = run_id
219
+ else:
220
+ body.update(_drop_none({"filters": resolve_filters(filter, filters_json), "outcome": outcome,
221
+ "start_date": start, "end_date": end, "name": name}))
222
+ client, _ = build_client()
223
+ _started(client, client.simulate(body), wait, timeout, kind="job")
224
+
225
+
226
+ # ---- jobs -----------------------------------------------------------------------
227
+ @jobs_app.command("get")
228
+ @command
229
+ def jobs_get(job_id: str = typer.Argument(...)) -> None:
230
+ """Status, progress and (when completed) the result of a job. Free."""
231
+ client, _ = build_client()
232
+ output_result(client.job_get(job_id), kind="job")
233
+
234
+
235
+ @jobs_app.command("cancel")
236
+ @command
237
+ def jobs_cancel(job_id: str = typer.Argument(...)) -> None:
238
+ """Stop a queued or running job."""
239
+ client, _ = build_client()
240
+ output_result(client.job_cancel(job_id), kind="job")
@@ -0,0 +1,195 @@
1
+ """filtrix runs / simulate / jobs: paths, bodies, exit codes, --wait polling."""
2
+ import json
3
+
4
+ import pytest
5
+ import respx
6
+ from httpx import Response
7
+ from typer.testing import CliRunner
8
+
9
+ import filtrix_cli.commands.research as research
10
+ from filtrix_cli.__main__ import app
11
+ from filtrix_cli.state import reset_state
12
+
13
+ runner = CliRunner()
14
+ BASE = "https://api.test"
15
+ QUEUED = {"job_id": "job-1", "status": "queued", "poll": "/api/v1/jobs/job-1"}
16
+
17
+
18
+ def setup_function():
19
+ reset_state()
20
+
21
+
22
+ @pytest.fixture(autouse=True)
23
+ def _env(monkeypatch):
24
+ monkeypatch.setenv("FILTRIX_API_KEY", "flt_x")
25
+ monkeypatch.setenv("FILTRIX_BASE_URL", BASE)
26
+
27
+
28
+ @pytest.fixture
29
+ def clock(monkeypatch):
30
+ state = {"now": 0.0, "sleeps": []}
31
+
32
+ def fake_sleep(seconds):
33
+ state["sleeps"].append(seconds)
34
+ state["now"] += seconds
35
+
36
+ monkeypatch.setattr(research, "_sleep", fake_sleep)
37
+ monkeypatch.setattr(research, "_clock", lambda: state["now"])
38
+ return state
39
+
40
+
41
+ def _job(status, **extra):
42
+ return {"id": "job-1", "kind": "simulation", "status": status, "progress": 50, "message": "m",
43
+ "result": None, "error": None, **extra}
44
+
45
+
46
+ def _out(result):
47
+ return json.loads(result.stdout)
48
+
49
+
50
+ @respx.mock
51
+ def test_runs_list_get_rows():
52
+ lst = respx.get(f"{BASE}/api/v1/runs").mock(return_value=Response(200, json={"total": 1, "runs": [{"id": 5}]}))
53
+ one = respx.get(f"{BASE}/api/v1/runs/5").mock(return_value=Response(200, json={"id": 5}))
54
+ rows = respx.get(f"{BASE}/api/v1/runs/5/rows").mock(return_value=Response(200, json={"total": 3, "rows": []}))
55
+
56
+ assert runner.invoke(app, ["runs", "list", "--limit", "5"]).exit_code == 0
57
+ assert _out(runner.invoke(app, ["runs", "get", "5"]))["id"] == 5
58
+ assert runner.invoke(app, ["runs", "rows", "5", "--limit", "50", "--offset", "100"]).exit_code == 0
59
+
60
+ assert dict(lst.calls.last.request.url.params) == {"limit": "5", "offset": "0"}
61
+ assert one.call_count == 1
62
+ assert dict(rows.calls.last.request.url.params) == {"limit": "50", "offset": "100"}
63
+
64
+
65
+ @respx.mock
66
+ def test_runs_save_posts_the_backtest_and_prints_the_job():
67
+ route = respx.post(f"{BASE}/api/v1/runs").mock(return_value=Response(202, json=QUEUED))
68
+
69
+ result = runner.invoke(app, ["runs", "save", "-f", "gap_gup>=10", "--name", "Gappers", "--outcome", "day_return"])
70
+
71
+ assert result.exit_code == 0, result.stdout
72
+ assert _out(result)["job_id"] == "job-1"
73
+ body = json.loads(route.calls.last.request.content)
74
+ assert body["filters"][0]["column"] == "gap_gup" and body["name"] == "Gappers"
75
+ assert body["outcome"] == "day_return" and body["row_filter"] == "all"
76
+
77
+
78
+ @respx.mock
79
+ def test_runs_save_wait_polls_until_done(clock):
80
+ respx.post(f"{BASE}/api/v1/runs").mock(return_value=Response(202, json=QUEUED))
81
+ respx.get(f"{BASE}/api/v1/jobs/job-1").mock(side_effect=[
82
+ Response(200, json=_job("running")), Response(200, json=_job("completed", result={"run_id": 9}))])
83
+
84
+ result = runner.invoke(app, ["runs", "save", "-f", "gap_gup>=10", "--wait"])
85
+
86
+ assert result.exit_code == 0
87
+ assert _out(result)["result"] == {"run_id": 9}
88
+ assert clock["sleeps"] == [2.0]
89
+
90
+
91
+ @respx.mock
92
+ def test_share_unshare_and_delete_needs_yes():
93
+ share = respx.post(f"{BASE}/api/v1/runs/5/share").mock(return_value=Response(200, json={"share_url": "u"}))
94
+ unshare = respx.delete(f"{BASE}/api/v1/runs/5/share").mock(return_value=Response(200, json={}))
95
+ delete = respx.delete(f"{BASE}/api/v1/runs/5").mock(return_value=Response(200, json={"deleted": True}))
96
+
97
+ assert runner.invoke(app, ["runs", "share", "5"]).exit_code == 0
98
+ assert runner.invoke(app, ["runs", "unshare", "5"]).exit_code == 0
99
+ refused = runner.invoke(app, ["runs", "delete", "5"])
100
+ assert refused.exit_code == 2 and delete.call_count == 0
101
+ assert runner.invoke(app, ["runs", "delete", "5", "--yes"]).exit_code == 0
102
+
103
+ assert share.call_count == unshare.call_count == delete.call_count == 1
104
+
105
+
106
+ @respx.mock
107
+ def test_runs_context():
108
+ route = respx.get(f"{BASE}/api/v1/runs/5/trade-context").mock(
109
+ return_value=Response(200, json={"run_id": 5, "daily": [], "intraday": []}))
110
+
111
+ result = runner.invoke(app, ["runs", "context", "5", "aapl", "2025-01-02", "--lookback", "60"])
112
+
113
+ assert result.exit_code == 0
114
+ assert dict(route.calls.last.request.url.params) == {"symbol": "AAPL", "date": "2025-01-02",
115
+ "daily_lookback": "60"}
116
+
117
+
118
+ @respx.mock
119
+ def test_simulate_on_a_run_sends_the_strategy():
120
+ route = respx.post(f"{BASE}/api/v1/simulations").mock(return_value=Response(202, json=QUEUED))
121
+
122
+ result = runner.invoke(app, ["simulate", "--run-id", "5", "--entry", "open_at_0930",
123
+ "--exit", "stop_loss_take_profit", "--sl", "0.02", "--tp", "0.05",
124
+ "--side", "short", "--bar-minutes", "5", "--limit-pairs", "100"])
125
+
126
+ assert result.exit_code == 0, result.stdout
127
+ assert json.loads(route.calls.last.request.content) == {
128
+ "run_id": 5, "side": "short", "bar_minutes": 5, "limit_pairs": 100,
129
+ "strategy": {"entry": {"type": "open_at_0930"},
130
+ "exit": {"type": "stop_loss_take_profit", "sl_pct": 0.02, "tp_pct": 0.05}}}
131
+
132
+
133
+ @respx.mock
134
+ def test_simulate_from_filters_with_wait(clock):
135
+ route = respx.post(f"{BASE}/api/v1/simulations").mock(return_value=Response(202, json=QUEUED))
136
+ respx.get(f"{BASE}/api/v1/jobs/job-1").mock(
137
+ return_value=Response(200, json=_job("completed", result={"summary": {"win_rate": 0.5}})))
138
+
139
+ result = runner.invoke(app, ["simulate", "-f", "gap_gup>=10", "--entry", "green_to_red", "--within-minutes", "30",
140
+ "--exit", "hold_minutes", "--hold-minutes", "60", "--name", "g2r", "--wait"])
141
+
142
+ assert result.exit_code == 0, result.stdout
143
+ assert _out(result)["result"]["summary"] == {"win_rate": 0.5}
144
+ body = json.loads(route.calls.last.request.content)
145
+ assert "run_id" not in body and body["filters"][0]["column"] == "gap_gup" and body["name"] == "g2r"
146
+ assert body["strategy"] == {"entry": {"type": "green_to_red", "within_minutes": 30},
147
+ "exit": {"type": "hold_minutes", "hold_minutes": 60}}
148
+
149
+
150
+ def test_simulate_needs_exactly_one_source():
151
+ neither = runner.invoke(app, ["simulate", "--entry", "open_at_0930", "--exit", "close_1600"])
152
+ both = runner.invoke(app, ["simulate", "--run-id", "5", "-f", "gap_gup>=10",
153
+ "--entry", "open_at_0930", "--exit", "close_1600"])
154
+
155
+ assert neither.exit_code == 2 and both.exit_code == 2
156
+
157
+
158
+ @respx.mock
159
+ def test_wait_on_a_failed_job_exits_1(clock):
160
+ respx.post(f"{BASE}/api/v1/simulations").mock(return_value=Response(202, json=QUEUED))
161
+ respx.get(f"{BASE}/api/v1/jobs/job-1").mock(
162
+ return_value=Response(200, json=_job("failed", error="The simulation failed. Retry later.")))
163
+
164
+ result = runner.invoke(app, ["simulate", "--run-id", "5", "--entry", "open_at_0930", "--exit", "close_1600",
165
+ "--wait"])
166
+
167
+ assert result.exit_code == 1
168
+ assert "The simulation failed" in result.stderr
169
+
170
+
171
+ @respx.mock
172
+ def test_wait_timeout_exits_6_and_names_the_job(clock):
173
+ respx.post(f"{BASE}/api/v1/simulations").mock(return_value=Response(202, json=QUEUED))
174
+ respx.get(f"{BASE}/api/v1/jobs/job-1").mock(return_value=Response(200, json=_job("running")))
175
+
176
+ result = runner.invoke(app, ["simulate", "--run-id", "5", "--entry", "open_at_0930", "--exit", "close_1600",
177
+ "--wait", "--timeout", "10"])
178
+
179
+ assert result.exit_code == 6
180
+ assert "filtrix jobs get job-1" in result.stderr
181
+ assert clock["now"] <= 12
182
+
183
+
184
+ @respx.mock
185
+ def test_jobs_get_and_cancel():
186
+ get = respx.get(f"{BASE}/api/v1/jobs/job-1").mock(return_value=Response(200, json=_job("running")))
187
+ cancel = respx.post(f"{BASE}/api/v1/jobs/job-1/cancel").mock(return_value=Response(200, json={"cancelled": True}))
188
+ gone = respx.post(f"{BASE}/api/v1/jobs/job-2/cancel").mock(
189
+ return_value=Response(409, json={"detail": "The job already finished."}))
190
+
191
+ assert _out(runner.invoke(app, ["jobs", "get", "job-1"]))["status"] == "running"
192
+ assert runner.invoke(app, ["jobs", "cancel", "job-1"]).exit_code == 0
193
+ assert runner.invoke(app, ["jobs", "cancel", "job-2"]).exit_code == 2
194
+
195
+ assert get.call_count == cancel.call_count == gone.call_count == 1
@@ -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.2.0" in result.stdout
11
+ assert "filtrix-cli 0.3.0" in result.stdout
12
12
 
13
13
 
14
14
  def test_no_args_shows_help():
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"
File without changes
File without changes