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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +4 -3
  2. package/README.zh.md +4 -3
  3. package/lib/agent/account-tools.d.ts +18 -0
  4. package/lib/agent/account-tools.d.ts.map +1 -0
  5. package/lib/agent/account-tools.js +127 -0
  6. package/lib/agent/account-tools.js.map +1 -0
  7. package/lib/agent/futures-tools.d.ts.map +1 -1
  8. package/lib/agent/futures-tools.js +1 -6
  9. package/lib/agent/futures-tools.js.map +1 -1
  10. package/lib/agent/ledger-tools.d.ts +15 -3
  11. package/lib/agent/ledger-tools.d.ts.map +1 -1
  12. package/lib/agent/ledger-tools.js +11 -15
  13. package/lib/agent/ledger-tools.js.map +1 -1
  14. package/lib/agent/tool-result.d.ts +19 -0
  15. package/lib/agent/tool-result.d.ts.map +1 -0
  16. package/lib/agent/tool-result.js +22 -0
  17. package/lib/agent/tool-result.js.map +1 -0
  18. package/lib/agent/tools.d.ts +10 -2
  19. package/lib/agent/tools.d.ts.map +1 -1
  20. package/lib/agent/tools.js +26 -11
  21. package/lib/agent/tools.js.map +1 -1
  22. package/lib/client.js +1448 -282
  23. package/lib/contract/accounts.d.ts +76 -0
  24. package/lib/contract/accounts.d.ts.map +1 -0
  25. package/lib/contract/accounts.js +6 -0
  26. package/lib/contract/accounts.js.map +1 -0
  27. package/lib/contract/common.d.ts +144 -0
  28. package/lib/contract/common.d.ts.map +1 -0
  29. package/lib/contract/common.js +33 -0
  30. package/lib/contract/common.js.map +1 -0
  31. package/lib/contract/domain.d.ts +196 -0
  32. package/lib/contract/domain.d.ts.map +1 -0
  33. package/lib/contract/domain.js +14 -0
  34. package/lib/contract/domain.js.map +1 -0
  35. package/lib/contract/errors.d.ts +6 -0
  36. package/lib/contract/errors.d.ts.map +1 -0
  37. package/lib/contract/errors.js +6 -0
  38. package/lib/contract/errors.js.map +1 -0
  39. package/lib/contract/index.d.ts +15 -0
  40. package/lib/contract/index.d.ts.map +1 -0
  41. package/lib/contract/index.js +15 -0
  42. package/lib/contract/index.js.map +1 -0
  43. package/lib/contract/ledger.d.ts +40 -0
  44. package/lib/contract/ledger.d.ts.map +1 -0
  45. package/lib/contract/ledger.js +6 -0
  46. package/lib/contract/ledger.js.map +1 -0
  47. package/lib/contract/market.d.ts +30 -0
  48. package/lib/contract/market.d.ts.map +1 -0
  49. package/lib/contract/market.js +6 -0
  50. package/lib/contract/market.js.map +1 -0
  51. package/lib/contract/rpc.d.ts +24 -0
  52. package/lib/contract/rpc.d.ts.map +1 -0
  53. package/lib/contract/rpc.js +6 -0
  54. package/lib/contract/rpc.js.map +1 -0
  55. package/lib/contract.d.ts +6 -403
  56. package/lib/contract.d.ts.map +1 -1
  57. package/lib/contract.js +6 -24
  58. package/lib/contract.js.map +1 -1
  59. package/lib/core/session.d.ts +1 -1
  60. package/lib/core/session.d.ts.map +1 -1
  61. package/lib/core/session.js +1 -2
  62. package/lib/core/session.js.map +1 -1
  63. package/lib/data/cached-market-data.d.ts +61 -0
  64. package/lib/data/cached-market-data.d.ts.map +1 -0
  65. package/lib/data/cached-market-data.js +174 -0
  66. package/lib/data/cached-market-data.js.map +1 -0
  67. package/lib/data/futures-market-data.d.ts.map +1 -1
  68. package/lib/data/futures-market-data.js +9 -10
  69. package/lib/data/futures-market-data.js.map +1 -1
  70. package/lib/index.d.ts +25 -1
  71. package/lib/index.d.ts.map +1 -1
  72. package/lib/index.js +156 -18
  73. package/lib/index.js.map +1 -1
  74. package/lib/service/account-moves.d.ts +64 -0
  75. package/lib/service/account-moves.d.ts.map +1 -0
  76. package/lib/service/account-moves.js +49 -0
  77. package/lib/service/account-moves.js.map +1 -0
  78. package/lib/service/accounts-rpc.d.ts +17 -0
  79. package/lib/service/accounts-rpc.d.ts.map +1 -0
  80. package/lib/service/accounts-rpc.js +77 -0
  81. package/lib/service/accounts-rpc.js.map +1 -0
  82. package/lib/service/compare-rpc.d.ts +22 -0
  83. package/lib/service/compare-rpc.d.ts.map +1 -0
  84. package/lib/service/compare-rpc.js +70 -0
  85. package/lib/service/compare-rpc.js.map +1 -0
  86. package/lib/service/errors.d.ts +20 -4
  87. package/lib/service/errors.d.ts.map +1 -1
  88. package/lib/service/errors.js +12 -5
  89. package/lib/service/errors.js.map +1 -1
  90. package/lib/service/futures-rpc.d.ts.map +1 -1
  91. package/lib/service/futures-rpc.js +7 -25
  92. package/lib/service/futures-rpc.js.map +1 -1
  93. package/lib/service/futures-service.d.ts +28 -8
  94. package/lib/service/futures-service.d.ts.map +1 -1
  95. package/lib/service/futures-service.js +144 -146
  96. package/lib/service/futures-service.js.map +1 -1
  97. package/lib/service/ledger-admin.d.ts +67 -0
  98. package/lib/service/ledger-admin.d.ts.map +1 -0
  99. package/lib/service/ledger-admin.js +102 -0
  100. package/lib/service/ledger-admin.js.map +1 -0
  101. package/lib/service/paper-service.d.ts +39 -12
  102. package/lib/service/paper-service.d.ts.map +1 -1
  103. package/lib/service/paper-service.js +177 -156
  104. package/lib/service/paper-service.js.map +1 -1
  105. package/lib/service/route.d.ts.map +1 -1
  106. package/lib/service/route.js +5 -2
  107. package/lib/service/route.js.map +1 -1
  108. package/lib/service/rpc-support.d.ts +34 -0
  109. package/lib/service/rpc-support.d.ts.map +1 -0
  110. package/lib/service/rpc-support.js +57 -0
  111. package/lib/service/rpc-support.js.map +1 -0
  112. package/lib/service/rpc.d.ts +20 -3
  113. package/lib/service/rpc.d.ts.map +1 -1
  114. package/lib/service/rpc.js +44 -25
  115. package/lib/service/rpc.js.map +1 -1
  116. package/lib/store/accounts.d.ts +110 -0
  117. package/lib/store/accounts.d.ts.map +1 -0
  118. package/lib/store/accounts.js +352 -0
  119. package/lib/store/accounts.js.map +1 -0
  120. package/lib/store/atomic-file.d.ts +16 -0
  121. package/lib/store/atomic-file.d.ts.map +1 -0
  122. package/lib/store/atomic-file.js +34 -0
  123. package/lib/store/atomic-file.js.map +1 -0
  124. package/lib/store/futures-repo.d.ts +8 -49
  125. package/lib/store/futures-repo.d.ts.map +1 -1
  126. package/lib/store/futures-repo.js +34 -246
  127. package/lib/store/futures-repo.js.map +1 -1
  128. package/lib/store/ledger-repo-base.d.ts +120 -0
  129. package/lib/store/ledger-repo-base.d.ts.map +1 -0
  130. package/lib/store/ledger-repo-base.js +275 -0
  131. package/lib/store/ledger-repo-base.js.map +1 -0
  132. package/lib/store/notes.d.ts +29 -0
  133. package/lib/store/notes.d.ts.map +1 -0
  134. package/lib/store/notes.js +78 -0
  135. package/lib/store/notes.js.map +1 -0
  136. package/lib/store/paths.d.ts +2 -0
  137. package/lib/store/paths.d.ts.map +1 -1
  138. package/lib/store/paths.js +4 -0
  139. package/lib/store/paths.js.map +1 -1
  140. package/lib/store/repo.d.ts +15 -55
  141. package/lib/store/repo.d.ts.map +1 -1
  142. package/lib/store/repo.js +41 -206
  143. package/lib/store/repo.js.map +1 -1
  144. package/lib/store/shortlist.d.ts.map +1 -1
  145. package/lib/store/shortlist.js +4 -6
  146. package/lib/store/shortlist.js.map +1 -1
  147. package/lib/store/snapshots.d.ts +0 -3
  148. package/lib/store/snapshots.d.ts.map +1 -1
  149. package/lib/store/snapshots.js +0 -3
  150. package/lib/store/snapshots.js.map +1 -1
  151. package/package.json +1 -1
  152. package/src/agent/account-tools.ts +136 -0
  153. package/src/agent/futures-tools.ts +1 -6
  154. package/src/agent/ledger-tools.ts +29 -16
  155. package/src/agent/tool-result.ts +27 -0
  156. package/src/agent/tools.ts +30 -10
  157. package/src/client/entry.js +14 -0
  158. package/src/client/parts/10-core.js +535 -0
  159. package/src/client/parts/20-styles.js +336 -0
  160. package/src/client/parts/30-atoms.js +769 -0
  161. package/src/client/parts/35-hooks.js +447 -0
  162. package/src/client/parts/40-stock-tabs.js +641 -0
  163. package/src/client/parts/50-futures.js +911 -0
  164. package/src/client/parts/60-shell.js +706 -0
  165. package/src/client/parts/70-plugin.js +67 -0
  166. package/src/contract/accounts.ts +82 -0
  167. package/src/contract/common.ts +173 -0
  168. package/src/contract/domain.ts +217 -0
  169. package/src/contract/errors.ts +34 -0
  170. package/src/contract/index.ts +15 -0
  171. package/src/contract/ledger.ts +42 -0
  172. package/src/contract/market.ts +39 -0
  173. package/src/contract/rpc.ts +15 -0
  174. package/src/contract.ts +6 -472
  175. package/src/core/session.ts +1 -2
  176. package/src/data/cached-market-data.ts +193 -0
  177. package/src/data/futures-market-data.ts +9 -10
  178. package/src/index.ts +168 -20
  179. package/src/service/account-moves.ts +72 -0
  180. package/src/service/accounts-rpc.ts +80 -0
  181. package/src/service/compare-rpc.ts +77 -0
  182. package/src/service/errors.ts +23 -4
  183. package/src/service/futures-rpc.ts +7 -24
  184. package/src/service/futures-service.ts +161 -159
  185. package/src/service/ledger-admin.ts +140 -0
  186. package/src/service/paper-service.ts +183 -153
  187. package/src/service/route.ts +5 -2
  188. package/src/service/rpc-support.ts +61 -0
  189. package/src/service/rpc.ts +59 -23
  190. package/src/store/accounts.ts +373 -0
  191. package/src/store/atomic-file.ts +37 -0
  192. package/src/store/futures-repo.ts +35 -260
  193. package/src/store/ledger-repo-base.ts +337 -0
  194. package/src/store/notes.ts +86 -0
  195. package/src/store/paths.ts +5 -0
  196. package/src/store/repo.ts +47 -229
  197. package/src/store/shortlist.ts +3 -5
  198. package/src/store/snapshots.ts +0 -3
  199. package/src/client/index.js +0 -3275
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Shared RPC scaffolding for every handler mounted on the paper-trading route.
3
+ *
4
+ * The stock, accounts, compare and futures handlers parse the same envelope and
5
+ * answer with the same `{ ok, value | error }` shape; only the domain error
6
+ * class differs. Keeping the guards here means one place decides what a
7
+ * malformed payload looks like, instead of four drifting copies.
8
+ * @module @dsh-ft/dsh-fft-paper-trading/service/rpc-support
9
+ */
10
+
11
+ import type { RpcResult } from '../contract.js'
12
+
13
+ /** Success envelope. */
14
+ export const ok = <T>(value: T): RpcResult<T> => ({ ok: true, value })
15
+
16
+ /** Failure envelope with an explicit code (argument or routing problem). */
17
+ export const fail = (code: string, message: string): RpcResult<never> => ({
18
+ ok: false,
19
+ error: { code, message },
20
+ })
21
+
22
+ /**
23
+ * Turn a thrown error into a failure envelope: domain errors keep their code,
24
+ * anything else becomes INTERNAL with the original message.
25
+ */
26
+ export function failure(error: unknown, isDomain: (error: unknown) => boolean): RpcResult<never> {
27
+ if (isDomain(error)) {
28
+ const domain = error as { code: string; message: string }
29
+ return fail(domain.code, domain.message)
30
+ }
31
+ return fail('INTERNAL', error instanceof Error ? error.message : String(error))
32
+ }
33
+
34
+ /** Creates the domain error a guard should throw; the handler owns the class. */
35
+ export type ArgumentErrorFactory = (message: string) => Error
36
+
37
+ /**
38
+ * Payload guards. `record` rejects non-objects; `allowEmpty` also accepts
39
+ * `undefined`/`null` as an empty object (the futures handler's historical
40
+ * contract for read endpoints).
41
+ */
42
+ export function argumentGuards(makeError: ArgumentErrorFactory) {
43
+ return {
44
+ record(value: unknown, options: { allowEmpty?: boolean } = {}): Record<string, unknown> {
45
+ if (value === undefined || value === null) {
46
+ if (options.allowEmpty === true) return {}
47
+ throw makeError('请求参数必须是对象')
48
+ }
49
+ if (typeof value !== 'object') throw makeError('请求参数必须是对象')
50
+ return value as Record<string, unknown>
51
+ },
52
+ text(value: unknown, field: string): string {
53
+ if (typeof value !== 'string' || value.trim() === '') throw makeError(`缺少 ${field}`)
54
+ return value.trim()
55
+ },
56
+ num(value: unknown, field: string): number {
57
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw makeError(`${field} 必须是数字`)
58
+ return value
59
+ },
60
+ }
61
+ }
@@ -1,28 +1,50 @@
1
- import type { BasketOrderInput, DataSourceStatus, OrderDraft, RpcResult, Side } from '../contract.js'
1
+ import type { AccountMeta, BasketOrderInput, DataSourceStatus, NoteView, OrderDraft, RpcResult, Side } from '../contract.js'
2
2
  import type { PaperService } from './paper-service.js'
3
3
  import { PaperError } from './errors.js'
4
+ import { argumentGuards, fail, failure, ok } from './rpc-support.js'
4
5
 
5
6
  export type PaperRpcHandler = (
6
7
  endpoint: string,
7
8
  payload: unknown,
8
9
  signal: AbortSignal,
10
+ /** Target account id or name; omitted means the kind's default account. */
11
+ account?: string,
9
12
  ) => Promise<RpcResult<unknown>>
10
13
 
11
- function record(value: unknown): Record<string, unknown> {
12
- if (typeof value !== 'object' || value === null) throw new PaperError('INVALID_ARGUMENT', '请求参数必须是对象')
13
- return value as Record<string, unknown>
14
+ /** One resolved account: the service plus the registry entry that guards it. */
15
+ export interface PaperRpcTarget {
16
+ service: PaperService
17
+ meta?: AccountMeta
14
18
  }
15
19
 
16
- function text(value: unknown, field: string): string {
17
- if (typeof value !== 'string' || value.trim() === '') throw new PaperError('INVALID_ARGUMENT', `缺少 ${field}`)
18
- return value.trim()
19
- }
20
+ /** Resolve an account reference to its service. Omitted reference = default. */
21
+ export type PaperRpcResolver = (account?: string) => Promise<PaperRpcTarget>
20
22
 
21
- function num(value: unknown, field: string): number {
22
- if (typeof value !== 'number' || !Number.isFinite(value)) throw new PaperError('INVALID_ARGUMENT', `${field} 必须是数字`)
23
- return value
23
+ /**
24
+ * Endpoints that change account state. A locked account may still be read,
25
+ * cancelled out of, and exported — that is how a frozen account stays
26
+ * inspectable while it cannot trade.
27
+ */
28
+ const MUTATING_ENDPOINTS: ReadonlySet<string> = new Set([
29
+ 'account/reset',
30
+ 'account/deposit',
31
+ 'account/withdraw',
32
+ 'ledger/restore',
33
+ 'order/place',
34
+ 'basket/place',
35
+ ])
36
+
37
+ /** Refuse a state change on a locked account before the service sees it. */
38
+ function guardAccount(meta: AccountMeta | undefined, endpoint: string): void {
39
+ if (meta === undefined || !MUTATING_ENDPOINTS.has(endpoint)) return
40
+ if (meta.locked === true) throw new PaperError('ACCOUNT_LOCKED', `账户「${meta.name}」已锁定,不能交易`)
24
41
  }
25
42
 
43
+ const guard = argumentGuards(message => new PaperError('INVALID_ARGUMENT', message))
44
+ const record = guard.record
45
+ const text = guard.text
46
+ const num = guard.num
47
+
26
48
  function draft(value: unknown): OrderDraft {
27
49
  const input = record(value)
28
50
  const side = text(input.side, 'side')
@@ -99,12 +121,24 @@ function period(value: unknown): '7d' | '30d' | 'all' {
99
121
  export interface PaperRpcOptions {
100
122
  /** Read-only data-source state for the panel header; absent means no service. */
101
123
  dataSource?: () => Promise<DataSourceStatus>
124
+ /**
125
+ * Per-account free-form notes. The handler only proxies them: no tool reaches
126
+ * this, it is the human's own space.
127
+ */
128
+ notes?: {
129
+ read: (accountId: string) => Promise<NoteView>
130
+ write: (accountId: string, text: unknown) => Promise<NoteView>
131
+ }
102
132
  }
103
133
 
104
- export function createPaperRpcHandler(service: PaperService, options: PaperRpcOptions = {}): PaperRpcHandler {
105
- return async (endpoint, payload, signal) => {
134
+ export function createPaperRpcHandler(source: PaperService | PaperRpcResolver, options: PaperRpcOptions = {}): PaperRpcHandler {
135
+ // A bare service keeps every pre-multi-account caller (and test) working.
136
+ const resolve: PaperRpcResolver = typeof source === 'function' ? source : async () => ({ service: source })
137
+ return async (endpoint, payload, signal, account) => {
106
138
  try {
107
- if (signal.aborted) throw new PaperError('INVALID_ARGUMENT', '请求已取消', 499)
139
+ if (signal.aborted) throw new PaperError('INVALID_ARGUMENT', '请求已取消')
140
+ const { service, meta } = await resolve(account)
141
+ guardAccount(meta, endpoint)
108
142
  switch (endpoint) {
109
143
  case 'health':
110
144
  return ok({ ok: true, version: 1 })
@@ -131,6 +165,15 @@ export function createPaperRpcHandler(service: PaperService, options: PaperRpcOp
131
165
  }
132
166
  case 'ledger/backup':
133
167
  return ok({ backedUp: await service.backupLedger() })
168
+ case 'note/get': {
169
+ if (options.notes === undefined || meta === undefined) throw new PaperError('INTERNAL', '笔记存储不可用')
170
+ return ok(await options.notes.read(meta.id))
171
+ }
172
+ case 'note/set': {
173
+ if (options.notes === undefined || meta === undefined) throw new PaperError('INTERNAL', '笔记存储不可用')
174
+ const input = record(payload ?? {})
175
+ return ok(await options.notes.write(meta.id, input.text))
176
+ }
134
177
  case 'settings/get':
135
178
  return ok(await service.settingsView())
136
179
  case 'market/quote': {
@@ -210,17 +253,10 @@ export function createPaperRpcHandler(service: PaperService, options: PaperRpcOp
210
253
  return ok(await service.review(period(input.period)))
211
254
  }
212
255
  default:
213
- throw new PaperError('INVALID_ARGUMENT', `未知 endpoint: ${endpoint}`, 404)
256
+ throw new PaperError('INVALID_ARGUMENT', `未知 endpoint: ${endpoint}`)
214
257
  }
215
258
  } catch (error) {
216
- if (error instanceof PaperError) {
217
- return { ok: false, error: { code: error.code, message: error.message } }
218
- }
219
- return { ok: false, error: { code: 'INTERNAL', message: error instanceof Error ? error.message : String(error) } }
259
+ return failure(error, item => item instanceof PaperError)
220
260
  }
221
261
  }
222
262
  }
223
-
224
- function ok(value: unknown): RpcResult<unknown> {
225
- return { ok: true, value }
226
- }
@@ -0,0 +1,373 @@
1
+ /**
2
+ * Registry of paper-trading accounts.
3
+ *
4
+ * One JSON file next to the ledgers (`$DSH_HOME/paper-trading/accounts.json`)
5
+ * owns the account list. Ledgers stay where they are: an account is just a
6
+ * directory name, so the registry never rewrites trading data and an old
7
+ * installation needs no migration.
8
+ *
9
+ * The registry deliberately knows nothing about sessions, models or owners —
10
+ * this plugin provides ledgers and tools, and every caller addresses an account
11
+ * by id or display name. Display names may repeat; `id` is the reliable handle.
12
+ *
13
+ * The file is rewritten atomically (temp file + rename) and every mutation goes
14
+ * through one Promise queue, mirroring {@link AccountRepo}'s single-writer rule.
15
+ * @module @dsh-ft/dsh-fft-paper-trading/store/accounts
16
+ */
17
+
18
+ import { mkdir, readdir, readFile, stat } from 'node:fs/promises'
19
+ import { join } from 'node:path'
20
+ import type { AccountKind, AccountMeta, AccountsView } from '../contract.js'
21
+ import { DEFAULT_ACCOUNT_ID, DEFAULT_SETTINGS } from '../contract.js'
22
+ import { FUTURES_ACCOUNT_ID } from '../futures-contract.js'
23
+ import { PaperError } from '../service/errors.js'
24
+ import { paperRoot } from './paths.js'
25
+ import { writeFileAtomic } from './atomic-file.js'
26
+
27
+ const REGISTRY_FILE = 'accounts.json'
28
+ const REGISTRY_VERSION = 4
29
+ /** Keeps one host's tick loop and the panel's account picker bounded. */
30
+ export const MAX_ACCOUNTS_PER_KIND = 20
31
+ export const ACCOUNT_NAME_MAX = 16
32
+ export const DEFAULT_TICK_MS = 5_000
33
+ const MIN_TICK_MS = 1_000
34
+ const MAX_TICK_MS = 300_000
35
+
36
+ /** On-disk shape. Unknown fields are ignored; a broken file must not block trading. */
37
+ interface AccountsFile {
38
+ version: number
39
+ updatedAt: string
40
+ tickMs: number
41
+ accounts: AccountMeta[]
42
+ }
43
+
44
+ export interface AccountRegistryOptions {
45
+ home: string
46
+ now?: () => Date
47
+ logger?: { warn(message: string): void }
48
+ /** Limits used only by tests. */
49
+ limits?: { maxPerKind?: number; tickMs?: { min?: number; max?: number } }
50
+ }
51
+
52
+ export class AccountRegistry {
53
+ private state: AccountsFile | undefined
54
+ private loading: Promise<AccountsFile> | undefined
55
+ private queue: Promise<unknown> = Promise.resolve()
56
+ private readonly now: () => Date
57
+ private readonly file: string
58
+ private readonly root: string
59
+
60
+ constructor(private readonly options: AccountRegistryOptions) {
61
+ this.now = options.now ?? (() => new Date())
62
+ this.root = paperRoot(options.home)
63
+ this.file = join(this.root, REGISTRY_FILE)
64
+ }
65
+
66
+ /** Absolute path of the registry file, for diagnostics and export. */
67
+ get filePath(): string {
68
+ return this.file
69
+ }
70
+
71
+ /** Load (once) and return the live view. */
72
+ private async ready(): Promise<AccountsFile> {
73
+ if (this.state !== undefined) return this.state
74
+ if (this.loading === undefined) {
75
+ this.loading = this.load().catch(error => {
76
+ // A transient read failure must not poison the instance for the rest
77
+ // of the session: drop the cached promise so the next call retries.
78
+ this.loading = undefined
79
+ throw error
80
+ })
81
+ }
82
+ return this.loading
83
+ }
84
+
85
+ private async load(): Promise<AccountsFile> {
86
+ let parsed: unknown
87
+ let readable = true
88
+ try {
89
+ parsed = JSON.parse(await readFile(this.file, 'utf8'))
90
+ } catch (error) {
91
+ const code = (error as NodeJS.ErrnoException).code
92
+ if (code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error
93
+ if (error instanceof SyntaxError) this.options.logger?.warn(`paper-trading: ignoring unreadable ${REGISTRY_FILE}`)
94
+ parsed = undefined
95
+ readable = code === 'ENOENT'
96
+ }
97
+ const state = this.normalise(parsed)
98
+ const discovered = await this.discover(state)
99
+ if (discovered) state.updatedAt = this.now().toISOString()
100
+ const changed = !readable || discovered || (parsed as AccountsFile | undefined)?.version !== REGISTRY_VERSION
101
+ if (changed) await this.save(state)
102
+ this.state = state
103
+ return state
104
+ }
105
+
106
+ /** Merge a persisted file over the defaults; never trust its shape. */
107
+ private normalise(persisted: unknown): AccountsFile {
108
+ const input = (typeof persisted === 'object' && persisted !== null ? persisted : {}) as Partial<AccountsFile>
109
+ const accounts: AccountMeta[] = []
110
+ for (const raw of Array.isArray(input.accounts) ? input.accounts : []) {
111
+ const meta = normaliseMeta(raw)
112
+ if (meta !== undefined && !accounts.some(item => item.id === meta.id)) accounts.push(meta)
113
+ }
114
+ for (const [id, name, kind] of [
115
+ [DEFAULT_ACCOUNT_ID, '默认账户', 'stock'],
116
+ [FUTURES_ACCOUNT_ID, '期货账户', 'futures'],
117
+ ] as const) {
118
+ if (!accounts.some(item => item.id === id)) {
119
+ accounts.push({ id, kind, name, createdAt: this.now().toISOString(), archived: false, locked: false })
120
+ }
121
+ }
122
+ return {
123
+ version: REGISTRY_VERSION,
124
+ updatedAt: typeof input.updatedAt === 'string' ? input.updatedAt : this.now().toISOString(),
125
+ tickMs: clampInt(input.tickMs, this.options.limits?.tickMs?.min ?? MIN_TICK_MS, this.options.limits?.tickMs?.max ?? MAX_TICK_MS, DEFAULT_TICK_MS),
126
+ accounts,
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Register ledger directories the file does not know about: an old install
132
+ * predates the registry, and a hand-made account directory should not vanish.
133
+ */
134
+ private async discover(state: AccountsFile): Promise<boolean> {
135
+ let entries: string[]
136
+ try {
137
+ entries = await readdir(this.root)
138
+ } catch {
139
+ return false
140
+ }
141
+ let changed = false
142
+ for (const entry of entries) {
143
+ if (entry === 'accounts.json' || entry === 'shortlist.json' || entry === 'backups') continue
144
+ if (state.accounts.some(item => item.id === entry)) {
145
+ const known = state.accounts.find(item => item.id === entry) as AccountMeta
146
+ if (known.missing === true) {
147
+ known.missing = false
148
+ changed = true
149
+ }
150
+ continue
151
+ }
152
+ try {
153
+ await stat(join(this.root, entry, 'events.jsonl'))
154
+ } catch {
155
+ continue
156
+ }
157
+ const kind: AccountKind = entry === FUTURES_ACCOUNT_ID ? 'futures' : 'stock'
158
+ state.accounts.push({ id: entry, kind, name: entry, createdAt: this.now().toISOString(), archived: false, locked: false })
159
+ changed = true
160
+ }
161
+ for (const meta of state.accounts) {
162
+ if (meta.id === DEFAULT_ACCOUNT_ID || meta.id === FUTURES_ACCOUNT_ID) continue
163
+ try {
164
+ await stat(join(this.root, meta.id))
165
+ } catch {
166
+ if (meta.missing !== true) {
167
+ meta.missing = true
168
+ changed = true
169
+ }
170
+ }
171
+ }
172
+ return changed
173
+ }
174
+
175
+ private async save(state: AccountsFile): Promise<void> {
176
+ await writeFileAtomic(this.file, `${JSON.stringify({ ...state, version: REGISTRY_VERSION }, null, 2)}\n`)
177
+ }
178
+
179
+ /** Serialise mutations the same way the ledger serialises appends. */
180
+ private enqueue<T>(task: () => Promise<T>): Promise<T> {
181
+ const next = this.queue.then(task)
182
+ this.queue = next.catch(() => undefined)
183
+ return next
184
+ }
185
+
186
+ private async mutate(task: (state: AccountsFile) => void): Promise<void> {
187
+ await this.enqueue(async () => {
188
+ const state = await this.ready()
189
+ task(state)
190
+ state.updatedAt = this.now().toISOString()
191
+ await this.save(state)
192
+ })
193
+ }
194
+
195
+ /**
196
+ * `includeArchived` keeps the picker clean but lets tooling (and the panel's
197
+ * "已归档" section) see everything; `kind` lets the stock panel ask for its
198
+ * plane without filtering client-side.
199
+ */
200
+ async view(options: { includeArchived?: boolean; kind?: AccountKind } = {}): Promise<AccountsView> {
201
+ const state = await this.ready()
202
+ let accounts = options.includeArchived === true ? state.accounts : state.accounts.filter(item => item.archived !== true)
203
+ if (options.kind !== undefined) accounts = accounts.filter(item => item.kind === options.kind)
204
+ return {
205
+ accounts: accounts.map(meta => ({ ...meta })),
206
+ defaultIds: { stock: DEFAULT_ACCOUNT_ID, futures: FUTURES_ACCOUNT_ID },
207
+ tickMs: state.tickMs,
208
+ }
209
+ }
210
+
211
+ /** Post-load lock flag; the service guard must not go stale on a copy. */
212
+ lockedSync(id: string): boolean {
213
+ return this.state?.accounts.some(item => item.id === id && item.locked === true) ?? false
214
+ }
215
+
216
+ /** Archived accounts are frozen like locked ones; the service asks this first. */
217
+ archivedSync(id: string): boolean {
218
+ return this.state?.accounts.some(item => item.id === id && item.archived === true) ?? false
219
+ }
220
+
221
+ async tickMs(): Promise<number> {
222
+ return (await this.ready()).tickMs
223
+ }
224
+
225
+ /**
226
+ * Resolve an account reference to its metadata.
227
+ *
228
+ * `undefined` means "the kind's default account", which keeps every caller
229
+ * that predates multi-account working unchanged. An id always wins; a name
230
+ * may be ambiguous because names are not unique, and ambiguity is an error
231
+ * rather than a guess.
232
+ */
233
+ async resolve(reference: string | undefined, kind: AccountKind = 'stock'): Promise<AccountMeta> {
234
+ const state = await this.ready()
235
+ if (reference === undefined) return this.requireDefault(state, kind)
236
+ if (reference.trim() === '') throw new PaperError('INVALID_ARGUMENT', '账户名不能为空')
237
+ const byId = state.accounts.find(item => item.id === reference)
238
+ if (byId !== undefined) return byId
239
+ const byName = state.accounts.filter(item => item.kind === kind && item.name === reference)
240
+ if (byName.length === 1) return byName[0] as AccountMeta
241
+ if (byName.length > 1) {
242
+ throw new PaperError('INVALID_ARGUMENT', `账户名「${reference}」不唯一,请改用账户 id:${byName.map(item => item.id).join('、')}`)
243
+ }
244
+ throw new PaperError('ACCOUNT_NOT_FOUND', `没有名为「${reference}」的账户`)
245
+ }
246
+
247
+ private requireDefault(state: AccountsFile, kind: AccountKind): AccountMeta {
248
+ const id = kind === 'futures' ? FUTURES_ACCOUNT_ID : DEFAULT_ACCOUNT_ID
249
+ const meta = state.accounts.find(item => item.id === id)
250
+ if (meta === undefined) throw new PaperError('ACCOUNT_NOT_FOUND', `默认账户 ${id} 不存在`)
251
+ return meta
252
+ }
253
+
254
+ async create(input: { name: string; kind?: AccountKind; initialCashCents?: number }): Promise<AccountMeta> {
255
+ const kind = input.kind ?? 'stock'
256
+ const name = validateName(input.name)
257
+ let created: AccountMeta | undefined
258
+ await this.mutate(state => {
259
+ const live = state.accounts.filter(item => item.kind === kind)
260
+ const limit = this.options.limits?.maxPerKind ?? MAX_ACCOUNTS_PER_KIND
261
+ if (live.length >= limit) throw new PaperError('ACCOUNT_LIMIT', `账户数量已达上限 ${limit}`)
262
+ created = {
263
+ id: this.nextId(state),
264
+ kind,
265
+ name,
266
+ createdAt: this.now().toISOString(),
267
+ archived: false,
268
+ locked: false,
269
+ ...(input.initialCashCents !== undefined ? { initialCashCents: Math.round(input.initialCashCents) } : {}),
270
+ }
271
+ state.accounts.push(created)
272
+ })
273
+ // Materialise the directory now: a registered account without a directory
274
+ // would look "missing" until its ledger is first opened.
275
+ await mkdir(join(this.root, (created as AccountMeta).id), { recursive: true })
276
+ return { ...(created as AccountMeta) }
277
+ }
278
+
279
+ private nextId(state: AccountsFile): string {
280
+ for (let attempt = 0; attempt < 50; attempt += 1) {
281
+ const id = `acc-${Math.random().toString(36).slice(2, 8)}`
282
+ if (!state.accounts.some(item => item.id === id)) return id
283
+ }
284
+ return `acc-${this.now().getTime().toString(36)}`
285
+ }
286
+
287
+ /** Change the display name only; the directory id never moves. */
288
+ async rename(reference: string, name: string): Promise<AccountMeta> {
289
+ const target = await this.resolve(reference)
290
+ if (target.id === FUTURES_ACCOUNT_ID) {
291
+ // The futures plane has a fixed panel and never reads the registry name,
292
+ // so renaming it would only create misleading metadata.
293
+ throw new PaperError('INVALID_ARGUMENT', '期货账户名称固定,不可改名')
294
+ }
295
+ const next = validateName(name)
296
+ await this.mutate(state => {
297
+ const meta = state.accounts.find(item => item.id === target.id) as AccountMeta
298
+ meta.name = next
299
+ })
300
+ return { ...((await this.resolve(target.id)) as AccountMeta) }
301
+ }
302
+
303
+ /** Flip a boolean flag on one account; used by archive/lock and their inverses. */
304
+ private async setFlag(reference: string, patch: Partial<Pick<AccountMeta, 'archived' | 'locked'>>): Promise<AccountMeta> {
305
+ const target = await this.resolve(reference)
306
+ if (patch.archived === true && (target.id === DEFAULT_ACCOUNT_ID || target.id === FUTURES_ACCOUNT_ID)) {
307
+ // Archiving the default would leave the panel without a picker entry that
308
+ // can never be selected back; the default account stays available.
309
+ throw new PaperError('INVALID_ARGUMENT', `默认账户不能归档(${target.name})`)
310
+ }
311
+ await this.mutate(state => {
312
+ const meta = state.accounts.find(item => item.id === target.id) as AccountMeta
313
+ Object.assign(meta, patch)
314
+ })
315
+ return { ...((await this.resolve(target.id)) as AccountMeta) }
316
+ }
317
+
318
+ archive(reference: string): Promise<AccountMeta> {
319
+ return this.setFlag(reference, { archived: true })
320
+ }
321
+
322
+ unarchive(reference: string): Promise<AccountMeta> {
323
+ return this.setFlag(reference, { archived: false })
324
+ }
325
+
326
+ lock(reference: string): Promise<AccountMeta> {
327
+ return this.setFlag(reference, { locked: true })
328
+ }
329
+
330
+ unlock(reference: string): Promise<AccountMeta> {
331
+ return this.setFlag(reference, { locked: false })
332
+ }
333
+ }
334
+
335
+ /** Trim and reject empty or over-long display names. Duplicates are allowed. */
336
+ function validateName(value: unknown): string {
337
+ if (typeof value !== 'string') throw new PaperError('INVALID_ARGUMENT', '账户名必须是字符串')
338
+ const name = value.trim()
339
+ if (name === '') throw new PaperError('INVALID_ARGUMENT', '账户名不能为空')
340
+ if ([...name].length > ACCOUNT_NAME_MAX) throw new PaperError('INVALID_ARGUMENT', `账户名不能超过 ${ACCOUNT_NAME_MAX} 个字符`)
341
+ return name
342
+ }
343
+
344
+ /** v1 wrote `archived` + bindings, v2 added the note, v3 dropped it, v4 renames `hidden` back to `archived`. */
345
+ function normaliseMeta(raw: unknown): AccountMeta | undefined {
346
+ if (typeof raw !== 'object' || raw === null) return undefined
347
+ const input = raw as Partial<AccountMeta> & { archived?: unknown; hidden?: unknown }
348
+ if (typeof input.id !== 'string' || input.id === '') return undefined
349
+ const kind: AccountKind = input.kind === 'futures' ? 'futures' : 'stock'
350
+ const name = typeof input.name === 'string' && input.name.trim() !== '' ? input.name.trim().slice(0, ACCOUNT_NAME_MAX) : input.id
351
+ return {
352
+ id: input.id,
353
+ kind,
354
+ name,
355
+ createdAt: typeof input.createdAt === 'string' ? input.createdAt : new Date(0).toISOString(),
356
+ // v3 wrote `hidden`, v1 wrote `archived`; both mean archived now.
357
+ archived: input.archived === true || input.hidden === true,
358
+ locked: input.locked === true,
359
+ ...(typeof input.initialCashCents === 'number' && Number.isFinite(input.initialCashCents) && input.initialCashCents > 0
360
+ ? { initialCashCents: Math.round(input.initialCashCents) }
361
+ : {}),
362
+ ...(input.missing === true ? { missing: true } : {}),
363
+ }
364
+ }
365
+
366
+ function clampInt(value: unknown, min: number, max: number, fallback: number): number {
367
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
368
+ return Math.min(max, Math.max(min, Math.round(value)))
369
+ }
370
+
371
+ /** Default starting cash for a brand-new account when the caller names no amount. */
372
+
373
+ export type { AccountsFile }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Atomic whole-file write shared by the small JSON files beside the ledgers.
3
+ *
4
+ * The event log has its own append/fsync path; the registry, the notes file,
5
+ * the shortlist and the futures contract cache are written whole. They all need
6
+ * the same guarantee — a crash leaves either the old or the new file, never a
7
+ * half-written one — and the same unique temp name, so two writers can never
8
+ * clobber each other's staging file.
9
+ * @module @dsh-ft/dsh-fft-paper-trading/store/atomic-file
10
+ */
11
+
12
+ import { randomUUID } from 'node:crypto'
13
+ import { mkdir, open, rename, unlink } from 'node:fs/promises'
14
+ import { dirname } from 'node:path'
15
+
16
+ export interface AtomicWriteOptions {
17
+ mode?: number
18
+ }
19
+
20
+ /** Write `content` to `file` via a fsynced sibling temp file and a rename. */
21
+ export async function writeFileAtomic(file: string, content: string, options: AtomicWriteOptions = {}): Promise<void> {
22
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 })
23
+ const temp = `${file}.tmp-${process.pid}-${randomUUID()}`
24
+ try {
25
+ const handle = await open(temp, 'w', options.mode ?? 0o600)
26
+ try {
27
+ await handle.writeFile(content, 'utf8')
28
+ await handle.sync()
29
+ } finally {
30
+ await handle.close()
31
+ }
32
+ await rename(temp, file)
33
+ } catch (error) {
34
+ await unlink(temp).catch(() => undefined)
35
+ throw error
36
+ }
37
+ }