@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,447 @@
1
+ /* 35 · hooks — stateful behaviour shared by the stock and futures dashboards. */
2
+ /**
3
+ * Rail width/height preference for one plane.
4
+ *
5
+ * A drag previews in memory and only writes local storage on release, so
6
+ * `applyLayout(patch, false)` stays cheap during a drag.
7
+ */
8
+ function useRailLayout(mode) {
9
+ const [layout, setLayout] = useState(() => readLayout()[mode])
10
+ const applyLayout = useCallback((patch, persist = true) => {
11
+ setLayout(prev => ({ ...prev, ...patch }))
12
+ if (persist) writeLayout(mode, patch)
13
+ }, [mode])
14
+ return [layout, applyLayout]
15
+ }
16
+
17
+ /**
18
+ * Run `work` every interval while the document is visible.
19
+ *
20
+ * The host scheduler is the primary matcher; this is only the visible
21
+ * panel's extra trigger, and a hidden panel must not poll.
22
+ */
23
+ function useVisiblePolling(work, intervalMs = 5000) {
24
+ useEffect(() => {
25
+ const timer = setInterval(() => {
26
+ if (document.visibilityState === 'visible') void work()
27
+ }, intervalMs)
28
+ return () => clearInterval(timer)
29
+ }, [work, intervalMs])
30
+ }
31
+
32
+ /**
33
+ * One account's free-form notes: load on account/tab switch, debounce the
34
+ * edits, flush on the way out. The model has no tool for this text.
35
+ *
36
+ * The in-flight save is stamped with its account id: a response that lands
37
+ * after the panel switched belongs to the old account and must not retarget
38
+ * later flushes.
39
+ */
40
+ function useAccountNotes(request, accountId, tab) {
41
+ const [text, setText] = useState('')
42
+ const [meta, setMeta] = useState(null)
43
+ const [status, setStatus] = useState('idle')
44
+ const [error, setError] = useState('')
45
+ const textRef = useRef('')
46
+ const timer = useRef(null)
47
+ const ref = useRef({ accountId: null, saved: '' })
48
+ const alive = useRef(true)
49
+ useEffect(() => {
50
+ alive.current = true
51
+ return () => { alive.current = false }
52
+ }, [])
53
+
54
+ const save = useCallback(async (value, id) => {
55
+ if (id === null || id === undefined) return
56
+ setStatus('saving')
57
+ try {
58
+ const view = await request('note/set', { text: value }, id)
59
+ if (!alive.current || ref.current.accountId !== id) return
60
+ ref.current = { accountId: id, saved: value }
61
+ setMeta(view)
62
+ setStatus('saved')
63
+ setError('')
64
+ } catch (cause) {
65
+ if (!alive.current || ref.current.accountId !== id) return
66
+ setStatus('error')
67
+ setError(errorOf(cause).text)
68
+ }
69
+ }, [])
70
+
71
+ /** Persist a pending edit now; a no-op when nothing changed. */
72
+ const flush = useCallback(async () => {
73
+ if (timer.current !== null) {
74
+ clearTimeout(timer.current)
75
+ timer.current = null
76
+ }
77
+ const { accountId: id, saved } = ref.current
78
+ if (id === null || textRef.current === saved) return
79
+ await save(textRef.current, id)
80
+ }, [save])
81
+
82
+ const load = useCallback(async (id, options = {}) => {
83
+ if (id === null) return
84
+ // Switching accounts must not drop the previous account's edit, but an
85
+ // explicit "重新加载" must: discard is what that button promises.
86
+ if (options.discard !== true) await flush()
87
+ else if (timer.current !== null) {
88
+ clearTimeout(timer.current)
89
+ timer.current = null
90
+ }
91
+ ref.current = { accountId: id, saved: '' }
92
+ // Blank the editor while loading: keeping the previous account's text
93
+ // would let a keystroke save it into the new account.
94
+ textRef.current = ''
95
+ setText('')
96
+ setStatus('idle')
97
+ setError('')
98
+ try {
99
+ const view = await request('note/get', {}, id)
100
+ if (!alive.current || ref.current.accountId !== id) return
101
+ ref.current = { accountId: id, saved: view.text }
102
+ textRef.current = view.text
103
+ setText(view.text)
104
+ setMeta(view)
105
+ } catch (cause) {
106
+ if (!alive.current) return
107
+ setError(errorOf(cause).text)
108
+ }
109
+ }, [flush])
110
+
111
+ const change = useCallback(value => {
112
+ setText(value)
113
+ textRef.current = value
114
+ setStatus('idle')
115
+ if (timer.current !== null) clearTimeout(timer.current)
116
+ const id = ref.current.accountId
117
+ timer.current = setTimeout(() => {
118
+ timer.current = null
119
+ void save(value, id)
120
+ }, 700)
121
+ }, [save])
122
+
123
+ useEffect(() => {
124
+ if (accountId !== null) void load(accountId)
125
+ }, [accountId, load])
126
+
127
+ useEffect(() => {
128
+ if (tab === 'notes') void load(accountId)
129
+ // eslint-disable-next-line react-hooks/exhaustive-deps
130
+ }, [tab, accountId, load])
131
+
132
+ // Leaving the tab (or the panel) within the debounce window still writes.
133
+ useEffect(() => () => {
134
+ if (timer.current !== null) clearTimeout(timer.current)
135
+ void flush()
136
+ }, [flush])
137
+
138
+ return {
139
+ text, meta, status, error,
140
+ change, flush, load,
141
+ reload: () => load(accountId, { discard: true }),
142
+ }
143
+ }
144
+
145
+ /**
146
+ * The stock account registry and the selected account.
147
+ *
148
+ * One place applies the selection: the dashboard's scope ref stamps
149
+ * account-scoped requests, so it is set before the reload; per-account view
150
+ * state is cleared so nothing from the previous ledger (a preview, a
151
+ * receipt) survives the switch. The futures ledger is filtered out: this
152
+ * panel only manages stock accounts, and picking futures would fail every
153
+ * request.
154
+ */
155
+ function useAccountRegistry({ scope, request, tab, loadAll, loadReviewDetail, loadCompare, clearView, setBusy, setError, setNotice, onNotes }) {
156
+ const [accounts, setAccounts] = useState(null)
157
+ const [archived, setArchived] = useState([])
158
+ const [tickMs, setTickMs] = useState(5000)
159
+ const [currentAccountId, setCurrentAccountId] = useState(null)
160
+ const [accountEditor, setAccountEditor] = useState(null)
161
+ const alive = useRef(true)
162
+ useEffect(() => {
163
+ alive.current = true
164
+ return () => { alive.current = false }
165
+ }, [])
166
+
167
+ /** The registry is metadata only: a failure leaves the panel on default. */
168
+ const loadAccounts = useCallback(async () => {
169
+ try {
170
+ // The panel asks for archived entries too: it renders them in the
171
+ // "已归档" section and needs them out of the selectable list only.
172
+ const view = await request('accounts/list', { kind: 'stock', includeArchived: true })
173
+ if (!alive.current) return
174
+ const visible = view.accounts.filter(item => item.archived !== true)
175
+ setAccounts(visible)
176
+ setArchived(view.accounts.filter(item => item.archived === true))
177
+ if (typeof view.tickMs === 'number' && view.tickMs > 0) setTickMs(view.tickMs)
178
+ setCurrentAccountId(previous => {
179
+ if (previous !== null && visible.some(item => item.id === previous)) return previous
180
+ const remembered = visible.find(item => item.id === readCurrentAccount())
181
+ return remembered === undefined ? view.defaultIds.stock : remembered.id
182
+ })
183
+ } catch {
184
+ // Keep whatever is selected; the default account still answers.
185
+ }
186
+ }, [])
187
+
188
+ const stockAccounts = useMemo(() => accounts ?? [], [accounts])
189
+ const currentAccount = useMemo(
190
+ () => stockAccounts.find(item => item.id === currentAccountId) ?? null,
191
+ [stockAccounts, currentAccountId],
192
+ )
193
+
194
+ useEffect(() => {
195
+ if (currentAccountId === null) return
196
+ scope.current = currentAccountId
197
+ writeCurrentAccount(currentAccountId)
198
+ clearView()
199
+ void loadAll()
200
+ if (tab === 'review') void loadReviewDetail()
201
+ if (tab === 'compare') void loadCompare()
202
+ // `tab` and `clearView` are read but not dependencies: switching tabs
203
+ // must not re-query, and the clear callback only touches setters.
204
+ // eslint-disable-next-line react-hooks/exhaustive-deps
205
+ }, [currentAccountId, loadAll, loadReviewDetail, loadCompare])
206
+
207
+ useEffect(() => {
208
+ void loadAccounts()
209
+ return () => { scope.current = null }
210
+ }, [loadAccounts])
211
+
212
+ /** Create/rename go through the registry, then re-read it. */
213
+ const submitAccountEditor = useCallback(async values => {
214
+ if (accountEditor === null) return
215
+ const mode = accountEditor
216
+ setBusy(true)
217
+ try {
218
+ if (mode === 'create') {
219
+ const created = await request('accounts/create', {
220
+ name: values.name.trim(),
221
+ ...(values.cash.trim() === '' ? {} : { initialCash: Number(values.cash) }),
222
+ })
223
+ await loadAccounts()
224
+ setNotice(`已创建账户「${created.name}」`)
225
+ scope.current = created.id
226
+ setCurrentAccountId(created.id)
227
+ } else {
228
+ await request('accounts/rename', { id: currentAccountId, name: values.name.trim() })
229
+ await loadAccounts()
230
+ setNotice('账户已改名')
231
+ }
232
+ setAccountEditor(null)
233
+ } catch (cause) {
234
+ setError(errorOf(cause))
235
+ } finally {
236
+ setBusy(false)
237
+ }
238
+ }, [accountEditor, currentAccountId, loadAccounts, setBusy, setError, setNotice])
239
+
240
+ /** Picker actions: editor modes open a form, archive/lock apply immediately. */
241
+ const runAccountAction = useCallback(async action => {
242
+ if (currentAccount === null) return
243
+ if (action === 'notes') {
244
+ onNotes()
245
+ return
246
+ }
247
+ if (action === 'create' || action === 'rename') {
248
+ setAccountEditor(action)
249
+ return
250
+ }
251
+ setBusy(true)
252
+ try {
253
+ if (action === 'archive') {
254
+ await request('accounts/archive', { id: currentAccount.id })
255
+ setNotice(`已归档「${currentAccount.name}」:数据保留,可随时恢复归档`)
256
+ // The reload drops it from the selectable list, so the selection
257
+ // effect moves the panel to another account on its own.
258
+ } else {
259
+ await rpc(currentAccount.locked ? 'accounts/unlock' : 'accounts/lock', { id: currentAccount.id })
260
+ setNotice(currentAccount.locked ? '已解锁账户' : '已锁定账户')
261
+ }
262
+ await loadAccounts()
263
+ } catch (cause) {
264
+ setError(errorOf(cause))
265
+ } finally {
266
+ setBusy(false)
267
+ }
268
+ }, [currentAccount, loadAccounts, onNotes, setBusy, setError, setNotice])
269
+
270
+ /** Bring one archived account back: unlock-free, selection follows it. */
271
+ const restoreArchived = useCallback(async id => {
272
+ setBusy(true)
273
+ try {
274
+ const meta = await request('accounts/unarchive', { id })
275
+ await loadAccounts()
276
+ setNotice(`已恢复归档「${meta.name}」`)
277
+ setCurrentAccountId(meta.id)
278
+ } catch (cause) {
279
+ setError(errorOf(cause))
280
+ } finally {
281
+ setBusy(false)
282
+ }
283
+ }, [loadAccounts, setBusy, setError, setNotice])
284
+
285
+ return {
286
+ accounts, archived, tickMs, stockAccounts, currentAccountId, setCurrentAccountId, currentAccount,
287
+ accountEditor, setAccountEditor, loadAccounts, restoreArchived,
288
+ submitAccountEditor, runAccountAction,
289
+ }
290
+ }
291
+
292
+ /**
293
+ * The open ticket's quote and preview.
294
+ *
295
+ * One preview per input change, debounced; the response carries the quote,
296
+ * so a complete draft costs a single request. While the draft is unfinished
297
+ * the price line asks for the quote alone — a limit order whose limit is
298
+ * still being typed must show what the stock costs. A nonce forces a
299
+ * re-preview after a fill or a reset without touching the form.
300
+ */
301
+ function useTicketPreview(request, form) {
302
+ const [preview, setPreview] = useState(null)
303
+ const [previewState, setPreviewState] = useState('idle')
304
+ const [previewError, setPreviewError] = useState('')
305
+ const [previewNonce, setPreviewNonce] = useState(0)
306
+ // Quote for an unfinished draft (symbol known, qty/limit still missing).
307
+ // A complete draft gets its quote from the preview response instead.
308
+ const [symbolQuote, setSymbolQuote] = useState(null)
309
+ const [quoteError, setQuoteError] = useState('')
310
+ const [quoteNotice, setQuoteNotice] = useState('')
311
+ const previewSymbol = useRef('')
312
+ const previewSeq = useRef(0)
313
+ // Symbols whose quote the blocked-preview path already asked for.
314
+ const quoteSymbol = useRef('')
315
+ const quoteRef = useRef(null)
316
+ const lastTicketRefresh = useRef(0)
317
+ const alive = useRef(true)
318
+ useEffect(() => {
319
+ alive.current = true
320
+ return () => { alive.current = false }
321
+ }, [])
322
+
323
+ const draft = useCallback(() => ({
324
+ symbol: form.symbol.trim(),
325
+ side: form.side,
326
+ type: form.type,
327
+ qty: Number(form.qty),
328
+ limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
329
+ price: form.type === 'market' && form.price !== '' ? Number(form.price) : undefined,
330
+ note: form.note.trim() === '' ? undefined : form.note.trim(),
331
+ }), [form])
332
+
333
+ // The note is not part of the preview: only the trading fields are.
334
+ const previewDraft = useCallback(() => ({
335
+ symbol: form.symbol.trim(),
336
+ side: form.side,
337
+ type: form.type,
338
+ qty: Number(form.qty),
339
+ limitPrice: form.type === 'limit' ? Number(form.limitPrice) : undefined,
340
+ price: form.type === 'market' && form.price !== '' ? Number(form.price) : undefined,
341
+ }), [form.symbol, form.side, form.type, form.qty, form.limitPrice, form.price])
342
+
343
+ useEffect(() => {
344
+ const current = previewDraft()
345
+ previewSeq.current += 1
346
+ const seq = previewSeq.current
347
+ if (previewBlockReason(current) !== '') {
348
+ previewSymbol.current = ''
349
+ setPreview(null)
350
+ setPreviewState('idle')
351
+ setPreviewError('')
352
+ if (current.symbol.length < 6) {
353
+ quoteSymbol.current = ''
354
+ setSymbolQuote(null)
355
+ setQuoteError('')
356
+ setQuoteNotice('')
357
+ return
358
+ }
359
+ if (quoteSymbol.current === current.symbol) return
360
+ const timer = setTimeout(() => {
361
+ request('market/quote', { symbols: [current.symbol] })
362
+ .then(result => {
363
+ if (!alive.current || seq !== previewSeq.current) return
364
+ const found = result.quotes[0] ?? null
365
+ quoteSymbol.current = found === null ? '' : current.symbol
366
+ setSymbolQuote(found)
367
+ setQuoteError(found ? '' : (result.notice ?? '没有查到行情'))
368
+ setQuoteNotice(found ? (result.notice ?? '') : '')
369
+ })
370
+ .catch(cause => {
371
+ if (!alive.current || seq !== previewSeq.current) return
372
+ quoteSymbol.current = ''
373
+ setSymbolQuote(null)
374
+ setQuoteError(errorOf(cause).text)
375
+ setQuoteNotice('')
376
+ })
377
+ }, 300)
378
+ return () => clearTimeout(timer)
379
+ }
380
+ quoteSymbol.current = current.symbol
381
+ // A completed draft gets its quote from the preview; any error left
382
+ // over from the earlier quote-only probe belongs to the old symbol and
383
+ // must not stay on screen after the ticket has been corrected.
384
+ setQuoteError('')
385
+ setQuoteNotice('')
386
+ if (previewSymbol.current !== current.symbol) {
387
+ previewSymbol.current = current.symbol
388
+ setPreview(null)
389
+ }
390
+ setPreviewState('loading')
391
+ const timer = setTimeout(() => {
392
+ request('order/preview', current)
393
+ .then(result => {
394
+ if (!alive.current || seq !== previewSeq.current) return
395
+ setPreview(result)
396
+ // Keep the quote for an unfinished draft: switching to 限价 must
397
+ // not blank the price line while the limit is still being typed.
398
+ if (result.quote) setSymbolQuote(result.quote)
399
+ setPreviewError('')
400
+ setPreviewState('ready')
401
+ })
402
+ .catch(cause => {
403
+ if (!alive.current || seq !== previewSeq.current) return
404
+ setPreviewError(errorOf(cause).text)
405
+ setPreviewState('error')
406
+ })
407
+ }, 300)
408
+ return () => clearTimeout(timer)
409
+ }, [previewDraft, previewNonce])
410
+
411
+ const quote = preview ? preview.quote ?? null : symbolQuote
412
+ quoteRef.current = quote
413
+
414
+ /**
415
+ * Re-price the open ticket on the polling beat. An unfinished draft only
416
+ * fetches the quote, so clear its dedupe key too; a degraded quote
417
+ * refreshes slowly, otherwise the 5 s beat is the biggest free-tier cost.
418
+ */
419
+ const maybeRefreshQuote = useCallback(() => {
420
+ if (Date.now() - lastTicketRefresh.current < ticketRefreshInterval(quoteRef.current)) return
421
+ lastTicketRefresh.current = Date.now()
422
+ quoteSymbol.current = ''
423
+ setPreviewNonce(value => value + 1)
424
+ }, [])
425
+
426
+ /** Retry the quote even when the symbol did not change. */
427
+ const forceQuoteRefresh = useCallback(() => {
428
+ quoteSymbol.current = ''
429
+ setPreviewNonce(value => value + 1)
430
+ }, [])
431
+
432
+ /** Drop the preview after a reset or fill; the next edit rebuilds it. */
433
+ const invalidate = useCallback(() => setPreview(null), [])
434
+ const bump = useCallback(() => setPreviewNonce(value => value + 1), [])
435
+ /** Clear everything that belonged to the previous account. */
436
+ const clear = useCallback(() => {
437
+ setPreview(null)
438
+ setSymbolQuote(null)
439
+ setQuoteError('')
440
+ setQuoteNotice('')
441
+ }, [])
442
+
443
+ return {
444
+ preview, previewState, previewError, symbolQuote, quote, quoteError, quoteNotice,
445
+ previewDraft, draft, maybeRefreshQuote, forceQuoteRefresh, invalidate, bump, clear,
446
+ }
447
+ }