@dsh-ft/dsh-fft-paper-trading 0.7.2 → 0.8.0

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 (199) hide show
  1. package/README.md +4 -3
  2. package/README.zh.md +4 -3
  3. package/lib/agent/account-tools.d.ts +18 -0
  4. package/lib/agent/account-tools.d.ts.map +1 -0
  5. package/lib/agent/account-tools.js +127 -0
  6. package/lib/agent/account-tools.js.map +1 -0
  7. package/lib/agent/futures-tools.d.ts.map +1 -1
  8. package/lib/agent/futures-tools.js +1 -6
  9. package/lib/agent/futures-tools.js.map +1 -1
  10. package/lib/agent/ledger-tools.d.ts +15 -3
  11. package/lib/agent/ledger-tools.d.ts.map +1 -1
  12. package/lib/agent/ledger-tools.js +11 -15
  13. package/lib/agent/ledger-tools.js.map +1 -1
  14. package/lib/agent/tool-result.d.ts +19 -0
  15. package/lib/agent/tool-result.d.ts.map +1 -0
  16. package/lib/agent/tool-result.js +22 -0
  17. package/lib/agent/tool-result.js.map +1 -0
  18. package/lib/agent/tools.d.ts +10 -2
  19. package/lib/agent/tools.d.ts.map +1 -1
  20. package/lib/agent/tools.js +26 -11
  21. package/lib/agent/tools.js.map +1 -1
  22. package/lib/client.js +1448 -282
  23. package/lib/contract/accounts.d.ts +76 -0
  24. package/lib/contract/accounts.d.ts.map +1 -0
  25. package/lib/contract/accounts.js +6 -0
  26. package/lib/contract/accounts.js.map +1 -0
  27. package/lib/contract/common.d.ts +144 -0
  28. package/lib/contract/common.d.ts.map +1 -0
  29. package/lib/contract/common.js +33 -0
  30. package/lib/contract/common.js.map +1 -0
  31. package/lib/contract/domain.d.ts +196 -0
  32. package/lib/contract/domain.d.ts.map +1 -0
  33. package/lib/contract/domain.js +14 -0
  34. package/lib/contract/domain.js.map +1 -0
  35. package/lib/contract/errors.d.ts +6 -0
  36. package/lib/contract/errors.d.ts.map +1 -0
  37. package/lib/contract/errors.js +6 -0
  38. package/lib/contract/errors.js.map +1 -0
  39. package/lib/contract/index.d.ts +15 -0
  40. package/lib/contract/index.d.ts.map +1 -0
  41. package/lib/contract/index.js +15 -0
  42. package/lib/contract/index.js.map +1 -0
  43. package/lib/contract/ledger.d.ts +40 -0
  44. package/lib/contract/ledger.d.ts.map +1 -0
  45. package/lib/contract/ledger.js +6 -0
  46. package/lib/contract/ledger.js.map +1 -0
  47. package/lib/contract/market.d.ts +30 -0
  48. package/lib/contract/market.d.ts.map +1 -0
  49. package/lib/contract/market.js +6 -0
  50. package/lib/contract/market.js.map +1 -0
  51. package/lib/contract/rpc.d.ts +24 -0
  52. package/lib/contract/rpc.d.ts.map +1 -0
  53. package/lib/contract/rpc.js +6 -0
  54. package/lib/contract/rpc.js.map +1 -0
  55. package/lib/contract.d.ts +6 -403
  56. package/lib/contract.d.ts.map +1 -1
  57. package/lib/contract.js +6 -24
  58. package/lib/contract.js.map +1 -1
  59. package/lib/core/session.d.ts +1 -1
  60. package/lib/core/session.d.ts.map +1 -1
  61. package/lib/core/session.js +1 -2
  62. package/lib/core/session.js.map +1 -1
  63. package/lib/data/cached-market-data.d.ts +61 -0
  64. package/lib/data/cached-market-data.d.ts.map +1 -0
  65. package/lib/data/cached-market-data.js +174 -0
  66. package/lib/data/cached-market-data.js.map +1 -0
  67. package/lib/data/futures-market-data.d.ts.map +1 -1
  68. package/lib/data/futures-market-data.js +9 -10
  69. package/lib/data/futures-market-data.js.map +1 -1
  70. package/lib/index.d.ts +25 -1
  71. package/lib/index.d.ts.map +1 -1
  72. package/lib/index.js +156 -18
  73. package/lib/index.js.map +1 -1
  74. package/lib/service/account-moves.d.ts +64 -0
  75. package/lib/service/account-moves.d.ts.map +1 -0
  76. package/lib/service/account-moves.js +49 -0
  77. package/lib/service/account-moves.js.map +1 -0
  78. package/lib/service/accounts-rpc.d.ts +17 -0
  79. package/lib/service/accounts-rpc.d.ts.map +1 -0
  80. package/lib/service/accounts-rpc.js +77 -0
  81. package/lib/service/accounts-rpc.js.map +1 -0
  82. package/lib/service/compare-rpc.d.ts +22 -0
  83. package/lib/service/compare-rpc.d.ts.map +1 -0
  84. package/lib/service/compare-rpc.js +70 -0
  85. package/lib/service/compare-rpc.js.map +1 -0
  86. package/lib/service/errors.d.ts +20 -4
  87. package/lib/service/errors.d.ts.map +1 -1
  88. package/lib/service/errors.js +12 -5
  89. package/lib/service/errors.js.map +1 -1
  90. package/lib/service/futures-rpc.d.ts.map +1 -1
  91. package/lib/service/futures-rpc.js +7 -25
  92. package/lib/service/futures-rpc.js.map +1 -1
  93. package/lib/service/futures-service.d.ts +28 -8
  94. package/lib/service/futures-service.d.ts.map +1 -1
  95. package/lib/service/futures-service.js +144 -146
  96. package/lib/service/futures-service.js.map +1 -1
  97. package/lib/service/ledger-admin.d.ts +67 -0
  98. package/lib/service/ledger-admin.d.ts.map +1 -0
  99. package/lib/service/ledger-admin.js +102 -0
  100. package/lib/service/ledger-admin.js.map +1 -0
  101. package/lib/service/paper-service.d.ts +39 -12
  102. package/lib/service/paper-service.d.ts.map +1 -1
  103. package/lib/service/paper-service.js +177 -156
  104. package/lib/service/paper-service.js.map +1 -1
  105. package/lib/service/route.d.ts.map +1 -1
  106. package/lib/service/route.js +5 -2
  107. package/lib/service/route.js.map +1 -1
  108. package/lib/service/rpc-support.d.ts +34 -0
  109. package/lib/service/rpc-support.d.ts.map +1 -0
  110. package/lib/service/rpc-support.js +57 -0
  111. package/lib/service/rpc-support.js.map +1 -0
  112. package/lib/service/rpc.d.ts +20 -3
  113. package/lib/service/rpc.d.ts.map +1 -1
  114. package/lib/service/rpc.js +44 -25
  115. package/lib/service/rpc.js.map +1 -1
  116. package/lib/store/accounts.d.ts +110 -0
  117. package/lib/store/accounts.d.ts.map +1 -0
  118. package/lib/store/accounts.js +352 -0
  119. package/lib/store/accounts.js.map +1 -0
  120. package/lib/store/atomic-file.d.ts +16 -0
  121. package/lib/store/atomic-file.d.ts.map +1 -0
  122. package/lib/store/atomic-file.js +34 -0
  123. package/lib/store/atomic-file.js.map +1 -0
  124. package/lib/store/futures-repo.d.ts +8 -49
  125. package/lib/store/futures-repo.d.ts.map +1 -1
  126. package/lib/store/futures-repo.js +34 -246
  127. package/lib/store/futures-repo.js.map +1 -1
  128. package/lib/store/ledger-repo-base.d.ts +120 -0
  129. package/lib/store/ledger-repo-base.d.ts.map +1 -0
  130. package/lib/store/ledger-repo-base.js +275 -0
  131. package/lib/store/ledger-repo-base.js.map +1 -0
  132. package/lib/store/notes.d.ts +29 -0
  133. package/lib/store/notes.d.ts.map +1 -0
  134. package/lib/store/notes.js +78 -0
  135. package/lib/store/notes.js.map +1 -0
  136. package/lib/store/paths.d.ts +2 -0
  137. package/lib/store/paths.d.ts.map +1 -1
  138. package/lib/store/paths.js +4 -0
  139. package/lib/store/paths.js.map +1 -1
  140. package/lib/store/repo.d.ts +15 -55
  141. package/lib/store/repo.d.ts.map +1 -1
  142. package/lib/store/repo.js +41 -206
  143. package/lib/store/repo.js.map +1 -1
  144. package/lib/store/shortlist.d.ts.map +1 -1
  145. package/lib/store/shortlist.js +4 -6
  146. package/lib/store/shortlist.js.map +1 -1
  147. package/lib/store/snapshots.d.ts +0 -3
  148. package/lib/store/snapshots.d.ts.map +1 -1
  149. package/lib/store/snapshots.js +0 -3
  150. package/lib/store/snapshots.js.map +1 -1
  151. package/package.json +1 -1
  152. package/src/agent/account-tools.ts +136 -0
  153. package/src/agent/futures-tools.ts +1 -6
  154. package/src/agent/ledger-tools.ts +29 -16
  155. package/src/agent/tool-result.ts +27 -0
  156. package/src/agent/tools.ts +30 -10
  157. package/src/client/entry.js +14 -0
  158. package/src/client/parts/10-core.js +535 -0
  159. package/src/client/parts/20-styles.js +336 -0
  160. package/src/client/parts/30-atoms.js +769 -0
  161. package/src/client/parts/35-hooks.js +447 -0
  162. package/src/client/parts/40-stock-tabs.js +641 -0
  163. package/src/client/parts/50-futures.js +911 -0
  164. package/src/client/parts/60-shell.js +706 -0
  165. package/src/client/parts/70-plugin.js +67 -0
  166. package/src/contract/accounts.ts +82 -0
  167. package/src/contract/common.ts +173 -0
  168. package/src/contract/domain.ts +217 -0
  169. package/src/contract/errors.ts +34 -0
  170. package/src/contract/index.ts +15 -0
  171. package/src/contract/ledger.ts +42 -0
  172. package/src/contract/market.ts +39 -0
  173. package/src/contract/rpc.ts +15 -0
  174. package/src/contract.ts +6 -472
  175. package/src/core/session.ts +1 -2
  176. package/src/data/cached-market-data.ts +193 -0
  177. package/src/data/futures-market-data.ts +9 -10
  178. package/src/index.ts +168 -20
  179. package/src/service/account-moves.ts +72 -0
  180. package/src/service/accounts-rpc.ts +80 -0
  181. package/src/service/compare-rpc.ts +77 -0
  182. package/src/service/errors.ts +23 -4
  183. package/src/service/futures-rpc.ts +7 -24
  184. package/src/service/futures-service.ts +161 -159
  185. package/src/service/ledger-admin.ts +140 -0
  186. package/src/service/paper-service.ts +183 -153
  187. package/src/service/route.ts +5 -2
  188. package/src/service/rpc-support.ts +61 -0
  189. package/src/service/rpc.ts +59 -23
  190. package/src/store/accounts.ts +373 -0
  191. package/src/store/atomic-file.ts +37 -0
  192. package/src/store/futures-repo.ts +35 -260
  193. package/src/store/ledger-repo-base.ts +337 -0
  194. package/src/store/notes.ts +86 -0
  195. package/src/store/paths.ts +5 -0
  196. package/src/store/repo.ts +47 -229
  197. package/src/store/shortlist.ts +3 -5
  198. package/src/store/snapshots.ts +0 -3
  199. package/src/client/index.js +0 -3275
@@ -1,3275 +0,0 @@
1
- window.__ModuleLoader__.load({
2
- id: '@dsh-ft/dsh-fft-paper-trading',
3
- factory: (require) => {
4
- var module = { exports: {} }
5
- var exports = module.exports
6
- const React = require('react')
7
- const { useCallback, useEffect, useMemo, useRef, useState } = React
8
- const h = React.createElement
9
-
10
- const ROUTE = '/api/ft-paper-trading'
11
- /** Release number stamped into the Feedback link title at build time. */
12
- const PAPER_VERSION = '__PAPER_VERSION__'
13
- /** Public repository; the panel links out and collects nothing itself. */
14
- const ISSUE_NEW = 'https://github.com/gigaflw/dsh-fft-paper-trading/issues/new'
15
- /**
16
- * Feedback opens the Bug form with the release already in the title: a
17
- * report without a version costs triage a round trip. GitHub honours only
18
- * `title`/`labels` on a form URL — a `body` param is ignored (and a blank
19
- * issue can 400 on repos that disable it) — so the body stays user-written.
20
- */
21
- const FEEDBACK_URL = `${ISSUE_NEW}?template=bug_report.yml&title=${encodeURIComponent(`[Bug] v${PAPER_VERSION} `)}`
22
- const PERIODS = [
23
- ['7d', '7 天'],
24
- ['30d', '30 天'],
25
- ['all', '全部'],
26
- ]
27
- // The futures account has no market page and no K-line: search lives inside
28
- // the ticket, so the wallet pages match the stock ones one for one.
29
- const FUTURES_TABS = ['trade', 'positions', 'orders', 'review']
30
- const FUTURES_TAB_LABEL = { trade: '交易', positions: '持仓', orders: '订单', review: '复盘' }
31
-
32
- /* ---------------------------------------------------------------- text --
33
- Pure formatting and vocabularies. Times are always zh-CN /
34
- Asia/Shanghai; numbers that are not finite render as `—` instead of a
35
- blank or `NaN`, and backend codes never leak into the main copy. */
36
-
37
- const TZ = 'Asia/Shanghai'
38
- // sv-SE formats as YYYY-MM-DD, which matches the trade-date column and the
39
- // header; zh-CN would print 2026/10/22 slashes instead.
40
- const dateTimeFormat = new Intl.DateTimeFormat('sv-SE', {
41
- timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit',
42
- hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
43
- })
44
- const timeFormat = new Intl.DateTimeFormat('zh-CN', {
45
- timeZone: TZ, hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
46
- })
47
-
48
- const isFiniteNumber = value => typeof value === 'number' && Number.isFinite(value)
49
- // Amounts read as money: group thousands and always show two decimals.
50
- const amountFormat = new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
51
- const money = value => isFiniteNumber(value) ? amountFormat.format(value) : '—'
52
- const cents = value => isFiniteNumber(value) ? amountFormat.format(value / 100) : '—'
53
- const pct = value => isFiniteNumber(value) ? `${(value * 100).toFixed(2)}%` : '—'
54
- const signed = value => {
55
- if (!isFiniteNumber(value)) return '—'
56
- // Zero is neither a gain nor a loss: no misleading "+0.00".
57
- return `${value > 0 ? '+' : ''}${amountFormat.format(value)}`
58
- }
59
- const tone = value => !isFiniteNumber(value) ? '' : value > 0 ? 'pt-up' : value < 0 ? 'pt-down' : ''
60
- const count = value => isFiniteNumber(value) ? String(Math.round(value)) : '—'
61
- const toDate = value => {
62
- if (value === undefined || value === null || value === '') return null
63
- const time = Date.parse(value)
64
- return Number.isNaN(time) ? null : new Date(time)
65
- }
66
- const dateTime = value => {
67
- const date = toDate(value)
68
- return date === null ? '—' : dateTimeFormat.format(date)
69
- }
70
- const clockTime = value => {
71
- const date = toDate(value)
72
- return date === null ? '—' : timeFormat.format(date)
73
- }
74
- const dateFormat = new Intl.DateTimeFormat('sv-SE', {
75
- timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit',
76
- })
77
- const shanghaiToday = () => dateFormat.format(new Date())
78
- /** After the close the ledger rolls to the next trading day; say so. */
79
- const tradeDateText = (value, estimated = false) => {
80
- if (!value) return '—'
81
- return value > shanghaiToday()
82
- ? `下一交易日${estimated ? '(按工作日估算)' : ''} ${value}`
83
- : value
84
- }
85
- /**
86
- * Trading-day source note for the header subtitle. Only rendered while the
87
- * weekday fallback is in use, so the normal state stays quiet.
88
- */
89
- const calendarNote = calendar => {
90
- if (calendar === null || calendar === undefined || calendar.source !== 'fallback') return null
91
- const detail = calendar.reason === undefined ? '' : `(${calendar.reason})`
92
- return h('span', {
93
- className: 'pt-note',
94
- title: `交易日历降级:按周一至周五估算,节假日会被当作交易日,影响 T+1 可卖、挂单过期、期货结算与下一交易日${detail}`,
95
- }, ' · 交易日历降级(按工作日估算)')
96
- }
97
- /** Canonical ids arrive from the host; the raw input keeps whatever was typed. */
98
- const halfWidthDigits = value => String(value ?? '')
99
- .replace(/[0-9]/g, character => String.fromCharCode(character.charCodeAt(0) - 0xFEE0))
100
- .replace(/[A-Z]/g, character => String.fromCharCode(character.charCodeAt(0) - 0xFEE0))
101
- // dsh_kline hands over its own suffixes (`600519.XSHG`, `000001.XSHE`); the
102
- // ticket shows the canonical `.SH` / `.SZ` form and the host accepts both.
103
- const HOST_EXCHANGES = { XSHG: 'SH', XSHE: 'SZ', BJSE: 'BJ' }
104
- const foldHostSymbol = value => {
105
- const text = halfWidthDigits(value).toUpperCase().trim()
106
- const suffix = /^(\d{6})\.([A-Z]{2,4})$/.exec(text)
107
- if (suffix === null) return text
108
- const exchange = HOST_EXCHANGES[suffix[2]]
109
- return exchange === undefined ? text : `${suffix[1]}.${exchange}`
110
- }
111
- // The ticket accepts `600519`, `600519.SH`, `600519.XSHG` and `SH600519`;
112
- // the host folds them into one canonical id, so the panel keeps letters.
113
- const symbolInput = value => {
114
- const text = foldHostSymbol(value).replace(/[^0-9A-Z.]/g, '').slice(0, 12)
115
- const prefix = /^(SH|SZ|BJ)(\d{6})$/.exec(text)
116
- return prefix === null ? text : `${prefix[2]}.${prefix[1]}`
117
- }
118
- const budgetInput = value => halfWidthDigits(value).replace(/[,,\s]/g, '')
119
- const symbolText = quote => [quote?.symbol, quote?.name].filter(text => text).join(' ')
120
- /**
121
- * Quote origin in human terms; the raw interface name is too technical.
122
- * A daily-bar quote is the free-tier fallback (last close), never a live
123
- * tick, so the label has to say which one it is.
124
- */
125
- const quoteSourceText = quote => {
126
- if (!quote || !quote.source) return 'FTShare'
127
- if (quote.source === 'manual') return '参考价'
128
- // Provenance, not tier: a keyed account can also end up on the daily close.
129
- if (quote.source === 'daily-bar') return '日K收盘'
130
- return 'FTShare 实时'
131
- }
132
- /**
133
- * Quote line time. Same-day data shows the clock only; a daily-close quote
134
- * (free tier) or any older timestamp carries its date, so yesterday's
135
- * close cannot read as today's live price.
136
- */
137
- const quoteUpdateText = quote => {
138
- if (!quote) return ''
139
- if (quote.source === 'manual') return '手动价'
140
- const ts = quote.marketTs
141
- if (ts === undefined || ts === null) return '更新 —'
142
- const date = dateFormat.format(new Date(ts))
143
- return date === shanghaiToday() ? `更新 ${clockTime(ts)}` : `更新 ${date.slice(5)} ${clockTime(ts)}`
144
- }
145
- /**
146
- * How often the open ticket should re-price itself. A live quote deserves
147
- * the 5 s beat; a daily-bar (free tier) or missing one does not, and on the
148
- * anonymous quota the 5 s re-preview alone would spend the day's budget.
149
- */
150
- const ticketRefreshInterval = quote =>
151
- quote === null || quote === undefined || quote.source === 'daily-bar' ? 300_000 : 5_000
152
- /**
153
- * Header badge copy for the four data-source states. The badge answers
154
- * "is an FTShare key configured" without ever showing the key itself; the
155
- * title carries the consequence (realtime vs daily-close pricing).
156
- */
157
- const DATA_SOURCE_STATE = {
158
- configured: { text: '数据源正常', title: 'FTShare API Key 已配置,可看实时行情' },
159
- free: {
160
- text: '免费数据源',
161
- title: '未配置 FTShare Key:免费档报价取日K收盘,可手填参考价交易',
162
- },
163
- none: { text: '无数据源', title: '未安装 FTShare 数据服务,行情不可用;可手填参考价交易' },
164
- invalid: { text: '数据源无效', title: 'FTShare Key 无法使用;请在「设置」中检查,可手填参考价交易' },
165
- }
166
- /** Badge suffix per recorded failure, so the header cannot read 正常 while quotes fail. */
167
- const DATA_PROBLEM_STATE = {
168
- 'no-key': '未配置 Key',
169
- 'invalid-key': 'Key 无效',
170
- 'plan-denied': '套餐未开通',
171
- quota: '额度用尽',
172
- network: '上游超时',
173
- upstream: '上游异常',
174
- }
175
- /**
176
- * Where a missing or rejected key gets fixed.
177
- *
178
- * The banner does not link out: the settings section already carries the
179
- * signup link in its 访问凭据 card, and the host exposes no client API that
180
- * opens settings from here, so the copy names the section instead of sending
181
- * the user to a second, differently-worded URL.
182
- */
183
- const KEY_SETTINGS = '设置 → 金融终端'
184
- /** One reason per stored value, so a new problem shows again after a dismissal. */
185
- const DATA_BANNER_DISMISS_KEY = 'paper-trading:data-banner-dismissed'
186
-
187
- /**
188
- * Model for the data banner.
189
- *
190
- * Order matters: a missing service beats any recorded failure (nothing can
191
- * work), a spent quota beats the plain "no key" hint (it explains why行情
192
- * stopped), and a runtime key rejection beats the configured badge.
193
- */
194
- function bannerModel(status) {
195
- if (status === null || status === undefined) return null
196
- if (status.state === 'none') {
197
- return {
198
- id: 'no-service', tone: 'info',
199
- title: '行情数据服务未安装',
200
- detail: '现在只能用参考价交易;安装 FTShare 数据服务后自动恢复。',
201
- actions: [],
202
- }
203
- }
204
- const noKeyBanner = {
205
- id: 'no-key', tone: 'info',
206
- // Quotes still work on the free tier (last daily close), so the banner
207
- // cannot say 行情未启用; what a key adds is the realtime feed.
208
- title: '免费档:报价取日K收盘',
209
- detail: `在 ${KEY_SETTINGS} 填入 API Key 可看实时行情。`,
210
- actions: [],
211
- }
212
- const problem = status.problem
213
- if (problem !== undefined && problem !== null) {
214
- switch (problem.reason) {
215
- case 'quota':
216
- return {
217
- id: 'quota', tone: 'warn',
218
- // 匿名档是「最近 24 小时 500 次」的滚动额度,不是一个自然日。
219
- title: '免费额度已用尽',
220
- detail: `请在 ${KEY_SETTINGS} 获取并填入 API Key;或等约 24 小时额度恢复。`,
221
- actions: ['retry'],
222
- }
223
- case 'plan-denied':
224
- // Without a key the realtime interface is simply not enabled; a
225
- // "套餐未开通" banner would send a keyless user to the wrong fix.
226
- return status.state === 'free'
227
- ? noKeyBanner
228
- : {
229
- id: 'plan-denied', tone: 'warn',
230
- title: '当前套餐未开通实时行情',
231
- detail: '可用日K收盘价模拟;套餐开通后刷新即可。',
232
- actions: ['retry'],
233
- }
234
- case 'invalid-key':
235
- // The anonymous channel also answers 401 for paid interfaces, so a
236
- // keyless user must see the "configure a key" hint, not "key bad".
237
- return status.state === 'free'
238
- ? noKeyBanner
239
- : {
240
- id: 'invalid-key', tone: 'error',
241
- title: 'FTShare 数据源无法使用',
242
- detail: `在 ${KEY_SETTINGS} 检查 API Key。`,
243
- actions: ['retry'],
244
- }
245
- case 'network':
246
- return {
247
- id: 'network', tone: 'warn',
248
- title: '行情服务暂时不可用',
249
- detail: '网络或上游超时,稍后重试;账本不受影响。',
250
- actions: ['retry'],
251
- }
252
- default:
253
- return {
254
- id: 'upstream', tone: 'warn',
255
- title: '行情服务上游异常',
256
- // 手填参考价只覆盖市价单(期货仅市价平仓),先说清最确定的一件事。
257
- detail: '稍后重试;账本不受影响。',
258
- actions: ['retry'],
259
- }
260
- }
261
- }
262
- if (status.state === 'invalid') {
263
- return {
264
- id: 'invalid-key', tone: 'error',
265
- title: 'FTShare 数据源无法使用',
266
- detail: `${status.message === undefined || status.message === '' ? 'Key 未通过验证' : status.message}。在 ${KEY_SETTINGS} 检查 API Key。`,
267
- actions: [],
268
- }
269
- }
270
- if (status.state === 'free') return noKeyBanner
271
- return null
272
- }
273
-
274
- function readBannerDismissal() {
275
- try {
276
- return window.localStorage.getItem(DATA_BANNER_DISMISS_KEY) ?? ''
277
- } catch {
278
- return ''
279
- }
280
- }
281
- /** Both sides are canonical ids (`000001.SZ`), so compare them verbatim. */
282
- const shortlisted = (shortlist, symbol) => shortlist.some(item => item === symbol)
283
-
284
- /**
285
- * Why the ticket cannot be previewed yet. An incomplete draft would
286
- * otherwise come back priced at 0.00 — a card that looks like a real
287
- * order for nothing — so the panel asks for the missing field instead.
288
- */
289
- const previewBlockReason = draft => {
290
- if (String(draft.symbol ?? '').trim().length < 6) return '输入代码后自动计算'
291
- const qty = Number(draft.qty)
292
- if (!Number.isInteger(qty) || qty <= 0) return '填写数量后自动计算'
293
- if (draft.type === 'limit' && !(Number(draft.limitPrice) > 0)) return '填写限价后自动计算'
294
- return ''
295
- }
296
-
297
- const STATUS_TEXT = {
298
- queued: '待开盘',
299
- pending: '挂单',
300
- partially_filled: '部分成交',
301
- filled: '成交',
302
- canceled: '已撤',
303
- rejected: '拒绝',
304
- expired: '过期',
305
- }
306
- /** Why the ticket is limited outside continuous trading. */
307
- const sessionNote = session => {
308
- if (!session || session.canMatch) return ''
309
- if (session.phase === 'auction_close') return '(收盘竞价暂不支持下单)'
310
- if (session.phase === 'pre_open') return '(集合竞价,09:30 开盘撮合)'
311
- if (session.phase === 'lunch') return '(午休,13:00 开盘撮合)'
312
- return '(盘后委托顺延至下一交易时段开盘)'
313
- }
314
- const PHASE_TEXT = {
315
- pre_open: '集合竞价',
316
- continuous_am: '上午连续竞价',
317
- lunch: '午休',
318
- continuous_pm: '下午连续竞价',
319
- auction_close: '收盘竞价',
320
- closed: '已收盘',
321
- }
322
- const CASH_TYPE_TEXT = {
323
- open: '初始资金',
324
- reset: '重置',
325
- deposit: '注资',
326
- withdraw: '提款',
327
- buy: '买入',
328
- sell: '卖出',
329
- fee: '费用',
330
- }
331
- const FUTURES_CASH_TYPE_TEXT = {
332
- open: '初始资金',
333
- deposit: '注资',
334
- withdraw: '提款',
335
- open_position: '开仓占用',
336
- close_position: '平仓释放',
337
- }
338
- const CANCEL_REASON_TEXT = {
339
- user: '手动撤单',
340
- expired: '当日有效期满',
341
- insufficient_cash: '资金不足',
342
- insufficient_position: '可卖不足',
343
- margin_unavailable: '可用资金不足',
344
- insufficient_margin: '保证金不足',
345
- risk: '强制平仓',
346
- expiry: '到期平仓',
347
- }
348
- /** Basket row states; the raw codes never reach the table. */
349
- const BASKET_STATUS_TEXT = {
350
- ok: '可买',
351
- zero_lot: '不足 1 手',
352
- no_quote: '无行情',
353
- suspended: '停牌',
354
- }
355
- const FUTURES_PHASE_TEXT = {
356
- pre_open: '待开盘',
357
- trading: '交易中',
358
- lunch: '休市',
359
- closed: '已收盘',
360
- }
361
- const FUTURES_STATUS_TEXT = {
362
- pending: '挂单',
363
- filled: '成交',
364
- canceled: '已撤',
365
- rejected: '拒绝',
366
- expired: '过期',
367
- }
368
- /** Position direction; orders use the open/close form below. */
369
- const FUTURES_SIDE_TEXT = { long: '多', short: '空' }
370
- const FUTURES_DIRECTION_TEXT = {
371
- long_open: '开多',
372
- short_open: '开空',
373
- long_close: '平多',
374
- short_close: '平空',
375
- }
376
- const directionText = (side, offset) => FUTURES_DIRECTION_TEXT[`${side}_${offset}`] ?? '—'
377
- const orderTypeText = type => type === 'limit' ? '限价' : '市价'
378
- const ERROR_TEXT = {
379
- ACCOUNT_BLOCKED: '账户已锁定:可让 AI 助手从备份恢复,或重置/导出账本',
380
- INVALID_ARGUMENT: '参数不合法',
381
- INVALID_SYMBOL: '证券代码不合法',
382
- INVALID_QTY: '数量不合法',
383
- INVALID_LOT: '买入数量必须是 100 股的整数倍',
384
- INSUFFICIENT_CASH: '可用资金不足',
385
- INSUFFICIENT_POSITION: '持仓不足',
386
- T1_LOCKED: '当日买入的股份不可卖出(T+1)',
387
- MAX_NOTIONAL: '超过单笔金额上限',
388
- ORDER_NOT_FOUND: '订单不存在',
389
- ORDER_NOT_PENDING: '订单不是挂单状态',
390
- QUOTE_UNAVAILABLE: '没有可用行情',
391
- SESSION_CLOSED: '当前时段不接受委托',
392
- AUCTION_ONLY: '当前时段不接受市价单',
393
- PRICE_LIMIT: '价格超出涨跌停范围',
394
- SUSPENDED: '标的停牌',
395
- UNSUPPORTED_INSTRUMENT: '该标的不支持交易',
396
- INSUFFICIENT_MARGIN: '保证金不足',
397
- CONTRACT_NOT_FOUND: '合约不存在',
398
- CONTRACT_EXPIRED: '合约临近交割或已到期',
399
- NO_VOLUME: '当日无成交',
400
- LIMIT_UNAVAILABLE: '暂无涨跌停数据',
401
- MARGIN_UNAVAILABLE: '暂无保证金率数据',
402
- INTERNAL: '内部错误',
403
- }
404
- const CODE_PREFIX = /^([A-Z_]+):\s*(.*)$/
405
- /** `T1_LOCKED: 可卖数量不足(可卖 0 股)` → the Chinese detail only. */
406
- const reasonText = (reason, scope = 'stock') => {
407
- if (!reason) return ''
408
- const matched = CODE_PREFIX.exec(reason)
409
- if (matched) return matched[2] || ERROR_TEXT[matched[1]] || reason
410
- if (reason === 'insufficient_position') return scope === 'futures' ? '可平不足' : '可卖不足'
411
- return CANCEL_REASON_TEXT[reason] ?? reason
412
- }
413
- // The host message is already a readable Chinese sentence and carries
414
- // the specifics ("最多 20 只,本次 21 只"); the code label is only a fallback.
415
- const errorText = (code, message) => (typeof message === 'string' && message.trim() !== '')
416
- ? message
417
- : (ERROR_TEXT[code] ?? '操作失败')
418
- const errorOf = cause => ({
419
- text: cause && cause.message ? cause.message : '操作失败',
420
- detail: cause && cause.detail ? cause.detail : '',
421
- })
422
-
423
- async function rpc(endpoint, payload) {
424
- const response = await fetch(ROUTE, {
425
- method: 'POST',
426
- headers: { 'content-type': 'application/json' },
427
- body: JSON.stringify({ endpoint, payload: payload ?? {} }),
428
- })
429
- let body = null
430
- try {
431
- body = await response.json()
432
- } catch {
433
- body = null
434
- }
435
- if (!response.ok || body === null || body.ok !== true) {
436
- const failureBody = body && body.error ? body.error : { code: 'INTERNAL', message: `HTTP ${response.status}` }
437
- const failure = new Error(errorText(failureBody.code, failureBody.message))
438
- failure.code = failureBody.code
439
- failure.detail = `${failureBody.code}: ${failureBody.message}`
440
- throw failure
441
- }
442
- return body.value
443
- }
444
-
445
- const CSS = `
446
- /* Accent comes from the shared FT brand layer; the local aliases keep the
447
- fallback in one place, so the panel still matches when fft-settings is
448
- absent. The brand layer publishes a value per palette. */
449
- .pt-root { --pt-accent:var(--ft-accent-warm,light-dark(#cf5623, #ff8352));
450
- --pt-accent-hover:var(--ft-accent-warm-hover,light-dark(#b8481b, #ff9a72));
451
- --pt-accent-ink:var(--ft-accent-warm-ink,light-dark(#ffffff, #1a120e));
452
- --pt-accent-soft:var(--ft-accent-warm-soft,light-dark(#fbeee8, #2b1d16));
453
- /* The page surface and its content use the whole centre column; the
454
- K-line rail takes a fixed share on wide screens instead of a
455
- centred reader column. */
456
- flex:1 1 auto; min-width:0; min-height:0; height:100%; box-sizing:border-box;
457
- overflow:auto; scrollbar-gutter:stable; width:100%; align-self:stretch;
458
- background:var(--dsw-alias-bg-base, #ffffff); color:var(--dsw-alias-label-primary, #171b22);
459
- font-size:var(--dsh-content-font-size-secondary, 13px); line-height:1.5; container:paper-panel / inline-size; }
460
- .pt-inner { display:flex; flex-direction:column; gap:10px; box-sizing:border-box;
461
- width:100%; margin:0 auto;
462
- padding:calc(28px + var(--dsh-frame-top-clearance, 0px)) clamp(16px, 2.2vw, 40px) 24px; }
463
- .pt-head { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; flex-wrap:wrap;
464
- padding-bottom:8px; border-bottom:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.12)); }
465
- .pt-title { font-size:16px; font-weight:500; letter-spacing:-.01em; margin:0; }
466
- .pt-sub { color:var(--dsw-alias-label-secondary, #49525f); font-size:12px; margin-top:2px; }
467
- /* The badge has no padding of its own and inherits the 1.5 line-height,
468
- while a button keeps the UA's smaller normal line-height; bottom
469
- alignment would lift the badge text away from the button labels. Sit on
470
- the row's centre line instead, the same one the padded buttons use. */
471
- .pt-source { display:inline-flex; align-items:center; gap:5px; font-size:12px;
472
- align-self:center; color:var(--dsw-alias-label-secondary, #49525f); white-space:nowrap; }
473
- .pt-source-dot { width:7px; height:7px; border-radius:50%;
474
- background:var(--dsw-alias-label-tertiary, #8b93a1); }
475
- .pt-source[data-state="configured"] .pt-source-dot { background:var(--dsw-alias-state-success-primary, #2f6b47); }
476
- .pt-source[data-state="free"] .pt-source-dot { background:var(--dsw-alias-state-warn-primary, #8a6410); }
477
- .pt-source[data-state="invalid"] .pt-source-dot { background:var(--dsw-alias-state-error-primary, #a33b2a); }
478
- .pt-data-banner { display:flex; gap:10px; justify-content:space-between; align-items:flex-start;
479
- padding:8px 10px; border-radius:var(--dsw-radius-sm, 8px);
480
- border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.14));
481
- border-left:3px solid var(--dsw-alias-label-tertiary, #8b93a1);
482
- background:var(--dsw-alias-bg-layer-2, #f7f8fa); }
483
- .pt-data-banner[data-tone="warn"] { border-left-color:var(--dsw-alias-state-warn-primary, #8a6410); }
484
- .pt-data-banner[data-tone="error"] { border-left-color:var(--dsw-alias-state-error-primary, #a33b2a); }
485
- .pt-data-banner-title { font-size:12px; font-weight:500; }
486
- .pt-data-banner-actions { display:flex; gap:6px; flex:0 0 auto; }
487
- .pt-stats { display:flex; border:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.12));
488
- border-radius:var(--dsw-radius-sm, 8px); background:var(--dsw-alias-bg-layer-2, #f7f8fa); overflow:hidden; }
489
- .pt-stat { flex:1 1 0; min-width:0; padding:7px 10px;
490
- border-right:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.10)); }
491
- .pt-stat:last-child { border-right:0; }
492
- .pt-stat-label { font-size:11px; letter-spacing:.04em; color:var(--dsw-alias-label-secondary, #49525f); }
493
- .pt-stat-value { font-size:16px; font-weight:500; margin-top:1px; font-variant-numeric:tabular-nums;
494
- font-family:"SF Mono", "JetBrains Mono", Menlo, monospace; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
495
- .pt-cash { display:flex; flex-direction:column; gap:8px; padding:8px 10px;
496
- border:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.12));
497
- border-radius:var(--dsw-radius-sm, 8px); background:var(--dsw-alias-bg-layer-2, #f7f8fa); }
498
- .pt-cash .pt-row { align-items:center; }
499
- .pt-up { color:var(--dsw-alias-state-error-primary, #b23b2e); }
500
- .pt-down { color:var(--dsw-alias-state-success-primary, #2f6b47); }
501
- .pt-tabs { display:flex; gap:4px; border:0; padding:0; margin-top:1px; }
502
- .pt-tab { border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.14));
503
- background:var(--dsw-alias-bg-base, #fff); padding:4px 10px; cursor:pointer;
504
- color:var(--dsw-alias-label-secondary, #49525f); border-radius:var(--dsw-radius-xs, 4px);
505
- font-size:12px; font-family:inherit; }
506
- .pt-tab:hover { background:var(--dsw-alias-interactive-bg-hover, #eef1f5); }
507
- .pt-tab[data-active="true"] { color:var(--dsw-alias-label-primary, #171b22);
508
- border-color:var(--pt-accent);
509
- background:var(--pt-accent-soft); font-weight:500; }
510
- .pt-btn { border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.18));
511
- background:var(--dsw-alias-bg-layer-1, #fff); color:inherit; border-radius:var(--dsw-radius-xs, 4px);
512
- padding:5px 9px; cursor:pointer; font-size:12px; font-family:inherit; }
513
- .pt-btn:hover { border-color:var(--pt-accent);
514
- background:var(--dsw-alias-interactive-bg-hover, #eef1f5); }
515
- .pt-btn[data-active="true"] { border-color:var(--pt-accent); background:var(--pt-accent-soft);
516
- color:var(--dsw-alias-label-primary, #171b22); font-weight:500; }
517
- .pt-btn[disabled] { opacity:.5; cursor:default; }
518
- .pt-btn-primary { background:var(--pt-accent);
519
- border-color:var(--pt-accent);
520
- color:var(--pt-accent-ink); font-weight:500; }
521
- .pt-btn-primary:hover { background:var(--pt-accent-hover); border-color:var(--pt-accent-hover); }
522
- .pt-btn-danger { color:var(--dsw-alias-state-error-primary, #a33b2a); }
523
- /* The only anchor styled as a button: a secondary utility, never an
524
- action, so it sits last in the header row. A normal line-height matches
525
- the UA default on button, keeping the two the same height. */
526
- .pt-feedback { text-decoration:none; display:inline-flex; align-items:center; line-height:normal; }
527
- .pt-row { display:flex; gap:8px; flex-wrap:wrap; align-items:flex-end; }
528
- .pt-field { display:flex; flex-direction:column; gap:3px; min-width:0; }
529
- .pt-field span { font-size:11px; color:var(--dsw-alias-label-secondary, #49525f); }
530
- .pt-input { width:100%; min-width:0; box-sizing:border-box; padding:5px 7px; font-size:12px;
531
- border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.18)); border-radius:var(--dsw-radius-xs, 4px);
532
- background:var(--dsw-alias-bg-base, #fff); color:inherit; font-family:inherit; }
533
- .pt-seg { display:flex; box-sizing:border-box; border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.18));
534
- border-radius:var(--dsw-radius-xs, 4px); overflow:hidden; }
535
- .pt-seg button { border:0; background:none; padding:5px 9px; cursor:pointer; font-size:12px;
536
- color:inherit; font-family:inherit; }
537
- /* A selection is state, not action: the active segment takes the soft
538
- accent tint plus a thin accent edge, so the only solid orange left on a
539
- page is the submit button. Same language as .pt-tab / .pt-btn. */
540
- .pt-seg button[data-active="true"] { background:var(--pt-accent-soft);
541
- color:var(--dsw-alias-label-primary, #171b22); font-weight:500;
542
- box-shadow:inset 0 0 0 1px var(--pt-accent); }
543
- .pt-quote { display:flex; gap:12px; flex-wrap:wrap; padding:7px 9px; border-radius:var(--dsw-radius-sm, 8px);
544
- background:var(--dsw-alias-bg-layer-2, #f7f8fa); font-variant-numeric:tabular-nums;
545
- border:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.08)); }
546
- .pt-preview { display:flex; flex-direction:column; gap:1px; }
547
- .pt-preview div { display:flex; justify-content:space-between; gap:12px; padding:2px 0; }
548
- .pt-preview .pt-warn { color:var(--dsw-alias-state-warn-primary, #8a6410); display:block; }
549
- .pt-receipt { margin-top:8px; padding:7px 9px; font-size:12px; border-radius:var(--dsw-radius-xs, 4px);
550
- border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.16));
551
- background:var(--dsw-alias-bg-layer-2, #f7f8fa); font-variant-numeric:tabular-nums; }
552
- .pt-receipt[data-state="filled"] { border-color:var(--dsw-alias-state-success-primary, #2f6b47); }
553
- .pt-receipt[data-state="rejected"] { color:var(--dsw-alias-state-error-primary, #a33b2a);
554
- border-color:var(--dsw-alias-state-error-primary, #a33b2a); }
555
- .pt-card { border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.12));
556
- border-radius:var(--dsw-radius-sm, 8px); background:var(--dsw-alias-bg-layer-1, #fff); padding:10px; min-width:0; }
557
- .pt-card-title { font-size:11px; font-weight:500; letter-spacing:.04em;
558
- color:var(--dsw-alias-label-secondary, #49525f); margin-bottom:8px; }
559
- /* Main workspace: the K-line rail sets the row height, so the left column
560
- stretches to the same bottom edge instead of ending mid-air. */
561
- .pt-workspace { display:grid; grid-template-columns:minmax(0, 1fr) clamp(380px, 38%, 760px);
562
- gap:10px; align-items:stretch; min-width:0; }
563
- .pt-main { display:flex; flex-direction:column; gap:10px; min-width:0; min-height:0;
564
- container:paper-main / inline-size; }
565
- .pt-tab-body { display:flex; flex-direction:column; gap:10px; flex:1 1 auto; min-height:0; }
566
- .pt-kline-rail { position:sticky; top:calc(12px + var(--dsh-frame-top-clearance, 0px)); align-self:start; min-width:0; }
567
- .pt-kline-card { display:flex; flex-direction:column; min-width:0; }
568
- .pt-kline-head { display:flex; align-items:flex-start; justify-content:space-between; gap:8px; flex-wrap:wrap; margin-bottom:8px; }
569
- .pt-kline-title { min-width:0; }
570
- .pt-kline-body { height:clamp(420px, calc(100vh - 250px), 720px); min-height:0; overflow:hidden;
571
- border:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.08)); border-radius:var(--dsw-radius-sm, 8px);
572
- background:var(--dsw-alias-bg-layer-2, #f7f8fa); }
573
- .pt-kline-slot, .pt-kline-body > div { width:100%; height:100%; min-height:0; }
574
- .pt-kline-body .pt-chart { height:100%; }
575
- .pt-kline-hint { margin-top:6px; font-size:11px; }
576
- /* Trade ticket: one form grid keeps every field and control on the same
577
- columns; the fee preview sits in the same card, not in a loose sibling. */
578
- .pt-trade { display:flex; flex-direction:column; gap:10px; flex:1 1 auto; min-height:0; }
579
- .pt-ticket-card { display:flex; flex-direction:column; gap:12px; flex:0 0 auto; }
580
- .pt-ticket { display:grid; grid-template-columns:minmax(0, 1fr) minmax(230px, 300px); gap:18px; align-items:start; }
581
- .pt-ticket-form { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr));
582
- gap:10px 12px; align-items:start; min-width:0; }
583
- .pt-span-2 { grid-column:1 / -1; }
584
- /* Direction and quantity read as one row of two halves at every
585
- breakpoint, so they never split into rows of their own. */
586
- .pt-field-pair { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr));
587
- gap:10px 12px; }
588
- .pt-field .pt-seg { width:100%; }
589
- .pt-field .pt-seg button { flex:1 1 0; }
590
- .pt-ticket-form .pt-input { height:30px; }
591
- .pt-preview-pane { min-width:0; border-left:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.10));
592
- padding-left:18px; }
593
- .pt-ticket-foot { display:flex; flex-direction:column; gap:8px;
594
- border-top:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.10)); padding-top:10px; }
595
- .pt-ticket-submit { width:100%; justify-content:center; padding:8px 12px; font-size:13px; }
596
- .pt-ticket-meta { display:flex; justify-content:space-between; gap:8px; flex-wrap:wrap; }
597
- /* Always-present book under the ticket: holdings or pending orders, so the
598
- left column always closes at the K-line's bottom edge. */
599
- .pt-trade-book { display:flex; flex-direction:column; gap:8px; flex:1 1 auto; min-height:150px; }
600
- .pt-book-head { display:flex; align-items:center; justify-content:space-between; gap:8px; flex-wrap:wrap; }
601
- .pt-book-scroll { flex:1 1 auto; min-height:0; overflow:auto; }
602
- .pt-book-empty { display:flex; align-items:center; justify-content:center; min-height:84px; }
603
- .pt-table-wrap { overflow-x:auto; min-width:0; }
604
- .pt-note-cell { display:inline-block; max-width:180px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; vertical-align:bottom; }
605
- .pt-table { width:100%; border-collapse:collapse; font-size:12px; min-width:0; }
606
- .pt-table th { text-align:left; font-weight:500; color:var(--dsw-alias-label-secondary, #49525f);
607
- font-size:11px; letter-spacing:.04em; padding:6px 7px;
608
- border-bottom:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.12)); white-space:nowrap; }
609
- .pt-table td { padding:6px 7px; border-bottom:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.08));
610
- font-variant-numeric:tabular-nums; white-space:nowrap; height:30px; }
611
- .pt-empty { color:var(--dsw-alias-label-secondary, #49525f); padding:12px 4px; }
612
- .pt-error { color:var(--dsw-alias-state-error-primary, #a33b2a);
613
- background:color-mix(in srgb, var(--dsw-alias-state-error-primary, #a33b2a) 10%, transparent);
614
- border-radius:var(--dsw-radius-xs, 4px); padding:7px 9px; }
615
- .pt-note { color:var(--dsw-alias-label-secondary, #49525f); font-size:12px; }
616
- .pt-blocked { color:var(--dsw-alias-state-error-primary, #a33b2a);
617
- border:0.5px solid var(--dsw-alias-state-error-primary, #a33b2a);
618
- border-radius:var(--dsw-radius-xs, 4px); padding:7px 9px;
619
- display:flex; align-items:center; justify-content:space-between; gap:8px; flex-wrap:wrap; }
620
- .pt-blocked-text { display:flex; flex-direction:column; gap:2px; min-width:0; flex:1 1 320px; }
621
- .pt-blocked-detail { font-size:11px; line-height:1.4; font-variant-numeric:tabular-nums;
622
- overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
623
- .pt-blocked-hint { font-size:11px; line-height:1.4; color:var(--dsw-alias-label-secondary, #49525f); }
624
- .pt-chart { width:100%; height:120px; display:block; }
625
- .pt-chart-wrap { border:0.5px solid var(--dsw-alias-border-l2, rgba(45,49,66,.12));
626
- border-radius:var(--dsw-radius-sm, 8px); padding:8px; }
627
- /* Futures: the element rail is narrower than the K-line rail, and the
628
- risk figure turns amber before the account reaches the liquidation line. */
629
- .pt-workspace-futures { grid-template-columns:minmax(0, 1fr) clamp(260px, 30%, 400px); }
630
- .pt-futures-rail { position:sticky; top:calc(12px + var(--dsh-frame-top-clearance, 0px)); align-self:start; min-width:0; }
631
- .pt-risk-high { color:var(--dsw-alias-state-warn-primary, #8a6410); }
632
- /* Breakpoints follow the panel's own width, not the window's: the centre
633
- column also yields to the sidebar and the right pane, so a wide screen
634
- can still leave a narrow trading surface. */
635
- @container paper-main (max-width: 640px) {
636
- .pt-ticket { grid-template-columns:minmax(0, 1fr); }
637
- .pt-preview-pane { border-left:0; border-top:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.10));
638
- padding-left:0; padding-top:12px; }
639
- }
640
- @container paper-main (max-width: 460px) { .pt-ticket-form { grid-template-columns:minmax(0, 1fr); } }
641
- @container paper-panel (max-width: 1100px) {
642
- .pt-workspace, .pt-workspace-futures { grid-template-columns:minmax(0, 1fr); }
643
- .pt-kline-rail { position:static; order:-1; }
644
- .pt-futures-rail { position:static; order:-1; }
645
- .pt-kline-body { height:360px; }
646
- }
647
- @container paper-panel (max-width: 760px) {
648
- .pt-stats { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); }
649
- .pt-stat:nth-child(2n) { border-right:0; }
650
- .pt-stat:nth-child(-n+2) { border-bottom:0.5px solid var(--dsw-alias-border-l4, rgba(45,49,66,.10)); }
651
- .pt-chart { height:96px; }
652
- }
653
- @container paper-panel (max-width: 520px) {
654
- .pt-inner { padding-left:12px; padding-right:12px; padding-bottom:20px; }
655
- .pt-stat-value { font-size:15px; }
656
- .pt-tabs { overflow-x:auto; }
657
- .pt-tab { flex:0 0 auto; }
658
- }
659
- .pt-root button:focus-visible, .pt-root input:focus-visible,
660
- .pt-root .pt-seg button:focus-visible, .pt-root .pt-tab:focus-visible {
661
- outline:2px solid var(--pt-accent); outline-offset:2px; }
662
- `
663
-
664
- /* ------------------------------------------------------------ atoms --- */
665
-
666
- function Field({ label, children, span = false }) {
667
- return h('label', { className: span ? 'pt-field pt-span-2' : 'pt-field' }, h('span', null, label), children)
668
- }
669
-
670
- /**
671
- * Header badge for the data source. `null` until the host has answered, so
672
- * the header never flashes a guess; a status `message` (failed validation,
673
- * unreadable settings) is appended to the tooltip only.
674
- *
675
- * A recorded quote failure overrides the configuration reading: the badge
676
- * answers "can quotes be fetched now", and "数据源正常" next to a quota
677
- * banner would contradict the banner right below it.
678
- */
679
- function DataSourceBadge({ status }) {
680
- if (status === null || status === undefined) return null
681
- const base = DATA_SOURCE_STATE[status.state] ?? DATA_SOURCE_STATE.none
682
- const problem = status.problem
683
- const failure = problem === undefined || problem === null
684
- ? undefined
685
- : DATA_PROBLEM_STATE[problem.reason] ?? '取数失败'
686
- const state = failure === undefined
687
- ? base
688
- : { text: `行情${failure}`, title: `最近一次取行情失败:${failure}` }
689
- const title = state === base && status.message !== undefined && status.message !== ''
690
- ? `${state.title}(${status.message})`
691
- : state.title
692
- return h('span', {
693
- className: 'pt-source', 'data-state': status.state, title, 'aria-label': `数据源:${state.text}`,
694
- },
695
- h('span', { className: 'pt-source-dot', 'aria-hidden': 'true' }),
696
- h('span', null, state.text))
697
- }
698
-
699
- /**
700
- * Actionable data banner. Dismissal is remembered per reason, so the same
701
- * cause stays quiet until it changes (then the new reason shows again).
702
- * The copy names the settings section instead of linking out — see
703
- * {@link KEY_SETTINGS}.
704
- */
705
- function DataBanner({ status, onRetry }) {
706
- const model = bannerModel(status)
707
- const [dismissed, setDismissed] = useState(readBannerDismissal)
708
- if (model === null || model.id === dismissed) return null
709
- const dismiss = () => {
710
- try {
711
- window.localStorage.setItem(DATA_BANNER_DISMISS_KEY, model.id)
712
- } catch {
713
- // Private mode: the banner simply reappears next render.
714
- }
715
- setDismissed(model.id)
716
- }
717
- return h('div', { className: 'pt-data-banner', 'data-tone': model.tone },
718
- h('div', { style: { minWidth: 0 } },
719
- h('div', { className: 'pt-data-banner-title' }, model.title),
720
- h('div', { className: 'pt-note' }, model.detail)),
721
- h('div', { className: 'pt-data-banner-actions' },
722
- model.actions.includes('retry')
723
- ? h('button', { className: 'pt-btn', onClick: onRetry }, '重试')
724
- : null,
725
- h('button', { className: 'pt-btn', onClick: dismiss, title: '本类原因不再提示' }, '关闭'),
726
- ))
727
- }
728
-
729
- /**
730
- * Support entry: a plain link to the public issue form. It reads nothing
731
- * from the ledger, so it is safe to show in every account state — including
732
- * a blocked one, where a report is most likely needed.
733
- */
734
- function FeedbackLink() {
735
- return h('a', {
736
- className: 'pt-btn pt-feedback', href: FEEDBACK_URL, target: '_blank', rel: 'noreferrer',
737
- title: '在 GitHub 报告问题',
738
- }, '反馈')
739
- }
740
-
741
- /** Wide tables scroll inside their own box instead of the page. */
742
- function Table({ children }) {
743
- return h('div', { className: 'pt-table-wrap' }, h('table', { className: 'pt-table' }, children))
744
- }
745
-
746
- /** A label/value row inside the `.pt-preview` cards. */
747
- const previewRow = (label, value, tone) => h('div', null, h('span', null, label), h('span', { className: tone || undefined }, value))
748
-
749
- /** One cell of the compact `.pt-stats` strip. */
750
- const statCell = (label, value, tone) => h('div', { className: 'pt-stat' },
751
- h('div', { className: 'pt-stat-label' }, label),
752
- h('div', { className: tone ? `pt-stat-value ${tone}` : 'pt-stat-value' }, value),
753
- )
754
-
755
- /** Yuan text → integer cents, or null when the input is not a usable amount. */
756
- function cashAmountCents(value) {
757
- const text = String(value ?? '').trim()
758
- if (text === '') return null
759
- const yuan = Number(text)
760
- if (!Number.isFinite(yuan) || yuan <= 0) return null
761
- const cents = Math.round(yuan * 100)
762
- return cents > 0 ? cents : null
763
- }
764
-
765
- const CASH_QUICK_AMOUNTS = [10000, 50000, 100000]
766
- const RESET_QUICK_AMOUNTS = [500000, 1000000, 2000000]
767
-
768
- /**
769
- * Inline cash in/out panel shared by the stock and futures headers.
770
- *
771
- * A modal would need focus handling and new CSS; an inline strip reuses the
772
- * existing `.pt-row`/`.pt-btn` atoms and can show the free-cash limit next to
773
- * the confirm button.
774
- */
775
- function CashMovePanel({ available, side, onSide, amount, onAmount, busy, onCancel, onSubmit }) {
776
- const cents = cashAmountCents(amount)
777
- const limitCents = Math.round(available * 100)
778
- const reason = cents === null ? '金额需为正数' : side === 'withdraw' && cents > limitCents ? '超过可提现金' : ''
779
- return h('div', { className: 'pt-cash' },
780
- h('div', { className: 'pt-row' },
781
- h('button', { className: 'pt-btn', 'data-active': side === 'deposit', onClick: () => onSide('deposit') }, '注资'),
782
- h('button', { className: 'pt-btn', 'data-active': side === 'withdraw', onClick: () => onSide('withdraw') }, '提款'),
783
- h('input', {
784
- className: 'pt-input', style: { width: 130 }, inputMode: 'decimal', placeholder: '金额(元)',
785
- value: amount, onChange: event => onAmount(event.target.value),
786
- }),
787
- CASH_QUICK_AMOUNTS.map(value => h('button', {
788
- key: value, className: 'pt-btn', onClick: () => onAmount(String(value)),
789
- }, `${value / 10000}万`)),
790
- side === 'withdraw' ? h('button', { className: 'pt-btn', onClick: () => onAmount(String(limitCents / 100)) }, '全部') : null,
791
- ),
792
- h('div', { className: 'pt-row' },
793
- h('div', { className: 'pt-note' }, side === 'deposit' ? '注资不计盈亏' : `可提 ${money(available)},不影响持仓`),
794
- h('button', { className: 'pt-btn', onClick: onCancel, disabled: busy }, '取消'),
795
- h('button', {
796
- className: 'pt-btn pt-btn-primary', onClick: onSubmit, disabled: busy || reason !== '', title: reason || undefined,
797
- }, busy ? '处理中…' : side === 'deposit' ? '确认注资' : '确认提款'),
798
- ),
799
- reason !== '' ? h('div', { className: 'pt-note pt-risk-high' }, reason) : null,
800
- )
801
- }
802
-
803
- /**
804
- * Inline reset confirmation with the starting cash.
805
- *
806
- * A reset keeps the previous settings, so an account opened at 10 万 would
807
- * otherwise stay there forever; the input lets the user pick the starting
808
- * cash in the same step, and reuses the cash panel's atoms.
809
- */
810
- function ResetPanel({ initialCash, amount, onAmount, busy, onCancel, onSubmit }) {
811
- const cents = cashAmountCents(amount)
812
- const reason = cents === null ? '初始资金需为正数' : ''
813
- return h('div', { className: 'pt-cash' },
814
- h('div', { className: 'pt-row' },
815
- h('div', { className: 'pt-note' }, '初始资金(元)'),
816
- h('input', {
817
- className: 'pt-input', style: { width: 130 }, inputMode: 'decimal', placeholder: `当前 ${money(initialCash)}`,
818
- value: amount, onChange: event => onAmount(event.target.value),
819
- }),
820
- RESET_QUICK_AMOUNTS.map(value => h('button', {
821
- key: value, className: 'pt-btn', onClick: () => onAmount(String(value)),
822
- }, `${value / 10000}万`)),
823
- ),
824
- h('div', { className: 'pt-row' },
825
- h('div', { className: 'pt-note' }, '重置会清空持仓与挂单,账本先备份'),
826
- h('button', { className: 'pt-btn', onClick: onCancel, disabled: busy }, '取消'),
827
- h('button', {
828
- className: 'pt-btn pt-btn-danger', onClick: onSubmit, disabled: busy || reason !== '', title: reason || undefined,
829
- }, busy ? '处理中…' : '确认重置'),
830
- ),
831
- reason !== '' ? h('div', { className: 'pt-note pt-risk-high' }, reason) : null,
832
- )
833
- }
834
-
835
- function DebouncedNumber({ value, onChange, placeholder, min, step }) {
836
- return h('input', {
837
- className: 'pt-input',
838
- type: 'number',
839
- value: value === '' ? '' : value,
840
- placeholder,
841
- min,
842
- step,
843
- onChange: event => onChange(event.target.value),
844
- })
845
- }
846
-
847
- /** Top-level account switch: the stock and futures ledgers are independent. */
848
- function AccountSwitch({ mode, onChange }) {
849
- return h('div', { className: 'pt-seg', role: 'group', 'aria-label': '账户' },
850
- [['stock', '股票'], ['futures', '期货']].map(([key, label]) =>
851
- h('button', { key, 'data-active': mode === key, onClick: () => onChange(key) }, label),
852
- ),
853
- )
854
- }
855
-
856
- function EquityChart({ points }) {
857
- // One snapshot cannot be a curve: show the value and say why it is flat.
858
- if (points.length < 2) {
859
- const only = points.length === 1 ? `最新权益 ${money(points[0].equity)} · ` : ''
860
- return h('div', { className: 'pt-empty' }, `${only}至少两个交易日后才有权益曲线`)
861
- }
862
- const width = 620
863
- const height = 160
864
- const values = points.map(point => point.equity)
865
- const min = Math.min(...values)
866
- const max = Math.max(...values)
867
- const span = max - min || Math.max(1, max * 0.02)
868
- const x = index => points.length === 1 ? 0 : (index / (points.length - 1)) * width
869
- const y = value => height - ((value - min) / span) * (height - 16) - 8
870
- const line = points.map((point, index) => `${index === 0 ? 'M' : 'L'}${x(index).toFixed(1)},${y(point.equity).toFixed(1)}`).join(' ')
871
- const area = `${line} L${width},${height} L0,${height} Z`
872
- return h('svg', { className: 'pt-chart', viewBox: `0 0 ${width} ${height}`, role: 'img', 'aria-label': '权益曲线' },
873
- h('path', { d: area, fill: 'var(--pt-accent)', fillOpacity: 0.10 }),
874
- h('path', { d: line, fill: 'none', stroke: 'var(--pt-accent)', strokeWidth: 1.6 }),
875
- h('text', { x: 4, y: 12, fontSize: 9, fill: 'var(--dsw-alias-label-secondary, #6b7480)' }, max.toFixed(0)),
876
- h('text', { x: 4, y: height - 2, fontSize: 9, fill: 'var(--dsw-alias-label-secondary, #6b7480)' }, min.toFixed(0)),
877
- )
878
- }
879
-
880
- /** Candlestick/line chart from daily or minute bars; no external chart lib. */
881
- function PriceChart({ bars, interval }) {
882
- if (!Array.isArray(bars) || bars.length === 0) return h('div', { className: 'pt-empty' }, '暂无 K 线数据')
883
- const width = 640
884
- const height = 200
885
- const min = Math.min(...bars.map(bar => bar.low ?? bar.close))
886
- const max = Math.max(...bars.map(bar => bar.high ?? bar.close))
887
- const span = max - min || Math.max(1, max * 0.02)
888
- const x = index => bars.length === 1 ? width / 2 : (index / (bars.length - 1)) * (width - 20) + 10
889
- const y = value => height - ((value - min) / span) * (height - 24) - 12
890
- const line = bars.map((bar, index) => `${index === 0 ? 'M' : 'L'}${x(index).toFixed(1)},${y(bar.close).toFixed(1)}`).join(' ')
891
- return h('svg', { className: 'pt-chart pt-chart-fill', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': interval === 'minute' ? '分时图' : '日K线' },
892
- interval === 'minute'
893
- ? h('path', { d: line, fill: 'none', stroke: 'var(--pt-accent, #cf5623)', strokeWidth: 1.6 })
894
- : h('g', null, bars.map((bar, index) => {
895
- const up = bar.close >= bar.open
896
- const color = up ? 'var(--pt-rise, #f04462)' : 'var(--pt-fall, #00b578)'
897
- const top = y(Math.max(bar.open, bar.close))
898
- const bottom = y(Math.min(bar.open, bar.close))
899
- return h('g', { key: `${bar.time}-${index}` },
900
- h('line', { x1: x(index), x2: x(index), y1: y(bar.high), y2: y(bar.low), stroke: color, strokeWidth: 1 }),
901
- h('rect', { x: x(index) - 2.5, y: top, width: 5, height: Math.max(1, bottom - top), fill: color }),
902
- )
903
- })),
904
- )
905
- }
906
-
907
- /* --------------------------------------------------------- K-line ----- */
908
-
909
- /** Elements that prove a slot actually draws something (icons and loading
910
- text do not count). */
911
- const PAINTED = 'canvas, iframe, svg, table, video'
912
-
913
- /**
914
- * Whether a subtree has real rendered content. Open shadow roots belong to
915
- * that subtree: dsh_kline mounts its whole chart inside
916
- * `host.attachShadow()`, so a light-DOM query alone reports a perfectly
917
- * healthy slot as empty.
918
- */
919
- function paintsSomething(root) {
920
- if (root === null || root === undefined || typeof root.querySelector !== 'function') return false
921
- if (root.querySelector(PAINTED) !== null) return true
922
- const own = root.shadowRoot
923
- if (own !== null && own !== undefined && paintsSomething(own)) return true
924
- for (const node of root.querySelectorAll('*')) {
925
- const shadow = node.shadowRoot
926
- if (shadow !== null && shadow !== undefined && paintsSomething(shadow)) return true
927
- }
928
- return false
929
- }
930
-
931
- /** Grace period for a registered slot to paint before the fallback takes
932
- over. Wall clock, so background timer throttling cannot stretch it. */
933
- const SLOT_PAINT_TIMEOUT = 6000
934
-
935
- /**
936
- * Always-visible K-line rail; dsh_kline fills the slot when installed.
937
- * The slot owns its own interval switch, so the built-in day/minute
938
- * buttons only exist for the fallback SVG (no dead controls).
939
- */
940
- function KlinePane({ renderSlot, symbol, quote, bars, error, interval, onInterval, onRefresh, onIdentity }) {
941
- const slot = typeof renderSlot === 'function'
942
- ? renderSlot('paperTrading.kline', { symbol, onIdentity })
943
- : null
944
- const hasSlot = slot !== null && slot !== undefined && slot !== false
945
- && !(Array.isArray(slot) && slot.length === 0)
946
- // A registered slot can still render an empty host (no data, failed
947
- // mount). Poll it briefly; if nothing shows up, fall back to the built-in
948
- // chart instead of leaving 35% of the panel blank. The timeout is wall
949
- // clock rather than a tick count: a hidden/occluded window throttles
950
- // timers to one per second (or per minute), which would otherwise keep
951
- // the rail on "加载中…" for minutes while a real chart is already drawn.
952
- const [slotFailed, setSlotFailed] = useState(false)
953
- const [slotChecking, setSlotChecking] = useState(hasSlot)
954
- const [slotNonce, setSlotNonce] = useState(0)
955
- const slotRef = useRef(null)
956
- useEffect(() => {
957
- if (!hasSlot) return undefined
958
- setSlotFailed(false)
959
- setSlotChecking(true)
960
- const deadline = Date.now() + SLOT_PAINT_TIMEOUT
961
- const timer = setInterval(() => {
962
- if (paintsSomething(slotRef.current)) { setSlotChecking(false); clearInterval(timer) }
963
- else if (Date.now() >= deadline) { setSlotFailed(true); setSlotChecking(false); clearInterval(timer) }
964
- }, 300)
965
- return () => clearInterval(timer)
966
- }, [hasSlot, symbol, slotNonce])
967
- const showFallback = !hasSlot || slotFailed
968
- return h('aside', { className: 'pt-kline-rail', 'aria-label': 'K线' },
969
- h('div', { className: 'pt-card pt-kline-card' },
970
- h('div', { className: 'pt-kline-head' },
971
- h('div', { className: 'pt-kline-title' },
972
- h('div', { className: 'pt-card-title', style: { margin: 0 } }, `${symbol || '—'} K线`),
973
- h('div', { className: 'pt-note' }, quote ? `${symbolText(quote)} · ${quote.source === 'daily-bar' ? '收盘' : '现价'} ${money(quote.last)}` : '等待行情'),
974
- ),
975
- showFallback ? h('div', { className: 'pt-row', style: { flexWrap: 'nowrap', alignItems: 'center' } },
976
- h('div', { className: 'pt-seg' },
977
- [['day', '日K'], ['minute', '分时']].map(([key, label]) =>
978
- h('button', { key, 'data-active': interval === key, onClick: () => onInterval(key) }, label),
979
- ),
980
- ),
981
- h('button', { className: 'pt-btn', onClick: onRefresh }, '刷新'),
982
- ) : null,
983
- ),
984
- h('div', { className: 'pt-kline-body' },
985
- showFallback
986
- ? h(PriceChart, { bars, interval })
987
- : h('div', { className: 'pt-kline-slot', ref: slotRef, key: slotNonce }, slot),
988
- ),
989
- showFallback ? h('div', { className: 'pt-note pt-kline-hint' },
990
- slotFailed
991
- ? 'K 线视图未加载,当前为内置简图。'
992
- : error !== '' ? error : '安装或升级 dsh_kline 后显示完整 K 线;当前为内置简图。',
993
- slotFailed ? h('button', {
994
- className: 'pt-btn', style: { marginLeft: 8 },
995
- onClick: () => { setSlotFailed(false); setSlotNonce(value => value + 1) },
996
- }, '重试 K 线') : null,
997
- ) : slotChecking ? h('div', { className: 'pt-note pt-kline-hint' }, 'K 线加载中…') : null,
998
- ),
999
- )
1000
- }
1001
-
1002
- /* ----------------------------------------------------------- tabs ----- */
1003
-
1004
- function TradeTab({
1005
- account, form, setForm, quote, quoteError, quoteNotice, preview, previewState, previewError, previewHint,
1006
- busy, onSubmit, submitReason, receipt, positions, pending, onCancel, onSell,
1007
- }) {
1008
- // Default to whichever book has content; the toggle keeps both one click away.
1009
- const [book, setBook] = useState(() => (positions.length === 0 && pending.length > 0 ? 'orders' : 'positions'))
1010
- const maxBuy = preview ? count(preview.maxBuyQty) : '—'
1011
- const priceLabel = form.type === 'limit' ? '限价' : '参考价(可选)'
1012
- const quoteHint = quote
1013
- ? null
1014
- : form.symbol.trim().length < 6
1015
- ? '输入代码后自动取行情'
1016
- : previewState === 'loading'
1017
- ? '取行情…'
1018
- : form.type === 'limit' ? '未取到行情,可填限价' : '未取到行情,可填参考价'
1019
- const emptyPreview = previewHint !== ''
1020
- ? previewHint
1021
- : previewState === 'loading' ? '计算中…' : previewError !== '' ? previewError : '计算中…'
1022
- return h('div', { className: 'pt-trade' },
1023
- h('div', { className: 'pt-card pt-ticket-card' },
1024
- h('div', { className: 'pt-ticket' },
1025
- h('div', { className: 'pt-ticket-form' },
1026
- h(Field, { label: '代码', span: true }, h('input', {
1027
- className: 'pt-input', value: form.symbol, maxLength: 12, spellCheck: false,
1028
- placeholder: '600519 / 000001.SZ',
1029
- onChange: event => setForm(prev => ({ ...prev, symbol: symbolInput(event.target.value) })),
1030
- })),
1031
- h('div', { className: 'pt-span-2 pt-field-pair' },
1032
- h(Field, { label: '方向' }, h('div', { className: 'pt-seg' },
1033
- [['buy', '买入'], ['sell', '卖出']].map(([key, label]) =>
1034
- h('button', { key, 'data-active': form.side === key, onClick: () => setForm(prev => ({ ...prev, side: key })) }, label),
1035
- ),
1036
- )),
1037
- h(Field, { label: '数量(100 股整数倍)' }, h(DebouncedNumber, {
1038
- value: form.qty, min: 0, step: 100,
1039
- onChange: value => setForm(prev => ({ ...prev, qty: value })),
1040
- })),
1041
- ),
1042
- h(Field, { label: '类型' }, h('div', { className: 'pt-seg' },
1043
- [['market', '市价'], ['limit', '限价']].map(([key, label]) =>
1044
- h('button', { key, 'data-active': form.type === key, onClick: () => setForm(prev => ({ ...prev, type: key })) }, label),
1045
- ),
1046
- )),
1047
- h(Field, { label: priceLabel }, h(DebouncedNumber, {
1048
- value: form.type === 'limit' ? form.limitPrice : form.price, min: 0, step: 0.01,
1049
- onChange: value => setForm(prev => prev.type === 'limit'
1050
- ? { ...prev, limitPrice: value }
1051
- : { ...prev, price: value }),
1052
- })),
1053
- h('div', { className: 'pt-span-2' },
1054
- quote
1055
- ? h('div', { className: 'pt-quote' },
1056
- h('span', null, symbolText(quote)),
1057
- h('span', null, `${quote.source === 'daily-bar' ? '收盘' : '现价'} ${money(quote.last)}`),
1058
- h('span', { className: 'pt-note' }, quoteUpdateText(quote)),
1059
- h('span', { className: 'pt-note' }, `来源 ${quoteSourceText(quote)}`),
1060
- quoteNotice !== '' && preview === null ? h('span', { className: 'pt-note' }, quoteNotice) : null,
1061
- )
1062
- : h('div', { className: 'pt-note' }, quoteHint),
1063
- ),
1064
- h(Field, { label: '备注(复盘用)', span: true }, h('input', {
1065
- className: 'pt-input', value: form.note, maxLength: 120,
1066
- onChange: event => setForm(prev => ({ ...prev, note: event.target.value })),
1067
- })),
1068
- quoteError !== '' ? h('div', { className: 'pt-error pt-span-2' }, quoteError) : null,
1069
- ),
1070
- h('div', { className: 'pt-preview-pane' },
1071
- h('div', { className: 'pt-card-title', style: { marginBottom: 6 } }, '预览'),
1072
- preview ? (preview.price > 0 ? h('div', { className: 'pt-preview' },
1073
- h('div', null, h('span', null, '预估成交价'), h('span', null, money(preview.price))),
1074
- h('div', null, h('span', null, '金额'), h('span', null, cents(preview.amountCents))),
1075
- h('div', null, h('span', null, '佣金'), h('span', null, cents(preview.commissionCents))),
1076
- h('div', null, h('span', null, '印花税'), h('span', null, cents(preview.stampCents))),
1077
- h('div', null, h('span', null, '过户费'), h('span', null, cents(preview.transferCents))),
1078
- h('div', null, h('span', null, '成交后现金'),
1079
- h('span', { className: preview.cashAfterCents < 0 ? 'pt-risk-high' : undefined }, cents(preview.cashAfterCents)),
1080
- ),
1081
- h('div', null, h('span', null, '最多可买'), h('span', null, `${count(preview.maxBuyQty)} 股`)),
1082
- previewState === 'loading' ? h('div', { className: 'pt-note' }, '计算中…') : null,
1083
- preview.warnings.length > 0 ? h('div', { className: 'pt-warn' }, preview.warnings.join(';')) : null,
1084
- previewState === 'error' && previewError !== '' ? h('div', { className: 'pt-warn' }, previewError) : null,
1085
- ) : h('div', { className: 'pt-empty' }, '没有可用行情,请填写参考价或改用限价单')) : h('div', { className: 'pt-empty' }, emptyPreview),
1086
- ),
1087
- ),
1088
- h('div', { className: 'pt-ticket-foot' },
1089
- submitReason !== '' ? h('div', { className: 'pt-note' }, `不可提交:${submitReason}`) : null,
1090
- h('button', {
1091
- className: 'pt-btn pt-btn-primary pt-ticket-submit', onClick: onSubmit, title: submitReason || undefined,
1092
- disabled: busy || submitReason !== '',
1093
- }, form.side === 'buy' ? '买入' : '卖出'),
1094
- h('div', { className: 'pt-ticket-meta' },
1095
- h('span', { className: 'pt-note' },
1096
- form.side === 'sell'
1097
- ? `可用 ${money(account.cash)}${preview ? ` · 可卖 ${count(preview.availableQty)} 股` : ''}`
1098
- : `可用 ${money(account.cash)}${preview ? ` · 最多可买 ${maxBuy} 股` : ''}`,
1099
- ),
1100
- ),
1101
- receipt ? h(ReceiptLine, { receipt }) : null,
1102
- ),
1103
- ),
1104
- h(TradeBook, { positions, pending, book, setBook, busy, onCancel, onSell }),
1105
- )
1106
- }
1107
-
1108
- /** Compact holdings/orders book, pinned under the ticket so the left column
1109
- always reaches the K-line's bottom edge. */
1110
- function TradeBook({ positions, pending, book, setBook, busy, onCancel, onSell }) {
1111
- const showPositions = book === 'positions'
1112
- return h('div', { className: 'pt-card pt-trade-book' },
1113
- h('div', { className: 'pt-book-head' },
1114
- h('div', { className: 'pt-seg' },
1115
- h('button', { 'data-active': showPositions, onClick: () => setBook('positions') }, `持仓 ${positions.length}`),
1116
- h('button', { 'data-active': !showPositions, onClick: () => setBook('orders') }, `挂单 ${pending.length}`),
1117
- ),
1118
- h('div', { className: 'pt-note' }, showPositions ? '成交后自动更新' : '未成交委托,可随时撤单'),
1119
- ),
1120
- h('div', { className: 'pt-book-scroll' },
1121
- showPositions
1122
- ? (positions.length === 0
1123
- ? h('div', { className: 'pt-empty pt-book-empty' }, '无持仓 · 成交后自动显示')
1124
- : h(Table, null,
1125
- h('thead', null, h('tr', null,
1126
- ['代码', '名称', '数量', '可卖', '成本', '现价', '浮盈亏'].map(label => h('th', { key: label }, label)),
1127
- h('th', null, '操作'),
1128
- )),
1129
- h('tbody', null, positions.map(position => h('tr', { key: position.symbol },
1130
- h('td', null, position.symbol),
1131
- h('td', null, position.name ?? '—'),
1132
- h('td', null, count(position.qty)),
1133
- h('td', null, count(position.available)),
1134
- h('td', null, money(position.avgCost)),
1135
- h('td', null, money(position.lastPrice)),
1136
- h('td', { className: tone(position.unrealizedPnlCents ?? 0) }, cents(position.unrealizedPnlCents)),
1137
- h('td', null, h('button', {
1138
- className: 'pt-btn', onClick: () => onSell(position), disabled: !(position.available > 0),
1139
- title: position.available > 0 ? undefined : 'T+1:今日买入的股份明日可卖',
1140
- }, '卖出')),
1141
- ))),
1142
- ))
1143
- : (pending.length === 0
1144
- ? h('div', { className: 'pt-empty pt-book-empty' }, '无挂单 · 未成交的限价委托会停在这里')
1145
- : h(Table, null,
1146
- h('thead', null, h('tr', null,
1147
- ['代码', '方向', '类型', '数量', '限价', '状态'].map(label => h('th', { key: label }, label)),
1148
- h('th', null, '操作'),
1149
- )),
1150
- h('tbody', null, pending.map(order => h('tr', { key: order.id },
1151
- h('td', null, order.symbol),
1152
- h('td', null, order.side === 'buy' ? '买' : '卖'),
1153
- h('td', null, order.type === 'limit' ? '限价' : '市价'),
1154
- h('td', null, count(order.qty)),
1155
- h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
1156
- h('td', null, STATUS_TEXT[order.status] ?? order.status),
1157
- h('td', null, h('button', { className: 'pt-btn', onClick: () => onCancel(order.id), disabled: busy }, '撤单')),
1158
- ))),
1159
- )),
1160
- ),
1161
- )
1162
- }
1163
-
1164
- /** Post-submit receipt, built from the ledger's fill record, not the draft. */
1165
- function ReceiptLine({ receipt }) {
1166
- if (receipt.failure !== undefined) {
1167
- return h('div', { className: 'pt-receipt', 'data-state': 'rejected', title: receipt.failure.detail || undefined },
1168
- `拒绝:${receipt.failure.text}`,
1169
- )
1170
- }
1171
- const { order, fill, cash } = receipt
1172
- const symbol = order.name ? `${order.symbol} ${order.name}` : order.symbol
1173
- const side = order.side === 'buy' ? '买入' : '卖出'
1174
- if (order.status === 'rejected') {
1175
- return h('div', { className: 'pt-receipt', 'data-state': 'rejected', title: order.reason || undefined },
1176
- `拒绝:${side} ${symbol} ${count(order.qty)} 股 · ${reasonText(order.reason) || '未通过风控'}`,
1177
- )
1178
- }
1179
- if (order.status === 'filled') {
1180
- const price = fill ? fill.price : order.fillPrice
1181
- const qty = fill ? fill.qty : order.filledQty
1182
- const amount = fill ? fill.amountCents : order.amountCents
1183
- const fees = fill ? fill.feesCents : order.feesCents
1184
- return h('div', { className: 'pt-receipt', 'data-state': 'filled', title: order.id },
1185
- `成交:${side} ${symbol} ${count(qty)} 股 · 价 ${money(price)} · 金额 ${cents(amount)} · 费用 ${cents(fees)} · 成交后现金 ${money(cash)} · 单 ${order.id}`,
1186
- )
1187
- }
1188
- const pendingText = order.status === 'queued'
1189
- ? '当前时段不撮合,已受理为下一交易时段开盘委托'
1190
- : '现价未穿越,成交前一直挂单'
1191
- return h('div', { className: 'pt-receipt', 'data-state': 'resting', title: order.id },
1192
- `挂单:${side} ${symbol} ${count(order.qty)} 股${order.limitPrice === undefined ? '' : ` @ ${money(order.limitPrice)}`} · ${pendingText} · 单 ${order.id}`,
1193
- )
1194
- }
1195
-
1196
- const marketSessionNote = session => {
1197
- if (!session || session.canMatch) return ''
1198
- if (session.phase === 'pre_open') return '集合竞价中,现价为最近一次行情'
1199
- if (session.phase === 'auction_close') return '收盘竞价中,现价为最近一次行情'
1200
- return '非交易时段,现价为最近一次行情'
1201
- }
1202
-
1203
- function MarketTab({ searchQuery, setSearchQuery, runSearch, searchHits, searchAttempted, shortlist, isShortlisted, toggleShortlist, marketList, marketBoard, setMarketBoard, shortlistOnly, setShortlistOnly, loadMarket, busy, adoptQuote, session }) {
1204
- const visibleQuotes = marketList === null
1205
- ? []
1206
- : marketList.quotes.filter(item => !shortlistOnly || isShortlisted(item.symbol)).slice(0, 50)
1207
- return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
1208
- h('div', { className: 'pt-card' },
1209
- h('div', { className: 'pt-card-title' }, '搜索标的'),
1210
- h('div', { className: 'pt-row' },
1211
- h('input', {
1212
- className: 'pt-input', style: { flex: 1, minWidth: 200 }, value: searchQuery,
1213
- placeholder: '代码或名称,例如 600519.SH / 贵州茅台',
1214
- onChange: event => setSearchQuery(event.target.value),
1215
- onKeyDown: event => { if (event.key === 'Enter') void runSearch() },
1216
- }),
1217
- h('button', { className: 'pt-btn', onClick: runSearch, disabled: busy }, '搜索'),
1218
- ),
1219
- searchHits.length > 0 ? h('div', { style: { marginTop: 8, display: 'flex', flexDirection: 'column', gap: 4 } },
1220
- searchHits.map(hit => h('div', { key: hit.symbol, className: 'pt-row' },
1221
- h('button', {
1222
- className: 'pt-btn', style: { flex: 1, justifyContent: 'flex-start' },
1223
- onClick: () => adoptQuote(hit.symbol, null),
1224
- }, `${hit.symbol} ${hit.name ?? ''}`),
1225
- h('button', { className: 'pt-btn', onClick: () => toggleShortlist(hit.symbol) }, isShortlisted(hit.symbol) ? '已备选' : '加备选'),
1226
- )),
1227
- ) : searchAttempted ? h('div', { className: 'pt-empty', style: { marginTop: 8 } }, '没有找到匹配标的') : null,
1228
- ),
1229
- h('div', { className: 'pt-card' },
1230
- h('div', { className: 'pt-row' },
1231
- h('div', { className: 'pt-card-title', style: { margin: 0 } }, '全市场'),
1232
- [['main', '主板'], ['star', '科创板'], ['chi_next', '创业板'], ['bjse', '北交所'], ['xshg', '沪市'], ['xshe', '深市']].map(([key, label]) =>
1233
- h('button', { key, className: 'pt-btn', 'data-active': marketBoard === key, onClick: () => setMarketBoard(key) }, label),
1234
- ),
1235
- h('button', { className: 'pt-btn', 'data-active': shortlistOnly, onClick: () => setShortlistOnly(value => !value) }, '只看备选'),
1236
- h('span', { className: 'pt-note' }, `第 ${marketList?.page ?? 1} 页`),
1237
- h('button', {
1238
- className: 'pt-btn', onClick: () => loadMarket(Math.max(1, (marketList?.page ?? 1) - 1)),
1239
- disabled: marketList === null || (marketList.page ?? 1) <= 1,
1240
- }, '上一页'),
1241
- h('button', {
1242
- className: 'pt-btn', onClick: () => loadMarket((marketList?.page ?? 1) + 1),
1243
- disabled: marketList !== null && marketList.quotes.length < 50,
1244
- }, '下一页'),
1245
- ),
1246
- marketSessionNote(session) !== ''
1247
- ? h('div', { className: 'pt-note' }, marketSessionNote(session))
1248
- : null,
1249
- marketList !== null && marketList.quotes.length > 0 && marketList.notice
1250
- ? h('div', { className: 'pt-note' }, marketList.notice)
1251
- : null,
1252
- marketList === null ? h('div', { className: 'pt-empty' }, '加载行情…')
1253
- : marketList.quotes.length === 0 ? h('div', { className: 'pt-empty' }, marketList.notice ?? '没有行情')
1254
- : visibleQuotes.length === 0
1255
- ? h('div', { className: 'pt-empty' }, shortlistOnly
1256
- ? (shortlist.length === 0 ? '还没有备选,点行情行的 ☆ 添加' : '本页没有备选,可翻页或关闭「只看备选」')
1257
- : '没有行情')
1258
- : h(Table, null,
1259
- h('thead', null, h('tr', null, ['代码', '名称', '现价', '涨跌幅', '备选'].map(label => h('th', { key: label }, label)))),
1260
- h('tbody', null, visibleQuotes.map(item => {
1261
- const change = item.prevClose && item.prevClose > 0 ? (item.last - item.prevClose) / item.prevClose : null
1262
- return h('tr', {
1263
- key: `${item.symbol}-${item.last}`, style: { cursor: 'pointer' },
1264
- onClick: () => adoptQuote(item.symbol, item),
1265
- },
1266
- h('td', null, item.symbol),
1267
- h('td', null, item.name ?? '—'),
1268
- h('td', null, money(item.last)),
1269
- h('td', { className: tone(change ?? 0) }, change === null ? '—' : pct(change)),
1270
- h('td', null, h('button', { className: 'pt-btn', onClick: event => { event.stopPropagation(); void toggleShortlist(item.symbol) } }, isShortlisted(item.symbol) ? '★' : '☆')),
1271
- )
1272
- })),
1273
- ),
1274
- ),
1275
- )
1276
- }
1277
-
1278
- function PositionsTab({ positions, onSell }) {
1279
- if (positions.length === 0) return h('div', { className: 'pt-empty' }, '无持仓 · 成交后自动显示,可在交易页下单')
1280
- return h(Table, null,
1281
- h('thead', null, h('tr', null,
1282
- ['代码', '名称', '数量', '可卖', '成本', '现价', '浮盈亏'].map(label => h('th', { key: label }, label)),
1283
- h('th', null, '操作'),
1284
- )),
1285
- h('tbody', null, positions.map(position => h('tr', { key: position.symbol },
1286
- h('td', null, position.symbol),
1287
- h('td', null, position.name ?? '—'),
1288
- h('td', null, count(position.qty)),
1289
- h('td', null, count(position.available)),
1290
- h('td', null, money(position.avgCost)),
1291
- h('td', null, money(position.lastPrice)),
1292
- h('td', { className: tone(position.unrealizedPnlCents ?? 0) }, cents(position.unrealizedPnlCents)),
1293
- h('td', null, h('button', {
1294
- className: 'pt-btn',
1295
- onClick: () => onSell(position),
1296
- disabled: !(position.available > 0),
1297
- title: position.available > 0 ? undefined : 'T+1:今日买入的股份明日可卖',
1298
- }, '卖出')),
1299
- ))),
1300
- )
1301
- }
1302
-
1303
- function OrdersTab({ pending, history, busy, onCancel }) {
1304
- return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } },
1305
- h('div', null,
1306
- h('div', { className: 'pt-sub' }, '挂单'),
1307
- pending.length === 0 ? h('div', { className: 'pt-empty' }, '无挂单') : h(Table, null,
1308
- h('thead', null, h('tr', null, ['代码', '方向', '类型', '数量', '限价', '状态', '备注', '操作'].map(label => h('th', { key: label }, label)))),
1309
- h('tbody', null, pending.map(order => h('tr', { key: order.id },
1310
- h('td', null, order.symbol),
1311
- h('td', null, order.side === 'buy' ? '买' : '卖'),
1312
- h('td', null, order.type === 'limit' ? '限价' : '市价'),
1313
- h('td', null, count(order.qty)),
1314
- h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
1315
- h('td', null, STATUS_TEXT[order.status] ?? order.status),
1316
- h('td', { title: order.note ?? undefined }, order.note === undefined ? '' : h('span', { className: 'pt-note-cell' }, order.note)),
1317
- h('td', null, h('button', { className: 'pt-btn', onClick: () => onCancel(order.id), disabled: busy }, '撤单')),
1318
- ))),
1319
- ),
1320
- pending.some(order => order.status === 'queued')
1321
- ? h('div', { className: 'pt-note' }, '「待开盘」:当前时段不撮合,下一交易时段开盘后按当时价格尝试成交,可随时撤单。')
1322
- : null,
1323
- ),
1324
- h('div', null,
1325
- h('div', { className: 'pt-sub' }, '历史'),
1326
- history.length === 0 ? h('div', { className: 'pt-empty' }, '无历史订单') : h(Table, null,
1327
- h('thead', null, h('tr', null, ['时间', '代码', '方向', '数量', '限价', '状态', '成交价', '原因', '备注'].map(label => h('th', { key: label }, label)))),
1328
- h('tbody', null, history.slice(0, 30).map(order => h('tr', { key: order.id },
1329
- h('td', null, dateTime(order.createdAt)),
1330
- h('td', null, order.symbol),
1331
- h('td', null, order.side === 'buy' ? '买' : '卖'),
1332
- h('td', null, count(order.qty)),
1333
- h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
1334
- h('td', null, STATUS_TEXT[order.status] ?? order.status),
1335
- h('td', null, order.fillPrice === undefined ? '—' : money(order.fillPrice)),
1336
- h('td', { title: order.reason ?? undefined }, reasonText(order.reason)),
1337
- h('td', { title: order.note ?? undefined }, order.note === undefined ? '' : h('span', { className: 'pt-note-cell' }, order.note)),
1338
- ))),
1339
- ),
1340
- history.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${history.length} 条`) : null,
1341
- ),
1342
- )
1343
- }
1344
-
1345
- function ReviewTab({ review, period, setPeriod, trades, daily, cashFlow, trips }) {
1346
- return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
1347
- h('div', { className: 'pt-row' }, PERIODS.map(([key, label]) =>
1348
- h('button', {
1349
- key, className: 'pt-btn', 'data-active': period === key,
1350
- onClick: () => setPeriod(key),
1351
- }, label),
1352
- )),
1353
- review ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
1354
- h('div', { className: 'pt-stats' },
1355
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '成交笔数'), h('div', { className: 'pt-stat-value' }, count(review.tradeCount))),
1356
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '已实现盈亏'), h('div', { className: `pt-stat-value ${tone(review.realizedPnl)}` }, signed(review.realizedPnl))),
1357
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '费用合计'), h('div', { className: 'pt-stat-value' }, money(review.totalFees))),
1358
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '最大回撤'), h('div', { className: 'pt-stat-value' }, pct(review.maxDrawdownPct))),
1359
- ),
1360
- h('div', { className: 'pt-chart-wrap' }, h(EquityChart, { points: review.equityCurve })),
1361
- h('div', null,
1362
- h('div', { className: 'pt-sub' }, '成交记录'),
1363
- trades.length === 0 ? h('div', { className: 'pt-empty' }, '无成交') : h(Table, null,
1364
- h('thead', null, h('tr', null, ['时间', '代码', '方向', '数量', '价格', '金额', '费用'].map(label => h('th', { key: label }, label)))),
1365
- h('tbody', null, trades.slice(0, 30).map(trade => h('tr', { key: trade.id },
1366
- h('td', null, dateTime(trade.ts)),
1367
- h('td', null, trade.symbol),
1368
- h('td', null, trade.side === 'buy' ? '买' : '卖'),
1369
- h('td', null, count(trade.qty)),
1370
- h('td', null, money(trade.price)),
1371
- h('td', null, cents(trade.amountCents)),
1372
- h('td', null, cents(trade.feesCents)),
1373
- ))),
1374
- ),
1375
- trades.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${trades.length} 条`) : null,
1376
- ),
1377
- h('div', null,
1378
- h('div', { className: 'pt-sub' }, '日终报告'),
1379
- daily.length === 0 ? h('div', { className: 'pt-empty' }, '暂无日终快照') : h(Table, null,
1380
- h('thead', null, h('tr', null, ['日期', '权益', '当日盈亏', '费用', '收盘价来源'].map(label => h('th', { key: label }, label)))),
1381
- h('tbody', null, daily.slice(-14).reverse().map(row => h('tr', { key: row.date },
1382
- h('td', null, row.date),
1383
- h('td', null, money(row.equity)),
1384
- h('td', { className: tone(row.dayPnl) }, signed(row.dayPnl)),
1385
- h('td', null, money(row.fees)),
1386
- h('td', null, row.closeSource === 'daily' ? '日K收盘' : row.closeSource === 'last' ? '最后报价' : '缺失'),
1387
- ))),
1388
- ),
1389
- daily.length > 14 ? h('div', { className: 'pt-note' }, `仅显示最近 14 个交易日,共 ${daily.length} 个`) : null,
1390
- ),
1391
- h('div', null,
1392
- h('div', { className: 'pt-sub' }, '资金流水'),
1393
- cashFlow.length === 0 ? h('div', { className: 'pt-empty' }, '暂无流水') : h(Table, null,
1394
- h('thead', null, h('tr', null, ['时间', '类型', '金额', '余额'].map(label => h('th', { key: label }, label)))),
1395
- h('tbody', null, cashFlow.slice(-30).reverse().map((row, index) => h('tr', { key: `${row.ts}-${index}` },
1396
- h('td', null, dateTime(row.ts)),
1397
- h('td', null, CASH_TYPE_TEXT[row.type] ?? row.type),
1398
- h('td', { className: tone(row.amount) }, signed(row.amount)),
1399
- h('td', null, money(row.balance)),
1400
- ))),
1401
- ),
1402
- cashFlow.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${cashFlow.length} 条`) : null,
1403
- ),
1404
- h('div', null,
1405
- h('div', { className: 'pt-sub' }, '回合统计(按标的)'),
1406
- trips.length === 0 ? h('div', { className: 'pt-empty' }, '暂无已平仓记录') : h(Table, null,
1407
- h('thead', null, h('tr', null, ['代码', '数量', '成本', '收入', '盈亏', '持有天数'].map(label => h('th', { key: label }, label)))),
1408
- h('tbody', null, trips.slice(-30).reverse().map(trip => h('tr', { key: trip.symbol },
1409
- h('td', null, trip.symbol),
1410
- h('td', null, count(trip.qty)),
1411
- h('td', null, money(trip.cost)),
1412
- h('td', null, money(trip.proceeds)),
1413
- h('td', { className: tone(trip.pnl) }, signed(trip.pnl)),
1414
- h('td', null, count(trip.holdingDays)),
1415
- ))),
1416
- ),
1417
- trips.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${trips.length} 条`) : null,
1418
- ),
1419
- ) : h('div', { className: 'pt-empty' }, '加载复盘…'),
1420
- )
1421
- }
1422
-
1423
- /* --------------------------------------------------------- basket ----- */
1424
-
1425
- /**
1426
- * Basket import: CSV in, host-computed plan out. Confirming submits the
1427
- * plan's `{symbol, qty}` rows verbatim, so the quantities the user sees are
1428
- * the quantities that reach the ledger. All state is local: leaving the tab
1429
- * unmounts the panel and clears the import.
1430
- */
1431
- function BasketTab({ account, onDone, resetNonce }) {
1432
- const [csv, setCsv] = useState('')
1433
- const [fileName, setFileName] = useState('')
1434
- const [budget, setBudget] = useState('')
1435
- const [preview, setPreview] = useState(null)
1436
- const [result, setResult] = useState(null)
1437
- const [busy, setBusy] = useState(false)
1438
- const [error, setError] = useState('')
1439
- // Frozen when a preview succeeds: retrying a lost response must resend
1440
- // the same batchId, otherwise the host would buy the basket twice.
1441
- const [batchId, setBatchId] = useState('')
1442
- const placing = useRef(false)
1443
- // A preview is only valid for the CSV/budget it was computed from.
1444
- const previewSeq = useRef(0)
1445
- // A reset changes the cash the preview was based on: drop it.
1446
- useEffect(() => {
1447
- previewSeq.current += 1
1448
- setBusy(false)
1449
- setPreview(null)
1450
- setResult(null)
1451
- setBatchId('')
1452
- setError('')
1453
- }, [resetNonce])
1454
- const nextBatchId = () => typeof crypto !== 'undefined' && crypto.randomUUID
1455
- ? crypto.randomUUID()
1456
- : `basket-${Date.now()}-${Math.random().toString(36).slice(2)}`
1457
-
1458
- // Empty means "host uses the available cash"; the input is yuan, cents go out.
1459
- const budgetCents = useMemo(() => {
1460
- const text = budget.trim()
1461
- if (text === '') return undefined
1462
- const value = Number(text)
1463
- return Number.isFinite(value) && value > 0 ? Math.round(value * 100) : NaN
1464
- }, [budget])
1465
-
1466
- const budgetInvalid = budget.trim() !== '' && Number.isNaN(budgetCents)
1467
-
1468
- const readFile = useCallback(async event => {
1469
- const file = event.target.files && event.target.files[0]
1470
- // Clear the value so picking the same file again still fires a change.
1471
- event.target.value = ''
1472
- if (!file) return
1473
- previewSeq.current += 1
1474
- setBusy(false)
1475
- setError('')
1476
- setPreview(null)
1477
- setResult(null)
1478
- setBatchId('')
1479
- setFileName(file.name)
1480
- // The RPC has the same cap; catching it here gives instant feedback.
1481
- if (file.size > 32 * 1024) {
1482
- setCsv('')
1483
- setError('CSV 文件不能超过 32 KiB')
1484
- return
1485
- }
1486
- try {
1487
- setCsv(await file.text())
1488
- } catch {
1489
- setError('读取文件失败')
1490
- }
1491
- }, [])
1492
-
1493
- const runPreview = useCallback(async () => {
1494
- if (csv.trim() === '') return
1495
- if (Number.isNaN(budgetCents)) {
1496
- setError('预算需为正数')
1497
- return
1498
- }
1499
- const seq = ++previewSeq.current
1500
- const sourceCsv = csv
1501
- setBusy(true)
1502
- setError('')
1503
- setResult(null)
1504
- try {
1505
- const payload = { csv: sourceCsv }
1506
- if (budgetCents !== undefined) payload.budgetCents = budgetCents
1507
- const next = await rpc('basket/preview', payload)
1508
- // A file/budget change while the request was in flight wins.
1509
- if (seq !== previewSeq.current) return
1510
- setPreview(next)
1511
- setBatchId(nextBatchId())
1512
- } catch (cause) {
1513
- if (seq === previewSeq.current) {
1514
- setError(errorOf(cause).text)
1515
- setPreview(null)
1516
- }
1517
- } finally {
1518
- if (seq === previewSeq.current) setBusy(false)
1519
- }
1520
- }, [csv, budgetCents])
1521
-
1522
- const rows = useMemo(
1523
- () => preview === null ? [] : preview.rows.filter(row => row.qty > 0).map(row => ({ symbol: row.symbol, qty: row.qty })),
1524
- [preview],
1525
- )
1526
- const placeReason = useMemo(() => {
1527
- if (account !== null && account.blocked === true) return '账户已锁定'
1528
- if (preview === null) return '先批量预览'
1529
- if (rows.length === 0) return '没有可下单的行'
1530
- if (preview.session && preview.session.phase === 'auction_close') return '收盘竞价暂不支持模拟撮合'
1531
- return ''
1532
- }, [account, preview, rows])
1533
-
1534
- const place = useCallback(async () => {
1535
- if (busy || placeReason !== '' || placing.current) return
1536
- placing.current = true
1537
- setBusy(true)
1538
- setError('')
1539
- try {
1540
- // Reuse the preview's id: a retry after a lost response must be
1541
- // idempotent on the host, not a second purchase.
1542
- const id = batchId !== '' ? batchId : nextBatchId()
1543
- setResult(await rpc('basket/place', { batchId: id, rows }))
1544
- if (typeof onDone === 'function') await onDone()
1545
- } catch (cause) {
1546
- setError(errorOf(cause).text)
1547
- } finally {
1548
- placing.current = false
1549
- setBusy(false)
1550
- }
1551
- }, [busy, placeReason, rows, onDone, batchId])
1552
-
1553
- return h('div', { className: 'pt-trade' },
1554
- h('div', { className: 'pt-card pt-ticket-card' },
1555
- h('div', { className: 'pt-card-title' }, '批量买入'),
1556
- h('div', { className: 'pt-row' },
1557
- h(Field, { label: 'CSV 文件' }, h('input', {
1558
- className: 'pt-input', type: 'file', accept: '.csv,text/csv', onChange: readFile,
1559
- })),
1560
- fileName !== '' ? h('div', { className: 'pt-note' }, fileName) : null,
1561
- h(Field, { label: '预算(元)' }, h('input', {
1562
- className: 'pt-input', style: { width: 140 }, value: budget, inputMode: 'decimal',
1563
- placeholder: account === null ? '默认可用现金' : `默认可用 ${money(account.cash)}`,
1564
- onChange: event => {
1565
- previewSeq.current += 1
1566
- setBusy(false)
1567
- setBudget(budgetInput(event.target.value))
1568
- setPreview(null)
1569
- setResult(null)
1570
- setBatchId('')
1571
- setError('')
1572
- },
1573
- })),
1574
- h('button', {
1575
- className: 'pt-btn pt-btn-primary', onClick: runPreview, disabled: busy || csv.trim() === '' || budgetInvalid,
1576
- title: budgetInvalid ? '预算需为正数' : csv.trim() === '' ? '请先选择 CSV 文件' : undefined,
1577
- }, busy ? '预览中…' : '批量预览'),
1578
- budgetInvalid ? h('div', { className: 'pt-note pt-risk-high' }, '预算需为正数') : null,
1579
- ),
1580
- h('div', { className: 'pt-note' }, csv.trim() === ''
1581
- ? '先选择 CSV 文件;两列「代码,权重」,最多 20 只'
1582
- : '两列「代码,权重」,最多 20 只,代码写 600519.SH 或 000001.SZ;仅连续竞价时段可下单'),
1583
- error !== '' ? h('div', { className: 'pt-error', style: { marginTop: 8 } }, error) : null,
1584
- ),
1585
- preview !== null ? h('div', { className: 'pt-card' },
1586
- h('div', { className: 'pt-card-title' }, '预览'),
1587
- h(Table, null,
1588
- h('thead', null, h('tr', null,
1589
- ['代码', '名称', '目标权重', '目标金额', '股数', '金额', '费用', '实际权重', '状态'].map(label => h('th', { key: label }, label)),
1590
- )),
1591
- h('tbody', null, preview.rows.map(row => h('tr', { key: row.symbol },
1592
- h('td', null, row.symbol),
1593
- h('td', null, row.name ?? '—'),
1594
- h('td', null, pct(row.weight)),
1595
- h('td', null, cents(row.targetCents)),
1596
- h('td', null, count(row.qty)),
1597
- h('td', null, cents(row.amountCents)),
1598
- h('td', null, cents(row.feesCents)),
1599
- h('td', null, pct(row.actualWeight)),
1600
- h('td', {
1601
- title: row.warning || undefined,
1602
- className: row.status === 'ok' ? undefined : 'pt-note',
1603
- }, BASKET_STATUS_TEXT[row.status] ?? row.status),
1604
- ))),
1605
- ),
1606
- h('div', { className: 'pt-quote', style: { marginTop: 8 } },
1607
- [['合计金额', preview.totalAmountCents], ['费用', preview.totalFeesCents],
1608
- ['剩余现金', preview.residualCents], ['成交后现金', preview.cashAfterCents]].map(([label, value]) =>
1609
- h('span', { key: label }, `${label} ${cents(value)}`)),
1610
- ),
1611
- preview.issues.length > 0 ? h('div', { className: 'pt-error', style: { marginTop: 8 } },
1612
- preview.issues.map(issue => `${issue.line > 0 ? `第 ${issue.line} 行:` : ''}${issue.message}`).join(';'),
1613
- ) : null,
1614
- preview.warnings.length > 0 ? h('div', { className: 'pt-note', style: { marginTop: 8 } }, preview.warnings.join(';')) : null,
1615
- h('div', { className: 'pt-row', style: { marginTop: 8 } },
1616
- placeReason !== '' ? h('div', { className: 'pt-note', style: { marginRight: 'auto' } }, placeReason) : null,
1617
- h('button', {
1618
- className: 'pt-btn pt-btn-primary', onClick: place, disabled: busy || placeReason !== '',
1619
- title: placeReason || undefined,
1620
- }, busy ? '提交中…' : '确认下单'),
1621
- ),
1622
- ) : null,
1623
- result !== null ? h('div', { className: 'pt-card' },
1624
- h('div', { className: 'pt-card-title' }, '下单结果'),
1625
- h(Table, null,
1626
- h('thead', null, h('tr', null,
1627
- ['代码', '状态', '数量', '成交价', '原因'].map(label => h('th', { key: label }, label)),
1628
- )),
1629
- h('tbody', null, result.rows.map(row => h('tr', { key: row.symbol },
1630
- h('td', null, row.symbol),
1631
- h('td', null, row.order ? STATUS_TEXT[row.order.status] ?? row.order.status : '拒绝'),
1632
- h('td', null, count(row.order ? row.order.qty : undefined)),
1633
- h('td', null, row.order && row.order.fillPrice !== undefined ? money(row.order.fillPrice) : '—'),
1634
- h('td', { title: row.error ?? row.order?.reason ?? undefined }, reasonText(row.error ?? row.order?.reason)),
1635
- ))),
1636
- ),
1637
- h('div', { className: 'pt-note', style: { marginTop: 8 } }, `成交后现金 ${cents(result.cashAfterCents)}`),
1638
- ) : null,
1639
- )
1640
- }
1641
-
1642
- /* -------------------------------------------------------- futures ----- */
1643
-
1644
- /**
1645
- * Futures dashboard: its own endpoints, polling loop and reset. The stock
1646
- * half never reads this state, so either account can fail or reset alone.
1647
- */
1648
- function FuturesDashboard({ accountSwitch }) {
1649
- const [account, setAccount] = useState(null)
1650
- const [status, setStatus] = useState(null)
1651
- const [positions, setPositions] = useState([])
1652
- const [orders, setOrders] = useState([])
1653
- const [review, setReview] = useState(null)
1654
- const [period, setPeriod] = useState('30d')
1655
- const periodRef = useRef(period)
1656
- useEffect(() => { periodRef.current = period }, [period])
1657
- const reviewSeq = useRef(0)
1658
- const loadAllSeq = useRef(0)
1659
- const [tab, setTab] = useState('trade')
1660
- const [error, setError] = useState(null)
1661
- const [notice, setNotice] = useState('')
1662
- const [busy, setBusy] = useState(false)
1663
- // Inline cash panel (注资/提款), hidden until the header button is pressed.
1664
- const [cashOpen, setCashOpen] = useState(false)
1665
- const [cashSide, setCashSide] = useState('deposit')
1666
- const [cashAmount, setCashAmount] = useState('')
1667
- const [cashFlow, setCashFlow] = useState([])
1668
- const submitting = useRef(false)
1669
- const placeKey = useRef({ key: '', id: '' })
1670
- const [searchQuery, setSearchQuery] = useState('')
1671
- const [searching, setSearching] = useState(false)
1672
- const [contracts, setContracts] = useState(null)
1673
- const [contractNotice, setContractNotice] = useState('')
1674
- const [contract, setContract] = useState(null)
1675
- const [quote, setQuote] = useState(null)
1676
- const [quoteNotice, setQuoteNotice] = useState('')
1677
- const [dataSource, setDataSource] = useState(null)
1678
- const quoteRef = useRef(null)
1679
- const lastTicketRefresh = useRef(0)
1680
- const quoteSeq = useRef(0)
1681
- const contractSeq = useRef(0)
1682
- const [preview, setPreview] = useState(null)
1683
- const [previewState, setPreviewState] = useState('idle')
1684
- const [previewError, setPreviewError] = useState('')
1685
- const [previewNonce, setPreviewNonce] = useState(0)
1686
- const [receipt, setReceipt] = useState(null)
1687
- const [form, setForm] = useState({
1688
- side: 'long', offset: 'open', type: 'market', qty: '1', limitPrice: '', price: '', note: '',
1689
- })
1690
-
1691
- const alive = useRef(true)
1692
- useEffect(() => {
1693
- alive.current = true
1694
- return () => { alive.current = false }
1695
- }, [])
1696
-
1697
- const loadAll = useCallback(async (quiet = false, reviewPeriod = period) => {
1698
- const seq = ++loadAllSeq.current
1699
- const requestedPeriod = reviewPeriod
1700
- try {
1701
- const [nextAccount, nextStatus, nextPositions, nextOrders, nextDataSource] = await Promise.all([
1702
- rpc('futures/account/get'),
1703
- rpc('futures/status'),
1704
- rpc('futures/positions'),
1705
- rpc('futures/orders'),
1706
- rpc('market/data-source'),
1707
- ])
1708
- if (!alive.current) return null
1709
- if (seq === loadAllSeq.current) {
1710
- setAccount(nextAccount)
1711
- setStatus(nextStatus)
1712
- setPositions(nextPositions)
1713
- setOrders(nextOrders)
1714
- setDataSource(nextDataSource)
1715
- if (!quiet) setError(null)
1716
- }
1717
- return { account: nextAccount }
1718
- } catch (cause) {
1719
- if (alive.current && seq === loadAllSeq.current) setError(errorOf(cause))
1720
- return null
1721
- }
1722
- }, [])
1723
-
1724
- useEffect(() => { loadAll() }, [loadAll])
1725
-
1726
- const loadReview = useCallback(async (key = period) => {
1727
- const seq = ++reviewSeq.current
1728
- try {
1729
- const [next, nextCash] = await Promise.all([
1730
- rpc('futures/review', { period: key }),
1731
- rpc('futures/cash/flow'),
1732
- ])
1733
- if (alive.current && seq === reviewSeq.current && key === periodRef.current) {
1734
- setReview(next)
1735
- setCashFlow(nextCash)
1736
- }
1737
- } catch (cause) {
1738
- if (alive.current && seq === reviewSeq.current && key === periodRef.current) setError(errorOf(cause))
1739
- }
1740
- }, [period])
1741
-
1742
- useEffect(() => {
1743
- if (tab === 'review') void loadReview()
1744
- }, [tab, loadReview])
1745
-
1746
- const fetchQuote = useCallback(async symbol => {
1747
- const seq = ++quoteSeq.current
1748
- try {
1749
- const result = await rpc('futures/quote', { symbols: [symbol] })
1750
- // A slower quote for a previously selected contract must not paint
1751
- // over the one the user is looking at now.
1752
- if (!alive.current || seq !== quoteSeq.current) return
1753
- const nextQuote = result.quotes[0] ?? null
1754
- setQuote(nextQuote)
1755
- setQuoteNotice(nextQuote === null ? (result.notice ?? '取不到行情,可手填参考价') : (result.notice ?? ''))
1756
- } catch {
1757
- if (!alive.current || seq !== quoteSeq.current) return
1758
- setQuote(null)
1759
- setQuoteNotice('取不到行情,可手填参考价')
1760
- }
1761
- }, [])
1762
-
1763
- // The host scheduler settles; this is the visible-panel extra trigger.
1764
- const poll = useCallback(async () => {
1765
- try {
1766
- const tick = await rpc('futures/tick')
1767
- if (!alive.current) return
1768
- if (tick.filled.length > 0) setNotice(`成交 ${tick.filled.length} 笔`)
1769
- if (tick.notices.length > 0) setNotice(tick.notices.join(';'))
1770
- await loadAll(true)
1771
- if (alive.current && tab === 'review') await loadReview(periodRef.current)
1772
- // Keep the selected contract's price and estimate moving while the
1773
- // panel is open; without this the ticket showed the selection price
1774
- // until the next edit. With no quote (free tier or an outage) retry
1775
- // slowly instead of every beat.
1776
- if (!alive.current || contract === null) return
1777
- if (Date.now() - lastTicketRefresh.current >= (quoteRef.current === null ? 300_000 : 5_000)) {
1778
- lastTicketRefresh.current = Date.now()
1779
- void fetchQuote(contract.symbol)
1780
- setPreviewNonce(value => value + 1)
1781
- }
1782
- } catch {
1783
- // Polling failures stay silent; the manual refresh shows the error.
1784
- }
1785
- }, [loadAll, contract, fetchQuote, tab, period, loadReview])
1786
-
1787
- useEffect(() => {
1788
- const timer = setInterval(() => {
1789
- if (document.visibilityState === 'visible') poll()
1790
- }, 5000)
1791
- return () => clearInterval(timer)
1792
- }, [poll])
1793
-
1794
- const searchContracts = useCallback(async (refresh = false) => {
1795
- const seq = ++contractSeq.current
1796
- setSearching(true)
1797
- try {
1798
- const payload = { limit: 20 }
1799
- if (searchQuery.trim() !== '') payload.query = searchQuery.trim()
1800
- if (refresh) payload.refresh = true
1801
- const result = await rpc('futures/contracts', payload)
1802
- if (!alive.current || seq !== contractSeq.current) return
1803
- setContracts(result.contracts ?? [])
1804
- setContractNotice(result.notice ?? '')
1805
- } catch (cause) {
1806
- if (alive.current && seq === contractSeq.current) setError(errorOf(cause))
1807
- } finally {
1808
- if (alive.current && seq === contractSeq.current) setSearching(false)
1809
- }
1810
- }, [searchQuery])
1811
-
1812
- const selectContract = useCallback(next => {
1813
- setContract(next)
1814
- setContracts(null)
1815
- setQuote(null)
1816
- setQuoteNotice('')
1817
- setPreview(null)
1818
- setPreviewError('')
1819
- setPreviewNonce(value => value + 1)
1820
- void fetchQuote(next.symbol)
1821
- }, [fetchQuote])
1822
-
1823
- /** Closing from a book only fills the ticket; the user still confirms. */
1824
- const selectPosition = useCallback(position => {
1825
- setContract({
1826
- symbol: position.symbol,
1827
- name: position.name,
1828
- multiplier: position.multiplier,
1829
- marginRate: position.marginRate,
1830
- deListDate: position.deListDate,
1831
- })
1832
- setQuote(null)
1833
- setQuoteNotice('')
1834
- setPreview(null)
1835
- setForm(prev => ({ ...prev, side: position.side, offset: 'close', type: 'market', qty: String(position.qty) }))
1836
- setTab('trade')
1837
- setPreviewNonce(value => value + 1)
1838
- void fetchQuote(position.symbol)
1839
- }, [fetchQuote])
1840
-
1841
- const futuresDraft = useCallback(() => ({
1842
- symbol: contract === null ? '' : contract.symbol,
1843
- side: form.side,
1844
- offset: form.offset,
1845
- type: form.type,
1846
- qty: Number(form.qty),
1847
- limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
1848
- // Manual fallback only for a market close, per the contract's draft shape.
1849
- price: form.type === 'market' && form.offset === 'close' && form.price !== '' ? Number(form.price) : undefined,
1850
- note: form.note.trim() === '' ? undefined : form.note.trim(),
1851
- }), [contract, form])
1852
-
1853
- const previewDraft = useCallback(() => contract === null ? null : {
1854
- symbol: contract.symbol,
1855
- side: form.side,
1856
- offset: form.offset,
1857
- type: form.type,
1858
- qty: Number(form.qty),
1859
- limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
1860
- price: form.type === 'market' && form.offset === 'close' && form.price !== '' ? Number(form.price) : undefined,
1861
- }, [
1862
- contract, form.side, form.offset, form.type, form.qty, form.limitPrice, form.price,
1863
- ])
1864
-
1865
- const previewSeq = useRef(0)
1866
- useEffect(() => {
1867
- previewSeq.current += 1
1868
- const seq = previewSeq.current
1869
- const draft = previewDraft()
1870
- if (draft === null) {
1871
- setPreview(null)
1872
- setPreviewState('idle')
1873
- setPreviewError('')
1874
- return
1875
- }
1876
- if (!Number.isInteger(draft.qty) || draft.qty <= 0 || (draft.type === 'limit' && !(draft.limitPrice > 0))) {
1877
- setPreview(null)
1878
- setPreviewState('idle')
1879
- setPreviewError('')
1880
- return
1881
- }
1882
- setPreviewState('loading')
1883
- const timer = setTimeout(() => {
1884
- rpc('futures/preview', draft)
1885
- .then(result => {
1886
- if (!alive.current || seq !== previewSeq.current) return
1887
- setPreview(result)
1888
- setPreviewError('')
1889
- setPreviewState('ready')
1890
- })
1891
- .catch(cause => {
1892
- if (!alive.current || seq !== previewSeq.current) return
1893
- setPreviewError(errorOf(cause).text)
1894
- setPreviewState('error')
1895
- })
1896
- }, 300)
1897
- return () => clearTimeout(timer)
1898
- }, [previewDraft, previewNonce])
1899
-
1900
- const pending = useMemo(() => orders.filter(order => order.status === 'pending'), [orders])
1901
- const history = useMemo(() => orders.filter(order => order.status !== 'pending'), [orders])
1902
-
1903
- const previewHint = useMemo(() => {
1904
- if (contract === null) return '搜索并选择合约后自动计算'
1905
- if (!Number.isInteger(Number(form.qty)) || Number(form.qty) <= 0) return '填写手数后自动计算'
1906
- if (form.type === 'limit' && !(Number(form.limitPrice) > 0)) return '填写限价后自动计算'
1907
- return ''
1908
- }, [contract, form.qty, form.type, form.limitPrice])
1909
-
1910
- const submitReason = useMemo(() => {
1911
- if (account === null) return '加载账户中'
1912
- if (account.blocked === true) return '账户已锁定'
1913
- if (contract === null) return '选择合约'
1914
- if (String(form.qty).trim() === '') return '填写手数'
1915
- const qty = Number(form.qty)
1916
- if (!Number.isInteger(qty) || qty <= 0) return '手数需为正整数'
1917
- if (form.type === 'limit' && !(Number(form.limitPrice) > 0)) return '填写限价'
1918
- if (form.type === 'limit' && preview !== null && preview.limit !== undefined) {
1919
- const price = Number(form.limitPrice)
1920
- if (price < preview.limit.lower || price > preview.limit.upper) return '价格超出涨跌停'
1921
- }
1922
- if (status !== null && status.canSubmit === false) return '当前时段不可下单'
1923
- if (form.type === 'market' && status !== null && status.canMatch === false) return '当前时段不能市价成交'
1924
- const hasQuote = quote !== null
1925
- || (quoteNotice === '' && preview !== null && preview.quote !== undefined && preview.quote !== null)
1926
- if (form.type === 'market' && !hasQuote && !(form.offset === 'close' && Number(form.price) > 0)) return '等待行情'
1927
- if (form.offset === 'close' && preview !== null && qty > preview.availableCloseQty) return '可平手数不足'
1928
- if (form.offset === 'open' && preview !== null && preview.cashAfterCents < 0) return '保证金不足'
1929
- return ''
1930
- }, [account, contract, form, status, preview, quote, quoteNotice])
1931
-
1932
- const doSubmit = useCallback(async () => {
1933
- if (submitReason !== '' || submitting.current) return
1934
- submitting.current = true
1935
- setBusy(true)
1936
- setReceipt(null)
1937
- try {
1938
- const current = futuresDraft()
1939
- const key = JSON.stringify(current)
1940
- if (placeKey.current.key !== key) {
1941
- placeKey.current = {
1942
- key,
1943
- id: typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `req-${Date.now()}-${Math.random().toString(36).slice(2)}`,
1944
- }
1945
- }
1946
- const order = await rpc('futures/order', { draft: current, requestId: placeKey.current.id })
1947
- const snapshot = await loadAll(true)
1948
- setReceipt({ order, cash: snapshot === null ? undefined : snapshot.account.cash })
1949
- placeKey.current = { key: '', id: '' }
1950
- setPreviewNonce(value => value + 1)
1951
- } catch (cause) {
1952
- setReceipt({ failure: errorOf(cause) })
1953
- } finally {
1954
- submitting.current = false
1955
- setBusy(false)
1956
- }
1957
- }, [submitReason, futuresDraft, loadAll])
1958
-
1959
- const cancel = useCallback(async orderId => {
1960
- setBusy(true)
1961
- try {
1962
- await rpc('futures/cancel', { orderId })
1963
- await loadAll(true)
1964
- } catch (cause) {
1965
- if (cause && (cause.code === 'ORDER_NOT_PENDING' || cause.code === 'ORDER_NOT_FOUND')) {
1966
- setNotice('订单已结束,列表已刷新')
1967
- await loadAll(true)
1968
- } else {
1969
- setError(errorOf(cause))
1970
- }
1971
- } finally {
1972
- setBusy(false)
1973
- }
1974
- }, [loadAll])
1975
-
1976
- const copyLedgerPath = useCallback(async () => {
1977
- const path = account !== null ? account.ledgerPath : undefined
1978
- if (path === undefined) return
1979
- const copied = typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText
1980
- ? await navigator.clipboard.writeText(path).then(() => true, () => false)
1981
- : false
1982
- setNotice(copied ? `已复制账本路径:${path}` : `账本路径:${path}`)
1983
- }, [account])
1984
-
1985
- const exportLedger = useCallback(async () => {
1986
- try {
1987
- const result = await rpc('futures/account/export')
1988
- if (!result.exists || !result.content) {
1989
- setNotice(result.notice ?? '账本文件尚未创建')
1990
- return
1991
- }
1992
- if (typeof document !== 'undefined' && typeof URL !== 'undefined' && typeof Blob !== 'undefined') {
1993
- const blob = new Blob([result.content], { type: 'application/x-ndjson' })
1994
- const url = URL.createObjectURL(blob)
1995
- const link = document.createElement('a')
1996
- link.href = url
1997
- link.download = 'futures-events.jsonl'
1998
- link.click()
1999
- URL.revokeObjectURL(url)
2000
- }
2001
- setNotice(`已导出期货账本:${result.path}`)
2002
- } catch (cause) {
2003
- setError(errorOf(cause))
2004
- }
2005
- }, [])
2006
-
2007
- const refreshAll = useCallback(async () => {
2008
- setBusy(true)
2009
- try {
2010
- await loadAll()
2011
- if (tab === 'review') await loadReview()
2012
- if (contract !== null) void fetchQuote(contract.symbol)
2013
- setPreviewNonce(value => value + 1)
2014
- } finally {
2015
- setBusy(false)
2016
- }
2017
- }, [loadAll, loadReview, tab, contract, fetchQuote])
2018
-
2019
- const reset = useCallback(async () => {
2020
- if (!window.confirm('重置期货模拟账户?持仓与挂单会清空;当前账本会先备份,可在备份里找回。')) return
2021
- setBusy(true)
2022
- try {
2023
- setAccount(await rpc('futures/account/reset', { confirm: true }))
2024
- setPreview(null)
2025
- setReceipt(null)
2026
- await loadAll(true)
2027
- if (tab === 'review') await loadReview()
2028
- setPreviewNonce(value => value + 1)
2029
- setNotice('期货账户已重置')
2030
- } catch (cause) {
2031
- setError(errorOf(cause))
2032
- } finally {
2033
- setBusy(false)
2034
- }
2035
- }, [loadAll, loadReview, tab])
2036
-
2037
- /** 注资/提款只动可用资金;保证金已被持仓占用,提款上限就是可用资金。 */
2038
- const moveCash = useCallback(async () => {
2039
- const cents = cashAmountCents(cashAmount)
2040
- if (cents === null) return
2041
- const amount = cents / 100
2042
- const depositing = cashSide === 'deposit'
2043
- setBusy(true)
2044
- try {
2045
- setAccount(await rpc(depositing ? 'futures/account/deposit' : 'futures/account/withdraw', { amount }))
2046
- await loadAll(true)
2047
- if (tab === 'review') await loadReview(periodRef.current)
2048
- setPreviewNonce(value => value + 1)
2049
- setCashAmount('')
2050
- setCashOpen(false)
2051
- setError(null)
2052
- setNotice(depositing ? `已注资 ${money(amount)}` : `已提款 ${money(amount)}`)
2053
- } catch (cause) {
2054
- setError(errorOf(cause))
2055
- } finally {
2056
- setBusy(false)
2057
- }
2058
- }, [cashAmount, cashSide, loadAll, loadReview, tab])
2059
-
2060
- if (account === null) {
2061
- return h('div', { className: 'pt-inner' },
2062
- h('div', { className: 'pt-head' },
2063
- h('div', null, h('h3', { className: 'pt-title' }, '模拟交易'), h('div', { className: 'pt-sub' }, '期货账户')),
2064
- h('div', { className: 'pt-row' }, accountSwitch,
2065
- h('button', { className: 'pt-btn', onClick: () => { setError(null); void loadAll() } }, '重试'),
2066
- ),
2067
- ),
2068
- error
2069
- ? h('div', { className: 'pt-error', title: error.detail || undefined }, error.text)
2070
- : h('div', { className: 'pt-empty' }, '加载期货模拟交易…'),
2071
- )
2072
- }
2073
-
2074
- // Amber from the configured warning line (80% by default), never hard-coded.
2075
- const riskWarn = isFiniteNumber(account.riskRatio) && account.riskRatio >= (account.settings?.warnRiskRatio ?? 0.8)
2076
- const displayQuote = quote ?? (quoteNotice === '' && preview !== null ? preview.quote ?? null : null)
2077
- quoteRef.current = displayQuote
2078
- const tabBar = h('div', { className: 'pt-tabs' }, FUTURES_TABS.map(key => {
2079
- const badge = key === 'positions' ? ` ${positions.length}` : key === 'orders' ? ` ${pending.length}` : ''
2080
- return h('button', {
2081
- key, className: 'pt-tab', 'data-active': tab === key, onClick: () => setTab(key),
2082
- }, `${FUTURES_TAB_LABEL[key]}${badge}`)
2083
- }))
2084
- const tabBody = tab === 'trade'
2085
- ? h(FuturesTradeTab, {
2086
- account, searchQuery, setSearchQuery, searchContracts, searching, contracts, contractNotice,
2087
- contract, selectContract, form, setForm, quote: displayQuote, quoteNotice,
2088
- preview, previewState, previewError, previewHint,
2089
- busy, onSubmit: doSubmit, submitReason, receipt,
2090
- positions, pending, onCancel: cancel, onClose: selectPosition,
2091
- })
2092
- : tab === 'positions'
2093
- ? h(FuturesPositionsTab, { positions, onClose: selectPosition })
2094
- : tab === 'orders'
2095
- ? h(FuturesOrdersTab, { pending, history, busy, onCancel: cancel })
2096
- : h(FuturesReviewTab, {
2097
- review, period,
2098
- setPeriod: key => setPeriod(key),
2099
- cashFlow,
2100
- })
2101
-
2102
- return h('div', { className: 'pt-inner' },
2103
- h('div', { className: 'pt-head' },
2104
- h('div', null,
2105
- h('h3', { className: 'pt-title' }, '模拟交易'),
2106
- h('div', { className: 'pt-sub' },
2107
- `期货 · ${tradeDateText(account.tradeDate, status?.calendar?.source === 'fallback')} · ${status ? FUTURES_PHASE_TEXT[status.phase] : '时段未知'} · 初始 ${money(account.initialCash)}${isFiniteNumber(account.netCashFlow) && account.netCashFlow !== 0 ? ` · 净入金 ${signed(account.netCashFlow)}` : ''} · ${account.blocked ? '已锁定' : '运行中'}`,
2108
- status && !status.canSubmit ? h('span', { className: 'pt-note' }, '(当前时段只读)') : null,
2109
- status !== null && status !== undefined ? calendarNote(status.calendar) : null,
2110
- ),
2111
- ),
2112
- h('div', { className: 'pt-row' },
2113
- accountSwitch,
2114
- h(DataSourceBadge, { status: dataSource }),
2115
- h('button', { className: 'pt-btn', onClick: refreshAll, disabled: busy }, '刷新'),
2116
- h('button', {
2117
- className: 'pt-btn', 'data-active': cashOpen, disabled: busy,
2118
- onClick: () => {
2119
- setError(null)
2120
- setCashOpen(value => !value)
2121
- },
2122
- }, '资金'),
2123
- h('button', { className: 'pt-btn pt-btn-danger', onClick: reset, disabled: busy }, '重置'),
2124
- h(FeedbackLink),
2125
- ),
2126
- ),
2127
- h(DataBanner, { status: dataSource, onRetry: refreshAll }),
2128
- cashOpen ? h(CashMovePanel, {
2129
- available: account.cash,
2130
- side: cashSide,
2131
- onSide: setCashSide,
2132
- amount: cashAmount,
2133
- onAmount: setCashAmount,
2134
- busy,
2135
- onCancel: () => {
2136
- setCashOpen(false)
2137
- setCashAmount('')
2138
- },
2139
- onSubmit: moveCash,
2140
- }) : null,
2141
- account.blocked ? h('div', { className: 'pt-blocked' },
2142
- h('div', { className: 'pt-blocked-text' },
2143
- h('div', null, '期货账本校验失败,账户已锁定。'),
2144
- account.blockedReason ? h('div', { className: 'pt-blocked-detail', title: account.blockedReason }, `原因:${account.blockedReason}`) : null,
2145
- account.ledgerPath ? h('div', { className: 'pt-blocked-detail', title: account.ledgerPath }, `账本:${account.ledgerPath}`) : null,
2146
- h('div', { className: 'pt-blocked-hint' }, '可让 AI 助手用 paper_ledger 从备份恢复;重置会先备份。'),
2147
- ),
2148
- h('div', { className: 'pt-row' },
2149
- h('button', { className: 'pt-btn', onClick: exportLedger, disabled: busy }, '导出账本'),
2150
- account.ledgerPath ? h('button', { className: 'pt-btn', onClick: copyLedgerPath, disabled: busy }, '复制路径') : null,
2151
- ),
2152
- ) : null,
2153
- h('div', { className: 'pt-stats' },
2154
- statCell('总权益', money(account.equity)),
2155
- statCell('可用资金', money(account.cash)),
2156
- statCell('保证金占用', money(account.margin)),
2157
- statCell('风险度', pct(account.riskRatio), riskWarn ? 'pt-risk-high' : ''),
2158
- ),
2159
- error ? h('div', { className: 'pt-error', title: error.detail || undefined }, error.text) : null,
2160
- notice ? h('div', { className: 'pt-note' }, notice) : null,
2161
- tab === 'trade'
2162
- ? h('div', { className: 'pt-workspace pt-workspace-futures' },
2163
- h('div', { className: 'pt-main' }, tabBar, h('div', { className: 'pt-tab-body' }, tabBody)),
2164
- h(FuturesContractRail, {
2165
- contract,
2166
- quote: displayQuote,
2167
- limit: preview !== null ? preview.limit ?? null : null,
2168
- }),
2169
- )
2170
- : h('div', { className: 'pt-main' }, tabBar, h('div', { className: 'pt-tab-body' }, tabBody)),
2171
- )
2172
- }
2173
-
2174
- /** Futures ticket: search picks the contract, direction is open/close × long/short. */
2175
- function FuturesTradeTab({
2176
- account, searchQuery, setSearchQuery, searchContracts, searching, contracts, contractNotice,
2177
- contract, selectContract, form, setForm, quote, quoteNotice, preview, previewState, previewError, previewHint,
2178
- busy, onSubmit, submitReason, receipt, positions, pending, onCancel, onClose,
2179
- }) {
2180
- const [book, setBook] = useState(() => (positions.length === 0 && pending.length > 0 ? 'orders' : 'positions'))
2181
- const emptyPreview = previewHint !== ''
2182
- ? previewHint
2183
- : previewState === 'loading' ? '计算中…' : previewError !== '' ? previewError : '计算中…'
2184
- return h('div', { className: 'pt-trade' },
2185
- h('div', { className: 'pt-card pt-ticket-card' },
2186
- h('div', { className: 'pt-row' },
2187
- h('input', {
2188
- className: 'pt-input', style: { flex: 1, minWidth: 180 }, value: searchQuery,
2189
- placeholder: '合约代码/品种/中文名,例如 rb2611',
2190
- onChange: event => setSearchQuery(event.target.value),
2191
- onKeyDown: event => { if (event.key === 'Enter') void searchContracts() },
2192
- }),
2193
- h('button', { className: 'pt-btn', onClick: () => searchContracts(), disabled: searching }, searching ? '搜索中…' : '搜索'),
2194
- h('button', { className: 'pt-btn', onClick: () => searchContracts(true), disabled: searching, title: '重新拉取合约列表' }, '刷新合约'),
2195
- ),
2196
- contracts !== null && contracts.length > 0 && contractNotice !== ''
2197
- ? h('div', { className: 'pt-note' }, contractNotice)
2198
- : null,
2199
- contracts === null
2200
- ? h('div', { className: 'pt-note' }, contract !== null ? `已选 ${contract.symbol} ${contract.name ?? ''}` : '输入代码搜索合约')
2201
- : contracts.length === 0
2202
- ? h('div', { className: 'pt-empty' }, contractNotice || '没有匹配的合约')
2203
- : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4, marginTop: 8, maxHeight: 150, overflow: 'auto' } },
2204
- contracts.map(item => h('button', {
2205
- key: item.symbol, className: 'pt-btn', 'data-active': contract !== null && contract.symbol === item.symbol,
2206
- style: { textAlign: 'left' },
2207
- onClick: () => selectContract(item),
2208
- }, `${item.symbol} ${item.name ?? ''}`)),
2209
- ),
2210
- h('div', { className: 'pt-ticket' },
2211
- h('div', { className: 'pt-ticket-form' },
2212
- h(Field, { label: '合约', span: true },
2213
- h('div', { className: 'pt-quote' },
2214
- contract !== null
2215
- ? h('span', null, `${contract.symbol} ${contract.name ?? ''}`)
2216
- : h('span', { className: 'pt-note' }, '尚未选择合约'),
2217
- quote !== null ? h('span', null, `最新 ${money(quote.last)}`) : null,
2218
- quote !== null ? h('span', { className: 'pt-note' }, quoteUpdateText(quote)) : null,
2219
- quoteNotice !== '' ? h('span', { className: 'pt-note' }, quoteNotice) : null,
2220
- ),
2221
- ),
2222
- h(Field, { label: '方向', span: true },
2223
- h('div', { className: 'pt-seg' },
2224
- [['long', 'open', '开多'], ['short', 'open', '开空'], ['long', 'close', '平多'], ['short', 'close', '平空']].map(([side, offset, label]) =>
2225
- h('button', {
2226
- key: `${side}_${offset}`, 'data-active': form.side === side && form.offset === offset,
2227
- onClick: () => setForm(prev => ({ ...prev, side, offset })),
2228
- }, label),
2229
- ),
2230
- ),
2231
- ),
2232
- h(Field, { label: '类型' }, h('div', { className: 'pt-seg' },
2233
- [['market', '市价'], ['limit', '限价']].map(([key, label]) =>
2234
- h('button', { key, 'data-active': form.type === key, onClick: () => setForm(prev => ({ ...prev, type: key })) }, label)),
2235
- )),
2236
- h(Field, { label: '手数' }, h(DebouncedNumber, {
2237
- value: form.qty, min: 1, step: 1,
2238
- onChange: value => setForm(prev => ({ ...prev, qty: value })),
2239
- })),
2240
- form.type === 'limit'
2241
- ? h(Field, { label: '限价' }, h(DebouncedNumber, {
2242
- value: form.limitPrice, min: 0, step: 0.01,
2243
- onChange: value => setForm(prev => ({ ...prev, limitPrice: value })),
2244
- }))
2245
- : form.offset === 'close'
2246
- ? h(Field, { label: '参考价(可选)' }, h(DebouncedNumber, {
2247
- value: form.price, min: 0, step: 0.01,
2248
- onChange: value => setForm(prev => ({ ...prev, price: value })),
2249
- }))
2250
- : h(Field, { label: '价格' }, h('div', { className: 'pt-note', style: { padding: '6px 0' } }, '按最新价成交')),
2251
- h(Field, { label: '备注(复盘用)', span: true }, h('input', {
2252
- className: 'pt-input', value: form.note, maxLength: 120,
2253
- onChange: event => setForm(prev => ({ ...prev, note: event.target.value })),
2254
- })),
2255
- ),
2256
- h('div', { className: 'pt-preview-pane' },
2257
- h('div', { className: 'pt-card-title', style: { marginBottom: 6 } }, '预览'),
2258
- preview !== null ? (preview.price > 0 ? h('div', { className: 'pt-preview' },
2259
- previewRow('预估成交价', money(preview.price)),
2260
- previewRow('合约价值', cents(preview.amountCents)),
2261
- previewRow('保证金', cents(preview.marginCents)),
2262
- previewRow('手续费', cents(preview.feesCents)),
2263
- previewRow('成交后现金', cents(preview.cashAfterCents), preview.cashAfterCents < 0 ? 'pt-risk-high' : undefined),
2264
- previewRow('风险度', pct(preview.riskRatioAfter), preview.riskRatioAfter >= (account.settings?.warnRiskRatio ?? 0.8) ? 'pt-risk-high' : undefined),
2265
- form.offset === 'open'
2266
- ? previewRow('最多可开', `${count(preview.maxOpenQty)} 手`)
2267
- : previewRow('平仓可平', `${count(preview.availableCloseQty)} 手`),
2268
- previewRow('涨停', preview.limit ? money(preview.limit.upper) : '—'),
2269
- previewRow('跌停', preview.limit ? money(preview.limit.lower) : '—'),
2270
- previewState === 'loading' ? h('div', { className: 'pt-note' }, '计算中…') : null,
2271
- preview.warnings.length > 0 ? h('div', { className: 'pt-warn' }, preview.warnings.join(';')) : null,
2272
- previewState === 'error' && previewError !== '' ? h('div', { className: 'pt-warn' }, previewError) : null,
2273
- ) : h('div', { className: 'pt-empty' }, '没有可用行情,暂不可开仓')) : h('div', { className: 'pt-empty' }, emptyPreview),
2274
- ),
2275
- ),
2276
- h('div', { className: 'pt-ticket-foot' },
2277
- submitReason !== '' ? h('div', { className: 'pt-note' }, `不可提交:${submitReason}`) : null,
2278
- h('button', {
2279
- className: 'pt-btn pt-btn-primary pt-ticket-submit', onClick: onSubmit,
2280
- title: submitReason || undefined,
2281
- disabled: busy || submitReason !== '',
2282
- }, directionText(form.side, form.offset)),
2283
- h('div', { className: 'pt-ticket-meta' },
2284
- h('span', { className: 'pt-note' },
2285
- `可用 ${money(account.cash)} · 保证金 ${money(account.margin)} · 风险度 ${pct(account.riskRatio)}`),
2286
- ),
2287
- receipt ? h(FuturesReceiptLine, { receipt }) : null,
2288
- ),
2289
- ),
2290
- h(FuturesBook, { positions, pending, book, setBook, busy, onCancel, onClose }),
2291
- )
2292
- }
2293
-
2294
- /** Persistent holdings/orders book under the futures ticket. */
2295
- function FuturesBook({ positions, pending, book, setBook, busy, onCancel, onClose }) {
2296
- const showPositions = book === 'positions'
2297
- return h('div', { className: 'pt-card pt-trade-book' },
2298
- h('div', { className: 'pt-book-head' },
2299
- h('div', { className: 'pt-seg' },
2300
- h('button', { 'data-active': showPositions, onClick: () => setBook('positions') }, `持仓 ${positions.length}`),
2301
- h('button', { 'data-active': !showPositions, onClick: () => setBook('orders') }, `挂单 ${pending.length}`),
2302
- ),
2303
- h('div', { className: 'pt-note' }, showPositions ? '收盘按结算价盯市' : '未成交委托,可随时撤单'),
2304
- ),
2305
- h('div', { className: 'pt-book-scroll' },
2306
- showPositions
2307
- ? (positions.length === 0
2308
- ? h('div', { className: 'pt-empty pt-book-empty' }, '无持仓 · 成交后自动显示')
2309
- : h(Table, null,
2310
- h('thead', null, h('tr', null,
2311
- ['合约', '方向', '手数', '今仓', '均价', '最新价', '浮盈亏'].map(label => h('th', { key: label }, label)),
2312
- h('th', null, '操作'),
2313
- )),
2314
- h('tbody', null, positions.map(position => h('tr', { key: `${position.symbol}-${position.side}` },
2315
- h('td', null, position.symbol),
2316
- h('td', null, FUTURES_SIDE_TEXT[position.side] ?? position.side),
2317
- h('td', null, count(position.qty)),
2318
- h('td', null, count(position.todayQty)),
2319
- h('td', null, money(position.avgPrice)),
2320
- h('td', null, money(position.lastPrice)),
2321
- h('td', { className: tone(position.unrealizedPnlCents ?? 0) }, cents(position.unrealizedPnlCents)),
2322
- h('td', null, h('button', {
2323
- className: 'pt-btn', onClick: () => onClose(position), disabled: !(position.qty > 0),
2324
- }, '平仓')),
2325
- ))),
2326
- ))
2327
- : (pending.length === 0
2328
- ? h('div', { className: 'pt-empty pt-book-empty' }, '无挂单 · 未成交的限价委托会停在这里')
2329
- : h(Table, null,
2330
- h('thead', null, h('tr', null,
2331
- ['合约', '方向', '类型', '手数', '限价', '状态'].map(label => h('th', { key: label }, label)),
2332
- h('th', null, '操作'),
2333
- )),
2334
- h('tbody', null, pending.map(order => h('tr', { key: order.id },
2335
- h('td', null, order.symbol),
2336
- h('td', null, directionText(order.side, order.offset)),
2337
- h('td', null, orderTypeText(order.type)),
2338
- h('td', null, count(order.qty)),
2339
- h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
2340
- h('td', null, FUTURES_STATUS_TEXT[order.status] ?? order.status),
2341
- h('td', null, h('button', { className: 'pt-btn', onClick: () => onCancel(order.id), disabled: busy }, '撤单')),
2342
- ))),
2343
- )),
2344
- ),
2345
- )
2346
- }
2347
-
2348
- function FuturesReceiptLine({ receipt }) {
2349
- if (receipt.failure !== undefined) {
2350
- return h('div', { className: 'pt-receipt', 'data-state': 'rejected', title: receipt.failure.detail || undefined },
2351
- `拒绝:${receipt.failure.text}`,
2352
- )
2353
- }
2354
- const { order, cash } = receipt
2355
- const direction = directionText(order.side, order.offset)
2356
- if (order.status === 'rejected') {
2357
- return h('div', { className: 'pt-receipt', 'data-state': 'rejected', title: order.reason || undefined },
2358
- `拒绝:${direction} ${order.symbol} ${count(order.qty)} 手 · ${reasonText(order.reason, 'futures') || '未通过风控'}`,
2359
- )
2360
- }
2361
- if (order.status === 'filled') {
2362
- return h('div', { className: 'pt-receipt', 'data-state': 'filled', title: order.id },
2363
- `成交:${direction} ${order.symbol} ${count(order.qty)} 手 · 价 ${money(order.fillPrice)} · 保证金 ${cents(order.marginCents)} · 费用 ${cents(order.feesCents)} · 成交后现金 ${money(cash)} · 单 ${order.id}`,
2364
- )
2365
- }
2366
- return h('div', { className: 'pt-receipt', 'data-state': 'resting', title: order.id },
2367
- `挂单:${direction} ${order.symbol} ${count(order.qty)} 手${order.limitPrice === undefined ? '' : ` @ ${money(order.limitPrice)}`} · 现价未穿越,成交前一直挂单 · 单 ${order.id}`,
2368
- )
2369
- }
2370
-
2371
- function FuturesPositionsTab({ positions, onClose }) {
2372
- if (positions.length === 0) return h('div', { className: 'pt-empty' }, '无持仓 · 开仓成交后自动显示')
2373
- return h(Table, null,
2374
- h('thead', null, h('tr', null,
2375
- ['合约', '方向', '手数', '今仓', '均价', '最新价', '浮盈亏', '保证金', '到期日'].map(label => h('th', { key: label }, label)),
2376
- h('th', null, '操作'),
2377
- )),
2378
- h('tbody', null, positions.map(position => h('tr', { key: `${position.symbol}-${position.side}` },
2379
- h('td', null, position.symbol),
2380
- h('td', null, FUTURES_SIDE_TEXT[position.side] ?? position.side),
2381
- h('td', null, count(position.qty)),
2382
- h('td', null, count(position.todayQty)),
2383
- h('td', null, money(position.avgPrice)),
2384
- h('td', null, money(position.lastPrice)),
2385
- h('td', { className: tone(position.unrealizedPnlCents ?? 0) }, cents(position.unrealizedPnlCents)),
2386
- h('td', null, cents(position.marginCents)),
2387
- h('td', null, position.deListDate ?? '—'),
2388
- h('td', null, h('button', { className: 'pt-btn', onClick: () => onClose(position) }, '平仓')),
2389
- ))),
2390
- )
2391
- }
2392
-
2393
- function FuturesOrdersTab({ pending, history, busy, onCancel }) {
2394
- return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } },
2395
- h('div', null,
2396
- h('div', { className: 'pt-sub' }, '挂单'),
2397
- pending.length === 0 ? h('div', { className: 'pt-empty' }, '无挂单') : h(Table, null,
2398
- h('thead', null, h('tr', null,
2399
- ['合约', '方向', '类型', '手数', '限价', '状态', '备注', '操作'].map(label => h('th', { key: label }, label)),
2400
- )),
2401
- h('tbody', null, pending.map(order => h('tr', { key: order.id },
2402
- h('td', null, order.symbol),
2403
- h('td', null, directionText(order.side, order.offset)),
2404
- h('td', null, orderTypeText(order.type)),
2405
- h('td', null, count(order.qty)),
2406
- h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
2407
- h('td', null, FUTURES_STATUS_TEXT[order.status] ?? order.status),
2408
- h('td', { title: order.note ?? undefined }, order.note === undefined ? '' : h('span', { className: 'pt-note-cell' }, order.note)),
2409
- h('td', null, h('button', { className: 'pt-btn', onClick: () => onCancel(order.id), disabled: busy }, '撤单')),
2410
- ))),
2411
- ),
2412
- pending.some(order => order.status === 'queued')
2413
- ? h('div', { className: 'pt-note' }, '「排队」:当前时段不撮合,下一交易时段会尝试成交,可随时撤单。')
2414
- : null,
2415
- ),
2416
- h('div', null,
2417
- h('div', { className: 'pt-sub' }, '历史'),
2418
- history.length === 0 ? h('div', { className: 'pt-empty' }, '无历史订单') : h(Table, null,
2419
- h('thead', null, h('tr', null,
2420
- ['时间', '合约', '方向', '类型', '手数', '限价', '状态', '成交价', '原因', '备注'].map(label => h('th', { key: label }, label)),
2421
- )),
2422
- h('tbody', null, history.slice(0, 30).map(order => h('tr', { key: order.id },
2423
- h('td', null, dateTime(order.createdAt)),
2424
- h('td', null, order.symbol),
2425
- h('td', null, directionText(order.side, order.offset)),
2426
- h('td', null, orderTypeText(order.type)),
2427
- h('td', null, count(order.qty)),
2428
- h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
2429
- h('td', null, FUTURES_STATUS_TEXT[order.status] ?? order.status),
2430
- h('td', null, order.fillPrice === undefined ? '—' : money(order.fillPrice)),
2431
- h('td', { title: order.reason ?? undefined }, reasonText(order.reason, 'futures')),
2432
- h('td', { title: order.note ?? undefined }, order.note === undefined ? '' : h('span', { className: 'pt-note-cell' }, order.note)),
2433
- ))),
2434
- ),
2435
- history.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${history.length} 条`) : null,
2436
- ),
2437
- )
2438
- }
2439
-
2440
- function FuturesReviewTab({ review, period, setPeriod, cashFlow }) {
2441
- return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
2442
- h('div', { className: 'pt-row' }, PERIODS.map(([key, label]) =>
2443
- h('button', { key, className: 'pt-btn', 'data-active': period === key, onClick: () => setPeriod(key) }, label),
2444
- )),
2445
- review !== null ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
2446
- h('div', { className: 'pt-stats' },
2447
- statCell('成交笔数', count(review.tradeCount)),
2448
- statCell('已实现盈亏', signed(review.realizedPnl), tone(review.realizedPnl)),
2449
- statCell('费用合计', money(review.totalFees)),
2450
- statCell('最大回撤', pct(review.maxDrawdownPct)),
2451
- ),
2452
- h('div', { className: 'pt-note' },
2453
- `开仓 ${count(review.openCount)} 笔 · 平仓 ${count(review.closeCount)} 笔 · 盈利 ${count(review.winCount)} 笔 · 亏损 ${count(review.lossCount)} 笔`),
2454
- h('div', { className: 'pt-chart-wrap' }, h(EquityChart, { points: review.equityCurve })),
2455
- h('div', null,
2456
- h('div', { className: 'pt-sub' }, '分品种统计'),
2457
- review.byProduct.length === 0 ? h('div', { className: 'pt-empty' }, '暂无成交') : h(Table, null,
2458
- h('thead', null, h('tr', null,
2459
- ['品种', '成交笔数', '已实现盈亏'].map(label => h('th', { key: label }, label)),
2460
- )),
2461
- h('tbody', null, review.byProduct.map(item => h('tr', { key: item.product },
2462
- h('td', null, String(item.product ?? '').toUpperCase()),
2463
- h('td', null, count(item.tradeCount)),
2464
- h('td', { className: tone(item.realizedPnl) }, signed(item.realizedPnl)),
2465
- ))),
2466
- ),
2467
- ),
2468
- h('div', null,
2469
- h('div', { className: 'pt-sub' }, '资金流水'),
2470
- cashFlow.length === 0 ? h('div', { className: 'pt-empty' }, '暂无流水') : h(Table, null,
2471
- h('thead', null, h('tr', null, ['时间', '类型', '金额', '余额'].map(label => h('th', { key: label }, label)))),
2472
- h('tbody', null, cashFlow.slice(-30).reverse().map((row, index) => h('tr', { key: `${row.ts}-${index}` },
2473
- h('td', null, dateTime(row.ts)),
2474
- h('td', null, FUTURES_CASH_TYPE_TEXT[row.type] ?? row.type),
2475
- h('td', { className: tone(row.amount) }, signed(row.amount)),
2476
- h('td', null, money(row.balance)),
2477
- ))),
2478
- ),
2479
- cashFlow.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${cashFlow.length} 条`) : null,
2480
- ),
2481
- ) : h('div', { className: 'pt-empty' }, '加载复盘…'),
2482
- )
2483
- }
2484
-
2485
- /** Right rail for the futures ticket: static terms plus the marked quote. */
2486
- function FuturesContractRail({ contract, quote, limit }) {
2487
- return h('aside', { className: 'pt-futures-rail', 'aria-label': '合约要素' },
2488
- h('div', { className: 'pt-card' },
2489
- h('div', { className: 'pt-card-title' }, '合约要素'),
2490
- contract === null
2491
- ? h('div', { className: 'pt-empty' }, '搜索并选择合约')
2492
- : h('div', { className: 'pt-preview' },
2493
- previewRow('合约', contract.symbol),
2494
- previewRow('名称', contract.name ?? '—'),
2495
- previewRow('交易所', contract.exchange ?? '—'),
2496
- previewRow('品种', contract.product ?? '—'),
2497
- previewRow('乘数', contract.multiplier === undefined ? '—' : count(contract.multiplier)),
2498
- previewRow('最小变动', money(contract.tickSize)),
2499
- previewRow('保证金率', pct(contract.marginRate)),
2500
- previewRow('到期日', contract.deListDate ?? '—'),
2501
- previewRow('涨停', limit === null ? '—' : money(limit.upper)),
2502
- previewRow('跌停', limit === null ? '—' : money(limit.lower)),
2503
- previewRow('最新价', quote === null ? '—' : money(quote.last),
2504
- quote !== null && quote.preSettlement !== undefined && quote.last !== quote.preSettlement
2505
- ? (quote.last > quote.preSettlement ? 'pt-up' : 'pt-down')
2506
- : undefined),
2507
- previewRow('昨结', quote === null || quote.preSettlement === undefined ? '—' : money(quote.preSettlement)),
2508
- ),
2509
- ),
2510
- )
2511
- }
2512
-
2513
- /* ---------------------------------------------------------- dashboard -- */
2514
-
2515
- /**
2516
- * Top-level shell: the account switch lives above both dashboards, so the
2517
- * stock half keeps its exact layout and the futures half mounts on demand.
2518
- */
2519
- function Dashboard({ renderSlot } = {}) {
2520
- const [accountMode, setAccountMode] = useState('stock')
2521
- const accountSwitch = h(AccountSwitch, { mode: accountMode, onChange: setAccountMode })
2522
- return h('div', { className: 'pt-root' },
2523
- h('style', null, CSS),
2524
- accountMode === 'futures'
2525
- ? h(FuturesDashboard, { accountSwitch })
2526
- : h(StockDashboard, { renderSlot, accountSwitch }),
2527
- )
2528
- }
2529
-
2530
- function StockDashboard({ renderSlot, accountSwitch }) {
2531
- const [account, setAccount] = useState(null)
2532
- const [orders, setOrders] = useState([])
2533
- const [trades, setTrades] = useState([])
2534
- const [review, setReview] = useState(null)
2535
- const [period, setPeriod] = useState('30d')
2536
- const periodRef = useRef(period)
2537
- useEffect(() => { periodRef.current = period }, [period])
2538
- const [tab, setTab] = useState('trade')
2539
- const [error, setError] = useState(null)
2540
- const [notice, setNotice] = useState('')
2541
- const [busy, setBusy] = useState(false)
2542
- const [resetNonce, setResetNonce] = useState(0)
2543
- // Inline cash panel (注资/提款), hidden until the header button is pressed.
2544
- const [cashOpen, setCashOpen] = useState(false)
2545
- const [cashSide, setCashSide] = useState('deposit')
2546
- const [cashAmount, setCashAmount] = useState('')
2547
- // Inline reset strip: picking the starting cash is part of the reset, so
2548
- // it replaces the browser confirm dialog instead of living in settings.
2549
- const [resetOpen, setResetOpen] = useState(false)
2550
- const [resetCash, setResetCash] = useState('')
2551
- const submitting = useRef(false)
2552
- const placeKey = useRef({ key: '', id: '' })
2553
- const [preview, setPreview] = useState(null)
2554
- const [previewState, setPreviewState] = useState('idle')
2555
- const [previewError, setPreviewError] = useState('')
2556
- const [previewNonce, setPreviewNonce] = useState(0)
2557
- const [quoteError, setQuoteError] = useState('')
2558
- const [quoteNotice, setQuoteNotice] = useState('')
2559
- const [dataSource, setDataSource] = useState(null)
2560
- const quoteRef = useRef(null)
2561
- const lastTicketRefresh = useRef(0)
2562
- // Quote for an unfinished draft (symbol known, qty/limit still missing).
2563
- // A complete draft gets its quote from the preview response instead.
2564
- const [symbolQuote, setSymbolQuote] = useState(null)
2565
- const [receipt, setReceipt] = useState(null)
2566
- const [session, setSession] = useState(null)
2567
- const [searchQuery, setSearchQuery] = useState('')
2568
- const [searchHits, setSearchHits] = useState([])
2569
- const [searchAttempted, setSearchAttempted] = useState(false)
2570
- const [marketList, setMarketList] = useState(null)
2571
- const [marketBoard, setMarketBoard] = useState('main')
2572
- const [bars, setBars] = useState([])
2573
- const [barError, setBarError] = useState('')
2574
- const barsSeq = useRef(0)
2575
- const [barInterval, setBarInterval] = useState('day')
2576
- const [daily, setDaily] = useState([])
2577
- const [cashFlow, setCashFlow] = useState([])
2578
- const [trips, setTrips] = useState([])
2579
- const [shortlist, setShortlist] = useState([])
2580
- // Read/write the shortlist through a ref so two clicks in one task see
2581
- // each other's optimistic change instead of both computing from stale
2582
- // state (which silently dropped the first symbol).
2583
- const shortlistRef = useRef([])
2584
- const shortlistSeq = useRef(0)
2585
- const searchSeq = useRef(0)
2586
- const marketSeq = useRef(0)
2587
- useEffect(() => { shortlistRef.current = shortlist }, [shortlist])
2588
- const [shortlistOnly, setShortlistOnly] = useState(false)
2589
- const [form, setForm] = useState({
2590
- symbol: '600519.SH',
2591
- side: 'buy',
2592
- type: 'market',
2593
- qty: '',
2594
- limitPrice: '',
2595
- price: '',
2596
- note: '',
2597
- })
2598
-
2599
- const alive = useRef(true)
2600
- const loadAllSeq = useRef(0)
2601
- const detailSeq = useRef(0)
2602
- useEffect(() => {
2603
- alive.current = true
2604
- return () => { alive.current = false }
2605
- }, [])
2606
-
2607
- const formSymbol = useRef(form.symbol)
2608
- useEffect(() => { formSymbol.current = form.symbol }, [form.symbol])
2609
-
2610
- const loadAll = useCallback(async (quiet = false, reviewPeriod = period) => {
2611
- const seq = ++loadAllSeq.current
2612
- const requestedPeriod = reviewPeriod
2613
- try {
2614
- const [nextAccount, nextOrders, nextTrades, nextReview, nextSession, nextDataSource] = await Promise.all([
2615
- rpc('account/get'),
2616
- rpc('list/orders'),
2617
- rpc('list/trades'),
2618
- rpc('review/get', { period: reviewPeriod }),
2619
- rpc('market/status'),
2620
- rpc('market/data-source'),
2621
- ])
2622
- if (!alive.current) return null
2623
- // A poll started before a period switch carries the old review;
2624
- // newer requests own the page state, but callers still get their own
2625
- // snapshot (order receipts need the fresh cash).
2626
- if (seq === loadAllSeq.current && requestedPeriod === periodRef.current) {
2627
- setAccount(nextAccount)
2628
- setOrders(nextOrders)
2629
- setTrades(nextTrades)
2630
- setReview(nextReview)
2631
- setSession(nextSession)
2632
- setDataSource(nextDataSource)
2633
- if (!quiet) setError(null)
2634
- }
2635
- return { account: nextAccount, orders: nextOrders, trades: nextTrades }
2636
- } catch (cause) {
2637
- if (alive.current && seq === loadAllSeq.current) setError(errorOf(cause))
2638
- return null
2639
- }
2640
- }, [period])
2641
-
2642
- const loadReviewDetail = useCallback(async () => {
2643
- const seq = ++detailSeq.current
2644
- try {
2645
- const [nextDaily, nextCash, nextTrips] = await Promise.all([
2646
- rpc('review/daily'),
2647
- rpc('cash/flow'),
2648
- rpc('review/roundtrips'),
2649
- ])
2650
- if (!alive.current || seq !== detailSeq.current) return
2651
- setDaily(nextDaily)
2652
- setCashFlow(nextCash)
2653
- setTrips(nextTrips)
2654
- } catch (cause) {
2655
- if (alive.current && seq === detailSeq.current) setError(errorOf(cause))
2656
- }
2657
- }, [])
2658
-
2659
- useEffect(() => { loadAll() }, [loadAll])
2660
-
2661
- const tick = useCallback(async () => {
2662
- try {
2663
- const result = await rpc('tick')
2664
- if (!alive.current) return
2665
- if (result.filled.length > 0) setNotice(`成交 ${result.filled.length} 笔`)
2666
- if (result.notices.length > 0) setNotice(result.notices.join(';'))
2667
- await loadAll(true, periodRef.current)
2668
- if (alive.current && tab === 'review') await loadReviewDetail()
2669
- // Re-price the open ticket: the quote strip and preview otherwise
2670
- // froze at the moment the symbol was entered. An unfinished draft
2671
- // only fetches the quote, so clear its dedupe key too. Degraded
2672
- // quotes refresh slowly, otherwise this 5 s beat is the biggest
2673
- // free-tier cost of all.
2674
- if (alive.current && Date.now() - lastTicketRefresh.current >= ticketRefreshInterval(quoteRef.current)) {
2675
- lastTicketRefresh.current = Date.now()
2676
- quoteSymbol.current = ''
2677
- setPreviewNonce(value => value + 1)
2678
- }
2679
- } catch {
2680
- // Polling failures stay silent; the manual refresh shows the error.
2681
- }
2682
- }, [loadAll, loadReviewDetail, tab])
2683
-
2684
- // The host scheduler is the primary matcher; this stays as a live extra
2685
- // trigger while the panel is visible.
2686
- useEffect(() => {
2687
- const timer = setInterval(() => {
2688
- if (document.visibilityState === 'visible') tick()
2689
- }, 5000)
2690
- return () => clearInterval(timer)
2691
- }, [tick])
2692
-
2693
- const loadBars = useCallback(async (symbol = form.symbol) => {
2694
- const seq = ++barsSeq.current
2695
- if (symbol.trim().length < 6) {
2696
- // Do not leave the previous symbol's candles under a new title.
2697
- if (alive.current) { setBars([]); setBarError('') }
2698
- return
2699
- }
2700
- try {
2701
- const result = await rpc('market/bars', { symbol: symbol.trim(), interval: barInterval, limit: 80 })
2702
- if (!alive.current || seq !== barsSeq.current) return
2703
- if (result.state === 'ok') {
2704
- setBars(result.bars ?? [])
2705
- setBarError('')
2706
- } else {
2707
- setBars([])
2708
- setBarError(result.notice ?? 'K 线数据暂不可用')
2709
- }
2710
- } catch (cause) {
2711
- if (!alive.current || seq !== barsSeq.current) return
2712
- setBars([])
2713
- setBarError('K 线数据暂不可用')
2714
- setError(errorOf(cause))
2715
- }
2716
- }, [form.symbol, barInterval])
2717
-
2718
- const runSearch = useCallback(async () => {
2719
- if (!searchQuery.trim()) { setSearchAttempted(false); return }
2720
- setSearchAttempted(true)
2721
- const seq = ++searchSeq.current
2722
- try {
2723
- const hits = await rpc('market/search', { query: searchQuery.trim(), limit: 12 })
2724
- if (alive.current && seq === searchSeq.current) setSearchHits(hits)
2725
- } catch (cause) {
2726
- if (alive.current && seq === searchSeq.current) setError(errorOf(cause))
2727
- }
2728
- }, [searchQuery])
2729
-
2730
- const loadMarket = useCallback(async (page = 1) => {
2731
- const seq = ++marketSeq.current
2732
- try {
2733
- const next = await rpc('market/list', { board: marketBoard, page, pageSize: 50 })
2734
- if (alive.current && seq === marketSeq.current) setMarketList(next)
2735
- } catch (cause) {
2736
- if (alive.current && seq === marketSeq.current) setError(errorOf(cause))
2737
- }
2738
- }, [marketBoard])
2739
-
2740
- /**
2741
- * Only a real K-line selection may rewrite the ticket. dsh_kline calls
2742
- * `onIdentity` on its own during mount/route changes, so an unchanged
2743
- * symbol must not pop "已从 K 线选择 …" over the user's real feedback.
2744
- */
2745
- const klineIdentity = useCallback((symbol, name) => {
2746
- const next = foldHostSymbol(symbol)
2747
- if (!next || next === String(formSymbol.current).trim().toUpperCase()) return
2748
- formSymbol.current = next
2749
- setForm(prev => ({ ...prev, symbol: next }))
2750
- setNotice(name ? `已从 K 线选择 ${name}` : '')
2751
- }, [])
2752
-
2753
- useEffect(() => { void loadBars() }, [loadBars])
2754
-
2755
- useEffect(() => {
2756
- if (tab === 'review') void loadReviewDetail()
2757
- }, [tab, loadReviewDetail])
2758
-
2759
- useEffect(() => {
2760
- if (tab === 'market') {
2761
- void loadMarket(1)
2762
- rpc('shortlist/get').then(result => { if (alive.current) setShortlist(result.symbols ?? []) }).catch(() => {})
2763
- }
2764
- }, [tab, marketBoard, loadMarket])
2765
-
2766
- const isShortlisted = useCallback(symbol => shortlisted(shortlist, symbol), [shortlist])
2767
-
2768
- const toggleShortlist = useCallback(async (symbol) => {
2769
- const code = symbol
2770
- // The server only ever sends canonical ids, and the same id is what the
2771
- // shortlist keeps, so one favourite cannot split across markets.
2772
- const current = shortlistRef.current
2773
- const next = current.some(item => item === code)
2774
- ? current.filter(item => item !== code)
2775
- : [...current, code]
2776
- shortlistRef.current = next
2777
- setShortlist(next)
2778
- const seq = ++shortlistSeq.current
2779
- try {
2780
- const result = await rpc('shortlist/set', { symbols: next })
2781
- if (!alive.current || seq !== shortlistSeq.current) return
2782
- shortlistRef.current = result.symbols ?? next
2783
- setShortlist(result.symbols ?? next)
2784
- } catch (cause) {
2785
- if (!alive.current) return
2786
- setError(errorOf(cause))
2787
- // The server is the source of truth after a failed write.
2788
- try {
2789
- const fresh = await rpc('shortlist/get')
2790
- if (alive.current && seq === shortlistSeq.current) {
2791
- shortlistRef.current = fresh.symbols ?? []
2792
- setShortlist(fresh.symbols ?? [])
2793
- }
2794
- } catch { /* keep the optimistic state */ }
2795
- }
2796
- }, [])
2797
-
2798
- const adoptQuote = useCallback(symbol => {
2799
- const next = symbol
2800
- formSymbol.current = next
2801
- setForm(prev => ({ ...prev, symbol: next }))
2802
- setTab('trade')
2803
- }, [])
2804
-
2805
- const draft = useCallback(() => ({
2806
- symbol: form.symbol.trim(),
2807
- side: form.side,
2808
- type: form.type,
2809
- qty: Number(form.qty),
2810
- limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
2811
- price: form.type === 'market' && form.price !== '' ? Number(form.price) : undefined,
2812
- note: form.note.trim() === '' ? undefined : form.note.trim(),
2813
- }), [form])
2814
-
2815
- // The note is not part of the preview: only the trading fields are.
2816
- const previewDraft = useCallback(() => ({
2817
- symbol: form.symbol.trim(),
2818
- side: form.side,
2819
- type: form.type,
2820
- qty: Number(form.qty),
2821
- limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
2822
- price: form.type === 'market' && form.price !== '' ? Number(form.price) : undefined,
2823
- }), [form.symbol, form.side, form.type, form.qty, form.limitPrice, form.price])
2824
-
2825
- const previewSymbol = useRef('')
2826
- const previewSeq = useRef(0)
2827
- // Symbols whose quote the blocked-preview path already asked for.
2828
- const quoteSymbol = useRef('')
2829
-
2830
- // One preview per input change, debounced; the response carries the quote,
2831
- // so a complete draft still costs a single request. While the draft is
2832
- // unfinished the price line asks for the quote alone — a limit order
2833
- // whose limit is still being typed must show what the stock costs.
2834
- useEffect(() => {
2835
- const current = previewDraft()
2836
- previewSeq.current += 1
2837
- const seq = previewSeq.current
2838
- if (previewBlockReason(current) !== '') {
2839
- previewSymbol.current = ''
2840
- setPreview(null)
2841
- setPreviewState('idle')
2842
- setPreviewError('')
2843
- if (current.symbol.length < 6) {
2844
- quoteSymbol.current = ''
2845
- setSymbolQuote(null)
2846
- setQuoteError('')
2847
- setQuoteNotice('')
2848
- return
2849
- }
2850
- if (quoteSymbol.current === current.symbol) return
2851
- const timer = setTimeout(() => {
2852
- rpc('market/quote', { symbols: [current.symbol] })
2853
- .then(result => {
2854
- if (!alive.current || seq !== previewSeq.current) return
2855
- const found = result.quotes[0] ?? null
2856
- quoteSymbol.current = found === null ? '' : current.symbol
2857
- setSymbolQuote(found)
2858
- setQuoteError(found ? '' : (result.notice ?? '没有查到行情'))
2859
- setQuoteNotice(found ? (result.notice ?? '') : '')
2860
- })
2861
- .catch(cause => {
2862
- if (!alive.current || seq !== previewSeq.current) return
2863
- quoteSymbol.current = ''
2864
- setSymbolQuote(null)
2865
- setQuoteError(errorOf(cause).text)
2866
- setQuoteNotice('')
2867
- })
2868
- }, 300)
2869
- return () => clearTimeout(timer)
2870
- }
2871
- quoteSymbol.current = current.symbol
2872
- // A completed draft gets its quote from the preview; any error left
2873
- // over from the earlier quote-only probe belongs to the old symbol and
2874
- // must not stay on screen after the ticket has been corrected.
2875
- setQuoteError('')
2876
- setQuoteNotice('')
2877
- if (previewSymbol.current !== current.symbol) {
2878
- previewSymbol.current = current.symbol
2879
- setPreview(null)
2880
- }
2881
- setPreviewState('loading')
2882
- const timer = setTimeout(() => {
2883
- rpc('order/preview', current)
2884
- .then(result => {
2885
- if (!alive.current || seq !== previewSeq.current) return
2886
- setPreview(result)
2887
- // Keep the quote for an unfinished draft: switching to 限价 must
2888
- // not blank the price line while the limit is still being typed.
2889
- if (result.quote) setSymbolQuote(result.quote)
2890
- setPreviewError('')
2891
- setPreviewState('ready')
2892
- })
2893
- .catch(cause => {
2894
- if (!alive.current || seq !== previewSeq.current) return
2895
- setPreviewError(errorOf(cause).text)
2896
- setPreviewState('error')
2897
- })
2898
- }, 300)
2899
- return () => clearTimeout(timer)
2900
- }, [previewDraft, previewNonce])
2901
-
2902
- const doSubmit = useCallback(async () => {
2903
- if (submitting.current) return
2904
- submitting.current = true
2905
- setBusy(true)
2906
- setReceipt(null)
2907
- try {
2908
- const current = draft()
2909
- const key = JSON.stringify(current)
2910
- if (placeKey.current.key !== key) {
2911
- placeKey.current = {
2912
- key,
2913
- id: typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `req-${Date.now()}-${Math.random().toString(36).slice(2)}`,
2914
- }
2915
- }
2916
- const order = await rpc('order/place', { draft: current, requestId: placeKey.current.id })
2917
- const snapshot = await loadAll(true)
2918
- const fill = snapshot === null ? undefined : snapshot.trades.find(item => item.orderId === order.id)
2919
- setReceipt({ order, fill, cash: snapshot === null ? undefined : snapshot.account.cash })
2920
- placeKey.current = { key: '', id: '' }
2921
- // Keep the card's numbers; recompute them against the new cash.
2922
- setPreviewNonce(value => value + 1)
2923
- } catch (cause) {
2924
- setReceipt({ failure: errorOf(cause) })
2925
- } finally {
2926
- submitting.current = false
2927
- setBusy(false)
2928
- }
2929
- }, [draft, loadAll])
2930
-
2931
- const cancel = useCallback(async orderId => {
2932
- setBusy(true)
2933
- try {
2934
- await rpc('order/cancel', { orderId })
2935
- await loadAll(true)
2936
- } catch (cause) {
2937
- // A lost response can make the retry see an already-finished order;
2938
- // resync instead of claiming the cancel failed.
2939
- if (cause && (cause.code === 'ORDER_NOT_PENDING' || cause.code === 'ORDER_NOT_FOUND')) {
2940
- setNotice('订单已结束,列表已刷新')
2941
- await loadAll(true)
2942
- } else {
2943
- setError(errorOf(cause))
2944
- }
2945
- } finally {
2946
- setBusy(false)
2947
- }
2948
- }, [loadAll])
2949
-
2950
- const copyLedgerPath = useCallback(async () => {
2951
- const path = account !== null ? account.ledgerPath : undefined
2952
- if (path === undefined) return
2953
- const copied = typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText
2954
- ? await navigator.clipboard.writeText(path).then(() => true, () => false)
2955
- : false
2956
- setNotice(copied ? `已复制账本路径:${path}` : `账本路径:${path}`)
2957
- }, [account])
2958
-
2959
- const exportLedger = useCallback(async () => {
2960
- try {
2961
- const result = await rpc('account/export')
2962
- if (!result.exists || !result.content) {
2963
- setNotice(result.notice ?? '账本文件尚未创建')
2964
- return
2965
- }
2966
- if (typeof document !== 'undefined' && typeof URL !== 'undefined' && typeof Blob !== 'undefined') {
2967
- const blob = new Blob([result.content], { type: 'application/x-ndjson' })
2968
- const url = URL.createObjectURL(blob)
2969
- const link = document.createElement('a')
2970
- link.href = url
2971
- link.download = 'paper-trading-events.jsonl'
2972
- link.click()
2973
- URL.revokeObjectURL(url)
2974
- }
2975
- if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
2976
- await navigator.clipboard.writeText(result.path).catch(() => {})
2977
- }
2978
- setNotice(`已导出账本:${result.path}`)
2979
- } catch (cause) {
2980
- setError(errorOf(cause))
2981
- }
2982
- }, [])
2983
-
2984
- const reset = useCallback(async () => {
2985
- const cents = cashAmountCents(resetCash)
2986
- if (cents === null) return
2987
- setBusy(true)
2988
- try {
2989
- setAccount(await rpc('account/reset', { confirm: true, initialCash: cents / 100 }))
2990
- setPreview(null)
2991
- setReceipt(null)
2992
- await loadAll(true)
2993
- await loadReviewDetail()
2994
- setPreviewNonce(value => value + 1)
2995
- setResetNonce(value => value + 1)
2996
- setResetOpen(false)
2997
- setResetCash('')
2998
- setNotice(`账户已重置,初始资金 ${money(cents / 100)}`)
2999
- } catch (cause) {
3000
- setError(errorOf(cause))
3001
- } finally {
3002
- setBusy(false)
3003
- }
3004
- }, [resetCash, loadAll, loadReviewDetail])
3005
-
3006
- /** 注资/提款:写一条账本事件,现金与总资产随之更新,盈亏剔除净入金。 */
3007
- const moveCash = useCallback(async () => {
3008
- const cents = cashAmountCents(cashAmount)
3009
- if (cents === null) return
3010
- const amount = cents / 100
3011
- const depositing = cashSide === 'deposit'
3012
- setBusy(true)
3013
- try {
3014
- setAccount(await rpc(depositing ? 'account/deposit' : 'account/withdraw', { amount }))
3015
- await loadAll(true)
3016
- await loadReviewDetail()
3017
- setPreviewNonce(value => value + 1)
3018
- setCashAmount('')
3019
- setCashOpen(false)
3020
- setError(null)
3021
- setNotice(depositing ? `已注资 ${money(amount)}` : `已提款 ${money(amount)}`)
3022
- } catch (cause) {
3023
- setError(errorOf(cause))
3024
- } finally {
3025
- setBusy(false)
3026
- }
3027
- }, [cashAmount, cashSide, loadAll, loadReviewDetail])
3028
-
3029
- /** Header refresh: account/orders/trades/review plus one fresh preview. */
3030
- const refreshAll = useCallback(async () => {
3031
- setBusy(true)
3032
- try {
3033
- await loadAll()
3034
- if (tab === 'review') await loadReviewDetail()
3035
- // 刷新 must also retry the current tab's own fetch, not just the
3036
- // account bundle: a failed market list otherwise stays broken.
3037
- if (tab === 'market') await loadMarket(marketList?.page ?? 1)
3038
- // Force the incomplete-draft quote branch to fetch again even when
3039
- // the symbol did not change (a transient quote failure is retryable).
3040
- quoteSymbol.current = ''
3041
- setPreviewNonce(value => value + 1)
3042
- } finally {
3043
- setBusy(false)
3044
- }
3045
- }, [loadAll, loadReviewDetail, tab, loadMarket, marketList?.page])
3046
-
3047
- /** Only real blockers disable submit; a failed preview never does. */
3048
- /** Read the flag outside the deps array: `account` is null on the first render. */
3049
- const blocked = account?.blocked === true
3050
- const quote = preview ? preview.quote ?? null : symbolQuote
3051
- quoteRef.current = quote
3052
- const submitReason = useMemo(() => {
3053
- if (account === null) return '加载账户中'
3054
- if (blocked) return '账户已锁定'
3055
- const symbol = form.symbol.trim()
3056
- if (symbol.length < 6) return '输入代码'
3057
- if (String(form.qty).trim() === '') return '填写数量'
3058
- const qty = Number(form.qty)
3059
- if (!Number.isInteger(qty) || qty <= 0) return '数量需为正整数'
3060
- if (form.side === 'buy' && qty % 100 !== 0) return '买入需 100 股整数倍'
3061
- if (form.type === 'limit' && !(Number(form.limitPrice) > 0)) return '填写限价'
3062
- if (session !== null && session.phase === 'auction_close') return '收盘竞价暂不支持模拟撮合'
3063
- if (form.type === 'market' && quote === null && !(Number(form.price) > 0)) return '无行情,请填参考价'
3064
- if (preview !== null && preview.quote?.status === 'suspended') return '停牌'
3065
- if (preview !== null && form.type === 'limit' && preview.priceLimit !== undefined) {
3066
- const price = Number(form.limitPrice)
3067
- if (price < preview.priceLimit.lower || price > preview.priceLimit.upper) return '价格超出涨跌停'
3068
- }
3069
- if (form.side === 'buy' && preview !== null && preview.cashAfterCents < 0) {
3070
- return `资金不足(还差 ${cents(-preview.cashAfterCents)})`
3071
- }
3072
- if (form.side === 'sell' && preview !== null && qty > preview.availableQty) return '可卖不足'
3073
- return ''
3074
- }, [blocked, form, session, quote, preview])
3075
- const pending = useMemo(() => orders.filter(order => order.status === 'pending' || order.status === 'queued' || order.status === 'partially_filled'), [orders])
3076
- const history = useMemo(() => orders.filter(order => order.status !== 'pending' && order.status !== 'queued' && order.status !== 'partially_filled'), [orders])
3077
- const positions = account?.positions ?? []
3078
-
3079
- /** Selling from a book only fills the ticket; the user still confirms. */
3080
- const sellPosition = useCallback(position => {
3081
- formSymbol.current = position.symbol
3082
- setForm(prev => ({ ...prev, symbol: position.symbol, side: 'sell', type: 'market', qty: String(Math.min(position.available, position.qty)) }))
3083
- setTab('trade')
3084
- }, [])
3085
-
3086
- if (account === null) {
3087
- return h('div', { className: 'pt-inner' },
3088
- h('div', { className: 'pt-head' },
3089
- h('div', null, h('h3', { className: 'pt-title' }, '模拟交易')),
3090
- h('div', { className: 'pt-row' }, accountSwitch,
3091
- h('button', { className: 'pt-btn', onClick: () => { setError(null); void loadAll() } }, '重试'),
3092
- ),
3093
- ),
3094
- error
3095
- ? h('div', { className: 'pt-error', title: error.detail || undefined }, error.text)
3096
- : h('div', { className: 'pt-empty' }, '加载模拟交易…'),
3097
- )
3098
- }
3099
-
3100
- return h('div', { className: 'pt-inner' },
3101
- h('div', { className: 'pt-head' },
3102
- h('div', null,
3103
- h('h3', { className: 'pt-title' }, '模拟交易'),
3104
- h('div', { className: 'pt-sub' },
3105
- `${tradeDateText(account.tradeDate, session?.calendar?.source === 'fallback')} · ${session ? PHASE_TEXT[session.phase] : '时段未知'} · 初始 ${money(account.initialCash)}${isFiniteNumber(account.netCashFlow) && account.netCashFlow !== 0 ? ` · 净入金 ${signed(account.netCashFlow)}` : ''} · ${account.blocked ? '已锁定' : '运行中'}`,
3106
- sessionNote(session) !== '' ? h('span', { className: 'pt-note' }, sessionNote(session)) : null,
3107
- session !== null && session !== undefined ? calendarNote(session.calendar) : null,
3108
- ),
3109
- ),
3110
- h('div', { className: 'pt-row' },
3111
- accountSwitch,
3112
- h(DataSourceBadge, { status: dataSource }),
3113
- h('button', { className: 'pt-btn', onClick: refreshAll, disabled: busy }, '刷新'),
3114
- h('button', {
3115
- className: 'pt-btn', 'data-active': cashOpen, disabled: busy,
3116
- onClick: () => {
3117
- setError(null)
3118
- setCashOpen(value => !value)
3119
- setResetOpen(false)
3120
- },
3121
- }, '资金'),
3122
- h('button', {
3123
- className: 'pt-btn pt-btn-danger', 'data-active': resetOpen, disabled: busy,
3124
- onClick: () => {
3125
- setError(null)
3126
- setResetOpen(value => !value)
3127
- setResetCash(String(account.initialCash))
3128
- setCashOpen(false)
3129
- },
3130
- }, '重置'),
3131
- h(FeedbackLink),
3132
- ),
3133
- ),
3134
- h(DataBanner, { status: dataSource, onRetry: refreshAll }),
3135
- cashOpen ? h(CashMovePanel, {
3136
- available: account.cash,
3137
- side: cashSide,
3138
- onSide: setCashSide,
3139
- amount: cashAmount,
3140
- onAmount: setCashAmount,
3141
- busy,
3142
- onCancel: () => {
3143
- setCashOpen(false)
3144
- setCashAmount('')
3145
- },
3146
- onSubmit: moveCash,
3147
- }) : null,
3148
- resetOpen ? h(ResetPanel, {
3149
- initialCash: account.initialCash,
3150
- amount: resetCash,
3151
- onAmount: setResetCash,
3152
- busy,
3153
- onCancel: () => {
3154
- setResetOpen(false)
3155
- setResetCash('')
3156
- },
3157
- onSubmit: reset,
3158
- }) : null,
3159
- account.blocked ? h('div', { className: 'pt-blocked' },
3160
- h('div', { className: 'pt-blocked-text' },
3161
- h('div', null, '账本校验失败,账户已锁定。'),
3162
- account.blockedReason ? h('div', { className: 'pt-blocked-detail', title: account.blockedReason }, `原因:${account.blockedReason}`) : null,
3163
- account.ledgerPath ? h('div', { className: 'pt-blocked-detail', title: account.ledgerPath }, `账本:${account.ledgerPath}`) : null,
3164
- h('div', { className: 'pt-blocked-hint' }, '可让 AI 助手用 paper_ledger 从备份恢复;重置会先备份。'),
3165
- ),
3166
- h('div', { className: 'pt-row' },
3167
- h('button', { className: 'pt-btn', onClick: exportLedger, disabled: busy }, '导出账本'),
3168
- account.ledgerPath ? h('button', { className: 'pt-btn', onClick: copyLedgerPath, disabled: busy }, '复制路径') : null,
3169
- ),
3170
- ) : null,
3171
- h('div', { className: 'pt-stats' },
3172
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '总资产'), h('div', { className: 'pt-stat-value' }, money(account.equity))),
3173
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '可用现金'), h('div', { className: 'pt-stat-value' }, money(account.cash))),
3174
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '累计盈亏'), h('div', { className: `pt-stat-value ${tone(account.pnl)}` }, signed(account.pnl))),
3175
- h('div', { className: 'pt-stat' }, h('div', { className: 'pt-stat-label' }, '今日盈亏'), h('div', { className: `pt-stat-value ${tone(account.todayPnl)}` }, signed(account.todayPnl))),
3176
- ),
3177
- error ? h('div', { className: 'pt-error', title: error.detail || undefined }, error.text) : null,
3178
- notice ? h('div', { className: 'pt-note' }, notice) : null,
3179
- h('div', { className: 'pt-workspace' },
3180
- h('div', { className: 'pt-main' },
3181
- h('div', { className: 'pt-tabs' },
3182
- [['trade', '交易'], ['basket', '批量'], ['market', '行情'], ['positions', `持仓 ${positions.length}`], ['orders', `订单 ${pending.length}`], ['review', '复盘']].map(([key, label]) =>
3183
- h('button', { key, className: 'pt-tab', 'data-active': tab === key, onClick: () => setTab(key) }, label),
3184
- ),
3185
- ),
3186
- h('div', { className: 'pt-tab-body' },
3187
- tab === 'trade' ? h(TradeTab, {
3188
- account, form, setForm, quote, quoteError, quoteNotice, preview, previewState, previewError,
3189
- previewHint: previewBlockReason(previewDraft()),
3190
- busy,
3191
- onSubmit: doSubmit,
3192
- submitReason,
3193
- receipt,
3194
- positions, pending,
3195
- onCancel: cancel,
3196
- onSell: sellPosition,
3197
- }) : null,
3198
- tab === 'basket' ? h(BasketTab, { account, onDone: refreshAll, resetNonce }) : null,
3199
- tab === 'market' ? h(MarketTab, {
3200
- searchQuery,
3201
- setSearchQuery: value => { setSearchQuery(value); setSearchAttempted(false) },
3202
- runSearch, searchHits, searchAttempted, shortlist, isShortlisted, toggleShortlist,
3203
- marketList, marketBoard, setMarketBoard, shortlistOnly, setShortlistOnly, loadMarket, busy, adoptQuote, session,
3204
- }) : null,
3205
- tab === 'positions' ? h(PositionsTab, {
3206
- positions,
3207
- onSell: sellPosition,
3208
- }) : null,
3209
- tab === 'orders' ? h(OrdersTab, { pending, history, busy, onCancel: cancel }) : null,
3210
- tab === 'review' ? h(ReviewTab, {
3211
- review, period,
3212
- setPeriod: key => setPeriod(key),
3213
- trades, daily, cashFlow, trips,
3214
- }) : null,
3215
- ),
3216
- ),
3217
- h(KlinePane, {
3218
- renderSlot,
3219
- symbol: quote && quote.symbol ? quote.symbol : form.symbol,
3220
- quote,
3221
- bars,
3222
- error: barError,
3223
- interval: barInterval,
3224
- onInterval: setBarInterval,
3225
- onRefresh: () => loadBars(),
3226
- onIdentity: klineIdentity,
3227
- }),
3228
- ),
3229
- )
3230
- }
3231
-
3232
- const PANEL_ID = 'ft-paper-trading'
3233
-
3234
- /** Candlestick glyph; the sidebar owns the button, label and tooltip. */
3235
- function PaperGlyph({ size }) {
3236
- const edge = Number(size) > 0 ? Number(size) : 16
3237
- return h('svg', {
3238
- width: edge, height: edge, viewBox: '0 0 16 16', 'aria-hidden': 'true',
3239
- fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round',
3240
- },
3241
- h('path', { d: 'M2 13.5V10M5.5 13.5V6M9 13.5V8.5M12.5 13.5V3.5' }),
3242
- h('path', { d: 'M1.5 2.5h13', opacity: 0.35 }),
3243
- )
3244
- }
3245
-
3246
- function apply(ctx) {
3247
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
3248
- name: 'sidebar.panellist',
3249
- id: PANEL_ID,
3250
- order: 30,
3251
- label: '模拟交易',
3252
- }, PaperGlyph))
3253
- ctx.slots.inject('main', () => ctx.slots.register({
3254
- name: 'main',
3255
- key: PANEL_ID,
3256
- children: {
3257
- 'paperTrading.kline': { kind: 'single', scope: 'root' },
3258
- },
3259
- }, Dashboard))
3260
- // The declared slot stays empty until dsh_kline fills it through its
3261
- // optional host contract; without that plugin (or on an older chart) the
3262
- // rail keeps its built-in simplified chart instead.
3263
- ctx.inject(['klinePanels'], scope => {
3264
- const panels = scope.get('klinePanels')
3265
- if (panels === undefined) return () => {}
3266
- return panels.mount('paperTrading.kline')
3267
- })
3268
- }
3269
-
3270
- const inject = ['slots']
3271
- exports.apply = apply
3272
- exports.inject = inject
3273
- return module.exports
3274
- },
3275
- })