cjtrade 0.5.0__py3-none-any.whl

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 (196) hide show
  1. cjtrade/README.md +106 -0
  2. cjtrade/__init__.py +9 -0
  3. cjtrade/apps/ArenaX/README.md +215 -0
  4. cjtrade/apps/ArenaX/__init__.py +1 -0
  5. cjtrade/apps/ArenaX/backtest_backend.py +82 -0
  6. cjtrade/apps/ArenaX/base_backend.py +1260 -0
  7. cjtrade/apps/ArenaX/brokerside_server.py +1199 -0
  8. cjtrade/apps/ArenaX/brokerside_server_admin_shell.py +431 -0
  9. cjtrade/apps/ArenaX/configs/backtest.cjsys +63 -0
  10. cjtrade/apps/ArenaX/configs/demo.cjsys +66 -0
  11. cjtrade/apps/ArenaX/configs/paper.cjsys +54 -0
  12. cjtrade/apps/ArenaX/configs/real.cjsys +64 -0
  13. cjtrade/apps/ArenaX/demo_backend.py +83 -0
  14. cjtrade/apps/ArenaX/market_data.py +417 -0
  15. cjtrade/apps/ArenaX/oder_result_helper.py +101 -0
  16. cjtrade/apps/ArenaX/paper_backend.py +200 -0
  17. cjtrade/apps/ArenaX/real_backend.py +287 -0
  18. cjtrade/apps/ArenaX/static/cj.ico +0 -0
  19. cjtrade/apps/ArenaX/time_in_force.py +149 -0
  20. cjtrade/apps/ArenaX/trading_calendar.py +104 -0
  21. cjtrade/apps/CJEdit/README.md +23 -0
  22. cjtrade/apps/CJEdit/__init__.py +0 -0
  23. cjtrade/apps/CJEdit/editor.py +75 -0
  24. cjtrade/apps/CJEdit/main.py +38 -0
  25. cjtrade/apps/CJEdit/pages/index.toml +35 -0
  26. cjtrade/apps/CJEdit/template.py +103 -0
  27. cjtrade/apps/CJNews/README.md +32 -0
  28. cjtrade/apps/CJNews/main.py +85 -0
  29. cjtrade/apps/CJShell/README.md +48 -0
  30. cjtrade/apps/CJShell/cjshell.py +1055 -0
  31. cjtrade/apps/CJShell/cjshell_legacy.py +995 -0
  32. cjtrade/apps/CJTrade/README.md +45 -0
  33. cjtrade/apps/CJTrade/__init__.py +0 -0
  34. cjtrade/apps/CJTrade/bot_a.py +26 -0
  35. cjtrade/apps/CJTrade/bot_b.py +40 -0
  36. cjtrade/apps/CJTrade/bot_c.py +34 -0
  37. cjtrade/apps/CJTrade/bot_custom.py +72 -0
  38. cjtrade/apps/CJTrade/bot_runner.py +505 -0
  39. cjtrade/apps/CJTrade/form.toml +79 -0
  40. cjtrade/apps/CJTrade/main.py +2067 -0
  41. cjtrade/apps/CJTrade/protocol.py +499 -0
  42. cjtrade/apps/CJTrade/status_api.py +574 -0
  43. cjtrade/apps/FinHub/README.md +185 -0
  44. cjtrade/apps/FinHub/__init__.py +0 -0
  45. cjtrade/apps/FinHub/auth.py +72 -0
  46. cjtrade/apps/FinHub/clients/__init__.py +52 -0
  47. cjtrade/apps/FinHub/clients/_segments.py +23 -0
  48. cjtrade/apps/FinHub/clients/arenax_client.py +308 -0
  49. cjtrade/apps/FinHub/clients/engine_client.py +144 -0
  50. cjtrade/apps/FinHub/clients/strategy_tool.py +131 -0
  51. cjtrade/apps/FinHub/clients/supervisor.py +632 -0
  52. cjtrade/apps/FinHub/config.py +79 -0
  53. cjtrade/apps/FinHub/database.py +42 -0
  54. cjtrade/apps/FinHub/main.py +1220 -0
  55. cjtrade/apps/FinHub/models.py +226 -0
  56. cjtrade/apps/FinHub/schemas.py +226 -0
  57. cjtrade/apps/FinHub/static/app.js +1636 -0
  58. cjtrade/apps/FinHub/static/login.js +48 -0
  59. cjtrade/apps/FinHub/static/register.js +53 -0
  60. cjtrade/apps/FinHub/static/style.css +119 -0
  61. cjtrade/apps/FinHub/static/vendor/codemirror.bundle.js +14 -0
  62. cjtrade/apps/FinHub/templates/index.html +590 -0
  63. cjtrade/apps/FinHub/templates/login.html +40 -0
  64. cjtrade/apps/FinHub/templates/register.html +55 -0
  65. cjtrade/apps/README.md +16 -0
  66. cjtrade/apps/insight.py +1613 -0
  67. cjtrade/apps/oneshot_backtest.py +493 -0
  68. cjtrade/apps/preload_prices.py +124 -0
  69. cjtrade/apps/strategy_tool.py +114 -0
  70. cjtrade/pkgs/__init__.py +0 -0
  71. cjtrade/pkgs/analytics/__init__.py +0 -0
  72. cjtrade/pkgs/analytics/backtest/__init__.py +4 -0
  73. cjtrade/pkgs/analytics/backtest/engine.py +347 -0
  74. cjtrade/pkgs/analytics/evaluation/__init__.py +1 -0
  75. cjtrade/pkgs/analytics/evaluation/multi_strategy_report.py +489 -0
  76. cjtrade/pkgs/analytics/evaluation/quantstats.py +485 -0
  77. cjtrade/pkgs/analytics/fundamental/__init__.py +333 -0
  78. cjtrade/pkgs/analytics/fundamental/models/__init__.py +1 -0
  79. cjtrade/pkgs/analytics/fundamental/models/announcement.py +56 -0
  80. cjtrade/pkgs/analytics/fundamental/models/company_info.py +27 -0
  81. cjtrade/pkgs/analytics/fundamental/models/financial_data.py +97 -0
  82. cjtrade/pkgs/analytics/fundamental/providers/__init__.py +1 -0
  83. cjtrade/pkgs/analytics/fundamental/providers/twse.py +690 -0
  84. cjtrade/pkgs/analytics/fundamental/utils/__init__.py +1 -0
  85. cjtrade/pkgs/analytics/fundamental/utils/parser.py +342 -0
  86. cjtrade/pkgs/analytics/informational/__init__.py +0 -0
  87. cjtrade/pkgs/analytics/informational/news_client.py +78 -0
  88. cjtrade/pkgs/analytics/informational/news_providers/__init__.py +14 -0
  89. cjtrade/pkgs/analytics/informational/news_providers/_base.py +47 -0
  90. cjtrade/pkgs/analytics/informational/news_providers/cnyes.py +317 -0
  91. cjtrade/pkgs/analytics/informational/news_providers/mock.py +94 -0
  92. cjtrade/pkgs/analytics/informational/news_providers/news_api.py +121 -0
  93. cjtrade/pkgs/analytics/informational/news_providers/statement_dog.py +33 -0
  94. cjtrade/pkgs/analytics/informational/sentiment_analysis.py +37 -0
  95. cjtrade/pkgs/analytics/technical/__init__.py +28 -0
  96. cjtrade/pkgs/analytics/technical/models/__init__.py +3 -0
  97. cjtrade/pkgs/analytics/technical/models/market_state.py +23 -0
  98. cjtrade/pkgs/analytics/technical/models/signal.py +21 -0
  99. cjtrade/pkgs/analytics/technical/strategies/fixed_price.py +46 -0
  100. cjtrade/pkgs/analytics/technical/talib_wrapper.py +56 -0
  101. cjtrade/pkgs/brokers/README.md +222 -0
  102. cjtrade/pkgs/brokers/__init__.py +0 -0
  103. cjtrade/pkgs/brokers/account_client.py +554 -0
  104. cjtrade/pkgs/brokers/arenax/__init__.py +0 -0
  105. cjtrade/pkgs/brokers/arenax/arenax_broker_api.py +660 -0
  106. cjtrade/pkgs/brokers/arenax/arenax_middleware.py +729 -0
  107. cjtrade/pkgs/brokers/base_broker_api.py +350 -0
  108. cjtrade/pkgs/brokers/sinopac/__init__.py +10 -0
  109. cjtrade/pkgs/brokers/sinopac/_internal_func.py +565 -0
  110. cjtrade/pkgs/brokers/sinopac/sinopac_broker_api.py +1209 -0
  111. cjtrade/pkgs/chart/__init__.py +13 -0
  112. cjtrade/pkgs/chart/_chart_base.py +60 -0
  113. cjtrade/pkgs/chart/_plotly.py +563 -0
  114. cjtrade/pkgs/chart/kbar_client.py +206 -0
  115. cjtrade/pkgs/chart/models/__init__.py +5 -0
  116. cjtrade/pkgs/chart/models/kbar_data.py +66 -0
  117. cjtrade/pkgs/chart/templates/chart_template.html +195 -0
  118. cjtrade/pkgs/config/__init__.py +0 -0
  119. cjtrade/pkgs/config/config_loader.py +212 -0
  120. cjtrade/pkgs/db/db_api.py +615 -0
  121. cjtrade/pkgs/db/db_base.py +58 -0
  122. cjtrade/pkgs/db/duckdb.py +57 -0
  123. cjtrade/pkgs/db/sql/create_arenax_local_price_db.sql +51 -0
  124. cjtrade/pkgs/db/sql/create_cj_order_map.sql +9 -0
  125. cjtrade/pkgs/db/sql/create_fill_ledger.sql +40 -0
  126. cjtrade/pkgs/db/sql/create_order_ledger.sql +36 -0
  127. cjtrade/pkgs/db/sqlcmd.py +58 -0
  128. cjtrade/pkgs/db/sqlite.py +77 -0
  129. cjtrade/pkgs/llm/__init__.py +0 -0
  130. cjtrade/pkgs/llm/_llm_base.py +34 -0
  131. cjtrade/pkgs/llm/azure_openai.py +76 -0
  132. cjtrade/pkgs/llm/chatpdf.py +77 -0
  133. cjtrade/pkgs/llm/gemini.py +54 -0
  134. cjtrade/pkgs/llm/llm_pool.py +80 -0
  135. cjtrade/pkgs/llm/mock_llm.py +34 -0
  136. cjtrade/pkgs/logger.py +200 -0
  137. cjtrade/pkgs/marketdata/__init__.py +36 -0
  138. cjtrade/pkgs/marketdata/aggregate.py +137 -0
  139. cjtrade/pkgs/marketdata/arenax.py +65 -0
  140. cjtrade/pkgs/marketdata/base.py +312 -0
  141. cjtrade/pkgs/marketdata/cache.py +116 -0
  142. cjtrade/pkgs/marketdata/compose.py +184 -0
  143. cjtrade/pkgs/marketdata/factory.py +90 -0
  144. cjtrade/pkgs/marketdata/finmind.py +195 -0
  145. cjtrade/pkgs/marketdata/offline.py +35 -0
  146. cjtrade/pkgs/marketdata/sinopac.py +85 -0
  147. cjtrade/pkgs/marketdata/yfinance.py +123 -0
  148. cjtrade/pkgs/models/__init__.py +7 -0
  149. cjtrade/pkgs/models/backtest.py +332 -0
  150. cjtrade/pkgs/models/cost.py +184 -0
  151. cjtrade/pkgs/models/event.py +349 -0
  152. cjtrade/pkgs/models/kbar.py +79 -0
  153. cjtrade/pkgs/models/order.py +174 -0
  154. cjtrade/pkgs/models/position.py +45 -0
  155. cjtrade/pkgs/models/product.py +75 -0
  156. cjtrade/pkgs/models/quote.py +196 -0
  157. cjtrade/pkgs/models/rank_type.py +10 -0
  158. cjtrade/pkgs/models/tick.py +37 -0
  159. cjtrade/pkgs/models/trade.py +59 -0
  160. cjtrade/pkgs/paths.py +242 -0
  161. cjtrade/pkgs/risk/__init__.py +5 -0
  162. cjtrade/pkgs/risk/pre_trade.py +249 -0
  163. cjtrade/pkgs/strategy/__init__.py +7 -0
  164. cjtrade/pkgs/strategy/adx.py +480 -0
  165. cjtrade/pkgs/strategy/authoring.py +802 -0
  166. cjtrade/pkgs/strategy/base_strategy.py +287 -0
  167. cjtrade/pkgs/strategy/baseline_0050.py +158 -0
  168. cjtrade/pkgs/strategy/bb.py +264 -0
  169. cjtrade/pkgs/strategy/dca.py +292 -0
  170. cjtrade/pkgs/strategy/donchian.py +271 -0
  171. cjtrade/pkgs/strategy/parameters/__init__.py +36 -0
  172. cjtrade/pkgs/strategy/parameters/config.py +96 -0
  173. cjtrade/pkgs/strategy/parameters/manager.py +279 -0
  174. cjtrade/pkgs/strategy/parameters/presets.py +178 -0
  175. cjtrade/pkgs/strategy/parameters/schema.py +286 -0
  176. cjtrade/pkgs/strategy/snr.py +236 -0
  177. cjtrade/pkgs/strategy/user_strategy.py +1015 -0
  178. cjtrade/pkgs/ui/__init__.py +15 -0
  179. cjtrade/pkgs/ui/__main__.py +36 -0
  180. cjtrade/pkgs/ui/base_renderer.py +40 -0
  181. cjtrade/pkgs/ui/engine.py +338 -0
  182. cjtrade/pkgs/ui/renderers/__init__.py +0 -0
  183. cjtrade/pkgs/ui/renderers/cli.py +349 -0
  184. cjtrade/pkgs/ui/renderers/web.py +388 -0
  185. cjtrade/pkgs/ui/renderers/zenity.py +233 -0
  186. cjtrade/pkgs/ui/schema.py +252 -0
  187. cjtrade/pkgs/ui/user_state.py +88 -0
  188. cjtrade/pkgs/utils/date.py +211 -0
  189. cjtrade/pkgs/utils/extras.py +37 -0
  190. cjtrade/pkgs/utils/ncal.py +128 -0
  191. cjtrade/py.typed +0 -0
  192. cjtrade-0.5.0.dist-info/METADATA +304 -0
  193. cjtrade-0.5.0.dist-info/RECORD +196 -0
  194. cjtrade-0.5.0.dist-info/WHEEL +4 -0
  195. cjtrade-0.5.0.dist-info/entry_points.txt +11 -0
  196. cjtrade-0.5.0.dist-info/licenses/LICENSE +21 -0
cjtrade/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # Source code in `apps`
2
+
3
+ See [here](./apps/README.md)
4
+
5
+ # Source code in `pkgs`
6
+
7
+ `pkgs` is the SDK. Nothing in here knows about an app, so anything an app does
8
+ twice belongs below.
9
+
10
+ ## `analytics/`
11
+
12
+ Commonly-used analytics methods, grouped by the kind of question they answer.
13
+
14
+ - **Fundamental (基本面)**: EPS, PB ratio, PE ratio, dividends, company info and
15
+ TWSE announcements.
16
+ - **Technical (技術面)**: SMA, MACD, RSI and the rest, as a thin wrapper over
17
+ TA-Lib.
18
+ - **Informational (消息面)**: news scraped from Cnyes (鉅亨網), StatementDog and
19
+ NewsAPI, with an LLM doing the sentiment analysis.
20
+ - **Backtest and evaluation**: the bar-by-bar backtest engine, and the
21
+ quantstats tearsheets and multi-strategy comparison reports built from its
22
+ results.
23
+
24
+ ## `brokers/`
25
+
26
+ **Integration with each broker's API** — Sinopac (永豐金證券), Cathay
27
+ (國泰證券), ArenaX (the built-in simulator) — behind one interface, so an app
28
+ written once can be pointed at a different broker without being rewritten.
29
+
30
+ See [here](./pkgs/brokers/README.md) for more info.
31
+
32
+ ## `chart/`
33
+
34
+ Drawing, rendering and saving K-bar (K線) charts.
35
+
36
+ ## `config/`
37
+
38
+ Reads the `*.cjconf` files that `scripts/gen_config.sh` generates — broker
39
+ credentials, LLM keys and other per-user settings — from the current directory
40
+ first and the user config directory after. One rule governs the whole search:
41
+ the first source to set a key wins, so an environment variable you exported
42
+ cannot be displaced by a file.
43
+
44
+ ## `db/`
45
+
46
+ Database core operations. SQLite (and a DuckDB backend alongside it) behind one
47
+ small API, plus the schemas under `sql/` for the price cache and the local
48
+ order and fill ledgers, so callers do not write SQL by hand.
49
+
50
+ ## `legacy/`
51
+
52
+ Don't touch it.
53
+
54
+ ## `llm/`
55
+
56
+ A unified interface to different LLM services, with a pool in front so a
57
+ failing backend falls through to the next one. Available backends: Gemini,
58
+ Azure OpenAI, and a mock for tests.
59
+
60
+ ## `models/`
61
+
62
+ Common data types for the whole project, for example
63
+
64
+ - `Position` (倉位)
65
+ - `Order` (訂單) and `OrderResult`
66
+ - `Product` (金融商品)
67
+ - `Quote` / `Snapshot` (報價)
68
+ - `Kbar` (K線)
69
+ - `Trade` (成交)
70
+
71
+ and more. If two packages need to agree on the shape of something, the shape
72
+ lives here.
73
+
74
+ ## `risk/`
75
+
76
+ Pre-trade checks (`pre_trade.py`): the questions that must be answered before
77
+ an order is allowed out, separate from whichever strategy asked for it.
78
+
79
+ ## `strategy/`
80
+
81
+ The strategies themselves (Bollinger Bands, Donchian breakout, support and
82
+ resistance, ADX regime switching, DCA, and a buy-and-hold baseline), the
83
+ `BaseStrategy` contract they implement, and the per-interval parameter presets.
84
+
85
+ `authoring.py` is the module a hand-written strategy imports. It is the whole
86
+ vocabulary such a file may use and it reaches no broker session: `buy()` there
87
+ returns an *intent*, and something above the strategy decides whether to place
88
+ it.
89
+
90
+ ## `ui/`
91
+
92
+ Renders a form from a TOML description, to the CLI, a browser or Zenity, and
93
+ remembers the answers between runs. This is what lets `poc/backtest.sh` be both
94
+ interactive and scriptable — a field whose flag is on the command line is never
95
+ prompted for.
96
+
97
+ ## `utils/`
98
+
99
+ Small shared helpers: date arithmetic, and a cross-platform `ncal` for printing
100
+ a month in the terminal.
101
+
102
+ ## `paths.py`
103
+
104
+ Where this machine keeps its data: price cache, reports, state, logs and
105
+ config. Call it instead of hardcoding a path, and honour `CJTRADE_HOME` for
106
+ free.
cjtrade/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """CJTrade: a Taiwan-stock trading framework with a simulated broker."""
2
+ from importlib.metadata import PackageNotFoundError
3
+ from importlib.metadata import version as _version
4
+
5
+ try:
6
+ # One source for the version: pyproject.toml, as installed.
7
+ __version__ = _version("cjtrade")
8
+ except PackageNotFoundError: # imported from a source tree, not installed
9
+ __version__ = "0+unknown"
@@ -0,0 +1,215 @@
1
+ # ArenaX (試煉場 券商模擬器)
2
+
3
+ ![](img/arenax.png)
4
+
5
+ ## Introduction
6
+
7
+ ArenaX is a simulated broker written for CJTrade.
8
+ It is a complete trading environment that behaves the way a real broker does, so
9
+ a client application cannot tell it apart from a paper trading service — the
10
+ same `AccountClient` code talks to both.
11
+
12
+ ArenaX provides:
13
+
14
+ - **Market data**
15
+ Prices come from any `MarketData` source (Sinopac, FinMind, yfinance, or one
16
+ you write), and are cached locally so a repeated run does not refetch them.
17
+
18
+ - **Price data playback**
19
+ Time in the virtual market is under your control. You set where the timeline
20
+ begins, how fast it advances, and you can pause it or step it yourself.
21
+
22
+ - **Order submission and matching**
23
+ Orders are matched against the incoming market data, with commission, 證交稅
24
+ and slippage applied, and with each order's time-in-force (ROD / IOC / FOK /
25
+ GTC) deciding when it expires.
26
+
27
+ - **Portfolio management**
28
+ Accounts, positions, balance and trade history are all tracked inside the
29
+ simulation, and a run can be resumed from a saved account snapshot.
30
+
31
+ Together this lets you test strategies and client applications without
32
+ connecting to a real broker or risking real money.
33
+
34
+ ## Modes
35
+
36
+ > :memo: Most of the **data** in this doc refers to **price data**.
37
+
38
+ There are 3 modes in ArenaX, categorised by their price data source and use
39
+ case. Each one ships its own `configs/<mode>.cjsys` and listens on its own port,
40
+ so two modes can run side by side without fighting over one.
41
+
42
+ | Mode | Default price sources | Default port | Typical Use Case |
43
+ | ---- | --------------------- | ------------ | ---------------- |
44
+ | `demo` (default) | `yfinance` | 8801 | Lightweight simulation **WITHOUT** needing a broker account |
45
+ | `backtest` | `sinopac,yfinance` | 8802 | Historical market replay for backtesting |
46
+ | `paper` | `sinopac` | 8803 | Paper trading with real-time market data |
47
+
48
+ <!-- cjcheck: static -->
49
+ ```sh
50
+ uv run arenaxd --backend=backtest # or demo / paper / real
51
+ ```
52
+
53
+ `--data` (or `AX_DATA_SOURCES`) chooses the price sources, tried in order:
54
+ `sinopac`, `finmind`, `yfinance`, `cache`, `offline`. Sinopac is logged in to only when a
55
+ source or the backend needs it, so a backtest can run with no broker account:
56
+
57
+ <!-- cjcheck: static -->
58
+ ```sh
59
+ uv run arenaxd --backend=backtest --data=finmind,yfinance
60
+ ```
61
+
62
+ FinMind reads `FINMIND_TOKEN` from your `.cjconf` and serves daily bars on a
63
+ free account; a 1m replay still needs a source of 1m bars for its window
64
+ (yfinance keeps only the last 30 days). From Python, pass any `MarketData` as
65
+ `ArenaX_BrokerSideServer(market_data=...)`.
66
+
67
+ Every source sits behind a price cache file. `--price-db` (or
68
+ `AX_PRICE_DB_PATH`) chooses the file; the default is the shared cache in the
69
+ platform cache directory. To run with no network at all, preload a file and
70
+ start with `--data=offline`, which serves only what the file holds:
71
+
72
+ <!-- cjcheck: static -->
73
+ ```sh
74
+ uv run preload-prices --price-db exp.db --symbols 2330,2317 --start 2026-10-26
75
+ CJTRADE_OFFLINE=1 uv run arenaxd --backend=demo --data=offline --price-db=exp.db
76
+ ```
77
+
78
+ `GET /api/v1/market/<symbol>/kbars` returns only bars that have closed on the
79
+ simulated clock. `start` and `end` take whole dates (`end` inclusive) or ISO
80
+ datetimes (a half-open window).
81
+
82
+ :warning: `arenaxd` reads `AX_*` environment variables before its config file,
83
+ and `load_dotenv(override=False)` means whatever is already exported wins. A
84
+ stale `AX_HOST_PORT` from an earlier session will therefore silently keep the
85
+ backtest backend on the demo port. `unset AX_HOST_PORT AX_HOST_ADDRESS
86
+ AX_STATE_FILE` before switching modes.
87
+
88
+ Starting the server and starting the simulated backend are two steps. The
89
+ process comes up first and then logs in and preloads price data, which takes
90
+ somewhere between a few seconds and a minute depending on the window. Until
91
+ that finishes, `/health` answers `"running": false` — poll it rather than
92
+ guessing with `sleep`.
93
+
94
+ ## Test with the server admin shell
95
+
96
+ ### Start the server first!
97
+
98
+ <!-- cjcheck: static -->
99
+ ```sh
100
+ uv run arenaxd
101
+ ```
102
+
103
+ ![server](./img/server.png)
104
+
105
+ ### Then open the admin shell
106
+
107
+ <!-- cjcheck: static -->
108
+ ```sh
109
+ uv run aresh # stands for "ARE"nax "SH"ell
110
+ ```
111
+
112
+ ![admin-shell](./img/admin_shell.png)
113
+
114
+ ## RESTful API
115
+
116
+ Everything below assumes the default demo port. Change `8801` to match your
117
+ mode.
118
+
119
+ ### Server and backend
120
+
121
+ 1. Check health — also the readiness probe:
122
+ <!-- cjcheck: static -->
123
+ ```sh
124
+ curl http://127.0.0.1:8801/health
125
+ ```
126
+
127
+ 2. Start the simulated backend:
128
+ <!-- cjcheck: static -->
129
+ ```sh
130
+ curl -X PUT -H "Content-Type: application/json" \
131
+ -d '{"running": true}' http://127.0.0.1:8801/api/v1/backend
132
+ ```
133
+
134
+ 3. Stop it again (the server process stays up):
135
+ <!-- cjcheck: static -->
136
+ ```sh
137
+ curl -X PUT -H "Content-Type: application/json" \
138
+ -d '{"running": false}' http://127.0.0.1:8801/api/v1/backend
139
+ ```
140
+
141
+ 4. Read the configuration the server and the backend are actually running with:
142
+ <!-- cjcheck: static -->
143
+ ```sh
144
+ curl http://127.0.0.1:8801/api/v1/config
145
+ ```
146
+
147
+ > `server_config` is the broker-side server's own config — listening address and
148
+ > port. `backend_config` is the core logic it runs: playback speed, backtest
149
+ > duration, cost model.
150
+
151
+ ### Clock
152
+
153
+ 5. Read the current market time:
154
+ <!-- cjcheck: static -->
155
+ ```sh
156
+ curl http://127.0.0.1:8801/api/v1/clock
157
+ ```
158
+
159
+ 6. Set where the timeline BEGINS. This is not "jump to this moment": it snaps to
160
+ 09:00, and unless told otherwise it also starts the clock and refetches the data
161
+ cache.
162
+ <!-- cjcheck: static -->
163
+ ```sh
164
+ curl -X PUT -H "Content-Type: application/json" \
165
+ -d '{"mock_init_time": "2026-03-20T00:00:00"}' \
166
+ http://127.0.0.1:8801/api/v1/clock/origin
167
+ ```
168
+
169
+ 7. List the bar timestamps a replay will step through. This is how a replay
170
+ driver (the trading engine's `ReplayClock`) finds its timeline: the kbars
171
+ route only returns bars the clock has already reached, while this returns
172
+ timestamps for the whole window, with no prices.
173
+
174
+ <!-- cjcheck: static -->
175
+ ```sh
176
+ curl "http://127.0.0.1:8801/api/v1/clock/timeline?symbols=2330,2317&start=2026-03-02&end=2026-03-07"
177
+ ```
178
+
179
+ ### Trading
180
+
181
+ A client opens a session first (`POST /api/v1/session`), and then uses:
182
+
183
+ | Route | Purpose |
184
+ | ----- | ------- |
185
+ | `GET /api/v1/account` | Balance and positions |
186
+ | `GET /api/v1/account/fills` | Fill history, filterable by session |
187
+ | `GET /api/v1/orders` | Everything resting or resolved |
188
+ | `POST /api/v1/orders` | Place one order |
189
+ | `GET /api/v1/orders/<id>` | One order's status |
190
+ | `DELETE /api/v1/orders/<id>` | Cancel it |
191
+ | `GET /api/v1/market/<symbol>/snapshot` | A quote: price, bid/ask, the day's range so far |
192
+ | `GET /api/v1/market/<symbol>/kbars` | Closed K-bars over a date range, up to the simulated clock |
193
+ | `GET /api/v1/market/data-availability` | Which symbols and windows are actually on disk |
194
+
195
+ The full interactive spec is served by the process itself — open
196
+ `http://127.0.0.1:8801/docs` while it is running.
197
+
198
+ ### Useful test scripts
199
+
200
+ 1. Watch how fast time progresses inside the ArenaX virtual environment:
201
+ <!-- cjcheck: static -->
202
+ ```sh
203
+ watch -n 3 -d --color "curl -s http://127.0.0.1:8801/api/v1/clock | jq ."
204
+ ```
205
+
206
+ 2. Print the backend and server config as it changes:
207
+ <!-- cjcheck: static -->
208
+ ```sh
209
+ watch -n 3 -d --color "curl -s http://127.0.0.1:8801/api/v1/config | jq ."
210
+ ```
211
+
212
+ ## Development
213
+
214
+ ### Current architecture
215
+ ![architecture](./img/arch.png)
@@ -0,0 +1 @@
1
+ """ArenaX application package."""
@@ -0,0 +1,82 @@
1
+ import random
2
+ from datetime import datetime
3
+ from datetime import timedelta
4
+ from time import sleep
5
+ from typing import Optional
6
+
7
+ from cjtrade.apps.ArenaX.base_backend import ArenaX_BackendBase
8
+ from cjtrade.apps.ArenaX.market_data import ArenaX_Market
9
+ from cjtrade.pkgs.brokers.account_client import AccountClient
10
+ from cjtrade.pkgs.logger import get_logger
11
+ from cjtrade.pkgs.logger import kv
12
+
13
+ log = get_logger("ArenaX.backend.backtest")
14
+
15
+
16
+ class ArenaX_Backend_Historical(ArenaX_BackendBase):
17
+ def __init__(
18
+ self,
19
+ state_file: Optional[str] = None, # snapshot to resume from; None = fresh
20
+ real_account: Optional[AccountClient] = None,
21
+ playback_speed: float = 1.0,
22
+ num_days_preload: int = 3,
23
+ skip_data_preload: bool = False,
24
+ backtest_start_date=None, # datetime | None; None → random
25
+ **kwargs
26
+ ) -> None:
27
+ super().__init__(
28
+ state_file=state_file,
29
+ real_account=real_account,
30
+ playback_speed=playback_speed,
31
+ num_days_preload=num_days_preload,
32
+ skip_data_preload=skip_data_preload,
33
+ **kwargs
34
+ )
35
+ self._backtest_start_date = backtest_start_date
36
+ self.market = ArenaX_Market(market_data=self.market_data, data=self.data)
37
+ if hasattr(self.market, "set_playback_speed"):
38
+ self.market.set_playback_speed(playback_speed)
39
+ self._initialize_market_time()
40
+
41
+ def _initialize_market_time(self) -> None:
42
+ if not self.market_data.supports("1m"):
43
+ raise ValueError(
44
+ f"the historical backend replays 1m bars, and {self.market_data.name} "
45
+ f"does not serve them; choose a source that does (e.g. sinopac, yfinance)")
46
+
47
+ # ── Fixed start_date path ─────────────────────────────────────
48
+ if self._backtest_start_date is not None:
49
+ start_dt = self._backtest_start_date
50
+ # Skip weekends
51
+ while start_dt.weekday() >= 5:
52
+ start_dt += timedelta(days=1)
53
+ start_dt = start_dt.replace(hour=9, minute=0, second=0, microsecond=0)
54
+ self.market.set_historical_time_abs(
55
+ real_init_time=datetime.now(),
56
+ mock_init_time=start_dt,
57
+ )
58
+ log.info("fixed start_date: %s", start_dt.date())
59
+ log.info("market time: %s", kv(self.market.get_market_time()))
60
+ # self.market.pause_time_progress()
61
+ # log.info("market time paused, waiting for client resume")
62
+ return
63
+
64
+ # ── Random start_date path ────────────────────────────────────
65
+ attempt, max_attempts = 0, 30
66
+ days_back = random.randint(self.num_days_preload, 1300)
67
+ dt = datetime.now() - timedelta(days=days_back)
68
+ sleep(1)
69
+
70
+ while not self.market.fetching_available(dt) and attempt < max_attempts:
71
+ sleep(0.5)
72
+ attempt += 1
73
+ days_back = random.randint(self.num_days_preload, 1300)
74
+ dt = datetime.now() - timedelta(days=days_back)
75
+
76
+ if attempt >= max_attempts:
77
+ log.error("no fetchable history found in %d attempts, try again", max_attempts)
78
+ return
79
+ self.market.set_historical_time(datetime.now(), days_back=days_back)
80
+ log.info("market time: %s", kv(self.market.get_market_time()))
81
+ # self.market.pause_time_progress()
82
+ # log.info("market time paused, waiting for client resume")