@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
@@ -12,7 +12,6 @@ import type {
12
12
  FillView,
13
13
  LedgerExport,
14
14
  LedgerSnapshotsView,
15
- LedgerSnapshotView,
16
15
  MarketStatus,
17
16
  OrderDraft,
18
17
  OrderView,
@@ -40,9 +39,11 @@ import { toAccountView, toFillView, toOrderView, toReview, previewOrder } from '
40
39
  import type { AccountState, LedgerEvent, Order } from '../core/types.js'
41
40
  import type { BarsResult, MarketDataPort, QuoteResult } from '../data/market-data-port.js'
42
41
  import type { TradingCalendarPort } from '../data/trading-calendar-port.js'
43
- import type { AccountStore, LedgerSnapshot } from '../store/port.js'
42
+ import type { AccountStore } from '../store/port.js'
44
43
  import type { ShortlistStore } from '../store/shortlist.js'
45
44
  import { PaperError } from './errors.js'
45
+ import { LedgerAdmin, type LedgerStatusView } from './ledger-admin.js'
46
+ import { moveCash as runCashMove, openAccountOnce } from './account-moves.js'
46
47
  import { QuoteRefreshGate } from './quote-gate.js'
47
48
  import { classifyDataProblem, friendlyDataNotice } from './data-source.js'
48
49
 
@@ -55,6 +56,13 @@ export interface PaperServiceOptions {
55
56
  accountId?: string
56
57
  now?: () => Date
57
58
  logger?: { warn(message: string): void }
59
+ /**
60
+ * Registry lock, read live so `accounts/lock` takes effect immediately.
61
+ * Checked inside the service because tools reach it without the RPC guard.
62
+ */
63
+ isLocked?: () => boolean
64
+ /** Archived accounts are frozen as well; asked before `isLocked`. */
65
+ isArchived?: () => boolean
58
66
  }
59
67
 
60
68
  /** Why the account is locked, flattened to one readable line. */
@@ -64,13 +72,6 @@ function reasonText(reason: string | undefined, limit = 120): string {
64
72
  return flat.length <= limit ? flat : `${flat.slice(0, limit)}…`
65
73
  }
66
74
 
67
- export interface LedgerStatus {
68
- path: string
69
- exists: boolean
70
- blocked: boolean
71
- blockedReason?: string
72
- }
73
-
74
75
  interface PlaceOutcome {
75
76
  orderId?: string
76
77
  duplicateId?: string
@@ -93,12 +94,33 @@ export class PaperService {
93
94
  private tickQuotes: { key: string; quotes: Quote[] } | undefined
94
95
  private dataProblem: DataProblem | undefined
95
96
 
97
+ private admin: LedgerAdmin<AccountState, AccountView> | undefined
98
+
96
99
  constructor(private readonly options: PaperServiceOptions) {
97
100
  this.settings = normalizeSettings(options.settings ?? DEFAULT_SETTINGS)
98
101
  this.accountId = options.accountId ?? DEFAULT_ACCOUNT_ID
99
102
  this.now = options.now ?? (() => new Date())
100
103
  }
101
104
 
105
+ /** Export/snapshot/recovery plumbing shared with the futures plane. */
106
+ private ledgerAdmin(): LedgerAdmin<AccountState, AccountView> {
107
+ if (this.admin === undefined) {
108
+ this.admin = new LedgerAdmin<AccountState, AccountView>({
109
+ repo: this.options.repo,
110
+ isBlocked: state => state.blocked,
111
+ blockedReason: state => state.blockedReason,
112
+ ledgerVersion: state => state.ledgerVersion,
113
+ viewOf: state => this.viewOf(state),
114
+ assertUnlocked: () => this.assertUnlocked(),
115
+ ts: () => this.ts(),
116
+ makeError: (code, message) => new PaperError(code as ConstructorParameters<typeof PaperError>[0], message),
117
+ label: 'paper-trading',
118
+ ...(this.options.logger === undefined ? {} : { logger: this.options.logger }),
119
+ })
120
+ }
121
+ return this.admin
122
+ }
123
+
102
124
  private ts(): string {
103
125
  return this.now().toISOString()
104
126
  }
@@ -110,10 +132,24 @@ export class PaperService {
110
132
  return path === undefined ? view : { ...view, ledgerPath: path }
111
133
  }
112
134
 
135
+ /**
136
+ * Refuse a state change on a registry-locked account. RPC checks this too;
137
+ * the service must as well, because the agent tools resolve services
138
+ * directly and never pass through the RPC guard.
139
+ */
140
+ private assertUnlocked(): void {
141
+ if (this.options.isArchived?.() === true) {
142
+ throw new PaperError('ACCOUNT_ARCHIVED', `账户「${this.accountId}」已归档,恢复归档后才能交易`)
143
+ }
144
+ if (this.options.isLocked?.() === true) {
145
+ throw new PaperError('ACCOUNT_LOCKED', `账户「${this.accountId}」已锁定,不能交易`)
146
+ }
147
+ }
148
+
113
149
  /** The single place that turns a blocked state into an error carrying its reason. */
114
150
  private blocked(state: AccountState): PaperError {
115
151
  const reason = reasonText(state.blockedReason)
116
- return new PaperError('ACCOUNT_BLOCKED', `账户已锁定,可用 paper_ledger 从备份恢复,或重置后继续${reason === '' ? '' : `(${reason})`}`, 409)
152
+ return new PaperError('ACCOUNT_BLOCKED', `账户已锁定,可用 paper_ledger 从备份恢复,或重置后继续${reason === '' ? '' : `(${reason})`}`)
117
153
  }
118
154
 
119
155
  async account(): Promise<AccountView> {
@@ -122,14 +158,13 @@ export class PaperService {
122
158
 
123
159
  /** Open the account on first use, through the store transaction. */
124
160
  private async ensureAccount(): Promise<AccountState> {
125
- const outcome = await this.options.repo.transact(async state => {
126
- if (state.tradeDate !== '') return { events: [], value: undefined }
127
- const now = this.now()
128
- const tradeDate = await this.tradeDateForNow()
129
- const result = openAccount(state, this.settings, tradeDate, now.toISOString(), this.accountId)
130
- return { events: result.events, value: undefined }
161
+ return openAccountOnce<AccountState, LedgerEvent>({
162
+ transact: build => this.options.repo.transact(build),
163
+ hasAccount: state => state.tradeDate !== '',
164
+ tradeDateForNow: () => this.tradeDateForNow(),
165
+ open: (state, tradeDate, ts) => openAccount(state, this.settings, tradeDate, ts, this.accountId),
166
+ now: () => this.now(),
131
167
  })
132
- return outcome.state
133
168
  }
134
169
 
135
170
  /** Open if needed, then advance the clock; every public read uses this. */
@@ -146,24 +181,34 @@ export class PaperService {
146
181
  /** Parse a symbol that may be any instrument (quote, chart, search result). */
147
182
  private identify(symbol: string): ListedSymbol {
148
183
  const parsed = tryParseSymbol(symbol)
149
- if (!parsed.ok) throw new PaperError(parsed.code, parsed.message, 400)
184
+ if (!parsed.ok) throw new PaperError(parsed.code, parsed.message)
150
185
  return parsed.symbol
151
186
  }
152
187
 
153
188
  /** Parse a symbol that must be an A-share stock; indices and funds cannot trade. */
154
189
  private identifyStock(symbol: string): ListedSymbol {
155
190
  const parsed = requireStock(symbol)
156
- if (!parsed.ok) throw new PaperError(parsed.code, parsed.message, 400)
191
+ if (!parsed.ok) throw new PaperError(parsed.code, parsed.message)
157
192
  return parsed.symbol
158
193
  }
159
194
 
160
195
  /** Symbols whose price the account cares about: open orders and held positions. */
161
- private symbolsInPlay(state: AccountState): string[] {
196
+ /**
197
+ * Symbols a tick has to touch.
198
+ *
199
+ * Resting orders are the only reason a background tick needs quotes. Positions
200
+ * are display state (`markPrices` never writes the ledger), so the host
201
+ * scheduler ticks with `includePositions: false` and an account that merely
202
+ * holds shares costs zero upstream calls until the panel polls.
203
+ */
204
+ private symbolsInPlay(state: AccountState, includePositions = true): string[] {
162
205
  const symbols = new Set<string>()
163
206
  for (const order of Object.values(state.orders)) {
164
207
  if (order.status === 'pending' || order.status === 'queued' || order.status === 'partially_filled') symbols.add(order.symbol)
165
208
  }
166
- for (const position of Object.values(state.positions)) symbols.add(position.symbol)
209
+ if (includePositions) {
210
+ for (const position of Object.values(state.positions)) symbols.add(position.symbol)
211
+ }
167
212
  return [...symbols]
168
213
  }
169
214
 
@@ -286,50 +331,72 @@ export class PaperService {
286
331
  /**
287
332
  * Idempotent clock advance: close every due trade date and open the next one.
288
333
  *
289
- * The whole advance runs as one store transaction. Concurrent readers queue
290
- * behind it, so the day-boundary events are generated exactly once and the
291
- * `seq` values stay contiguous. Missed sessions produce snapshots only, never
292
- * fills.
334
+ * Two phases. The plan (calendar queries + boundary quotes) is built against a
335
+ * clone of the current state *outside* the store's single-writer queue, so a
336
+ * slow market-data call can never block reads and writes of this account.
337
+ * The transaction then re-checks that nobody wrote in the meantime and appends
338
+ * the pre-built events, so the day-boundary events still land exactly once and
339
+ * the `seq` values stay contiguous. A lost race only defers the advance to the
340
+ * next read; it never duplicates or drops a boundary. Missed sessions produce
341
+ * snapshots only, never fills.
293
342
  */
294
343
  private async advanceTo(): Promise<AccountState> {
295
- const outcome = await this.options.repo.transact(async state => {
296
- if (state.tradeDate === '' || state.blocked) return { events: [], value: undefined }
297
- const now = this.now()
298
- const nowIso = now.toISOString()
299
- const today = todayTradeDate(now)
300
- let current = state
301
- const events: LedgerEvent[] = []
302
- const apply = (result: EngineResult): void => {
303
- events.push(...result.events)
304
- current = result.state
344
+ const snapshot = await this.options.repo.current()
345
+ if (snapshot.tradeDate === '' || snapshot.blocked) return snapshot
346
+ const now = this.now()
347
+ const nowIso = now.toISOString()
348
+ const today = todayTradeDate(now)
349
+ // The clone is the planning input: a concurrent writer may mutate the live
350
+ // state object while boundary quotes are in flight, and the plan must see
351
+ // one consistent version of it.
352
+ const base = structuredClone(snapshot)
353
+ // Primitive fingerprint: the live state object is mutated in place by any
354
+ // concurrent write, so comparing object fields later would always match.
355
+ const plannedFor = { seq: base.lastSeq, tradeDate: base.tradeDate }
356
+ const planned = await this.planAdvance(base, nowIso, today)
357
+ if (planned.length === 0) return snapshot
358
+ const outcome = await this.options.repo.transact(current => {
359
+ if (current.lastSeq !== plannedFor.seq || current.tradeDate !== plannedFor.tradeDate) {
360
+ return { events: [], value: undefined }
305
361
  }
306
- for (let guard = 0; guard < 400; guard += 1) {
307
- if (current.tradeDate < today) {
308
- const next = await this.options.calendar.nextTradingDay(current.tradeDate)
309
- if (nowIso >= isoAtShanghai(current.tradeDate, 15 * 60)) {
310
- if (!this.hasClosed(current, current.tradeDate)) apply(await this.buildClose(current, current.tradeDate, next, nowIso))
311
- }
312
- if (nowIso >= isoAtShanghai(next, 9 * 60 + 15)) apply(this.buildPreOpen(current, next))
313
- if (nowIso < isoAtShanghai(next, 9 * 60 + 30)) break
314
- apply(await this.buildOpen(current, next, nowIso))
315
- continue
362
+ return { events: planned, value: undefined }
363
+ })
364
+ return outcome.state
365
+ }
366
+
367
+ /** Build the due day-boundary events; all network calls happen here, unlocked. */
368
+ private async planAdvance(base: AccountState, nowIso: string, today: string): Promise<LedgerEvent[]> {
369
+ let current = base
370
+ const events: LedgerEvent[] = []
371
+ const apply = (result: EngineResult): void => {
372
+ events.push(...result.events)
373
+ current = result.state
374
+ }
375
+ for (let guard = 0; guard < 400; guard += 1) {
376
+ if (current.tradeDate < today) {
377
+ const next = await this.options.calendar.nextTradingDay(current.tradeDate)
378
+ if (nowIso >= isoAtShanghai(current.tradeDate, 15 * 60)) {
379
+ if (!this.hasClosed(current, current.tradeDate)) apply(await this.buildClose(current, current.tradeDate, next, nowIso))
316
380
  }
317
- if (current.tradeDate === today) {
318
- if (await this.options.calendar.isTradingDay(today)) {
319
- if (nowIso >= isoAtShanghai(today, 9 * 60 + 30) && current.lastOpenedDate !== today) {
320
- apply(await this.buildOpen(current, today, nowIso))
321
- }
322
- if (nowIso >= isoAtShanghai(today, 15 * 60) && !this.hasClosed(current, today)) {
323
- const next = await this.options.calendar.nextTradingDay(today)
324
- apply(await this.buildClose(current, today, next, nowIso))
325
- }
381
+ if (nowIso >= isoAtShanghai(next, 9 * 60 + 15)) apply(this.buildPreOpen(current, next))
382
+ if (nowIso < isoAtShanghai(next, 9 * 60 + 30)) break
383
+ apply(await this.buildOpen(current, next, nowIso))
384
+ continue
385
+ }
386
+ if (current.tradeDate === today) {
387
+ if (await this.options.calendar.isTradingDay(today)) {
388
+ if (nowIso >= isoAtShanghai(today, 9 * 60 + 30) && current.lastOpenedDate !== today) {
389
+ apply(await this.buildOpen(current, today, nowIso))
390
+ }
391
+ if (nowIso >= isoAtShanghai(today, 15 * 60) && !this.hasClosed(current, today)) {
392
+ const next = await this.options.calendar.nextTradingDay(today)
393
+ apply(await this.buildClose(current, today, next, nowIso))
326
394
  }
327
395
  }
328
- break
329
396
  }
330
- return { events, value: undefined }
331
- })
332
- return outcome.state
397
+ break
398
+ }
399
+ return events
333
400
  }
334
401
 
335
402
  /**
@@ -403,12 +470,13 @@ export class PaperService {
403
470
  // (A market order without any quote keeps its warning, so the tool and the
404
471
  // panel can still explain what the user must fill in.)
405
472
  if (draft.type === 'limit' && estimatePrice(draft, quote) === null) {
406
- throw new PaperError('INVALID_ARGUMENT', '限价单必须给出正的限价', 400)
473
+ throw new PaperError('INVALID_ARGUMENT', '限价单必须给出正的限价')
407
474
  }
408
475
  return previewOrder(state, draft, quote, state.settings, await this.marketStatusAt(state, this.ts()))
409
476
  }
410
477
 
411
478
  async place(input: OrderDraft, requestId: string = randomUUID()): Promise<OrderView> {
479
+ this.assertUnlocked()
412
480
  const draft = { ...input, symbol: this.identifyStock(input.symbol).id }
413
481
  const state = await this.sync()
414
482
  // A locked account must answer with the lock (and its reason) even when the
@@ -422,7 +490,7 @@ export class PaperService {
422
490
  // is taken as a queued order instead of a rejection. The closing auction
423
491
  // has no window left today, so it stays rejected.
424
492
  if (phase === 'auction_close') {
425
- throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合', 409)
493
+ throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合')
426
494
  }
427
495
  const quote = await this.quoteFor(draft)
428
496
  const tradeDate = await this.orderDateFor(state, now, phase)
@@ -438,7 +506,16 @@ export class PaperService {
438
506
  })
439
507
  if (outcome.value.duplicateId !== undefined) {
440
508
  const duplicate = outcome.state.orders[outcome.value.duplicateId]
441
- if (duplicate === undefined) throw new PaperError('ORDER_NOT_FOUND', '订单不存在', 404)
509
+ if (duplicate === undefined) throw new PaperError('ORDER_NOT_FOUND', '订单不存在')
510
+ // Same requestId must describe the same order, like the futures plane:
511
+ // silently returning the old order for a different draft made a retry
512
+ // look successful while the new order was never placed.
513
+ const limitPrice = draft.limitPrice
514
+ if (duplicate.symbol !== draft.symbol || duplicate.side !== draft.side
515
+ || duplicate.type !== draft.type || duplicate.qty !== draft.qty
516
+ || duplicate.limitPrice !== limitPrice || (duplicate.note ?? '') !== (draft.note ?? '')) {
517
+ throw new PaperError('INVALID_ARGUMENT', 'requestId 已被另一笔不同的委托占用')
518
+ }
442
519
  return toOrderView(duplicate)
443
520
  }
444
521
  if (outcome.value.blocked === true || outcome.state.blocked) {
@@ -456,7 +533,7 @@ export class PaperService {
456
533
  */
457
534
  async basketPreview(csv: string, budgetCents?: number): Promise<BasketPreview> {
458
535
  if (budgetCents !== undefined && (!Number.isSafeInteger(budgetCents) || budgetCents <= 0)) {
459
- throw new PaperError('INVALID_ARGUMENT', '预算必须是正整数(分)', 400)
536
+ throw new PaperError('INVALID_ARGUMENT', '预算必须是正整数(分)')
460
537
  }
461
538
  const state = await this.sync()
462
539
  const parsed = parseBasketCsv(csv)
@@ -502,6 +579,7 @@ export class PaperService {
502
579
  * the batch continues.
503
580
  */
504
581
  async basketPlace(rows: readonly BasketOrderInput[], batchId?: string): Promise<BasketOrderResult> {
582
+ this.assertUnlocked()
505
583
  const inputs = this.basketRows(rows)
506
584
  const batch = batchId === undefined || batchId.trim() === '' ? randomUUID() : batchId.trim()
507
585
  const state = await this.sync()
@@ -511,7 +589,7 @@ export class PaperService {
511
589
  // Outside continuous trading the batch is queued like a single market
512
590
  // order; only the closing auction is rejected because no window follows.
513
591
  if (phase === 'auction_close') {
514
- throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合', 409)
592
+ throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合')
515
593
  }
516
594
  const matchable = canMatch(phase)
517
595
 
@@ -532,7 +610,7 @@ export class PaperService {
532
610
  continue
533
611
  }
534
612
  if (existing.qty !== row.qty) {
535
- throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${existing.qty} 股)`, 400)
613
+ throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${existing.qty} 股)`)
536
614
  }
537
615
  reused.set(row.symbol, existing)
538
616
  }
@@ -572,7 +650,6 @@ export class PaperService {
572
650
  throw new PaperError(
573
651
  'INSUFFICIENT_CASH',
574
652
  `整批需要 ${(totalCostCents / 100).toFixed(2)} 元,可用现金 ${(state.cashCents / 100).toFixed(2)} 元`,
575
- 409,
576
653
  )
577
654
  }
578
655
 
@@ -586,7 +663,7 @@ export class PaperService {
586
663
  const duplicate = Object.values(working.orders).find(order => order.requestId === requestId)
587
664
  if (duplicate !== undefined) {
588
665
  if (duplicate.qty !== row.qty) {
589
- throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${duplicate.qty} 股)`, 400)
666
+ throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${duplicate.qty} 股)`)
590
667
  }
591
668
  results.push(this.basketResultRow(row.symbol, duplicate))
592
669
  continue
@@ -594,7 +671,7 @@ export class PaperService {
594
671
  const quote = quotes.get(row.symbol)
595
672
  // Pending rows passed the quote pre-check; a gap here is a logic error,
596
673
  // so refuse instead of submitting half a batch.
597
- if (quote === undefined) throw new PaperError('QUOTE_UNAVAILABLE', `${row.symbol} 没有可用行情`, 409)
674
+ if (quote === undefined) throw new PaperError('QUOTE_UNAVAILABLE', `${row.symbol} 没有可用行情`)
598
675
  const result = submit(
599
676
  working,
600
677
  { symbol: row.symbol, side: 'buy', type: 'market', qty: row.qty, name: quote.name, tradeDate },
@@ -616,20 +693,20 @@ export class PaperService {
616
693
  /** Shape-level basket checks that must run before any pre-check touches IO. */
617
694
  private basketRows(rows: readonly BasketOrderInput[]): BasketOrderInput[] {
618
695
  if (!Array.isArray(rows) || rows.length < 1 || rows.length > 20) {
619
- throw new PaperError('INVALID_ARGUMENT', 'rows 需要 1 到 20 行', 400)
696
+ throw new PaperError('INVALID_ARGUMENT', 'rows 需要 1 到 20 行')
620
697
  }
621
698
  const seen = new Set<string>()
622
699
  const checked: BasketOrderInput[] = []
623
700
  for (const row of rows) {
624
701
  const raw = typeof row.symbol === 'string' ? row.symbol.trim() : ''
625
- if (raw === '') throw new PaperError('INVALID_ARGUMENT', '证券代码不能为空', 400)
702
+ if (raw === '') throw new PaperError('INVALID_ARGUMENT', '证券代码不能为空')
626
703
  const symbol = this.identifyStock(raw).id
627
- if (seen.has(symbol)) throw new PaperError('INVALID_ARGUMENT', `证券代码重复:${symbol}`, 400)
704
+ if (seen.has(symbol)) throw new PaperError('INVALID_ARGUMENT', `证券代码重复:${symbol}`)
628
705
  seen.add(symbol)
629
706
  if (!Number.isInteger(row.qty) || row.qty <= 0) {
630
- throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是正整数`, 400)
707
+ throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是正整数`)
631
708
  }
632
- if (row.qty % 100 !== 0) throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是 100 股的整数倍`, 400)
709
+ if (row.qty % 100 !== 0) throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是 100 股的整数倍`)
633
710
  checked.push({ symbol, qty: row.qty })
634
711
  }
635
712
  return checked
@@ -646,8 +723,7 @@ export class PaperService {
646
723
 
647
724
  /** A row failed pre-check: the batch is refused with that row's code. */
648
725
  private basketRejection(symbol: string, code: ErrorCode, message: string): PaperError {
649
- const status = code.startsWith('INVALID') ? 400 : 409
650
- return new PaperError(code, `${symbol}: ${message}`, status)
726
+ return new PaperError(code, `${symbol}: ${message}`)
651
727
  }
652
728
 
653
729
  async cancel(orderId: string): Promise<OrderView> {
@@ -661,14 +737,14 @@ export class PaperService {
661
737
  return { events: result.events, value: {} }
662
738
  })
663
739
  if (outcome.value.blocked === true) throw this.blocked(outcome.state)
664
- if (outcome.value.missing === true) throw new PaperError('ORDER_NOT_FOUND', '订单不存在', 404)
665
- if (outcome.value.notPending === true) throw new PaperError('ORDER_NOT_PENDING', '订单不是挂单状态', 409)
740
+ if (outcome.value.missing === true) throw new PaperError('ORDER_NOT_FOUND', '订单不存在')
741
+ if (outcome.value.notPending === true) throw new PaperError('ORDER_NOT_PENDING', '订单不是挂单状态')
666
742
  const order = outcome.state.orders[orderId]
667
- if (order === undefined) throw new PaperError('ORDER_NOT_FOUND', '订单不存在', 404)
743
+ if (order === undefined) throw new PaperError('ORDER_NOT_FOUND', '订单不存在')
668
744
  return toOrderView(order)
669
745
  }
670
746
 
671
- async tick(): Promise<TickView> {
747
+ async tick(options: { includePositions?: boolean } = {}): Promise<TickView> {
672
748
  const state = await this.sync()
673
749
  const now = this.ts()
674
750
  const phase = this.phaseFor(state, now)
@@ -679,7 +755,11 @@ export class PaperService {
679
755
  if (!canMatch(phase)) {
680
756
  return { tradeDate: state.tradeDate, filled: [], expired: [], quotes: [], notices: [] }
681
757
  }
682
- const symbols = this.symbolsInPlay(state)
758
+ const symbols = this.symbolsInPlay(state, options.includePositions !== false)
759
+ // Nothing to match and no display to refresh: skip the quote call entirely.
760
+ if (symbols.length === 0) {
761
+ return { tradeDate: state.tradeDate, filled: [], expired: [], quotes: [], notices: [] }
762
+ }
683
763
  const key = symbols.join(',')
684
764
  const nowMs = this.now().getTime()
685
765
  // The panel and the host scheduler beat on the same service instance; the
@@ -806,7 +886,7 @@ export class PaperService {
806
886
  }
807
887
 
808
888
  async setShortlist(symbols: string[]): Promise<string[]> {
809
- if (this.options.shortlist === undefined) throw new PaperError('INVALID_ARGUMENT', '备选存储不可用', 503)
889
+ if (this.options.shortlist === undefined) throw new PaperError('INVALID_ARGUMENT', '备选存储不可用')
810
890
  const ids: string[] = []
811
891
  for (const symbol of symbols) {
812
892
  const id = this.identify(symbol).id
@@ -983,9 +1063,10 @@ export class PaperService {
983
1063
  * fields. The write is an atomic temp-file rename.
984
1064
  */
985
1065
  async reset(confirm: boolean, initialCashCents?: number): Promise<AccountView> {
986
- if (confirm !== true) throw new PaperError('INVALID_ARGUMENT', '重置需要 confirm=true', 400)
1066
+ this.assertUnlocked()
1067
+ if (confirm !== true) throw new PaperError('INVALID_ARGUMENT', '重置需要 confirm=true')
987
1068
  if (initialCashCents !== undefined && (!Number.isSafeInteger(initialCashCents) || initialCashCents <= 0)) {
988
- throw new PaperError('INVALID_ARGUMENT', '初始资金必须是正整数(分)', 400)
1069
+ throw new PaperError('INVALID_ARGUMENT', '初始资金必须是正整数(分)')
989
1070
  }
990
1071
  const ts = this.ts()
991
1072
  await this.options.repo.backup(ts)
@@ -1011,50 +1092,38 @@ export class PaperService {
1011
1092
 
1012
1093
  /** Add cash to the account; the amount is yuan from the UI, stored as cents. */
1013
1094
  async deposit(amount: number): Promise<AccountView> {
1095
+ this.assertUnlocked()
1014
1096
  return this.moveCash('deposit', amount)
1015
1097
  }
1016
1098
 
1017
1099
  /** Take cash out, never more than the free cash at the moment of the write. */
1018
1100
  async withdraw(amount: number): Promise<AccountView> {
1101
+ this.assertUnlocked()
1019
1102
  return this.moveCash('withdraw', amount)
1020
1103
  }
1021
1104
 
1022
1105
  private async moveCash(kind: 'deposit' | 'withdraw', amount: number): Promise<AccountView> {
1023
- const amountCents = this.cashAmountCents(amount)
1024
- const state = await this.sync()
1025
- if (state.blocked) throw this.blocked(state)
1026
- const outcome = await this.options.repo.transact<{ blocked: boolean; insufficient: boolean }>(current => {
1027
- if (current.blocked) return { events: [], value: { blocked: true, insufficient: false } }
1028
- // Re-checked inside the transaction: a concurrent buy may have spent the
1029
- // cash between `sync()` and this write.
1030
- if (kind === 'withdraw' && amountCents > current.cashCents) {
1031
- return { events: [], value: { blocked: false, insufficient: true } }
1032
- }
1033
- const result = kind === 'deposit' ? depositCash(current, amountCents, this.ts()) : withdrawCash(current, amountCents, this.ts())
1034
- return { events: result.events, value: { blocked: false, insufficient: false } }
1035
- })
1036
- if (outcome.value.blocked === true) throw this.blocked(outcome.state)
1037
- if (outcome.value.insufficient === true) throw new PaperError('INSUFFICIENT_CASH', '可提现金不足', 409)
1038
- return this.viewOf(outcome.state)
1106
+ return runCashMove<AccountState, AccountView, LedgerEvent>({
1107
+ sync: () => this.sync(),
1108
+ transact: build => this.options.repo.transact(build),
1109
+ isBlocked: state => state.blocked,
1110
+ blocked: state => this.blocked(state),
1111
+ cashCents: state => state.cashCents,
1112
+ deposit: depositCash,
1113
+ withdraw: withdrawCash,
1114
+ viewOf: state => this.viewOf(state),
1115
+ ts: () => this.ts(),
1116
+ }, kind, this.cashAmountCents(amount))
1039
1117
  }
1040
1118
 
1041
1119
  /** `amount` is yuan from the UI; the ledger stores integer cents. */
1042
1120
  private cashAmountCents(amount: number): number {
1043
- if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {
1044
- throw new PaperError('INVALID_ARGUMENT', '金额必须是正数', 400)
1045
- }
1046
- const cents = Math.round(amount * 100)
1047
- if (!Number.isSafeInteger(cents) || cents <= 0) {
1048
- throw new PaperError('INVALID_ARGUMENT', '金额至少 0.01 元', 400)
1049
- }
1050
- return cents
1121
+ return this.ledgerAdmin().cashAmountCents(amount)
1051
1122
  }
1052
1123
 
1053
1124
  /** Read-only export of the raw ledger, for a locked account's banner. */
1054
1125
  async exportLedger(): Promise<LedgerExport> {
1055
- const ledger = await this.options.repo.readLedger()
1056
- if (ledger.content === null) return { path: ledger.path, exists: false, notice: '账本文件尚未创建' }
1057
- return { path: ledger.path, exists: true, content: ledger.content }
1126
+ return this.ledgerAdmin().exportLedger()
1058
1127
  }
1059
1128
 
1060
1129
  /**
@@ -1063,18 +1132,8 @@ export class PaperService {
1063
1132
  * `exportLedger` exists for downloading; this is the answer a human or an
1064
1133
  * agent needs to locate the file and name the failing invariant.
1065
1134
  */
1066
- async ledgerStatus(): Promise<LedgerStatus> {
1067
- const ledger = await this.options.repo.readLedger()
1068
- const state = await this.options.repo.current().catch(error => {
1069
- this.options.logger?.warn(`paper-trading: ledger status could not replay: ${String(error)}`)
1070
- return undefined
1071
- })
1072
- return {
1073
- path: ledger.path,
1074
- exists: ledger.content !== null,
1075
- blocked: state?.blocked === true,
1076
- blockedReason: state?.blockedReason,
1077
- }
1135
+ async ledgerStatus(): Promise<LedgerStatusView> {
1136
+ return this.ledgerAdmin().ledgerStatus()
1078
1137
  }
1079
1138
 
1080
1139
  /**
@@ -1084,15 +1143,7 @@ export class PaperService {
1084
1143
  * which replay cleanly, and whether one needs migration first.
1085
1144
  */
1086
1145
  async ledgerSnapshots(): Promise<LedgerSnapshotsView> {
1087
- const state = await this.options.repo.current().catch(() => undefined)
1088
- const snapshots = await this.options.repo.snapshots()
1089
- return {
1090
- path: this.options.repo.ledgerPath ?? '',
1091
- blocked: state?.blocked === true,
1092
- blockedReason: state?.blockedReason,
1093
- ledgerVersion: state?.ledgerVersion,
1094
- snapshots: snapshots.map(toSnapshotView),
1095
- }
1146
+ return this.ledgerAdmin().ledgerSnapshots()
1096
1147
  }
1097
1148
 
1098
1149
  /**
@@ -1103,18 +1154,12 @@ export class PaperService {
1103
1154
  * before touching the file.
1104
1155
  */
1105
1156
  async restoreLedger(name: string, confirm: boolean): Promise<AccountView> {
1106
- if (confirm !== true) throw new PaperError('INVALID_ARGUMENT', '恢复账本需要 confirm=true', 400)
1107
- try {
1108
- return this.viewOf(await this.options.repo.restore(name))
1109
- } catch (error) {
1110
- throw new PaperError('LEDGER_RESTORE_FAILED', error instanceof Error ? error.message : String(error), 409)
1111
- }
1157
+ return this.ledgerAdmin().restoreLedger(name, confirm)
1112
1158
  }
1113
1159
 
1114
1160
  /** Take one manual snapshot (the automatic one runs at most daily). */
1115
1161
  async backupLedger(): Promise<boolean> {
1116
- const stamp = this.ts().replace(/[:.]/g, '-')
1117
- return this.options.repo.backup(`manual-${stamp}`)
1162
+ return this.ledgerAdmin().backupLedger()
1118
1163
  }
1119
1164
 
1120
1165
  /** Exposed for tests/scenarios: current equity in cents after advancing the clock. */
@@ -1124,18 +1169,3 @@ export class PaperService {
1124
1169
  }
1125
1170
  }
1126
1171
 
1127
- /** Ledger cents → the yuan the rest of the views use. */
1128
- function toSnapshotView(snapshot: LedgerSnapshot): LedgerSnapshotView {
1129
- return {
1130
- name: snapshot.name,
1131
- createdAt: snapshot.createdAt,
1132
- bytes: snapshot.bytes,
1133
- ledgerVersion: snapshot.ledgerVersion,
1134
- lastSeq: snapshot.lastSeq,
1135
- tradeDate: snapshot.tradeDate,
1136
- cash: snapshot.cashCents / 100,
1137
- valid: snapshot.valid,
1138
- migratable: snapshot.migratable,
1139
- problem: snapshot.problem,
1140
- }
1141
- }
@@ -48,15 +48,18 @@ export function createPaperRoute(handler: PaperRpcHandler): PaperRoute {
48
48
  if (typeof body !== 'object' || body === null) {
49
49
  return json(400, failure('INVALID_ARGUMENT', '请求体必须是对象'))
50
50
  }
51
- const { endpoint, payload } = body as { endpoint?: unknown; payload?: unknown }
51
+ const { endpoint, payload, account } = body as { endpoint?: unknown; payload?: unknown; account?: unknown }
52
52
  if (typeof endpoint !== 'string' || endpoint === '') {
53
53
  return json(400, failure('INVALID_ARGUMENT', '缺少 endpoint'))
54
54
  }
55
+ if (account !== undefined && typeof account !== 'string') {
56
+ return json(400, failure('INVALID_ARGUMENT', 'account 必须是字符串'))
57
+ }
55
58
  const controller = new AbortController()
56
59
  const abort = () => controller.abort()
57
60
  request.signal.addEventListener('abort', abort, { once: true })
58
61
  try {
59
- const result = await handler(endpoint, payload, controller.signal)
62
+ const result = await handler(endpoint, payload, controller.signal, account)
60
63
  return json(200, result)
61
64
  } finally {
62
65
  request.signal.removeEventListener('abort', abort)