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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +4 -3
  2. package/README.zh.md +4 -3
  3. package/lib/agent/account-tools.d.ts +18 -0
  4. package/lib/agent/account-tools.d.ts.map +1 -0
  5. package/lib/agent/account-tools.js +127 -0
  6. package/lib/agent/account-tools.js.map +1 -0
  7. package/lib/agent/futures-tools.d.ts.map +1 -1
  8. package/lib/agent/futures-tools.js +1 -6
  9. package/lib/agent/futures-tools.js.map +1 -1
  10. package/lib/agent/ledger-tools.d.ts +15 -3
  11. package/lib/agent/ledger-tools.d.ts.map +1 -1
  12. package/lib/agent/ledger-tools.js +11 -15
  13. package/lib/agent/ledger-tools.js.map +1 -1
  14. package/lib/agent/tool-result.d.ts +19 -0
  15. package/lib/agent/tool-result.d.ts.map +1 -0
  16. package/lib/agent/tool-result.js +22 -0
  17. package/lib/agent/tool-result.js.map +1 -0
  18. package/lib/agent/tools.d.ts +10 -2
  19. package/lib/agent/tools.d.ts.map +1 -1
  20. package/lib/agent/tools.js +26 -11
  21. package/lib/agent/tools.js.map +1 -1
  22. package/lib/client.js +1448 -282
  23. package/lib/contract/accounts.d.ts +76 -0
  24. package/lib/contract/accounts.d.ts.map +1 -0
  25. package/lib/contract/accounts.js +6 -0
  26. package/lib/contract/accounts.js.map +1 -0
  27. package/lib/contract/common.d.ts +144 -0
  28. package/lib/contract/common.d.ts.map +1 -0
  29. package/lib/contract/common.js +33 -0
  30. package/lib/contract/common.js.map +1 -0
  31. package/lib/contract/domain.d.ts +196 -0
  32. package/lib/contract/domain.d.ts.map +1 -0
  33. package/lib/contract/domain.js +14 -0
  34. package/lib/contract/domain.js.map +1 -0
  35. package/lib/contract/errors.d.ts +6 -0
  36. package/lib/contract/errors.d.ts.map +1 -0
  37. package/lib/contract/errors.js +6 -0
  38. package/lib/contract/errors.js.map +1 -0
  39. package/lib/contract/index.d.ts +15 -0
  40. package/lib/contract/index.d.ts.map +1 -0
  41. package/lib/contract/index.js +15 -0
  42. package/lib/contract/index.js.map +1 -0
  43. package/lib/contract/ledger.d.ts +40 -0
  44. package/lib/contract/ledger.d.ts.map +1 -0
  45. package/lib/contract/ledger.js +6 -0
  46. package/lib/contract/ledger.js.map +1 -0
  47. package/lib/contract/market.d.ts +30 -0
  48. package/lib/contract/market.d.ts.map +1 -0
  49. package/lib/contract/market.js +6 -0
  50. package/lib/contract/market.js.map +1 -0
  51. package/lib/contract/rpc.d.ts +24 -0
  52. package/lib/contract/rpc.d.ts.map +1 -0
  53. package/lib/contract/rpc.js +6 -0
  54. package/lib/contract/rpc.js.map +1 -0
  55. package/lib/contract.d.ts +6 -403
  56. package/lib/contract.d.ts.map +1 -1
  57. package/lib/contract.js +6 -24
  58. package/lib/contract.js.map +1 -1
  59. package/lib/core/session.d.ts +1 -1
  60. package/lib/core/session.d.ts.map +1 -1
  61. package/lib/core/session.js +1 -2
  62. package/lib/core/session.js.map +1 -1
  63. package/lib/data/cached-market-data.d.ts +61 -0
  64. package/lib/data/cached-market-data.d.ts.map +1 -0
  65. package/lib/data/cached-market-data.js +174 -0
  66. package/lib/data/cached-market-data.js.map +1 -0
  67. package/lib/data/futures-market-data.d.ts.map +1 -1
  68. package/lib/data/futures-market-data.js +9 -10
  69. package/lib/data/futures-market-data.js.map +1 -1
  70. package/lib/index.d.ts +25 -1
  71. package/lib/index.d.ts.map +1 -1
  72. package/lib/index.js +156 -18
  73. package/lib/index.js.map +1 -1
  74. package/lib/service/account-moves.d.ts +64 -0
  75. package/lib/service/account-moves.d.ts.map +1 -0
  76. package/lib/service/account-moves.js +49 -0
  77. package/lib/service/account-moves.js.map +1 -0
  78. package/lib/service/accounts-rpc.d.ts +17 -0
  79. package/lib/service/accounts-rpc.d.ts.map +1 -0
  80. package/lib/service/accounts-rpc.js +77 -0
  81. package/lib/service/accounts-rpc.js.map +1 -0
  82. package/lib/service/compare-rpc.d.ts +22 -0
  83. package/lib/service/compare-rpc.d.ts.map +1 -0
  84. package/lib/service/compare-rpc.js +70 -0
  85. package/lib/service/compare-rpc.js.map +1 -0
  86. package/lib/service/errors.d.ts +20 -4
  87. package/lib/service/errors.d.ts.map +1 -1
  88. package/lib/service/errors.js +12 -5
  89. package/lib/service/errors.js.map +1 -1
  90. package/lib/service/futures-rpc.d.ts.map +1 -1
  91. package/lib/service/futures-rpc.js +7 -25
  92. package/lib/service/futures-rpc.js.map +1 -1
  93. package/lib/service/futures-service.d.ts +28 -8
  94. package/lib/service/futures-service.d.ts.map +1 -1
  95. package/lib/service/futures-service.js +144 -146
  96. package/lib/service/futures-service.js.map +1 -1
  97. package/lib/service/ledger-admin.d.ts +67 -0
  98. package/lib/service/ledger-admin.d.ts.map +1 -0
  99. package/lib/service/ledger-admin.js +102 -0
  100. package/lib/service/ledger-admin.js.map +1 -0
  101. package/lib/service/paper-service.d.ts +39 -12
  102. package/lib/service/paper-service.d.ts.map +1 -1
  103. package/lib/service/paper-service.js +177 -156
  104. package/lib/service/paper-service.js.map +1 -1
  105. package/lib/service/route.d.ts.map +1 -1
  106. package/lib/service/route.js +5 -2
  107. package/lib/service/route.js.map +1 -1
  108. package/lib/service/rpc-support.d.ts +34 -0
  109. package/lib/service/rpc-support.d.ts.map +1 -0
  110. package/lib/service/rpc-support.js +57 -0
  111. package/lib/service/rpc-support.js.map +1 -0
  112. package/lib/service/rpc.d.ts +20 -3
  113. package/lib/service/rpc.d.ts.map +1 -1
  114. package/lib/service/rpc.js +44 -25
  115. package/lib/service/rpc.js.map +1 -1
  116. package/lib/store/accounts.d.ts +110 -0
  117. package/lib/store/accounts.d.ts.map +1 -0
  118. package/lib/store/accounts.js +352 -0
  119. package/lib/store/accounts.js.map +1 -0
  120. package/lib/store/atomic-file.d.ts +16 -0
  121. package/lib/store/atomic-file.d.ts.map +1 -0
  122. package/lib/store/atomic-file.js +34 -0
  123. package/lib/store/atomic-file.js.map +1 -0
  124. package/lib/store/futures-repo.d.ts +8 -49
  125. package/lib/store/futures-repo.d.ts.map +1 -1
  126. package/lib/store/futures-repo.js +34 -246
  127. package/lib/store/futures-repo.js.map +1 -1
  128. package/lib/store/ledger-repo-base.d.ts +120 -0
  129. package/lib/store/ledger-repo-base.d.ts.map +1 -0
  130. package/lib/store/ledger-repo-base.js +275 -0
  131. package/lib/store/ledger-repo-base.js.map +1 -0
  132. package/lib/store/notes.d.ts +29 -0
  133. package/lib/store/notes.d.ts.map +1 -0
  134. package/lib/store/notes.js +78 -0
  135. package/lib/store/notes.js.map +1 -0
  136. package/lib/store/paths.d.ts +2 -0
  137. package/lib/store/paths.d.ts.map +1 -1
  138. package/lib/store/paths.js +4 -0
  139. package/lib/store/paths.js.map +1 -1
  140. package/lib/store/repo.d.ts +15 -55
  141. package/lib/store/repo.d.ts.map +1 -1
  142. package/lib/store/repo.js +41 -206
  143. package/lib/store/repo.js.map +1 -1
  144. package/lib/store/shortlist.d.ts.map +1 -1
  145. package/lib/store/shortlist.js +4 -6
  146. package/lib/store/shortlist.js.map +1 -1
  147. package/lib/store/snapshots.d.ts +0 -3
  148. package/lib/store/snapshots.d.ts.map +1 -1
  149. package/lib/store/snapshots.js +0 -3
  150. package/lib/store/snapshots.js.map +1 -1
  151. package/package.json +1 -1
  152. package/src/agent/account-tools.ts +136 -0
  153. package/src/agent/futures-tools.ts +1 -6
  154. package/src/agent/ledger-tools.ts +29 -16
  155. package/src/agent/tool-result.ts +27 -0
  156. package/src/agent/tools.ts +30 -10
  157. package/src/client/entry.js +14 -0
  158. package/src/client/parts/10-core.js +535 -0
  159. package/src/client/parts/20-styles.js +336 -0
  160. package/src/client/parts/30-atoms.js +769 -0
  161. package/src/client/parts/35-hooks.js +447 -0
  162. package/src/client/parts/40-stock-tabs.js +641 -0
  163. package/src/client/parts/50-futures.js +911 -0
  164. package/src/client/parts/60-shell.js +706 -0
  165. package/src/client/parts/70-plugin.js +67 -0
  166. package/src/contract/accounts.ts +82 -0
  167. package/src/contract/common.ts +173 -0
  168. package/src/contract/domain.ts +217 -0
  169. package/src/contract/errors.ts +34 -0
  170. package/src/contract/index.ts +15 -0
  171. package/src/contract/ledger.ts +42 -0
  172. package/src/contract/market.ts +39 -0
  173. package/src/contract/rpc.ts +15 -0
  174. package/src/contract.ts +6 -472
  175. package/src/core/session.ts +1 -2
  176. package/src/data/cached-market-data.ts +193 -0
  177. package/src/data/futures-market-data.ts +9 -10
  178. package/src/index.ts +168 -20
  179. package/src/service/account-moves.ts +72 -0
  180. package/src/service/accounts-rpc.ts +80 -0
  181. package/src/service/compare-rpc.ts +77 -0
  182. package/src/service/errors.ts +23 -4
  183. package/src/service/futures-rpc.ts +7 -24
  184. package/src/service/futures-service.ts +161 -159
  185. package/src/service/ledger-admin.ts +140 -0
  186. package/src/service/paper-service.ts +183 -153
  187. package/src/service/route.ts +5 -2
  188. package/src/service/rpc-support.ts +61 -0
  189. package/src/service/rpc.ts +59 -23
  190. package/src/store/accounts.ts +373 -0
  191. package/src/store/atomic-file.ts +37 -0
  192. package/src/store/futures-repo.ts +35 -260
  193. package/src/store/ledger-repo-base.ts +337 -0
  194. package/src/store/notes.ts +86 -0
  195. package/src/store/paths.ts +5 -0
  196. package/src/store/repo.ts +47 -229
  197. package/src/store/shortlist.ts +3 -5
  198. package/src/store/snapshots.ts +0 -3
  199. package/src/client/index.js +0 -3275
@@ -1,36 +1,22 @@
1
1
  /**
2
2
  * Futures ledger repository: `$DSH_HOME/paper-trading/futures/events.jsonl`.
3
3
  *
4
- * Same durability model as the stock account — one write queue, contiguous
4
+ * Storage is the shared {@link LedgerRepoBase}: one write queue, contiguous
5
5
  * sequence numbers, fsync per append, atomic replacement for reset/repair, a
6
- * backup before any destructive operation, and automatic `blocked` state when
7
- * replay finds an inconsistency. Recovery is shared with the stock ledger:
8
- * daily automatic snapshots, a snapshot list, and restoring one into the
9
- * running process.
10
- *
6
+ * backup before any destructive operation, automatic `blocked` state when
7
+ * replay finds an inconsistency, daily snapshots and in-process restore. This
8
+ * file only supplies the futures fold (replay/verify/summary) and the futures
9
+ * mark tick, which quantizes prices to the contract tick.
11
10
  * @module @dsh-ft/dsh-fft-paper-trading/store/futures-repo
12
11
  */
13
12
 
14
- import { resolve } from 'node:path'
15
13
  import { FUTURES_ACCOUNT_ID, FUTURES_LEDGER_VERSION } from '../futures-contract.js'
16
- import { applyEvent, emptyState, verify } from '../core/futures/ledger.js'
14
+ import { applyEvent, verify } from '../core/futures/ledger.js'
17
15
  import { quantizePrice } from '../core/futures/money.js'
18
- import {
19
- prepareFuturesLedger,
20
- replayFutures,
21
- type PreparedFuturesLedger,
22
- } from '../core/futures/replay.js'
16
+ import { prepareFuturesLedger, replayFutures } from '../core/futures/replay.js'
23
17
  import type { FuturesAccountState, FuturesLedgerEvent } from '../core/futures/types.js'
24
- import { EventStore, readEventsFile } from './event-store.js'
18
+ import { LedgerRepoBase, type LedgerPlane, type LedgerRepoOptions } from './ledger-repo-base.js'
25
19
  import type { LedgerSnapshot } from './port.js'
26
- import { backupsDir, eventsPath } from './paths.js'
27
- import {
28
- ensureAutoSnapshot,
29
- listSnapshotFiles,
30
- snapshotPath,
31
- writeSnapshot,
32
- type SnapshotFile,
33
- } from './snapshots.js'
34
20
 
35
21
  export interface FuturesRepoOptions {
36
22
  home: string
@@ -83,147 +69,35 @@ function futuresLedgerVersionOf(events: readonly FuturesLedgerEvent[]): number {
83
69
  return FUTURES_LEDGER_VERSION
84
70
  }
85
71
 
86
- /**
87
- * Loads, replays and appends the single futures ledger.
88
- *
89
- * Every write goes through one Promise queue and one sequence invariant, so a
90
- * concurrent read cannot duplicate a settlement event. Repairs and resets use
91
- * an atomic file replacement; a rejected write never touches the file.
92
- */
93
- export class FuturesRepo implements FuturesStore {
94
- private readonly store: EventStore<FuturesLedgerEvent>
95
- private readonly accountId: string
96
- private state: FuturesAccountState | undefined
97
- private loading: Promise<FuturesAccountState> | undefined
98
- private queue: Promise<unknown> = Promise.resolve()
99
-
100
- constructor(private readonly options: FuturesRepoOptions) {
101
- this.accountId = options.accountId ?? FUTURES_ACCOUNT_ID
102
- this.store = new EventStore<FuturesLedgerEvent>(eventsPath(options.home, this.accountId))
103
- }
104
-
105
- get ledgerPath(): string {
106
- return this.store.filePath
107
- }
108
-
109
- private backups(): string {
110
- return backupsDir(this.options.home, this.accountId)
111
- }
112
-
113
- private async ensureLoaded(): Promise<FuturesAccountState> {
114
- if (this.state !== undefined) return this.state
115
- if (this.loading === undefined) this.loading = this.loadOnce()
116
- return this.loading
117
- }
118
-
119
- private async loadOnce(): Promise<FuturesAccountState> {
120
- const { events, skipped } = await this.store.readAll()
121
- if (skipped > 0) this.options.logger?.warn(`paper-trading: dropped ${skipped} malformed futures ledger line(s)`)
122
-
123
- const prepared = prepareFuturesLedger(events)
124
- const source = prepared.issues.length > 0 ? events : prepared.events
125
- const result = replayFutures(source, this.accountId)
126
- this.state = result.state
127
-
128
- const issues = [...prepared.issues, ...result.issues]
129
- if (issues.length > 0 && !result.state.blocked) {
130
- await this.recordViolation(issues)
131
- } else if (prepared.issues.length === 0 && prepared.duplicates > 0) {
132
- this.state = await this.compact(prepared, result.state)
133
- }
134
-
135
- if (!this.state.blocked) {
136
- await ensureAutoSnapshot(this.store, this.backups(), { logger: this.options.logger })
137
- }
138
- return this.state
139
- }
140
-
141
- private async compact(prepared: PreparedFuturesLedger, state: FuturesAccountState): Promise<FuturesAccountState> {
142
- const seq = state.lastSeq + 1
143
- const event: FuturesLedgerEvent = {
144
- seq,
145
- id: `evt-${seq}`,
146
- ts: new Date().toISOString(),
147
- type: 'ledger.repaired',
148
- payload: { dropped: prepared.duplicates },
149
- }
150
- try {
151
- await writeSnapshot(this.store, this.backups(), 'repair')
152
- await this.store.replace([...prepared.events, event])
153
- applyEvent(state, event)
154
- this.options.logger?.warn(`paper-trading: dropped ${prepared.duplicates} duplicate futures ledger event(s)`)
155
- } catch (error) {
156
- this.options.logger?.warn(`paper-trading: futures ledger repair failed, kept in memory only: ${String(error)}`)
157
- }
158
- return state
159
- }
72
+ /** How the futures plane folds its event log; storage mechanics are shared. */
73
+ const FUTURES_PLANE: LedgerPlane<FuturesAccountState, FuturesLedgerEvent> = {
74
+ label: 'paper-trading: futures',
75
+ prepare: prepareFuturesLedger,
76
+ replay: (events, accountId) => replayFutures(events, accountId),
77
+ applyEvent,
78
+ verify,
79
+ summary: state => ({
80
+ lastSeq: state.lastSeq,
81
+ tradeDate: state.tradeDate,
82
+ cashCents: state.cashCents,
83
+ blocked: state.blocked,
84
+ ...(state.blockedReason === undefined ? {} : { blockedReason: state.blockedReason }),
85
+ }),
86
+ ledgerVersion: futuresLedgerVersionOf,
87
+ // Futures historically hands the planned events back on a blocked account;
88
+ // the caller checks `outcome.events` rather than relying on the drop.
89
+ dropEventsWhenBlocked: false,
90
+ }
160
91
 
161
- private async recordViolation(issues: string[]): Promise<void> {
162
- const state = this.state
163
- if (state === undefined || state.blocked) return
164
- const seq = state.lastSeq + 1
165
- const event: FuturesLedgerEvent = {
166
- seq,
167
- id: `evt-${seq}`,
168
- ts: new Date().toISOString(),
169
- type: 'ledger.violation',
170
- payload: { check: 'replay', expected: 'consistent', actual: issues.join('; ') },
92
+ /** Loads, replays and appends the single futures ledger. */
93
+ export class FuturesRepo extends LedgerRepoBase<FuturesAccountState, FuturesLedgerEvent> implements FuturesStore {
94
+ constructor(options: FuturesRepoOptions) {
95
+ const ledgerOptions: LedgerRepoOptions = {
96
+ home: options.home,
97
+ accountId: options.accountId ?? FUTURES_ACCOUNT_ID,
98
+ ...(options.logger === undefined ? {} : { logger: options.logger }),
171
99
  }
172
- await this.store.append([event])
173
- applyEvent(state, event)
174
- this.state = state
175
- this.options.logger?.warn(`paper-trading: futures ledger violation, account blocked: ${issues.join('; ')}`)
176
- }
177
-
178
- async current(): Promise<FuturesAccountState> {
179
- return this.ensureLoaded()
180
- }
181
-
182
- async transact<T>(
183
- build: (state: FuturesAccountState) => FuturesTransaction<T> | Promise<FuturesTransaction<T>>,
184
- ): Promise<FuturesTransactionOutcome<T>> {
185
- return this.enqueue(async () => {
186
- const state = await this.ensureLoaded()
187
- const built = await build(state)
188
- const events = built.events
189
- if (events.length === 0) return { state, value: built.value, events }
190
- if (state.blocked) {
191
- this.options.logger?.warn(`paper-trading: futures account blocked, dropped ${events.length} event(s)`)
192
- return { state, value: built.value, events }
193
- }
194
- this.assertSequence(state, events)
195
- await this.store.append(events)
196
- for (const event of events) applyEvent(state, event)
197
- const issues = verify(state)
198
- this.state = state
199
- if (issues.length > 0) await this.recordViolation(issues)
200
- return { state: this.state ?? state, value: built.value, events }
201
- })
202
- }
203
-
204
- async append(events: readonly FuturesLedgerEvent[]): Promise<FuturesAccountState> {
205
- const outcome = await this.transact(() => ({ events: [...events], value: undefined }))
206
- return outcome.state
207
- }
208
-
209
- /**
210
- * Replace the file with a new ledger (reset, compaction). Validated and
211
- * replayed before the atomic rename, so a reset never leaves a ledger that
212
- * would lock the account on the next start.
213
- */
214
- async replace(events: readonly FuturesLedgerEvent[]): Promise<FuturesAccountState> {
215
- return this.enqueue(async () => {
216
- this.assertSequence(emptyState(this.accountId), events)
217
- const result = replayFutures([...events], this.accountId)
218
- if (result.issues.length > 0) {
219
- throw new Error(`paper-trading: refusing an inconsistent futures ledger: ${result.issues.join('; ')}`)
220
- }
221
- await this.ensureLoaded()
222
- await this.store.replace(events)
223
- this.state = result.state
224
- this.loading = Promise.resolve(result.state)
225
- return this.state
226
- })
100
+ super(FUTURES_PLANE, ledgerOptions)
227
101
  }
228
102
 
229
103
  /** Refresh position marks for the views only; never writes the ledger. */
@@ -240,103 +114,4 @@ export class FuturesRepo implements FuturesStore {
240
114
  return state
241
115
  })
242
116
  }
243
-
244
- async backup(label: string): Promise<boolean> {
245
- return this.enqueue(async () => {
246
- const stamp = label.replace(/[:.]/g, '-')
247
- return this.store.backup(`${this.backups()}/events-${stamp}.jsonl`)
248
- })
249
- }
250
-
251
- async readLedger(): Promise<FuturesLedgerFile> {
252
- return { path: resolve(this.store.filePath), content: await this.store.readText() }
253
- }
254
-
255
- /** List snapshots with replay metadata, newest first. */
256
- async snapshots(): Promise<LedgerSnapshot[]> {
257
- const files = await listSnapshotFiles(this.backups())
258
- const snapshots: LedgerSnapshot[] = []
259
- for (const file of files) snapshots.push(await this.inspectSnapshot(file))
260
- return snapshots
261
- }
262
-
263
- private async inspectSnapshot(file: SnapshotFile): Promise<LedgerSnapshot> {
264
- const base = {
265
- name: file.name,
266
- createdAt: new Date(file.mtimeMs).toISOString(),
267
- bytes: file.bytes,
268
- }
269
- try {
270
- const { events, skipped } = await readEventsFile<FuturesLedgerEvent>(file.path)
271
- const prepared = prepareFuturesLedger(events)
272
- const source = prepared.issues.length > 0 ? events : prepared.events
273
- const result = replayFutures(source, this.accountId)
274
- const issues = [...prepared.issues, ...result.issues]
275
- if (skipped > 0) issues.push(`含 ${skipped} 行无法解析`)
276
- const ledgerVersion = futuresLedgerVersionOf(source)
277
- return {
278
- ...base,
279
- ledgerVersion,
280
- lastSeq: result.state.lastSeq,
281
- tradeDate: result.state.tradeDate,
282
- cashCents: result.state.cashCents,
283
- valid: issues.length === 0 && !result.state.blocked,
284
- migratable: false,
285
- problem: issues[0] ?? (result.state.blocked ? result.state.blockedReason : undefined),
286
- }
287
- } catch (error) {
288
- return {
289
- ...base,
290
- ledgerVersion: 0,
291
- lastSeq: 0,
292
- tradeDate: '',
293
- cashCents: 0,
294
- valid: false,
295
- migratable: false,
296
- problem: String(error),
297
- }
298
- }
299
- }
300
-
301
- /**
302
- * Replace the live futures ledger with one snapshot.
303
- *
304
- * Allowed while blocked; validated before the live file is touched, and the
305
- * current file is snapshotted first so the recovery can be undone.
306
- */
307
- async restore(name: string): Promise<FuturesAccountState> {
308
- const file = snapshotPath(this.backups(), name)
309
- return this.enqueue(async () => {
310
- await this.ensureLoaded().catch(() => undefined)
311
- const { events, skipped } = await readEventsFile<FuturesLedgerEvent>(file)
312
- if (events.length === 0 && skipped === 0) throw new Error(`快照 ${name} 是空的`)
313
- if (skipped > 0) throw new Error(`快照 ${name} 含 ${skipped} 行无法解析,拒绝恢复`)
314
- const prepared = prepareFuturesLedger(events)
315
- if (prepared.issues.length > 0) throw new Error(`快照 ${name} 结构损坏:${prepared.issues.join('; ')}`)
316
- const result = replayFutures(prepared.events, this.accountId)
317
- if (result.issues.length > 0) throw new Error(`快照 ${name} 对账失败:${result.issues.join('; ')}`)
318
- if (result.state.blocked) throw new Error(`快照 ${name} 无法恢复:${result.state.blockedReason ?? '版本不兼容'}`)
319
- await writeSnapshot(this.store, this.backups(), 'pre-restore')
320
- await this.store.replace(prepared.events)
321
- this.state = result.state
322
- this.loading = Promise.resolve(result.state)
323
- return this.state
324
- })
325
- }
326
-
327
- private assertSequence(state: FuturesAccountState, events: readonly FuturesLedgerEvent[]): void {
328
- let expected = state.lastSeq + 1
329
- for (const event of events) {
330
- if (!Number.isInteger(event.seq) || event.seq !== expected) {
331
- throw new Error(`paper-trading: futures ledger seq mismatch: expected ${expected}, got ${String(event.seq)}`)
332
- }
333
- expected += 1
334
- }
335
- }
336
-
337
- private enqueue<T>(task: () => Promise<T>): Promise<T> {
338
- const run = this.queue.then(task, task)
339
- this.queue = run.then(() => undefined, () => undefined)
340
- return run
341
- }
342
117
  }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Shared single-writer ledger repository.
3
+ *
4
+ * The stock and futures ledgers have the same persistence contract — one
5
+ * append-only JSONL file, one Promise queue, contiguous `seq`, atomic replace,
6
+ * daily snapshots and in-process restore — and differed only in how an event is
7
+ * folded into their state. That common half lives here once; each plane supplies
8
+ * a {@link LedgerPlane} adapter (replay/verify/summary) plus its own markPrices.
9
+ *
10
+ * Loading is also shared: malformed tails are dropped, duplicate sequences are
11
+ * repaired, an inconsistent replay records a violation (which freezes the
12
+ * account) instead of throwing, and a known older version may migrate in place.
13
+ * @module @dsh-ft/dsh-fft-paper-trading/store/ledger-repo-base
14
+ */
15
+
16
+ import { resolve } from 'node:path'
17
+ import { EventStore, readEventsFile, type StoredLedgerEvent } from './event-store.js'
18
+ import type { LedgerFile, LedgerSnapshot } from './port.js'
19
+ import { backupsDir, eventsPath } from './paths.js'
20
+ import {
21
+ ensureAutoSnapshot,
22
+ listSnapshotFiles,
23
+ snapshotPath,
24
+ writeSnapshot,
25
+ type SnapshotFile,
26
+ } from './snapshots.js'
27
+
28
+ /** The parts of a ledger that the base class needs to inspect. */
29
+ export interface LedgerSummary {
30
+ lastSeq: number
31
+ tradeDate: string
32
+ cashCents: number
33
+ blocked: boolean
34
+ blockedReason?: string
35
+ }
36
+
37
+ /**
38
+ * How one plane folds its event log.
39
+ *
40
+ * `prepare` drops malformed/duplicate entries and reports what it saw;
41
+ * `replay` then rebuilds the state from the tolerant event list.
42
+ */
43
+ export interface LedgerPlane<S, E extends StoredLedgerEvent> {
44
+ /** Log prefix, e.g. `paper-trading` or `paper-trading: futures`. */
45
+ label: string
46
+ /** Events a reset writes; used to validate a replacement. */
47
+ prepare: (events: E[]) => { events: E[]; issues: string[]; duplicates: number }
48
+ replay: (events: E[], accountId: string) => { state: S; issues: string[] }
49
+ applyEvent: (state: S, event: E) => S
50
+ verify: (state: S) => string[]
51
+ summary: (state: S) => LedgerSummary
52
+ ledgerVersion: (events: readonly E[]) => number
53
+ /**
54
+ * When the account is blocked, drop planned writes (stock) or hand them back
55
+ * (futures) — the latter only affects an internal caller and is kept for
56
+ * behavior compatibility.
57
+ */
58
+ dropEventsWhenBlocked: boolean
59
+ }
60
+
61
+ /** One queued write: events to append plus the value the caller asked for. */
62
+ export interface LedgerTransaction<T, E> {
63
+ events: E[]
64
+ value: T
65
+ }
66
+
67
+ export interface LedgerTransactionOutcome<S, T, E> {
68
+ state: S
69
+ value: T
70
+ /** Events that actually reached the file; empty when the store refused. */
71
+ events: E[]
72
+ }
73
+
74
+ export interface LedgerRepoOptions {
75
+ home: string
76
+ accountId: string
77
+ logger?: { warn(message: string): void }
78
+ }
79
+
80
+ export class LedgerRepoBase<S, E extends StoredLedgerEvent> {
81
+ protected readonly store: EventStore<E>
82
+ protected state: S | undefined
83
+ protected loading: Promise<S> | undefined
84
+ protected queue: Promise<unknown> = Promise.resolve()
85
+
86
+ constructor(
87
+ protected readonly plane: LedgerPlane<S, E>,
88
+ protected readonly options: LedgerRepoOptions,
89
+ ) {
90
+ this.store = new EventStore<E>(eventsPath(options.home, options.accountId))
91
+ }
92
+
93
+ /** Absolute path of `events.jsonl`, surfaced so a locked account is fixable. */
94
+ get ledgerPath(): string {
95
+ return this.store.filePath
96
+ }
97
+
98
+ protected backups(): string {
99
+ return backupsDir(this.options.home, this.options.accountId)
100
+ }
101
+
102
+ /** Serialise writes the same way the ledger does; a failed task cannot poison the queue. */
103
+ protected enqueue<T>(task: () => Promise<T>): Promise<T> {
104
+ const run = this.queue.then(task, task)
105
+ this.queue = run.then(() => undefined, () => undefined)
106
+ return run
107
+ }
108
+
109
+ protected async ensureLoaded(): Promise<S> {
110
+ if (this.state !== undefined) return this.state
111
+ if (this.loading === undefined) this.loading = this.loadOnce()
112
+ return this.loading
113
+ }
114
+
115
+ private async loadOnce(): Promise<S> {
116
+ const { events, skipped } = await this.store.readAll()
117
+ if (skipped > 0) this.warn(`dropped ${skipped} malformed ledger line(s)`)
118
+
119
+ const prepared = this.plane.prepare(events)
120
+ // Conflicting same-seq events are real corruption: replay the original file
121
+ // untouched so the violation reports what is actually there.
122
+ const source = prepared.issues.length > 0 ? events : prepared.events
123
+ const migrated = prepared.issues.length === 0 ? await this.tryMigrate(prepared.events) : undefined
124
+ if (migrated !== undefined) {
125
+ this.state = migrated
126
+ } else {
127
+ const result = this.plane.replay(source, this.options.accountId)
128
+ this.state = result.state
129
+ const issues = [...prepared.issues, ...result.issues]
130
+ if (issues.length > 0 && !this.plane.summary(result.state).blocked) {
131
+ await this.recordViolation(issues)
132
+ } else if (prepared.issues.length === 0 && prepared.duplicates > 0) {
133
+ this.state = await this.compact(prepared)
134
+ }
135
+ }
136
+ // A known-good copy from before this session is what recovery falls back on;
137
+ // it is deliberately skipped for a blocked ledger (that file is evidence).
138
+ if (!this.plane.summary(this.state).blocked) {
139
+ await ensureAutoSnapshot(this.store, this.backups(), { logger: this.options.logger })
140
+ }
141
+ return this.state
142
+ }
143
+
144
+ /** Planes with a migration chain override this; the default has none. */
145
+ protected async tryMigrate(_events: E[]): Promise<S | undefined> {
146
+ return undefined
147
+ }
148
+
149
+ private async compact(prepared: { events: E[]; duplicates: number }): Promise<S> {
150
+ const state = this.state as S
151
+ const seq = this.plane.summary(state).lastSeq + 1
152
+ const event = {
153
+ seq,
154
+ id: `evt-${seq}`,
155
+ ts: new Date().toISOString(),
156
+ type: 'ledger.repaired',
157
+ payload: { dropped: prepared.duplicates },
158
+ } as unknown as E
159
+ try {
160
+ await writeSnapshot(this.store, this.backups(), 'repair')
161
+ await this.store.replace([...prepared.events, event])
162
+ this.plane.applyEvent(state, event)
163
+ this.warn(`dropped ${prepared.duplicates} duplicate ledger event(s)`)
164
+ } catch (error) {
165
+ this.warn(`ledger repair failed, kept in memory only: ${String(error)}`)
166
+ }
167
+ return state
168
+ }
169
+
170
+ private async recordViolation(issues: string[]): Promise<void> {
171
+ const state = this.state
172
+ if (state === undefined || this.plane.summary(state).blocked) return
173
+ const seq = this.plane.summary(state).lastSeq + 1
174
+ const event = {
175
+ seq,
176
+ id: `evt-${seq}`,
177
+ ts: new Date().toISOString(),
178
+ type: 'ledger.violation',
179
+ payload: { check: 'replay', expected: 'consistent', actual: issues.join('; ') },
180
+ } as unknown as E
181
+ await this.store.append([event])
182
+ this.plane.applyEvent(state, event)
183
+ this.state = state
184
+ this.warn(`ledger violation, account blocked: ${issues.join('; ')}`)
185
+ }
186
+
187
+ private warn(message: string): void {
188
+ this.options.logger?.warn(`${this.plane.label}: ${message}`)
189
+ }
190
+
191
+ async current(): Promise<S> {
192
+ return this.ensureLoaded()
193
+ }
194
+
195
+ async transact<T>(build: (state: S) => LedgerTransaction<T, E> | Promise<LedgerTransaction<T, E>>): Promise<LedgerTransactionOutcome<S, T, E>> {
196
+ return this.enqueue(async () => {
197
+ const state = await this.ensureLoaded()
198
+ const built = await build(state)
199
+ const events = built.events
200
+ if (events.length === 0) return { state, value: built.value, events }
201
+ if (this.plane.summary(state).blocked) {
202
+ this.warn(`account blocked, dropped ${events.length} event(s)`)
203
+ return { state, value: built.value, events: this.plane.dropEventsWhenBlocked ? [] : events }
204
+ }
205
+ this.assertSequence(state, events)
206
+ await this.store.append(events)
207
+ for (const event of events) this.plane.applyEvent(state, event)
208
+ const issues = this.plane.verify(state)
209
+ this.state = state
210
+ if (issues.length > 0) await this.recordViolation(issues)
211
+ return { state: this.state ?? state, value: built.value, events }
212
+ })
213
+ }
214
+
215
+ async append(events: readonly E[]): Promise<S> {
216
+ const outcome = await this.transact(() => ({ events: [...events], value: undefined }))
217
+ return outcome.state
218
+ }
219
+
220
+ /**
221
+ * Replace the file with a new ledger (reset, compaction).
222
+ *
223
+ * The replacement is validated and replayed before the atomic rename, so a
224
+ * reset never leaves a ledger that would lock the account on the next start.
225
+ */
226
+ async replace(events: readonly E[]): Promise<S> {
227
+ return this.enqueue(async () => {
228
+ this.assertSequence(undefined, events)
229
+ const result = this.plane.replay([...events], this.options.accountId)
230
+ if (result.issues.length > 0) {
231
+ throw new Error(`${this.plane.label}: refusing an inconsistent ledger: ${result.issues.join('; ')}`)
232
+ }
233
+ // Settle any in-flight load first: it may still repair or block the old file.
234
+ await this.ensureLoaded()
235
+ await this.store.replace(events)
236
+ this.state = result.state
237
+ this.loading = Promise.resolve(result.state)
238
+ return this.state
239
+ })
240
+ }
241
+
242
+ /** Copy the event file into `backups/`, named after the reset timestamp. */
243
+ async backup(label: string): Promise<boolean> {
244
+ return this.enqueue(async () => {
245
+ const stamp = label.replace(/[:.]/g, '-')
246
+ return this.store.backup(`${this.backups()}/events-${stamp}.jsonl`)
247
+ })
248
+ }
249
+
250
+ /** Raw file text for the export endpoint; `content: null` means "not created yet". */
251
+ async readLedger(): Promise<LedgerFile> {
252
+ return { path: resolve(this.store.filePath), content: await this.store.readText() }
253
+ }
254
+
255
+ /** List snapshots with replay metadata, newest first. */
256
+ async snapshots(): Promise<LedgerSnapshot[]> {
257
+ const files = await listSnapshotFiles(this.backups())
258
+ const snapshots: LedgerSnapshot[] = []
259
+ for (const file of files) snapshots.push(await this.inspectSnapshot(file))
260
+ return snapshots
261
+ }
262
+
263
+ protected async inspectSnapshot(file: SnapshotFile): Promise<LedgerSnapshot> {
264
+ const base = {
265
+ name: file.name,
266
+ createdAt: new Date(file.mtimeMs).toISOString(),
267
+ bytes: file.bytes,
268
+ }
269
+ try {
270
+ const { events, skipped } = await readEventsFile<E>(file.path)
271
+ const prepared = this.plane.prepare(events)
272
+ const source = prepared.issues.length > 0 ? events : prepared.events
273
+ const result = this.plane.replay(source, this.options.accountId)
274
+ const issues = [...prepared.issues, ...result.issues]
275
+ if (skipped > 0) issues.push(`含 ${skipped} 行无法解析`)
276
+ const summary = this.plane.summary(result.state)
277
+ return {
278
+ ...base,
279
+ ledgerVersion: this.plane.ledgerVersion(source),
280
+ lastSeq: summary.lastSeq,
281
+ tradeDate: summary.tradeDate,
282
+ cashCents: summary.cashCents,
283
+ valid: issues.length === 0 && !summary.blocked,
284
+ migratable: false,
285
+ problem: issues[0] ?? (summary.blocked ? summary.blockedReason : undefined),
286
+ }
287
+ } catch (error) {
288
+ return {
289
+ ...base,
290
+ ledgerVersion: 0,
291
+ lastSeq: 0,
292
+ tradeDate: '',
293
+ cashCents: 0,
294
+ valid: false,
295
+ migratable: false,
296
+ problem: String(error),
297
+ }
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Replace the live ledger with one snapshot.
303
+ *
304
+ * Allowed while blocked; validated before the live file is touched, and the
305
+ * current file is snapshotted first so the recovery can be undone.
306
+ */
307
+ async restore(name: string): Promise<S> {
308
+ const file = snapshotPath(this.backups(), name)
309
+ return this.enqueue(async () => {
310
+ await this.ensureLoaded().catch(() => undefined)
311
+ const { events, skipped } = await readEventsFile<E>(file)
312
+ if (events.length === 0 && skipped === 0) throw new Error(`快照 ${name} 是空的`)
313
+ if (skipped > 0) throw new Error(`快照 ${name} 含 ${skipped} 行无法解析,拒绝恢复`)
314
+ const prepared = this.plane.prepare(events)
315
+ if (prepared.issues.length > 0) throw new Error(`快照 ${name} 结构损坏:${prepared.issues.join('; ')}`)
316
+ const result = this.plane.replay(prepared.events, this.options.accountId)
317
+ if (result.issues.length > 0) throw new Error(`快照 ${name} 对账失败:${result.issues.join('; ')}`)
318
+ const summary = this.plane.summary(result.state)
319
+ if (summary.blocked) throw new Error(`快照 ${name} 无法恢复:${summary.blockedReason ?? '版本不兼容'}`)
320
+ await writeSnapshot(this.store, this.backups(), 'pre-restore')
321
+ await this.store.replace(prepared.events)
322
+ this.state = result.state
323
+ this.loading = Promise.resolve(result.state)
324
+ return this.state
325
+ })
326
+ }
327
+
328
+ protected assertSequence(state: S | undefined, events: readonly E[]): void {
329
+ let expected = (state === undefined ? 0 : this.plane.summary(state).lastSeq) + 1
330
+ for (const event of events) {
331
+ if (!Number.isInteger(event.seq) || event.seq !== expected) {
332
+ throw new Error(`${this.plane.label}: ledger seq mismatch: expected ${expected}, got ${String(event.seq)}`)
333
+ }
334
+ expected += 1
335
+ }
336
+ }
337
+ }