@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
@@ -0,0 +1,911 @@
1
+ /* 50 · futures — the futures dashboard and its tabs/rail. */
2
+
3
+ /* -------------------------------------------------------- futures ----- */
4
+
5
+ /**
6
+ * Futures dashboard: its own endpoints, polling loop and reset. The stock
7
+ * half never reads this state, so either account can fail or reset alone.
8
+ */
9
+ function FuturesDashboard({ accountSwitch }) {
10
+ const [account, setAccount] = useState(null)
11
+ const [status, setStatus] = useState(null)
12
+ const [positions, setPositions] = useState([])
13
+ const [orders, setOrders] = useState([])
14
+ const [review, setReview] = useState(null)
15
+ const [period, setPeriod] = useState('30d')
16
+ const periodRef = useRef(period)
17
+ useEffect(() => { periodRef.current = period }, [period])
18
+ const reviewSeq = useRef(0)
19
+ const loadAllSeq = useRef(0)
20
+ const [tab, setTab] = useState('trade')
21
+ const [error, setError] = useState(null)
22
+ const [notice, setNotice] = useState('')
23
+ const [busy, setBusy] = useState(false)
24
+ // Inline cash panel (注资/提款), hidden until the header button is pressed.
25
+ const [cashOpen, setCashOpen] = useState(false)
26
+ const [cashSide, setCashSide] = useState('deposit')
27
+ const [cashAmount, setCashAmount] = useState('')
28
+ const [cashFlow, setCashFlow] = useState([])
29
+ const submitting = useRef(false)
30
+ const placeKey = useRef({ key: '', id: '' })
31
+ const [searchQuery, setSearchQuery] = useState('')
32
+ const [searching, setSearching] = useState(false)
33
+ const [contracts, setContracts] = useState(null)
34
+ const [contractNotice, setContractNotice] = useState('')
35
+ const [contract, setContract] = useState(null)
36
+ const [quote, setQuote] = useState(null)
37
+ const [quoteNotice, setQuoteNotice] = useState('')
38
+ const [dataSource, setDataSource] = useState(null)
39
+ const dataSourceRef = useRef(null)
40
+ const quoteRef = useRef(null)
41
+ const lastTicketRefresh = useRef(0)
42
+ const quoteSeq = useRef(0)
43
+ const contractSeq = useRef(0)
44
+ const [preview, setPreview] = useState(null)
45
+ const [previewState, setPreviewState] = useState('idle')
46
+ const [previewError, setPreviewError] = useState('')
47
+ const [previewNonce, setPreviewNonce] = useState(0)
48
+ const [receipt, setReceipt] = useState(null)
49
+ const [form, setForm] = useState({
50
+ side: 'long', offset: 'open', type: 'market', qty: '1', limitPrice: '', price: '', note: '',
51
+ })
52
+ const [layout, applyLayout] = useRailLayout('futures')
53
+
54
+ const alive = useRef(true)
55
+ useEffect(() => {
56
+ alive.current = true
57
+ return () => { alive.current = false }
58
+ }, [])
59
+
60
+ const loadAll = useCallback(async (quiet = false, reviewPeriod = periodRef.current) => {
61
+ const seq = ++loadAllSeq.current
62
+ const requestedPeriod = reviewPeriod
63
+ try {
64
+ const [nextAccount, nextStatus, nextPositions, nextOrders, nextDataSource] = await Promise.all([
65
+ rpc('futures/account/get'),
66
+ rpc('futures/status'),
67
+ rpc('futures/positions'),
68
+ rpc('futures/orders'),
69
+ rpc('market/data-source'),
70
+ ])
71
+ if (!alive.current) return null
72
+ if (seq === loadAllSeq.current) {
73
+ setAccount(nextAccount)
74
+ setStatus(nextStatus)
75
+ setPositions(nextPositions)
76
+ setOrders(nextOrders)
77
+ setDataSource(nextDataSource)
78
+ dataSourceRef.current = nextDataSource
79
+ if (!quiet) setError(null)
80
+ }
81
+ return { account: nextAccount }
82
+ } catch (cause) {
83
+ if (alive.current && seq === loadAllSeq.current) setError(errorOf(cause))
84
+ return null
85
+ }
86
+ }, [])
87
+
88
+ useEffect(() => { loadAll() }, [loadAll])
89
+
90
+ const loadReview = useCallback(async (key = period) => {
91
+ const seq = ++reviewSeq.current
92
+ try {
93
+ const [next, nextCash] = await Promise.all([
94
+ rpc('futures/review', { period: key }),
95
+ rpc('futures/cash/flow'),
96
+ ])
97
+ if (alive.current && seq === reviewSeq.current && key === periodRef.current) {
98
+ setReview(next)
99
+ setCashFlow(nextCash)
100
+ }
101
+ } catch (cause) {
102
+ if (alive.current && seq === reviewSeq.current && key === periodRef.current) setError(errorOf(cause))
103
+ }
104
+ }, [])
105
+
106
+ useEffect(() => {
107
+ if (tab === 'review') void loadReview()
108
+ }, [tab, loadReview])
109
+
110
+ // A period switch reloads the review bundle (account cards included)
111
+ // without touching the ticket, which the old loadAll dependency did by
112
+ // accident. `tab` is read at switch time only.
113
+ const periodMounted = useRef(false)
114
+ useEffect(() => {
115
+ if (!periodMounted.current) {
116
+ periodMounted.current = true
117
+ return
118
+ }
119
+ void loadAll(false, period)
120
+ if (tab === 'review') void loadReview(period)
121
+ // eslint-disable-next-line react-hooks/exhaustive-deps
122
+ }, [period, loadAll, loadReview])
123
+
124
+ const fetchQuote = useCallback(async symbol => {
125
+ const seq = ++quoteSeq.current
126
+ try {
127
+ const result = await rpc('futures/quote', { symbols: [symbol] })
128
+ // A slower quote for a previously selected contract must not paint
129
+ // over the one the user is looking at now.
130
+ if (!alive.current || seq !== quoteSeq.current) return
131
+ const nextQuote = result.quotes[0] ?? null
132
+ setQuote(nextQuote)
133
+ setQuoteNotice(nextQuote === null ? (result.notice ?? '取不到行情,可手填参考价') : (result.notice ?? ''))
134
+ } catch {
135
+ if (!alive.current || seq !== quoteSeq.current) return
136
+ setQuote(null)
137
+ setQuoteNotice('取不到行情,可手填参考价')
138
+ }
139
+ }, [])
140
+
141
+ // The host scheduler settles; this is the visible-panel extra trigger.
142
+ const poll = useCallback(async () => {
143
+ try {
144
+ const tick = await rpc('futures/tick')
145
+ if (!alive.current) return
146
+ if (tick.filled.length > 0) setNotice(`成交 ${tick.filled.length} 笔`)
147
+ if (tick.notices.length > 0) setNotice(tick.notices.join(';'))
148
+ await loadAll(true)
149
+ if (alive.current && tab === 'review') await loadReview(periodRef.current)
150
+ // Keep the selected contract's price and estimate moving while the
151
+ // panel is open; without this the ticket showed the selection price
152
+ // until the next edit. With no quote (free tier or an outage) retry
153
+ // slowly instead of every beat.
154
+ if (!alive.current || contract === null) return
155
+ // A free-tier quote is yesterday's close and does not move: re-price
156
+ // at the degraded cadence instead of spending the 5 s beat. The data
157
+ // source, not the quote object, tells free tier from configured.
158
+ const refreshInterval = dataSourceRef.current?.state === 'configured' ? 5_000 : 300_000
159
+ if (Date.now() - lastTicketRefresh.current >= refreshInterval) {
160
+ lastTicketRefresh.current = Date.now()
161
+ void fetchQuote(contract.symbol)
162
+ setPreviewNonce(value => value + 1)
163
+ }
164
+ } catch {
165
+ // Polling failures stay silent; the manual refresh shows the error.
166
+ }
167
+ }, [loadAll, contract, fetchQuote, tab, loadReview])
168
+
169
+ useVisiblePolling(poll)
170
+
171
+ const searchContracts = useCallback(async (refresh = false) => {
172
+ const seq = ++contractSeq.current
173
+ setSearching(true)
174
+ try {
175
+ const payload = { limit: 20 }
176
+ if (searchQuery.trim() !== '') payload.query = searchQuery.trim()
177
+ if (refresh) payload.refresh = true
178
+ const result = await rpc('futures/contracts', payload)
179
+ if (!alive.current || seq !== contractSeq.current) return
180
+ setContracts(result.contracts ?? [])
181
+ setContractNotice(result.notice ?? '')
182
+ } catch (cause) {
183
+ if (alive.current && seq === contractSeq.current) setError(errorOf(cause))
184
+ } finally {
185
+ if (alive.current && seq === contractSeq.current) setSearching(false)
186
+ }
187
+ }, [searchQuery])
188
+
189
+ const selectContract = useCallback(next => {
190
+ setContract(next)
191
+ setContracts(null)
192
+ setQuote(null)
193
+ setQuoteNotice('')
194
+ setPreview(null)
195
+ setPreviewError('')
196
+ setPreviewNonce(value => value + 1)
197
+ void fetchQuote(next.symbol)
198
+ }, [fetchQuote])
199
+
200
+ /** Closing from a book only fills the ticket; the user still confirms. */
201
+ const selectPosition = useCallback(position => {
202
+ setContract({
203
+ symbol: position.symbol,
204
+ name: position.name,
205
+ multiplier: position.multiplier,
206
+ marginRate: position.marginRate,
207
+ deListDate: position.deListDate,
208
+ })
209
+ setQuote(null)
210
+ setQuoteNotice('')
211
+ setPreview(null)
212
+ setForm(prev => ({ ...prev, side: position.side, offset: 'close', type: 'market', qty: String(position.qty) }))
213
+ setTab('trade')
214
+ setPreviewNonce(value => value + 1)
215
+ void fetchQuote(position.symbol)
216
+ }, [fetchQuote])
217
+
218
+ const futuresDraft = useCallback(() => ({
219
+ symbol: contract === null ? '' : contract.symbol,
220
+ side: form.side,
221
+ offset: form.offset,
222
+ type: form.type,
223
+ qty: Number(form.qty),
224
+ limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
225
+ // Manual fallback only for a market close, per the contract's draft shape.
226
+ price: form.type === 'market' && form.offset === 'close' && form.price !== '' ? Number(form.price) : undefined,
227
+ note: form.note.trim() === '' ? undefined : form.note.trim(),
228
+ }), [contract, form])
229
+
230
+ const previewDraft = useCallback(() => contract === null ? null : {
231
+ symbol: contract.symbol,
232
+ side: form.side,
233
+ offset: form.offset,
234
+ type: form.type,
235
+ qty: Number(form.qty),
236
+ limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
237
+ price: form.type === 'market' && form.offset === 'close' && form.price !== '' ? Number(form.price) : undefined,
238
+ }, [
239
+ contract, form.side, form.offset, form.type, form.qty, form.limitPrice, form.price,
240
+ ])
241
+
242
+ const previewSeq = useRef(0)
243
+ useEffect(() => {
244
+ previewSeq.current += 1
245
+ const seq = previewSeq.current
246
+ const draft = previewDraft()
247
+ if (draft === null) {
248
+ setPreview(null)
249
+ setPreviewState('idle')
250
+ setPreviewError('')
251
+ return
252
+ }
253
+ if (!Number.isInteger(draft.qty) || draft.qty <= 0 || (draft.type === 'limit' && !(draft.limitPrice > 0))) {
254
+ setPreview(null)
255
+ setPreviewState('idle')
256
+ setPreviewError('')
257
+ return
258
+ }
259
+ setPreviewState('loading')
260
+ const timer = setTimeout(() => {
261
+ rpc('futures/preview', draft)
262
+ .then(result => {
263
+ if (!alive.current || seq !== previewSeq.current) return
264
+ setPreview(result)
265
+ setPreviewError('')
266
+ setPreviewState('ready')
267
+ })
268
+ .catch(cause => {
269
+ if (!alive.current || seq !== previewSeq.current) return
270
+ setPreviewError(errorOf(cause).text)
271
+ setPreviewState('error')
272
+ })
273
+ }, 300)
274
+ return () => clearTimeout(timer)
275
+ }, [previewDraft, previewNonce])
276
+
277
+ const pending = useMemo(() => orders.filter(order => order.status === 'pending'), [orders])
278
+ const history = useMemo(() => orders.filter(order => order.status !== 'pending'), [orders])
279
+
280
+ const previewHint = useMemo(() => {
281
+ if (contract === null) return '搜索并选择合约后自动计算'
282
+ if (!Number.isInteger(Number(form.qty)) || Number(form.qty) <= 0) return '填写手数后自动计算'
283
+ if (form.type === 'limit' && !(Number(form.limitPrice) > 0)) return '填写限价后自动计算'
284
+ return ''
285
+ }, [contract, form.qty, form.type, form.limitPrice])
286
+
287
+ const submitReason = useMemo(() => {
288
+ if (account === null) return '加载账户中'
289
+ if (account.blocked === true) return '账本异常,需恢复或重置'
290
+ if (contract === null) return '选择合约'
291
+ if (String(form.qty).trim() === '') return '填写手数'
292
+ const qty = Number(form.qty)
293
+ if (!Number.isInteger(qty) || qty <= 0) return '手数需为正整数'
294
+ if (form.type === 'limit' && !(Number(form.limitPrice) > 0)) return '填写限价'
295
+ if (form.type === 'limit' && preview !== null && preview.limit !== undefined) {
296
+ const price = Number(form.limitPrice)
297
+ if (price < preview.limit.lower || price > preview.limit.upper) return '价格超出涨跌停'
298
+ }
299
+ if (status !== null && status.canSubmit === false) return '当前时段不可下单'
300
+ if (form.type === 'market' && status !== null && status.canMatch === false) return '当前时段不能市价成交'
301
+ const hasQuote = quote !== null
302
+ || (quoteNotice === '' && preview !== null && preview.quote !== undefined && preview.quote !== null)
303
+ if (form.type === 'market' && !hasQuote && !(form.offset === 'close' && Number(form.price) > 0)) return '等待行情'
304
+ if (form.offset === 'close' && preview !== null && qty > preview.availableCloseQty) return '可平手数不足'
305
+ if (form.offset === 'open' && preview !== null && preview.cashAfterCents < 0) return '保证金不足'
306
+ return ''
307
+ }, [account, contract, form, status, preview, quote, quoteNotice])
308
+
309
+ const doSubmit = useCallback(async () => {
310
+ if (submitReason !== '' || submitting.current) return
311
+ submitting.current = true
312
+ setBusy(true)
313
+ setReceipt(null)
314
+ try {
315
+ const current = futuresDraft()
316
+ const key = JSON.stringify(current)
317
+ if (placeKey.current.key !== key) {
318
+ placeKey.current = {
319
+ key,
320
+ id: typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `req-${Date.now()}-${Math.random().toString(36).slice(2)}`,
321
+ }
322
+ }
323
+ const order = await rpc('futures/order', { draft: current, requestId: placeKey.current.id })
324
+ const snapshot = await loadAll(true)
325
+ setReceipt({ order, cash: snapshot === null ? undefined : snapshot.account.cash })
326
+ placeKey.current = { key: '', id: '' }
327
+ setPreviewNonce(value => value + 1)
328
+ } catch (cause) {
329
+ setReceipt({ failure: errorOf(cause) })
330
+ } finally {
331
+ submitting.current = false
332
+ setBusy(false)
333
+ }
334
+ }, [submitReason, futuresDraft, loadAll])
335
+
336
+ const cancel = useCallback(async orderId => {
337
+ setBusy(true)
338
+ try {
339
+ await rpc('futures/cancel', { orderId })
340
+ await loadAll(true)
341
+ } catch (cause) {
342
+ if (cause && (cause.code === 'ORDER_NOT_PENDING' || cause.code === 'ORDER_NOT_FOUND')) {
343
+ setNotice('订单已结束,列表已刷新')
344
+ await loadAll(true)
345
+ } else {
346
+ setError(errorOf(cause))
347
+ }
348
+ } finally {
349
+ setBusy(false)
350
+ }
351
+ }, [loadAll])
352
+
353
+ const copyLedgerPath = useCallback(async () => {
354
+ const path = account !== null ? account.ledgerPath : undefined
355
+ if (path === undefined) return
356
+ const copied = typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText
357
+ ? await navigator.clipboard.writeText(path).then(() => true, () => false)
358
+ : false
359
+ setNotice(copied ? `已复制账本路径:${path}` : `账本路径:${path}`)
360
+ }, [account])
361
+
362
+ const exportLedger = useCallback(async () => {
363
+ try {
364
+ const result = await rpc('futures/account/export')
365
+ if (!result.exists || !result.content) {
366
+ setNotice(result.notice ?? '账本文件尚未创建')
367
+ return
368
+ }
369
+ if (typeof document !== 'undefined' && typeof URL !== 'undefined' && typeof Blob !== 'undefined') {
370
+ const blob = new Blob([result.content], { type: 'application/x-ndjson' })
371
+ const url = URL.createObjectURL(blob)
372
+ const link = document.createElement('a')
373
+ link.href = url
374
+ link.download = 'futures-events.jsonl'
375
+ link.click()
376
+ URL.revokeObjectURL(url)
377
+ }
378
+ setNotice(`已导出期货账本:${result.path}`)
379
+ } catch (cause) {
380
+ setError(errorOf(cause))
381
+ }
382
+ }, [])
383
+
384
+ const refreshAll = useCallback(async () => {
385
+ setBusy(true)
386
+ try {
387
+ await loadAll()
388
+ if (tab === 'review') await loadReview()
389
+ if (contract !== null) void fetchQuote(contract.symbol)
390
+ setPreviewNonce(value => value + 1)
391
+ } finally {
392
+ setBusy(false)
393
+ }
394
+ }, [loadAll, loadReview, tab, contract, fetchQuote])
395
+
396
+ const reset = useCallback(async () => {
397
+ if (!window.confirm('重置期货模拟账户?持仓与挂单会清空;当前账本会先备份,可在备份里找回。')) return
398
+ setBusy(true)
399
+ try {
400
+ setAccount(await rpc('futures/account/reset', { confirm: true }))
401
+ setPreview(null)
402
+ setReceipt(null)
403
+ await loadAll(true)
404
+ if (tab === 'review') await loadReview()
405
+ setPreviewNonce(value => value + 1)
406
+ setNotice('期货账户已重置')
407
+ } catch (cause) {
408
+ setError(errorOf(cause))
409
+ } finally {
410
+ setBusy(false)
411
+ }
412
+ }, [loadAll, loadReview, tab])
413
+
414
+ /** 注资/提款只动可用资金;保证金已被持仓占用,提款上限就是可用资金。 */
415
+ const moveCash = useCallback(async () => {
416
+ const cents = cashAmountCents(cashAmount)
417
+ if (cents === null) return
418
+ const amount = cents / 100
419
+ const depositing = cashSide === 'deposit'
420
+ setBusy(true)
421
+ try {
422
+ setAccount(await rpc(depositing ? 'futures/account/deposit' : 'futures/account/withdraw', { amount }))
423
+ await loadAll(true)
424
+ if (tab === 'review') await loadReview(periodRef.current)
425
+ setPreviewNonce(value => value + 1)
426
+ setCashAmount('')
427
+ setCashOpen(false)
428
+ setError(null)
429
+ setNotice(depositing ? `已注资 ${money(amount)}` : `已提款 ${money(amount)}`)
430
+ } catch (cause) {
431
+ setError(errorOf(cause))
432
+ } finally {
433
+ setBusy(false)
434
+ }
435
+ }, [cashAmount, cashSide, loadAll, loadReview, tab])
436
+
437
+ if (account === null) {
438
+ return h('div', { className: 'pt-inner' },
439
+ h('div', { className: 'pt-head' },
440
+ h('div', null, h('h3', { className: 'pt-title' }, '模拟交易'), h('div', { className: 'pt-sub' }, '期货账户')),
441
+ h('div', { className: 'pt-row' }, accountSwitch,
442
+ h('button', { className: 'pt-btn', onClick: () => { setError(null); void loadAll() } }, '重试'),
443
+ ),
444
+ ),
445
+ error
446
+ ? h('div', { className: 'pt-error', title: error.detail || undefined }, error.text)
447
+ : h('div', { className: 'pt-empty' }, '加载期货模拟交易…'),
448
+ )
449
+ }
450
+
451
+ // Amber from the configured warning line (80% by default), never hard-coded.
452
+ const riskWarn = isFiniteNumber(account.riskRatio) && account.riskRatio >= (account.settings?.warnRiskRatio ?? 0.8)
453
+ const displayQuote = quote ?? (quoteNotice === '' && preview !== null ? preview.quote ?? null : null)
454
+ quoteRef.current = displayQuote
455
+ const tabBar = h('div', { className: 'pt-tabs' }, FUTURES_TABS.map(key => {
456
+ const badge = key === 'positions' ? ` ${positions.length}` : key === 'orders' ? ` ${pending.length}` : ''
457
+ return h('button', {
458
+ key, className: 'pt-tab', 'data-active': tab === key, onClick: () => setTab(key),
459
+ }, `${FUTURES_TAB_LABEL[key]}${badge}`)
460
+ }))
461
+ const tabBody = tab === 'trade'
462
+ ? h(FuturesTradeTab, {
463
+ account, searchQuery, setSearchQuery, searchContracts, searching, contracts, contractNotice,
464
+ contract, selectContract, form, setForm, quote: displayQuote, quoteNotice,
465
+ preview, previewState, previewError, previewHint,
466
+ busy, onSubmit: doSubmit, submitReason, receipt,
467
+ positions, pending, onCancel: cancel, onClose: selectPosition,
468
+ })
469
+ : tab === 'positions'
470
+ ? h(FuturesPositionsTab, { positions, onClose: selectPosition })
471
+ : tab === 'orders'
472
+ ? h(FuturesOrdersTab, { pending, history, busy, onCancel: cancel })
473
+ : h(FuturesReviewTab, {
474
+ review, period,
475
+ setPeriod: key => setPeriod(key),
476
+ cashFlow,
477
+ })
478
+
479
+ return h('div', { className: 'pt-inner' },
480
+ h('div', { className: 'pt-head' },
481
+ h('div', null,
482
+ h('h3', { className: 'pt-title' }, '模拟交易'),
483
+ h('div', { className: 'pt-sub' },
484
+ `期货 · ${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 ? '已锁定' : '运行中'}`,
485
+ status && !status.canSubmit ? h('span', { className: 'pt-note' }, '(当前时段只读)') : null,
486
+ status !== null && status !== undefined ? calendarNote(status.calendar) : null,
487
+ ),
488
+ ),
489
+ h('div', { className: 'pt-row' },
490
+ accountSwitch,
491
+ h(DataSourceBadge, { status: dataSource }),
492
+ h('button', { className: 'pt-btn', onClick: refreshAll, disabled: busy }, '刷新'),
493
+ h('button', {
494
+ className: 'pt-btn', 'data-active': cashOpen, disabled: busy,
495
+ onClick: () => {
496
+ setError(null)
497
+ setCashOpen(value => !value)
498
+ },
499
+ }, '资金'),
500
+ h('button', { className: 'pt-btn pt-btn-danger', onClick: reset, disabled: busy }, '重置'),
501
+ h(FeedbackLink),
502
+ ),
503
+ ),
504
+ h(DataBanner, { status: dataSource, onRetry: refreshAll }),
505
+ cashOpen ? h(CashMovePanel, {
506
+ available: account.cash,
507
+ side: cashSide,
508
+ onSide: setCashSide,
509
+ amount: cashAmount,
510
+ onAmount: setCashAmount,
511
+ busy,
512
+ onCancel: () => {
513
+ setCashOpen(false)
514
+ setCashAmount('')
515
+ },
516
+ onSubmit: moveCash,
517
+ }) : null,
518
+ account.blocked ? h('div', { className: 'pt-blocked' },
519
+ h('div', { className: 'pt-blocked-text' },
520
+ h('div', null, '期货账本校验失败,账户已冻结。'),
521
+ account.blockedReason ? h('div', { className: 'pt-blocked-detail', title: account.blockedReason }, `原因:${account.blockedReason}`) : null,
522
+ account.ledgerPath ? h('div', { className: 'pt-blocked-detail', title: account.ledgerPath }, `账本:${account.ledgerPath}`) : null,
523
+ h('div', { className: 'pt-blocked-hint' }, '可让 AI 助手用 paper_ledger 从备份恢复;重置会先备份。'),
524
+ ),
525
+ h('div', { className: 'pt-row' },
526
+ h('button', { className: 'pt-btn', onClick: exportLedger, disabled: busy }, '导出账本'),
527
+ account.ledgerPath ? h('button', { className: 'pt-btn', onClick: copyLedgerPath, disabled: busy }, '复制路径') : null,
528
+ ),
529
+ ) : null,
530
+ h('div', { className: 'pt-stats' },
531
+ statCell('总权益', money(account.equity)),
532
+ statCell('可用资金', money(account.cash)),
533
+ statCell('保证金占用', money(account.margin)),
534
+ statCell('风险度', pct(account.riskRatio), riskWarn ? 'pt-risk-high' : ''),
535
+ ),
536
+ error ? h('div', { className: 'pt-error', title: error.detail || undefined }, error.text) : null,
537
+ notice ? h('div', { className: 'pt-note' }, notice) : null,
538
+ tab === 'trade'
539
+ ? h('div', {
540
+ className: 'pt-workspace pt-workspace-futures',
541
+ 'data-rail-width': layout.rail === null ? undefined : String(layout.rail),
542
+ 'data-rail-collapsed': layout.collapsed ? 'true' : undefined,
543
+ style: layout.rail === null ? undefined : { '--pt-rail-width': `${layout.rail}px` },
544
+ },
545
+ h('div', { className: 'pt-main' }, tabBar, h('div', { className: 'pt-tab-body' }, tabBody)),
546
+ h(FuturesContractRail, {
547
+ contract,
548
+ quote: displayQuote,
549
+ limit: preview !== null ? preview.limit ?? null : null,
550
+ collapsed: layout.collapsed,
551
+ onCollapse: () => applyLayout({ collapsed: true }),
552
+ onExpand: () => applyLayout({ collapsed: false }),
553
+ onRail: value => applyLayout({ rail: value }, false),
554
+ onRailCommit: value => applyLayout({ rail: value }),
555
+ onRailReset: () => applyLayout({ rail: null }),
556
+ }),
557
+ )
558
+ : h('div', { className: 'pt-main' }, tabBar, h('div', { className: 'pt-tab-body' }, tabBody)),
559
+ )
560
+ }
561
+
562
+ /** Futures ticket: search picks the contract, direction is open/close × long/short. */
563
+ function FuturesTradeTab({
564
+ account, searchQuery, setSearchQuery, searchContracts, searching, contracts, contractNotice,
565
+ contract, selectContract, form, setForm, quote, quoteNotice, preview, previewState, previewError, previewHint,
566
+ busy, onSubmit, submitReason, receipt, positions, pending, onCancel, onClose,
567
+ }) {
568
+ const [book, setBook] = useState(() => (positions.length === 0 && pending.length > 0 ? 'orders' : 'positions'))
569
+ const emptyPreview = previewHint !== ''
570
+ ? previewHint
571
+ : previewState === 'loading' ? '计算中…' : previewError !== '' ? previewError : '计算中…'
572
+ return h('div', { className: 'pt-trade' },
573
+ h('div', { className: 'pt-card pt-ticket-card' },
574
+ h('div', { className: 'pt-row' },
575
+ h('input', {
576
+ className: 'pt-input', style: { flex: 1, minWidth: 180 }, value: searchQuery,
577
+ placeholder: '合约代码/品种/中文名,例如 rb2611',
578
+ onChange: event => setSearchQuery(event.target.value),
579
+ onKeyDown: event => { if (event.key === 'Enter') void searchContracts() },
580
+ }),
581
+ h('button', { className: 'pt-btn', onClick: () => searchContracts(), disabled: searching }, searching ? '搜索中…' : '搜索'),
582
+ h('button', { className: 'pt-btn', onClick: () => searchContracts(true), disabled: searching, title: '重新拉取合约列表' }, '刷新合约'),
583
+ ),
584
+ contracts !== null && contracts.length > 0 && contractNotice !== ''
585
+ ? h('div', { className: 'pt-note' }, contractNotice)
586
+ : null,
587
+ contracts === null
588
+ ? h('div', { className: 'pt-note' }, contract !== null ? `已选 ${contract.symbol} ${contract.name ?? ''}` : '输入代码搜索合约')
589
+ : contracts.length === 0
590
+ ? h('div', { className: 'pt-empty' }, contractNotice || '没有匹配的合约')
591
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4, marginTop: 8, maxHeight: 150, overflow: 'auto' } },
592
+ contracts.map(item => h('button', {
593
+ key: item.symbol, className: 'pt-btn', 'data-active': contract !== null && contract.symbol === item.symbol,
594
+ style: { textAlign: 'left' },
595
+ onClick: () => selectContract(item),
596
+ }, `${item.symbol} ${item.name ?? ''}`)),
597
+ ),
598
+ h('div', { className: 'pt-ticket' },
599
+ h('div', { className: 'pt-ticket-form' },
600
+ h(Field, { label: '合约', span: true },
601
+ h('div', { className: 'pt-quote' },
602
+ contract !== null
603
+ ? h('span', null, `${contract.symbol} ${contract.name ?? ''}`)
604
+ : h('span', { className: 'pt-note' }, '尚未选择合约'),
605
+ quote !== null ? h('span', null, `最新 ${money(quote.last)}`) : null,
606
+ quote !== null ? h('span', { className: 'pt-note' }, quoteUpdateText(quote)) : null,
607
+ quoteNotice !== '' ? h('span', { className: 'pt-note' }, quoteNotice) : null,
608
+ ),
609
+ ),
610
+ h(Field, { label: '方向', span: true },
611
+ h('div', { className: 'pt-seg' },
612
+ [['long', 'open', '开多'], ['short', 'open', '开空'], ['long', 'close', '平多'], ['short', 'close', '平空']].map(([side, offset, label]) =>
613
+ h('button', {
614
+ key: `${side}_${offset}`, 'data-active': form.side === side && form.offset === offset,
615
+ onClick: () => setForm(prev => ({ ...prev, side, offset })),
616
+ }, label),
617
+ ),
618
+ ),
619
+ ),
620
+ h(Field, { label: '类型' }, h('div', { className: 'pt-seg' },
621
+ [['market', '市价'], ['limit', '限价']].map(([key, label]) =>
622
+ h('button', { key, 'data-active': form.type === key, onClick: () => setForm(prev => ({ ...prev, type: key })) }, label)),
623
+ )),
624
+ h(Field, { label: '手数' }, h(DebouncedNumber, {
625
+ value: form.qty, min: 1, step: 1,
626
+ onChange: value => setForm(prev => ({ ...prev, qty: value })),
627
+ })),
628
+ form.type === 'limit'
629
+ ? h(Field, { label: '限价' }, h(DebouncedNumber, {
630
+ value: form.limitPrice, min: 0, step: 0.01,
631
+ onChange: value => setForm(prev => ({ ...prev, limitPrice: value })),
632
+ }))
633
+ : form.offset === 'close'
634
+ ? h(Field, { label: '参考价(可选)' }, h(DebouncedNumber, {
635
+ value: form.price, min: 0, step: 0.01,
636
+ onChange: value => setForm(prev => ({ ...prev, price: value })),
637
+ }))
638
+ : h(Field, { label: '价格' }, h('div', { className: 'pt-note', style: { padding: '6px 0' } }, '按最新价成交')),
639
+ h(Field, { label: '备注(复盘用)', span: true }, h('input', {
640
+ className: 'pt-input', value: form.note, maxLength: 120,
641
+ onChange: event => setForm(prev => ({ ...prev, note: event.target.value })),
642
+ })),
643
+ ),
644
+ h('div', { className: 'pt-preview-pane' },
645
+ h('div', { className: 'pt-card-title', style: { marginBottom: 6 } }, '预览'),
646
+ preview !== null ? (preview.price > 0 ? h('div', { className: 'pt-preview' },
647
+ previewRow('预估成交价', money(preview.price)),
648
+ previewRow('合约价值', cents(preview.amountCents)),
649
+ previewRow('保证金', cents(preview.marginCents)),
650
+ previewRow('手续费', cents(preview.feesCents)),
651
+ previewRow('成交后现金', cents(preview.cashAfterCents), preview.cashAfterCents < 0 ? 'pt-risk-high' : undefined),
652
+ previewRow('风险度', pct(preview.riskRatioAfter), preview.riskRatioAfter >= (account.settings?.warnRiskRatio ?? 0.8) ? 'pt-risk-high' : undefined),
653
+ form.offset === 'open'
654
+ ? previewRow('最多可开', `${count(preview.maxOpenQty)} 手`)
655
+ : previewRow('平仓可平', `${count(preview.availableCloseQty)} 手`),
656
+ previewRow('涨停', preview.limit ? money(preview.limit.upper) : '—'),
657
+ previewRow('跌停', preview.limit ? money(preview.limit.lower) : '—'),
658
+ previewState === 'loading' ? h('div', { className: 'pt-note' }, '计算中…') : null,
659
+ preview.warnings.length > 0 ? h('div', { className: 'pt-warn' }, preview.warnings.join(';')) : null,
660
+ previewState === 'error' && previewError !== '' ? h('div', { className: 'pt-warn' }, previewError) : null,
661
+ ) : h('div', { className: 'pt-empty' }, '没有可用行情,暂不可开仓')) : h('div', { className: 'pt-empty' }, emptyPreview),
662
+ ),
663
+ ),
664
+ h('div', { className: 'pt-ticket-foot' },
665
+ submitReason !== '' ? h('div', { className: 'pt-note' }, `不可提交:${submitReason}`) : null,
666
+ h('button', {
667
+ className: 'pt-btn pt-btn-primary pt-ticket-submit', onClick: onSubmit,
668
+ title: submitReason || undefined,
669
+ disabled: busy || submitReason !== '',
670
+ }, directionText(form.side, form.offset)),
671
+ h('div', { className: 'pt-ticket-meta' },
672
+ h('span', { className: 'pt-note' },
673
+ `可用 ${money(account.cash)} · 保证金 ${money(account.margin)} · 风险度 ${pct(account.riskRatio)}`),
674
+ ),
675
+ receipt ? h(FuturesReceiptLine, { receipt }) : null,
676
+ ),
677
+ ),
678
+ h(FuturesBook, { positions, pending, book, setBook, busy, onCancel, onClose }),
679
+ )
680
+ }
681
+
682
+ /** Persistent holdings/orders book under the futures ticket. */
683
+ function FuturesBook({ positions, pending, book, setBook, busy, onCancel, onClose }) {
684
+ const showPositions = book === 'positions'
685
+ return h('div', { className: 'pt-card pt-trade-book' },
686
+ h('div', { className: 'pt-book-head' },
687
+ h('div', { className: 'pt-seg' },
688
+ h('button', { 'data-active': showPositions, onClick: () => setBook('positions') }, `持仓 ${positions.length}`),
689
+ h('button', { 'data-active': !showPositions, onClick: () => setBook('orders') }, `挂单 ${pending.length}`),
690
+ ),
691
+ h('div', { className: 'pt-note' }, showPositions ? '收盘按结算价盯市' : '未成交委托,可随时撤单'),
692
+ ),
693
+ h('div', { className: 'pt-book-scroll' },
694
+ showPositions
695
+ ? (positions.length === 0
696
+ ? h('div', { className: 'pt-empty pt-book-empty' }, '无持仓 · 成交后自动显示')
697
+ : h(Table, null,
698
+ h('thead', null, h('tr', null,
699
+ ['合约', '方向', '手数', '今仓', '均价', '最新价', '浮盈亏'].map(label => h('th', { key: label }, label)),
700
+ h('th', null, '操作'),
701
+ )),
702
+ h('tbody', null, positions.map(position => h('tr', { key: `${position.symbol}-${position.side}` },
703
+ h('td', null, position.symbol),
704
+ h('td', null, FUTURES_SIDE_TEXT[position.side] ?? position.side),
705
+ h('td', null, count(position.qty)),
706
+ h('td', null, count(position.todayQty)),
707
+ h('td', null, money(position.avgPrice)),
708
+ h('td', null, money(position.lastPrice)),
709
+ h('td', { className: tone(position.unrealizedPnlCents ?? 0) }, cents(position.unrealizedPnlCents)),
710
+ h('td', null, h('button', {
711
+ className: 'pt-btn', onClick: () => onClose(position), disabled: !(position.qty > 0),
712
+ }, '平仓')),
713
+ ))),
714
+ ))
715
+ : (pending.length === 0
716
+ ? h('div', { className: 'pt-empty pt-book-empty' }, '无挂单 · 未成交的限价委托会停在这里')
717
+ : h(Table, null,
718
+ h('thead', null, h('tr', null,
719
+ ['合约', '方向', '类型', '手数', '限价', '状态'].map(label => h('th', { key: label }, label)),
720
+ h('th', null, '操作'),
721
+ )),
722
+ h('tbody', null, pending.map(order => h('tr', { key: order.id },
723
+ h('td', null, order.symbol),
724
+ h('td', null, directionText(order.side, order.offset)),
725
+ h('td', null, orderTypeText(order.type)),
726
+ h('td', null, count(order.qty)),
727
+ h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
728
+ h('td', null, FUTURES_STATUS_TEXT[order.status] ?? order.status),
729
+ h('td', null, h('button', { className: 'pt-btn', onClick: () => onCancel(order.id), disabled: busy }, '撤单')),
730
+ ))),
731
+ )),
732
+ ),
733
+ )
734
+ }
735
+
736
+ function FuturesReceiptLine({ receipt }) {
737
+ if (receipt.failure !== undefined) {
738
+ return h('div', { className: 'pt-receipt', 'data-state': 'rejected', title: receipt.failure.detail || undefined },
739
+ `拒绝:${receipt.failure.text}`,
740
+ )
741
+ }
742
+ const { order, cash } = receipt
743
+ const direction = directionText(order.side, order.offset)
744
+ if (order.status === 'rejected') {
745
+ return h('div', { className: 'pt-receipt', 'data-state': 'rejected', title: order.reason || undefined },
746
+ `拒绝:${direction} ${order.symbol} ${count(order.qty)} 手 · ${reasonText(order.reason, 'futures') || '未通过风控'}`,
747
+ )
748
+ }
749
+ if (order.status === 'filled') {
750
+ return h('div', { className: 'pt-receipt', 'data-state': 'filled', title: order.id },
751
+ `成交:${direction} ${order.symbol} ${count(order.qty)} 手 · 价 ${money(order.fillPrice)} · 保证金 ${cents(order.marginCents)} · 费用 ${cents(order.feesCents)} · 成交后现金 ${money(cash)} · 单 ${order.id}`,
752
+ )
753
+ }
754
+ return h('div', { className: 'pt-receipt', 'data-state': 'resting', title: order.id },
755
+ `挂单:${direction} ${order.symbol} ${count(order.qty)} 手${order.limitPrice === undefined ? '' : ` @ ${money(order.limitPrice)}`} · 现价未穿越,成交前一直挂单 · 单 ${order.id}`,
756
+ )
757
+ }
758
+
759
+ function FuturesPositionsTab({ positions, onClose }) {
760
+ if (positions.length === 0) return h('div', { className: 'pt-empty' }, '无持仓 · 开仓成交后自动显示')
761
+ return h(Table, null,
762
+ h('thead', null, h('tr', null,
763
+ ['合约', '方向', '手数', '今仓', '均价', '最新价', '浮盈亏', '保证金', '到期日'].map(label => h('th', { key: label }, label)),
764
+ h('th', null, '操作'),
765
+ )),
766
+ h('tbody', null, positions.map(position => h('tr', { key: `${position.symbol}-${position.side}` },
767
+ h('td', null, position.symbol),
768
+ h('td', null, FUTURES_SIDE_TEXT[position.side] ?? position.side),
769
+ h('td', null, count(position.qty)),
770
+ h('td', null, count(position.todayQty)),
771
+ h('td', null, money(position.avgPrice)),
772
+ h('td', null, money(position.lastPrice)),
773
+ h('td', { className: tone(position.unrealizedPnlCents ?? 0) }, cents(position.unrealizedPnlCents)),
774
+ h('td', null, cents(position.marginCents)),
775
+ h('td', null, position.deListDate ?? '—'),
776
+ h('td', null, h('button', { className: 'pt-btn', onClick: () => onClose(position) }, '平仓')),
777
+ ))),
778
+ )
779
+ }
780
+
781
+ function FuturesOrdersTab({ pending, history, busy, onCancel }) {
782
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } },
783
+ h('div', null,
784
+ h('div', { className: 'pt-sub' }, '挂单'),
785
+ pending.length === 0 ? h('div', { className: 'pt-empty' }, '无挂单') : h(Table, null,
786
+ h('thead', null, h('tr', null,
787
+ ['合约', '方向', '类型', '手数', '限价', '状态', '备注', '操作'].map(label => h('th', { key: label }, label)),
788
+ )),
789
+ h('tbody', null, pending.map(order => h('tr', { key: order.id },
790
+ h('td', null, order.symbol),
791
+ h('td', null, directionText(order.side, order.offset)),
792
+ h('td', null, orderTypeText(order.type)),
793
+ h('td', null, count(order.qty)),
794
+ h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
795
+ h('td', null, FUTURES_STATUS_TEXT[order.status] ?? order.status),
796
+ h('td', { title: order.note ?? undefined }, order.note === undefined ? '' : h('span', { className: 'pt-note-cell' }, order.note)),
797
+ h('td', null, h('button', { className: 'pt-btn', onClick: () => onCancel(order.id), disabled: busy }, '撤单')),
798
+ ))),
799
+ ),
800
+ pending.some(order => order.status === 'queued')
801
+ ? h('div', { className: 'pt-note' }, '「排队」:当前时段不撮合,下一交易时段会尝试成交,可随时撤单。')
802
+ : null,
803
+ ),
804
+ h('div', null,
805
+ h('div', { className: 'pt-sub' }, '历史'),
806
+ history.length === 0 ? h('div', { className: 'pt-empty' }, '无历史订单') : h(Table, null,
807
+ h('thead', null, h('tr', null,
808
+ ['时间', '合约', '方向', '类型', '手数', '限价', '状态', '成交价', '原因', '备注'].map(label => h('th', { key: label }, label)),
809
+ )),
810
+ h('tbody', null, history.slice(0, 30).map(order => h('tr', { key: order.id },
811
+ h('td', null, dateTime(order.createdAt)),
812
+ h('td', null, order.symbol),
813
+ h('td', null, directionText(order.side, order.offset)),
814
+ h('td', null, orderTypeText(order.type)),
815
+ h('td', null, count(order.qty)),
816
+ h('td', null, order.limitPrice === undefined ? '—' : money(order.limitPrice)),
817
+ h('td', null, FUTURES_STATUS_TEXT[order.status] ?? order.status),
818
+ h('td', null, order.fillPrice === undefined ? '—' : money(order.fillPrice)),
819
+ h('td', { title: order.reason ?? undefined }, reasonText(order.reason, 'futures')),
820
+ h('td', { title: order.note ?? undefined }, order.note === undefined ? '' : h('span', { className: 'pt-note-cell' }, order.note)),
821
+ ))),
822
+ ),
823
+ history.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${history.length} 条`) : null,
824
+ ),
825
+ )
826
+ }
827
+
828
+ function FuturesReviewTab({ review, period, setPeriod, cashFlow }) {
829
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
830
+ h('div', { className: 'pt-row' }, PERIODS.map(([key, label]) =>
831
+ h('button', { key, className: 'pt-btn', 'data-active': period === key, onClick: () => setPeriod(key) }, label),
832
+ )),
833
+ review !== null ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
834
+ h('div', { className: 'pt-stats' },
835
+ statCell('成交笔数', count(review.tradeCount)),
836
+ statCell('已实现盈亏', signed(review.realizedPnl), tone(review.realizedPnl)),
837
+ statCell('费用合计', money(review.totalFees)),
838
+ statCell('最大回撤', pct(review.maxDrawdownPct)),
839
+ ),
840
+ h('div', { className: 'pt-note' },
841
+ `开仓 ${count(review.openCount)} 笔 · 平仓 ${count(review.closeCount)} 笔 · 盈利 ${count(review.winCount)} 笔 · 亏损 ${count(review.lossCount)} 笔`),
842
+ h('div', { className: 'pt-chart-wrap' }, h(EquityChart, { points: review.equityCurve })),
843
+ h('div', null,
844
+ h('div', { className: 'pt-sub' }, '分品种统计'),
845
+ review.byProduct.length === 0 ? h('div', { className: 'pt-empty' }, '暂无成交') : h(Table, null,
846
+ h('thead', null, h('tr', null,
847
+ ['品种', '成交笔数', '已实现盈亏'].map(label => h('th', { key: label }, label)),
848
+ )),
849
+ h('tbody', null, review.byProduct.map(item => h('tr', { key: item.product },
850
+ h('td', null, String(item.product ?? '').toUpperCase()),
851
+ h('td', null, count(item.tradeCount)),
852
+ h('td', { className: tone(item.realizedPnl) }, signed(item.realizedPnl)),
853
+ ))),
854
+ ),
855
+ ),
856
+ h('div', null,
857
+ h('div', { className: 'pt-sub' }, '资金流水'),
858
+ cashFlow.length === 0 ? h('div', { className: 'pt-empty' }, '暂无流水') : h(Table, null,
859
+ h('thead', null, h('tr', null, ['时间', '类型', '金额', '余额'].map(label => h('th', { key: label }, label)))),
860
+ h('tbody', null, cashFlow.slice(-30).reverse().map((row, index) => h('tr', { key: `${row.ts}-${index}` },
861
+ h('td', null, dateTime(row.ts)),
862
+ h('td', null, FUTURES_CASH_TYPE_TEXT[row.type] ?? row.type),
863
+ h('td', { className: tone(row.amount) }, signed(row.amount)),
864
+ h('td', null, money(row.balance)),
865
+ ))),
866
+ ),
867
+ cashFlow.length > 30 ? h('div', { className: 'pt-note' }, `仅显示最近 30 条,共 ${cashFlow.length} 条`) : null,
868
+ ),
869
+ ) : h('div', { className: 'pt-empty' }, '加载复盘…'),
870
+ )
871
+ }
872
+
873
+ /** Right rail for the futures ticket: static terms plus the marked quote. */
874
+ function FuturesContractRail({
875
+ contract, quote, limit, collapsed, onCollapse, onExpand, onRail, onRailCommit, onRailReset,
876
+ }) {
877
+ if (collapsed) return h(CollapsedRail, { label: '合约要素栏', className: 'pt-futures-rail', onExpand })
878
+ return h('aside', { className: 'pt-futures-rail', 'aria-label': '合约要素' },
879
+ h(RailSplitHandle, {
880
+ mode: 'futures', label: '调整合约要素栏宽度',
881
+ onPreview: onRail, onCommit: onRailCommit, onReset: onRailReset,
882
+ }),
883
+ h('div', { className: 'pt-card' },
884
+ h('div', { className: 'pt-card-head' },
885
+ h('div', { className: 'pt-card-title', style: { margin: 0 } }, '合约要素'),
886
+ h(RailToggle, { label: '合约要素栏', onClick: onCollapse }),
887
+ ),
888
+ contract === null
889
+ ? h('div', { className: 'pt-empty' }, '搜索并选择合约')
890
+ : h('div', { className: 'pt-preview' },
891
+ previewRow('合约', contract.symbol),
892
+ previewRow('名称', contract.name ?? '—'),
893
+ previewRow('交易所', contract.exchange ?? '—'),
894
+ previewRow('品种', contract.product ?? '—'),
895
+ previewRow('乘数', contract.multiplier === undefined ? '—' : count(contract.multiplier)),
896
+ previewRow('最小变动', money(contract.tickSize)),
897
+ previewRow('保证金率', pct(contract.marginRate)),
898
+ previewRow('到期日', contract.deListDate ?? '—'),
899
+ previewRow('涨停', limit === null ? '—' : money(limit.upper)),
900
+ previewRow('跌停', limit === null ? '—' : money(limit.lower)),
901
+ previewRow('最新价', quote === null ? '—' : money(quote.last),
902
+ quote !== null && quote.preSettlement !== undefined && quote.last !== quote.preSettlement
903
+ ? (quote.last > quote.preSettlement ? 'pt-up' : 'pt-down')
904
+ : undefined),
905
+ previewRow('昨结', quote === null || quote.preSettlement === undefined ? '—' : money(quote.preSettlement)),
906
+ ),
907
+ ),
908
+ )
909
+ }
910
+
911
+ /* ---------------------------------------------------------- dashboard -- */