@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,6 +12,8 @@ import { roundPrice } from '../core/money.js';
12
12
  import { checkOrder, estimatePrice } from '../core/risk.js';
13
13
  import { toAccountView, toFillView, toOrderView, toReview, previewOrder } from '../core/views.js';
14
14
  import { PaperError } from './errors.js';
15
+ import { LedgerAdmin } from './ledger-admin.js';
16
+ import { moveCash as runCashMove, openAccountOnce } from './account-moves.js';
15
17
  import { QuoteRefreshGate } from './quote-gate.js';
16
18
  import { classifyDataProblem, friendlyDataNotice } from './data-source.js';
17
19
  /** Why the account is locked, flattened to one readable line. */
@@ -30,12 +32,31 @@ export class PaperService {
30
32
  quoteGate = new QuoteRefreshGate();
31
33
  tickQuotes;
32
34
  dataProblem;
35
+ admin;
33
36
  constructor(options) {
34
37
  this.options = options;
35
38
  this.settings = normalizeSettings(options.settings ?? DEFAULT_SETTINGS);
36
39
  this.accountId = options.accountId ?? DEFAULT_ACCOUNT_ID;
37
40
  this.now = options.now ?? (() => new Date());
38
41
  }
42
+ /** Export/snapshot/recovery plumbing shared with the futures plane. */
43
+ ledgerAdmin() {
44
+ if (this.admin === undefined) {
45
+ this.admin = new LedgerAdmin({
46
+ repo: this.options.repo,
47
+ isBlocked: state => state.blocked,
48
+ blockedReason: state => state.blockedReason,
49
+ ledgerVersion: state => state.ledgerVersion,
50
+ viewOf: state => this.viewOf(state),
51
+ assertUnlocked: () => this.assertUnlocked(),
52
+ ts: () => this.ts(),
53
+ makeError: (code, message) => new PaperError(code, message),
54
+ label: 'paper-trading',
55
+ ...(this.options.logger === undefined ? {} : { logger: this.options.logger }),
56
+ });
57
+ }
58
+ return this.admin;
59
+ }
39
60
  ts() {
40
61
  return this.now().toISOString();
41
62
  }
@@ -45,25 +66,36 @@ export class PaperService {
45
66
  const path = this.options.repo.ledgerPath;
46
67
  return path === undefined ? view : { ...view, ledgerPath: path };
47
68
  }
69
+ /**
70
+ * Refuse a state change on a registry-locked account. RPC checks this too;
71
+ * the service must as well, because the agent tools resolve services
72
+ * directly and never pass through the RPC guard.
73
+ */
74
+ assertUnlocked() {
75
+ if (this.options.isArchived?.() === true) {
76
+ throw new PaperError('ACCOUNT_ARCHIVED', `账户「${this.accountId}」已归档,恢复归档后才能交易`);
77
+ }
78
+ if (this.options.isLocked?.() === true) {
79
+ throw new PaperError('ACCOUNT_LOCKED', `账户「${this.accountId}」已锁定,不能交易`);
80
+ }
81
+ }
48
82
  /** The single place that turns a blocked state into an error carrying its reason. */
49
83
  blocked(state) {
50
84
  const reason = reasonText(state.blockedReason);
51
- return new PaperError('ACCOUNT_BLOCKED', `账户已锁定,可用 paper_ledger 从备份恢复,或重置后继续${reason === '' ? '' : `(${reason})`}`, 409);
85
+ return new PaperError('ACCOUNT_BLOCKED', `账户已锁定,可用 paper_ledger 从备份恢复,或重置后继续${reason === '' ? '' : `(${reason})`}`);
52
86
  }
53
87
  async account() {
54
88
  return this.viewOf(await this.sync());
55
89
  }
56
90
  /** Open the account on first use, through the store transaction. */
57
91
  async ensureAccount() {
58
- const outcome = await this.options.repo.transact(async (state) => {
59
- if (state.tradeDate !== '')
60
- return { events: [], value: undefined };
61
- const now = this.now();
62
- const tradeDate = await this.tradeDateForNow();
63
- const result = openAccount(state, this.settings, tradeDate, now.toISOString(), this.accountId);
64
- return { events: result.events, value: undefined };
92
+ return openAccountOnce({
93
+ transact: build => this.options.repo.transact(build),
94
+ hasAccount: state => state.tradeDate !== '',
95
+ tradeDateForNow: () => this.tradeDateForNow(),
96
+ open: (state, tradeDate, ts) => openAccount(state, this.settings, tradeDate, ts, this.accountId),
97
+ now: () => this.now(),
65
98
  });
66
- return outcome.state;
67
99
  }
68
100
  /** Open if needed, then advance the clock; every public read uses this. */
69
101
  async sync() {
@@ -78,25 +110,35 @@ export class PaperService {
78
110
  identify(symbol) {
79
111
  const parsed = tryParseSymbol(symbol);
80
112
  if (!parsed.ok)
81
- throw new PaperError(parsed.code, parsed.message, 400);
113
+ throw new PaperError(parsed.code, parsed.message);
82
114
  return parsed.symbol;
83
115
  }
84
116
  /** Parse a symbol that must be an A-share stock; indices and funds cannot trade. */
85
117
  identifyStock(symbol) {
86
118
  const parsed = requireStock(symbol);
87
119
  if (!parsed.ok)
88
- throw new PaperError(parsed.code, parsed.message, 400);
120
+ throw new PaperError(parsed.code, parsed.message);
89
121
  return parsed.symbol;
90
122
  }
91
123
  /** Symbols whose price the account cares about: open orders and held positions. */
92
- symbolsInPlay(state) {
124
+ /**
125
+ * Symbols a tick has to touch.
126
+ *
127
+ * Resting orders are the only reason a background tick needs quotes. Positions
128
+ * are display state (`markPrices` never writes the ledger), so the host
129
+ * scheduler ticks with `includePositions: false` and an account that merely
130
+ * holds shares costs zero upstream calls until the panel polls.
131
+ */
132
+ symbolsInPlay(state, includePositions = true) {
93
133
  const symbols = new Set();
94
134
  for (const order of Object.values(state.orders)) {
95
135
  if (order.status === 'pending' || order.status === 'queued' || order.status === 'partially_filled')
96
136
  symbols.add(order.symbol);
97
137
  }
98
- for (const position of Object.values(state.positions))
99
- symbols.add(position.symbol);
138
+ if (includePositions) {
139
+ for (const position of Object.values(state.positions))
140
+ symbols.add(position.symbol);
141
+ }
100
142
  return [...symbols];
101
143
  }
102
144
  /**
@@ -215,54 +257,76 @@ export class PaperService {
215
257
  /**
216
258
  * Idempotent clock advance: close every due trade date and open the next one.
217
259
  *
218
- * The whole advance runs as one store transaction. Concurrent readers queue
219
- * behind it, so the day-boundary events are generated exactly once and the
220
- * `seq` values stay contiguous. Missed sessions produce snapshots only, never
221
- * fills.
260
+ * Two phases. The plan (calendar queries + boundary quotes) is built against a
261
+ * clone of the current state *outside* the store's single-writer queue, so a
262
+ * slow market-data call can never block reads and writes of this account.
263
+ * The transaction then re-checks that nobody wrote in the meantime and appends
264
+ * the pre-built events, so the day-boundary events still land exactly once and
265
+ * the `seq` values stay contiguous. A lost race only defers the advance to the
266
+ * next read; it never duplicates or drops a boundary. Missed sessions produce
267
+ * snapshots only, never fills.
222
268
  */
223
269
  async advanceTo() {
224
- const outcome = await this.options.repo.transact(async (state) => {
225
- if (state.tradeDate === '' || state.blocked)
270
+ const snapshot = await this.options.repo.current();
271
+ if (snapshot.tradeDate === '' || snapshot.blocked)
272
+ return snapshot;
273
+ const now = this.now();
274
+ const nowIso = now.toISOString();
275
+ const today = todayTradeDate(now);
276
+ // The clone is the planning input: a concurrent writer may mutate the live
277
+ // state object while boundary quotes are in flight, and the plan must see
278
+ // one consistent version of it.
279
+ const base = structuredClone(snapshot);
280
+ // Primitive fingerprint: the live state object is mutated in place by any
281
+ // concurrent write, so comparing object fields later would always match.
282
+ const plannedFor = { seq: base.lastSeq, tradeDate: base.tradeDate };
283
+ const planned = await this.planAdvance(base, nowIso, today);
284
+ if (planned.length === 0)
285
+ return snapshot;
286
+ const outcome = await this.options.repo.transact(current => {
287
+ if (current.lastSeq !== plannedFor.seq || current.tradeDate !== plannedFor.tradeDate) {
226
288
  return { events: [], value: undefined };
227
- const now = this.now();
228
- const nowIso = now.toISOString();
229
- const today = todayTradeDate(now);
230
- let current = state;
231
- const events = [];
232
- const apply = (result) => {
233
- events.push(...result.events);
234
- current = result.state;
235
- };
236
- for (let guard = 0; guard < 400; guard += 1) {
237
- if (current.tradeDate < today) {
238
- const next = await this.options.calendar.nextTradingDay(current.tradeDate);
239
- if (nowIso >= isoAtShanghai(current.tradeDate, 15 * 60)) {
240
- if (!this.hasClosed(current, current.tradeDate))
241
- apply(await this.buildClose(current, current.tradeDate, next, nowIso));
242
- }
243
- if (nowIso >= isoAtShanghai(next, 9 * 60 + 15))
244
- apply(this.buildPreOpen(current, next));
245
- if (nowIso < isoAtShanghai(next, 9 * 60 + 30))
246
- break;
247
- apply(await this.buildOpen(current, next, nowIso));
248
- continue;
289
+ }
290
+ return { events: planned, value: undefined };
291
+ });
292
+ return outcome.state;
293
+ }
294
+ /** Build the due day-boundary events; all network calls happen here, unlocked. */
295
+ async planAdvance(base, nowIso, today) {
296
+ let current = base;
297
+ const events = [];
298
+ const apply = (result) => {
299
+ events.push(...result.events);
300
+ current = result.state;
301
+ };
302
+ for (let guard = 0; guard < 400; guard += 1) {
303
+ if (current.tradeDate < today) {
304
+ const next = await this.options.calendar.nextTradingDay(current.tradeDate);
305
+ if (nowIso >= isoAtShanghai(current.tradeDate, 15 * 60)) {
306
+ if (!this.hasClosed(current, current.tradeDate))
307
+ apply(await this.buildClose(current, current.tradeDate, next, nowIso));
249
308
  }
250
- if (current.tradeDate === today) {
251
- if (await this.options.calendar.isTradingDay(today)) {
252
- if (nowIso >= isoAtShanghai(today, 9 * 60 + 30) && current.lastOpenedDate !== today) {
253
- apply(await this.buildOpen(current, today, nowIso));
254
- }
255
- if (nowIso >= isoAtShanghai(today, 15 * 60) && !this.hasClosed(current, today)) {
256
- const next = await this.options.calendar.nextTradingDay(today);
257
- apply(await this.buildClose(current, today, next, nowIso));
258
- }
309
+ if (nowIso >= isoAtShanghai(next, 9 * 60 + 15))
310
+ apply(this.buildPreOpen(current, next));
311
+ if (nowIso < isoAtShanghai(next, 9 * 60 + 30))
312
+ break;
313
+ apply(await this.buildOpen(current, next, nowIso));
314
+ continue;
315
+ }
316
+ if (current.tradeDate === today) {
317
+ if (await this.options.calendar.isTradingDay(today)) {
318
+ if (nowIso >= isoAtShanghai(today, 9 * 60 + 30) && current.lastOpenedDate !== today) {
319
+ apply(await this.buildOpen(current, today, nowIso));
320
+ }
321
+ if (nowIso >= isoAtShanghai(today, 15 * 60) && !this.hasClosed(current, today)) {
322
+ const next = await this.options.calendar.nextTradingDay(today);
323
+ apply(await this.buildClose(current, today, next, nowIso));
259
324
  }
260
325
  }
261
- break;
262
326
  }
263
- return { events, value: undefined };
264
- });
265
- return outcome.state;
327
+ break;
328
+ }
329
+ return events;
266
330
  }
267
331
  /**
268
332
  * Quote for a draft, with `prevClose` recovered from the daily bars.
@@ -336,11 +400,12 @@ export class PaperService {
336
400
  // (A market order without any quote keeps its warning, so the tool and the
337
401
  // panel can still explain what the user must fill in.)
338
402
  if (draft.type === 'limit' && estimatePrice(draft, quote) === null) {
339
- throw new PaperError('INVALID_ARGUMENT', '限价单必须给出正的限价', 400);
403
+ throw new PaperError('INVALID_ARGUMENT', '限价单必须给出正的限价');
340
404
  }
341
405
  return previewOrder(state, draft, quote, state.settings, await this.marketStatusAt(state, this.ts()));
342
406
  }
343
407
  async place(input, requestId = randomUUID()) {
408
+ this.assertUnlocked();
344
409
  const draft = { ...input, symbol: this.identifyStock(input.symbol).id };
345
410
  const state = await this.sync();
346
411
  // A locked account must answer with the lock (and its reason) even when the
@@ -355,7 +420,7 @@ export class PaperService {
355
420
  // is taken as a queued order instead of a rejection. The closing auction
356
421
  // has no window left today, so it stays rejected.
357
422
  if (phase === 'auction_close') {
358
- throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合', 409);
423
+ throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合');
359
424
  }
360
425
  const quote = await this.quoteFor(draft);
361
426
  const tradeDate = await this.orderDateFor(state, now, phase);
@@ -374,7 +439,16 @@ export class PaperService {
374
439
  if (outcome.value.duplicateId !== undefined) {
375
440
  const duplicate = outcome.state.orders[outcome.value.duplicateId];
376
441
  if (duplicate === undefined)
377
- throw new PaperError('ORDER_NOT_FOUND', '订单不存在', 404);
442
+ throw new PaperError('ORDER_NOT_FOUND', '订单不存在');
443
+ // Same requestId must describe the same order, like the futures plane:
444
+ // silently returning the old order for a different draft made a retry
445
+ // look successful while the new order was never placed.
446
+ const limitPrice = draft.limitPrice;
447
+ if (duplicate.symbol !== draft.symbol || duplicate.side !== draft.side
448
+ || duplicate.type !== draft.type || duplicate.qty !== draft.qty
449
+ || duplicate.limitPrice !== limitPrice || (duplicate.note ?? '') !== (draft.note ?? '')) {
450
+ throw new PaperError('INVALID_ARGUMENT', 'requestId 已被另一笔不同的委托占用');
451
+ }
378
452
  return toOrderView(duplicate);
379
453
  }
380
454
  if (outcome.value.blocked === true || outcome.state.blocked) {
@@ -392,7 +466,7 @@ export class PaperService {
392
466
  */
393
467
  async basketPreview(csv, budgetCents) {
394
468
  if (budgetCents !== undefined && (!Number.isSafeInteger(budgetCents) || budgetCents <= 0)) {
395
- throw new PaperError('INVALID_ARGUMENT', '预算必须是正整数(分)', 400);
469
+ throw new PaperError('INVALID_ARGUMENT', '预算必须是正整数(分)');
396
470
  }
397
471
  const state = await this.sync();
398
472
  const parsed = parseBasketCsv(csv);
@@ -439,6 +513,7 @@ export class PaperService {
439
513
  * the batch continues.
440
514
  */
441
515
  async basketPlace(rows, batchId) {
516
+ this.assertUnlocked();
442
517
  const inputs = this.basketRows(rows);
443
518
  const batch = batchId === undefined || batchId.trim() === '' ? randomUUID() : batchId.trim();
444
519
  const state = await this.sync();
@@ -449,7 +524,7 @@ export class PaperService {
449
524
  // Outside continuous trading the batch is queued like a single market
450
525
  // order; only the closing auction is rejected because no window follows.
451
526
  if (phase === 'auction_close') {
452
- throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合', 409);
527
+ throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合');
453
528
  }
454
529
  const matchable = canMatch(phase);
455
530
  // Orders of an earlier attempt of the same batch are reused and skipped in
@@ -470,7 +545,7 @@ export class PaperService {
470
545
  continue;
471
546
  }
472
547
  if (existing.qty !== row.qty) {
473
- throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${existing.qty} 股)`, 400);
548
+ throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${existing.qty} 股)`);
474
549
  }
475
550
  reused.set(row.symbol, existing);
476
551
  }
@@ -501,7 +576,7 @@ export class PaperService {
501
576
  totalCostCents += check.amountCents + computeFees(check.amountCents, 'buy', state.settings).totalCents;
502
577
  }
503
578
  if (totalCostCents > state.cashCents) {
504
- throw new PaperError('INSUFFICIENT_CASH', `整批需要 ${(totalCostCents / 100).toFixed(2)} 元,可用现金 ${(state.cashCents / 100).toFixed(2)} 元`, 409);
579
+ throw new PaperError('INSUFFICIENT_CASH', `整批需要 ${(totalCostCents / 100).toFixed(2)} 元,可用现金 ${(state.cashCents / 100).toFixed(2)} 元`);
505
580
  }
506
581
  const outcome = await this.options.repo.transact(current => {
507
582
  if (current.blocked)
@@ -514,7 +589,7 @@ export class PaperService {
514
589
  const duplicate = Object.values(working.orders).find(order => order.requestId === requestId);
515
590
  if (duplicate !== undefined) {
516
591
  if (duplicate.qty !== row.qty) {
517
- throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${duplicate.qty} 股)`, 400);
592
+ throw new PaperError('INVALID_ARGUMENT', `${row.symbol} 与同批次已提交的数量不一致(原 ${duplicate.qty} 股)`);
518
593
  }
519
594
  results.push(this.basketResultRow(row.symbol, duplicate));
520
595
  continue;
@@ -523,7 +598,7 @@ export class PaperService {
523
598
  // Pending rows passed the quote pre-check; a gap here is a logic error,
524
599
  // so refuse instead of submitting half a batch.
525
600
  if (quote === undefined)
526
- throw new PaperError('QUOTE_UNAVAILABLE', `${row.symbol} 没有可用行情`, 409);
601
+ throw new PaperError('QUOTE_UNAVAILABLE', `${row.symbol} 没有可用行情`);
527
602
  const result = submit(working, { symbol: row.symbol, side: 'buy', type: 'market', qty: row.qty, name: quote.name, tradeDate }, quote, requestId, now, { matchable, phase });
528
603
  events.push(...result.events);
529
604
  working = result.state;
@@ -538,23 +613,23 @@ export class PaperService {
538
613
  /** Shape-level basket checks that must run before any pre-check touches IO. */
539
614
  basketRows(rows) {
540
615
  if (!Array.isArray(rows) || rows.length < 1 || rows.length > 20) {
541
- throw new PaperError('INVALID_ARGUMENT', 'rows 需要 1 到 20 行', 400);
616
+ throw new PaperError('INVALID_ARGUMENT', 'rows 需要 1 到 20 行');
542
617
  }
543
618
  const seen = new Set();
544
619
  const checked = [];
545
620
  for (const row of rows) {
546
621
  const raw = typeof row.symbol === 'string' ? row.symbol.trim() : '';
547
622
  if (raw === '')
548
- throw new PaperError('INVALID_ARGUMENT', '证券代码不能为空', 400);
623
+ throw new PaperError('INVALID_ARGUMENT', '证券代码不能为空');
549
624
  const symbol = this.identifyStock(raw).id;
550
625
  if (seen.has(symbol))
551
- throw new PaperError('INVALID_ARGUMENT', `证券代码重复:${symbol}`, 400);
626
+ throw new PaperError('INVALID_ARGUMENT', `证券代码重复:${symbol}`);
552
627
  seen.add(symbol);
553
628
  if (!Number.isInteger(row.qty) || row.qty <= 0) {
554
- throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是正整数`, 400);
629
+ throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是正整数`);
555
630
  }
556
631
  if (row.qty % 100 !== 0)
557
- throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是 100 股的整数倍`, 400);
632
+ throw new PaperError('INVALID_ARGUMENT', `${symbol} 数量必须是 100 股的整数倍`);
558
633
  checked.push({ symbol, qty: row.qty });
559
634
  }
560
635
  return checked;
@@ -570,8 +645,7 @@ export class PaperService {
570
645
  }
571
646
  /** A row failed pre-check: the batch is refused with that row's code. */
572
647
  basketRejection(symbol, code, message) {
573
- const status = code.startsWith('INVALID') ? 400 : 409;
574
- return new PaperError(code, `${symbol}: ${message}`, status);
648
+ return new PaperError(code, `${symbol}: ${message}`);
575
649
  }
576
650
  async cancel(orderId) {
577
651
  const state = await this.sync();
@@ -590,15 +664,15 @@ export class PaperService {
590
664
  if (outcome.value.blocked === true)
591
665
  throw this.blocked(outcome.state);
592
666
  if (outcome.value.missing === true)
593
- throw new PaperError('ORDER_NOT_FOUND', '订单不存在', 404);
667
+ throw new PaperError('ORDER_NOT_FOUND', '订单不存在');
594
668
  if (outcome.value.notPending === true)
595
- throw new PaperError('ORDER_NOT_PENDING', '订单不是挂单状态', 409);
669
+ throw new PaperError('ORDER_NOT_PENDING', '订单不是挂单状态');
596
670
  const order = outcome.state.orders[orderId];
597
671
  if (order === undefined)
598
- throw new PaperError('ORDER_NOT_FOUND', '订单不存在', 404);
672
+ throw new PaperError('ORDER_NOT_FOUND', '订单不存在');
599
673
  return toOrderView(order);
600
674
  }
601
- async tick() {
675
+ async tick(options = {}) {
602
676
  const state = await this.sync();
603
677
  const now = this.ts();
604
678
  const phase = this.phaseFor(state, now);
@@ -609,7 +683,11 @@ export class PaperService {
609
683
  if (!canMatch(phase)) {
610
684
  return { tradeDate: state.tradeDate, filled: [], expired: [], quotes: [], notices: [] };
611
685
  }
612
- const symbols = this.symbolsInPlay(state);
686
+ const symbols = this.symbolsInPlay(state, options.includePositions !== false);
687
+ // Nothing to match and no display to refresh: skip the quote call entirely.
688
+ if (symbols.length === 0) {
689
+ return { tradeDate: state.tradeDate, filled: [], expired: [], quotes: [], notices: [] };
690
+ }
613
691
  const key = symbols.join(',');
614
692
  const nowMs = this.now().getTime();
615
693
  // The panel and the host scheduler beat on the same service instance; the
@@ -729,7 +807,7 @@ export class PaperService {
729
807
  }
730
808
  async setShortlist(symbols) {
731
809
  if (this.options.shortlist === undefined)
732
- throw new PaperError('INVALID_ARGUMENT', '备选存储不可用', 503);
810
+ throw new PaperError('INVALID_ARGUMENT', '备选存储不可用');
733
811
  const ids = [];
734
812
  for (const symbol of symbols) {
735
813
  const id = this.identify(symbol).id;
@@ -899,10 +977,11 @@ export class PaperService {
899
977
  * fields. The write is an atomic temp-file rename.
900
978
  */
901
979
  async reset(confirm, initialCashCents) {
980
+ this.assertUnlocked();
902
981
  if (confirm !== true)
903
- throw new PaperError('INVALID_ARGUMENT', '重置需要 confirm=true', 400);
982
+ throw new PaperError('INVALID_ARGUMENT', '重置需要 confirm=true');
904
983
  if (initialCashCents !== undefined && (!Number.isSafeInteger(initialCashCents) || initialCashCents <= 0)) {
905
- throw new PaperError('INVALID_ARGUMENT', '初始资金必须是正整数(分)', 400);
984
+ throw new PaperError('INVALID_ARGUMENT', '初始资金必须是正整数(分)');
906
985
  }
907
986
  const ts = this.ts();
908
987
  await this.options.repo.backup(ts);
@@ -927,51 +1006,34 @@ export class PaperService {
927
1006
  }
928
1007
  /** Add cash to the account; the amount is yuan from the UI, stored as cents. */
929
1008
  async deposit(amount) {
1009
+ this.assertUnlocked();
930
1010
  return this.moveCash('deposit', amount);
931
1011
  }
932
1012
  /** Take cash out, never more than the free cash at the moment of the write. */
933
1013
  async withdraw(amount) {
1014
+ this.assertUnlocked();
934
1015
  return this.moveCash('withdraw', amount);
935
1016
  }
936
1017
  async moveCash(kind, amount) {
937
- const amountCents = this.cashAmountCents(amount);
938
- const state = await this.sync();
939
- if (state.blocked)
940
- throw this.blocked(state);
941
- const outcome = await this.options.repo.transact(current => {
942
- if (current.blocked)
943
- return { events: [], value: { blocked: true, insufficient: false } };
944
- // Re-checked inside the transaction: a concurrent buy may have spent the
945
- // cash between `sync()` and this write.
946
- if (kind === 'withdraw' && amountCents > current.cashCents) {
947
- return { events: [], value: { blocked: false, insufficient: true } };
948
- }
949
- const result = kind === 'deposit' ? depositCash(current, amountCents, this.ts()) : withdrawCash(current, amountCents, this.ts());
950
- return { events: result.events, value: { blocked: false, insufficient: false } };
951
- });
952
- if (outcome.value.blocked === true)
953
- throw this.blocked(outcome.state);
954
- if (outcome.value.insufficient === true)
955
- throw new PaperError('INSUFFICIENT_CASH', '可提现金不足', 409);
956
- return this.viewOf(outcome.state);
1018
+ return runCashMove({
1019
+ sync: () => this.sync(),
1020
+ transact: build => this.options.repo.transact(build),
1021
+ isBlocked: state => state.blocked,
1022
+ blocked: state => this.blocked(state),
1023
+ cashCents: state => state.cashCents,
1024
+ deposit: depositCash,
1025
+ withdraw: withdrawCash,
1026
+ viewOf: state => this.viewOf(state),
1027
+ ts: () => this.ts(),
1028
+ }, kind, this.cashAmountCents(amount));
957
1029
  }
958
1030
  /** `amount` is yuan from the UI; the ledger stores integer cents. */
959
1031
  cashAmountCents(amount) {
960
- if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {
961
- throw new PaperError('INVALID_ARGUMENT', '金额必须是正数', 400);
962
- }
963
- const cents = Math.round(amount * 100);
964
- if (!Number.isSafeInteger(cents) || cents <= 0) {
965
- throw new PaperError('INVALID_ARGUMENT', '金额至少 0.01 元', 400);
966
- }
967
- return cents;
1032
+ return this.ledgerAdmin().cashAmountCents(amount);
968
1033
  }
969
1034
  /** Read-only export of the raw ledger, for a locked account's banner. */
970
1035
  async exportLedger() {
971
- const ledger = await this.options.repo.readLedger();
972
- if (ledger.content === null)
973
- return { path: ledger.path, exists: false, notice: '账本文件尚未创建' };
974
- return { path: ledger.path, exists: true, content: ledger.content };
1036
+ return this.ledgerAdmin().exportLedger();
975
1037
  }
976
1038
  /**
977
1039
  * Where the ledger is and why it is locked — without the raw text.
@@ -980,17 +1042,7 @@ export class PaperService {
980
1042
  * agent needs to locate the file and name the failing invariant.
981
1043
  */
982
1044
  async ledgerStatus() {
983
- const ledger = await this.options.repo.readLedger();
984
- const state = await this.options.repo.current().catch(error => {
985
- this.options.logger?.warn(`paper-trading: ledger status could not replay: ${String(error)}`);
986
- return undefined;
987
- });
988
- return {
989
- path: ledger.path,
990
- exists: ledger.content !== null,
991
- blocked: state?.blocked === true,
992
- blockedReason: state?.blockedReason,
993
- };
1045
+ return this.ledgerAdmin().ledgerStatus();
994
1046
  }
995
1047
  /**
996
1048
  * Snapshots that can be restored, newest first, plus the live ledger's state.
@@ -999,15 +1051,7 @@ export class PaperService {
999
1051
  * which replay cleanly, and whether one needs migration first.
1000
1052
  */
1001
1053
  async ledgerSnapshots() {
1002
- const state = await this.options.repo.current().catch(() => undefined);
1003
- const snapshots = await this.options.repo.snapshots();
1004
- return {
1005
- path: this.options.repo.ledgerPath ?? '',
1006
- blocked: state?.blocked === true,
1007
- blockedReason: state?.blockedReason,
1008
- ledgerVersion: state?.ledgerVersion,
1009
- snapshots: snapshots.map(toSnapshotView),
1010
- };
1054
+ return this.ledgerAdmin().ledgerSnapshots();
1011
1055
  }
1012
1056
  /**
1013
1057
  * Replace the live ledger with one snapshot.
@@ -1017,19 +1061,11 @@ export class PaperService {
1017
1061
  * before touching the file.
1018
1062
  */
1019
1063
  async restoreLedger(name, confirm) {
1020
- if (confirm !== true)
1021
- throw new PaperError('INVALID_ARGUMENT', '恢复账本需要 confirm=true', 400);
1022
- try {
1023
- return this.viewOf(await this.options.repo.restore(name));
1024
- }
1025
- catch (error) {
1026
- throw new PaperError('LEDGER_RESTORE_FAILED', error instanceof Error ? error.message : String(error), 409);
1027
- }
1064
+ return this.ledgerAdmin().restoreLedger(name, confirm);
1028
1065
  }
1029
1066
  /** Take one manual snapshot (the automatic one runs at most daily). */
1030
1067
  async backupLedger() {
1031
- const stamp = this.ts().replace(/[:.]/g, '-');
1032
- return this.options.repo.backup(`manual-${stamp}`);
1068
+ return this.ledgerAdmin().backupLedger();
1033
1069
  }
1034
1070
  /** Exposed for tests/scenarios: current equity in cents after advancing the clock. */
1035
1071
  async equityCents() {
@@ -1037,19 +1073,4 @@ export class PaperService {
1037
1073
  return equityCents(state);
1038
1074
  }
1039
1075
  }
1040
- /** Ledger cents → the yuan the rest of the views use. */
1041
- function toSnapshotView(snapshot) {
1042
- return {
1043
- name: snapshot.name,
1044
- createdAt: snapshot.createdAt,
1045
- bytes: snapshot.bytes,
1046
- ledgerVersion: snapshot.ledgerVersion,
1047
- lastSeq: snapshot.lastSeq,
1048
- tradeDate: snapshot.tradeDate,
1049
- cash: snapshot.cashCents / 100,
1050
- valid: snapshot.valid,
1051
- migratable: snapshot.migratable,
1052
- problem: snapshot.problem,
1053
- };
1054
- }
1055
1076
  //# sourceMappingURL=paper-service.js.map