@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.
- package/README.md +4 -3
- package/README.zh.md +4 -3
- package/lib/agent/account-tools.d.ts +18 -0
- package/lib/agent/account-tools.d.ts.map +1 -0
- package/lib/agent/account-tools.js +127 -0
- package/lib/agent/account-tools.js.map +1 -0
- package/lib/agent/futures-tools.d.ts.map +1 -1
- package/lib/agent/futures-tools.js +1 -6
- package/lib/agent/futures-tools.js.map +1 -1
- package/lib/agent/ledger-tools.d.ts +15 -3
- package/lib/agent/ledger-tools.d.ts.map +1 -1
- package/lib/agent/ledger-tools.js +11 -15
- package/lib/agent/ledger-tools.js.map +1 -1
- package/lib/agent/tool-result.d.ts +19 -0
- package/lib/agent/tool-result.d.ts.map +1 -0
- package/lib/agent/tool-result.js +22 -0
- package/lib/agent/tool-result.js.map +1 -0
- package/lib/agent/tools.d.ts +10 -2
- package/lib/agent/tools.d.ts.map +1 -1
- package/lib/agent/tools.js +26 -11
- package/lib/agent/tools.js.map +1 -1
- package/lib/client.js +1448 -282
- package/lib/contract/accounts.d.ts +76 -0
- package/lib/contract/accounts.d.ts.map +1 -0
- package/lib/contract/accounts.js +6 -0
- package/lib/contract/accounts.js.map +1 -0
- package/lib/contract/common.d.ts +144 -0
- package/lib/contract/common.d.ts.map +1 -0
- package/lib/contract/common.js +33 -0
- package/lib/contract/common.js.map +1 -0
- package/lib/contract/domain.d.ts +196 -0
- package/lib/contract/domain.d.ts.map +1 -0
- package/lib/contract/domain.js +14 -0
- package/lib/contract/domain.js.map +1 -0
- package/lib/contract/errors.d.ts +6 -0
- package/lib/contract/errors.d.ts.map +1 -0
- package/lib/contract/errors.js +6 -0
- package/lib/contract/errors.js.map +1 -0
- package/lib/contract/index.d.ts +15 -0
- package/lib/contract/index.d.ts.map +1 -0
- package/lib/contract/index.js +15 -0
- package/lib/contract/index.js.map +1 -0
- package/lib/contract/ledger.d.ts +40 -0
- package/lib/contract/ledger.d.ts.map +1 -0
- package/lib/contract/ledger.js +6 -0
- package/lib/contract/ledger.js.map +1 -0
- package/lib/contract/market.d.ts +30 -0
- package/lib/contract/market.d.ts.map +1 -0
- package/lib/contract/market.js +6 -0
- package/lib/contract/market.js.map +1 -0
- package/lib/contract/rpc.d.ts +24 -0
- package/lib/contract/rpc.d.ts.map +1 -0
- package/lib/contract/rpc.js +6 -0
- package/lib/contract/rpc.js.map +1 -0
- package/lib/contract.d.ts +6 -403
- package/lib/contract.d.ts.map +1 -1
- package/lib/contract.js +6 -24
- package/lib/contract.js.map +1 -1
- package/lib/core/session.d.ts +1 -1
- package/lib/core/session.d.ts.map +1 -1
- package/lib/core/session.js +1 -2
- package/lib/core/session.js.map +1 -1
- package/lib/data/cached-market-data.d.ts +61 -0
- package/lib/data/cached-market-data.d.ts.map +1 -0
- package/lib/data/cached-market-data.js +174 -0
- package/lib/data/cached-market-data.js.map +1 -0
- package/lib/data/futures-market-data.d.ts.map +1 -1
- package/lib/data/futures-market-data.js +9 -10
- package/lib/data/futures-market-data.js.map +1 -1
- package/lib/index.d.ts +25 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +156 -18
- package/lib/index.js.map +1 -1
- package/lib/service/account-moves.d.ts +64 -0
- package/lib/service/account-moves.d.ts.map +1 -0
- package/lib/service/account-moves.js +49 -0
- package/lib/service/account-moves.js.map +1 -0
- package/lib/service/accounts-rpc.d.ts +17 -0
- package/lib/service/accounts-rpc.d.ts.map +1 -0
- package/lib/service/accounts-rpc.js +77 -0
- package/lib/service/accounts-rpc.js.map +1 -0
- package/lib/service/compare-rpc.d.ts +22 -0
- package/lib/service/compare-rpc.d.ts.map +1 -0
- package/lib/service/compare-rpc.js +70 -0
- package/lib/service/compare-rpc.js.map +1 -0
- package/lib/service/errors.d.ts +20 -4
- package/lib/service/errors.d.ts.map +1 -1
- package/lib/service/errors.js +12 -5
- package/lib/service/errors.js.map +1 -1
- package/lib/service/futures-rpc.d.ts.map +1 -1
- package/lib/service/futures-rpc.js +7 -25
- package/lib/service/futures-rpc.js.map +1 -1
- package/lib/service/futures-service.d.ts +28 -8
- package/lib/service/futures-service.d.ts.map +1 -1
- package/lib/service/futures-service.js +144 -146
- package/lib/service/futures-service.js.map +1 -1
- package/lib/service/ledger-admin.d.ts +67 -0
- package/lib/service/ledger-admin.d.ts.map +1 -0
- package/lib/service/ledger-admin.js +102 -0
- package/lib/service/ledger-admin.js.map +1 -0
- package/lib/service/paper-service.d.ts +39 -12
- package/lib/service/paper-service.d.ts.map +1 -1
- package/lib/service/paper-service.js +177 -156
- package/lib/service/paper-service.js.map +1 -1
- package/lib/service/route.d.ts.map +1 -1
- package/lib/service/route.js +5 -2
- package/lib/service/route.js.map +1 -1
- package/lib/service/rpc-support.d.ts +34 -0
- package/lib/service/rpc-support.d.ts.map +1 -0
- package/lib/service/rpc-support.js +57 -0
- package/lib/service/rpc-support.js.map +1 -0
- package/lib/service/rpc.d.ts +20 -3
- package/lib/service/rpc.d.ts.map +1 -1
- package/lib/service/rpc.js +44 -25
- package/lib/service/rpc.js.map +1 -1
- package/lib/store/accounts.d.ts +110 -0
- package/lib/store/accounts.d.ts.map +1 -0
- package/lib/store/accounts.js +352 -0
- package/lib/store/accounts.js.map +1 -0
- package/lib/store/atomic-file.d.ts +16 -0
- package/lib/store/atomic-file.d.ts.map +1 -0
- package/lib/store/atomic-file.js +34 -0
- package/lib/store/atomic-file.js.map +1 -0
- package/lib/store/futures-repo.d.ts +8 -49
- package/lib/store/futures-repo.d.ts.map +1 -1
- package/lib/store/futures-repo.js +34 -246
- package/lib/store/futures-repo.js.map +1 -1
- package/lib/store/ledger-repo-base.d.ts +120 -0
- package/lib/store/ledger-repo-base.d.ts.map +1 -0
- package/lib/store/ledger-repo-base.js +275 -0
- package/lib/store/ledger-repo-base.js.map +1 -0
- package/lib/store/notes.d.ts +29 -0
- package/lib/store/notes.d.ts.map +1 -0
- package/lib/store/notes.js +78 -0
- package/lib/store/notes.js.map +1 -0
- package/lib/store/paths.d.ts +2 -0
- package/lib/store/paths.d.ts.map +1 -1
- package/lib/store/paths.js +4 -0
- package/lib/store/paths.js.map +1 -1
- package/lib/store/repo.d.ts +15 -55
- package/lib/store/repo.d.ts.map +1 -1
- package/lib/store/repo.js +41 -206
- package/lib/store/repo.js.map +1 -1
- package/lib/store/shortlist.d.ts.map +1 -1
- package/lib/store/shortlist.js +4 -6
- package/lib/store/shortlist.js.map +1 -1
- package/lib/store/snapshots.d.ts +0 -3
- package/lib/store/snapshots.d.ts.map +1 -1
- package/lib/store/snapshots.js +0 -3
- package/lib/store/snapshots.js.map +1 -1
- package/package.json +1 -1
- package/src/agent/account-tools.ts +136 -0
- package/src/agent/futures-tools.ts +1 -6
- package/src/agent/ledger-tools.ts +29 -16
- package/src/agent/tool-result.ts +27 -0
- package/src/agent/tools.ts +30 -10
- package/src/client/entry.js +14 -0
- package/src/client/parts/10-core.js +535 -0
- package/src/client/parts/20-styles.js +336 -0
- package/src/client/parts/30-atoms.js +769 -0
- package/src/client/parts/35-hooks.js +447 -0
- package/src/client/parts/40-stock-tabs.js +641 -0
- package/src/client/parts/50-futures.js +911 -0
- package/src/client/parts/60-shell.js +706 -0
- package/src/client/parts/70-plugin.js +67 -0
- package/src/contract/accounts.ts +82 -0
- package/src/contract/common.ts +173 -0
- package/src/contract/domain.ts +217 -0
- package/src/contract/errors.ts +34 -0
- package/src/contract/index.ts +15 -0
- package/src/contract/ledger.ts +42 -0
- package/src/contract/market.ts +39 -0
- package/src/contract/rpc.ts +15 -0
- package/src/contract.ts +6 -472
- package/src/core/session.ts +1 -2
- package/src/data/cached-market-data.ts +193 -0
- package/src/data/futures-market-data.ts +9 -10
- package/src/index.ts +168 -20
- package/src/service/account-moves.ts +72 -0
- package/src/service/accounts-rpc.ts +80 -0
- package/src/service/compare-rpc.ts +77 -0
- package/src/service/errors.ts +23 -4
- package/src/service/futures-rpc.ts +7 -24
- package/src/service/futures-service.ts +161 -159
- package/src/service/ledger-admin.ts +140 -0
- package/src/service/paper-service.ts +183 -153
- package/src/service/route.ts +5 -2
- package/src/service/rpc-support.ts +61 -0
- package/src/service/rpc.ts +59 -23
- package/src/store/accounts.ts +373 -0
- package/src/store/atomic-file.ts +37 -0
- package/src/store/futures-repo.ts +35 -260
- package/src/store/ledger-repo-base.ts +337 -0
- package/src/store/notes.ts +86 -0
- package/src/store/paths.ts +5 -0
- package/src/store/repo.ts +47 -229
- package/src/store/shortlist.ts +3 -5
- package/src/store/snapshots.ts +0 -3
- package/src/client/index.js +0 -3275
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { todayTradeDate, tradeDateOf } from '../core/calendar.js'
|
|
4
4
|
import type { FuturesExchange } from '../futures-contract.js'
|
|
5
5
|
import { resolveDshHome } from '../store/paths.js'
|
|
6
|
+
import { writeFileAtomic } from '../store/atomic-file.js'
|
|
6
7
|
import type { FtshareDataLike } from './ftshare-market-data.js'
|
|
7
8
|
import type {
|
|
8
9
|
FuturesContractMeta,
|
|
@@ -355,13 +356,13 @@ export class FtshareFuturesMarketData implements FuturesMarketDataPort {
|
|
|
355
356
|
const tradeDate = todayTradeDate()
|
|
356
357
|
if (!refresh) {
|
|
357
358
|
if (this.cache?.tradeDate === tradeDate) return { state: 'ok', value: this.cache.contracts }
|
|
358
|
-
const file = this.readCacheFile()
|
|
359
|
+
const file = await this.readCacheFile()
|
|
359
360
|
if (file?.tradeDate === tradeDate) {
|
|
360
361
|
this.cache = file
|
|
361
362
|
return { state: 'ok', value: file.contracts }
|
|
362
363
|
}
|
|
363
364
|
}
|
|
364
|
-
const previous = this.cache ?? this.readCacheFile()
|
|
365
|
+
const previous = this.cache ?? await this.readCacheFile()
|
|
365
366
|
const fetched = await this.fetchContracts()
|
|
366
367
|
if (fetched.state !== 'ok') {
|
|
367
368
|
return this.contractsFallback(fetched.state, fetched.notice ?? '合约索引不可用', previous)
|
|
@@ -374,7 +375,7 @@ export class FtshareFuturesMarketData implements FuturesMarketDataPort {
|
|
|
374
375
|
return { state: 'ok', value: [], notice: '合约索引没有可交易合约' }
|
|
375
376
|
}
|
|
376
377
|
this.cache = { tradeDate, contracts }
|
|
377
|
-
this.writeCacheFile({ tradeDate, savedAt: new Date().toISOString(), contracts })
|
|
378
|
+
await this.writeCacheFile({ tradeDate, savedAt: new Date().toISOString(), contracts })
|
|
378
379
|
return { state: 'ok', value: contracts }
|
|
379
380
|
}
|
|
380
381
|
|
|
@@ -832,9 +833,9 @@ export class FtshareFuturesMarketData implements FuturesMarketDataPort {
|
|
|
832
833
|
}
|
|
833
834
|
}
|
|
834
835
|
|
|
835
|
-
private readCacheFile(): ContractsCache | undefined {
|
|
836
|
+
private async readCacheFile(): Promise<ContractsCache | undefined> {
|
|
836
837
|
try {
|
|
837
|
-
const parsed = JSON.parse(
|
|
838
|
+
const parsed = JSON.parse(await readFile(this.cachePath(), 'utf8')) as unknown
|
|
838
839
|
if (!isRecord(parsed) || typeof parsed.tradeDate !== 'string' || !Array.isArray(parsed.contracts)) {
|
|
839
840
|
return undefined
|
|
840
841
|
}
|
|
@@ -851,11 +852,9 @@ export class FtshareFuturesMarketData implements FuturesMarketDataPort {
|
|
|
851
852
|
}
|
|
852
853
|
}
|
|
853
854
|
|
|
854
|
-
private writeCacheFile(file: CacheFile): void {
|
|
855
|
+
private async writeCacheFile(file: CacheFile): Promise<void> {
|
|
855
856
|
try {
|
|
856
|
-
|
|
857
|
-
mkdirSync(join(resolveDshHome(), 'paper-trading', 'futures'), { recursive: true })
|
|
858
|
-
writeFileSync(path, JSON.stringify(file), 'utf8')
|
|
857
|
+
await writeFileAtomic(this.cachePath(), JSON.stringify(file))
|
|
859
858
|
} catch {
|
|
860
859
|
// The cache is best effort; failing to persist it must not fail the call.
|
|
861
860
|
}
|
package/src/index.ts
CHANGED
|
@@ -5,6 +5,11 @@
|
|
|
5
5
|
* the `paper_*` tools lazily; the browser half is a separate static module
|
|
6
6
|
* loaded by DSH's module scan.
|
|
7
7
|
*
|
|
8
|
+
* Accounts: the registry (`accounts.json`) owns the account list, so this entry
|
|
9
|
+
* builds one {@link PaperService} per stock account on demand and hands every
|
|
10
|
+
* resolved target to the same RPC route. The default account is created eagerly
|
|
11
|
+
* because the tools predate multi-account and still bind to it.
|
|
12
|
+
*
|
|
8
13
|
* The three attachments are independent on purpose. Market data is the only
|
|
9
14
|
* optional dependency — the ledger, the panel and the tools must stay available
|
|
10
15
|
* without it, so quotes degrade to the port's `failed` state instead of taking
|
|
@@ -14,37 +19,52 @@
|
|
|
14
19
|
|
|
15
20
|
import type { Context } from '@deepseek-ai/cordis'
|
|
16
21
|
import type {} from '@deepseek-ai/dsh-tools'
|
|
22
|
+
import { registerAccountTools } from './agent/account-tools.js'
|
|
17
23
|
import { registerFuturesTools } from './agent/futures-tools.js'
|
|
18
24
|
import { registerLedgerTools } from './agent/ledger-tools.js'
|
|
19
|
-
import { registerPaperTools, type ToolsLike } from './agent/tools.js'
|
|
25
|
+
import { registerPaperTools, type ServiceResolver, type ToolsLike } from './agent/tools.js'
|
|
26
|
+
import { CachedMarketData } from './data/cached-market-data.js'
|
|
20
27
|
import { FtshareMarketData, type FtshareDataLike } from './data/ftshare-market-data.js'
|
|
21
28
|
import { FtshareFuturesMarketData } from './data/futures-market-data.js'
|
|
22
29
|
import { FtshareTradingCalendar } from './data/ftshare-trading-calendar.js'
|
|
23
30
|
import type { MarketDataPort } from './data/market-data-port.js'
|
|
31
|
+
import { UnavailableMarketData } from './data/unavailable-market-data.js'
|
|
24
32
|
import type { TradingCalendarPort } from './data/trading-calendar-port.js'
|
|
25
33
|
import { WeekdayTradingCalendar } from './data/trading-calendar-port.js'
|
|
26
|
-
import {
|
|
34
|
+
import { createAccountsRpcHandler } from './service/accounts-rpc.js'
|
|
35
|
+
import { createCompareRpcHandler } from './service/compare-rpc.js'
|
|
36
|
+
import { PaperError } from './service/errors.js'
|
|
27
37
|
import { FuturesService } from './service/futures-service.js'
|
|
28
38
|
import { createFuturesRpcHandler } from './service/futures-rpc.js'
|
|
29
39
|
import { PaperService } from './service/paper-service.js'
|
|
30
40
|
import { createPaperRoute, type HostConnectionLike } from './service/route.js'
|
|
31
|
-
import { createPaperRpcHandler, type PaperRpcHandler } from './service/rpc.js'
|
|
41
|
+
import { createPaperRpcHandler, type PaperRpcHandler, type PaperRpcResolver } from './service/rpc.js'
|
|
32
42
|
import { PaperScheduler } from './service/scheduler.js'
|
|
33
43
|
import { probeDataSource, type FtshareSettingsLike } from './service/data-source.js'
|
|
44
|
+
import { AccountNotes } from './store/notes.js'
|
|
45
|
+
import { AccountRegistry, DEFAULT_TICK_MS } from './store/accounts.js'
|
|
34
46
|
import { AccountRepo } from './store/repo.js'
|
|
35
47
|
import { FuturesRepo } from './store/futures-repo.js'
|
|
36
48
|
import { resolveDshHome } from './store/paths.js'
|
|
37
49
|
import { ShortlistStore } from './store/shortlist.js'
|
|
38
|
-
import { DEFAULT_ACCOUNT_ID, type DataSourceStatus } from './contract.js'
|
|
50
|
+
import { DEFAULT_ACCOUNT_ID, DEFAULT_SETTINGS, type AccountMeta, type DataSourceStatus } from './contract.js'
|
|
39
51
|
import { UnavailableFuturesMarketData } from './data/unavailable-futures-market-data.js'
|
|
40
52
|
import type { FuturesMarketDataPort } from './data/futures-market-data-port.js'
|
|
53
|
+
import { FUTURES_ACCOUNT_ID } from './futures-contract.js'
|
|
41
54
|
|
|
42
55
|
export * from './contract.js'
|
|
43
56
|
export { PaperService } from './service/paper-service.js'
|
|
44
57
|
export { createPaperRpcHandler } from './service/rpc.js'
|
|
58
|
+
export type { PaperRpcTarget, PaperRpcResolver } from './service/rpc.js'
|
|
59
|
+
export { createAccountsRpcHandler } from './service/accounts-rpc.js'
|
|
60
|
+
export { createCompareRpcHandler } from './service/compare-rpc.js'
|
|
61
|
+
export { registerAccountTools } from './agent/account-tools.js'
|
|
45
62
|
export { createPaperRoute } from './service/route.js'
|
|
46
63
|
export { PaperScheduler } from './service/scheduler.js'
|
|
47
64
|
export { AccountRepo } from './store/repo.js'
|
|
65
|
+
export { AccountRegistry, DEFAULT_TICK_MS, MAX_ACCOUNTS_PER_KIND } from './store/accounts.js'
|
|
66
|
+
export { AccountNotes } from './store/notes.js'
|
|
67
|
+
export { CachedMarketData } from './data/cached-market-data.js'
|
|
48
68
|
export { FtshareMarketData } from './data/ftshare-market-data.js'
|
|
49
69
|
export { FtshareFuturesMarketData } from './data/futures-market-data.js'
|
|
50
70
|
export { FtshareTradingCalendar } from './data/ftshare-trading-calendar.js'
|
|
@@ -59,20 +79,40 @@ export { UnavailableFuturesMarketData } from './data/unavailable-futures-market-
|
|
|
59
79
|
|
|
60
80
|
export const name = '@dsh-ft/dsh-fft-paper-trading'
|
|
61
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Test seams. Production omits all of them: the real clock and the FTShare
|
|
84
|
+
* adapters are used. The golden suite injects a frozen clock and deterministic
|
|
85
|
+
* data ports to pin end-to-end behavior across refactors.
|
|
86
|
+
*/
|
|
87
|
+
export interface ApplyOptions {
|
|
88
|
+
now?: () => Date
|
|
89
|
+
marketData?: MarketDataPort
|
|
90
|
+
futuresMarketData?: FuturesMarketDataPort
|
|
91
|
+
}
|
|
92
|
+
|
|
62
93
|
/**
|
|
63
94
|
* Services are attached lazily: the browser scan needs this row's fiber, so the
|
|
64
95
|
* plugin must not gate activation on optional services.
|
|
65
96
|
*/
|
|
66
|
-
export function apply(ctx: Context): void {
|
|
97
|
+
export function apply(ctx: Context, options: ApplyOptions = {}): void {
|
|
67
98
|
const logger = ctx.logger('ft-paper-trading')
|
|
68
99
|
const home = resolveDshHome()
|
|
69
|
-
const repo = new AccountRepo({ home, accountId: DEFAULT_ACCOUNT_ID, logger })
|
|
70
100
|
const shortlist = new ShortlistStore(home)
|
|
101
|
+
const registry = new AccountRegistry({
|
|
102
|
+
home,
|
|
103
|
+
logger,
|
|
104
|
+
...(options.now === undefined ? {} : { now: options.now }),
|
|
105
|
+
})
|
|
106
|
+
// Notes live beside each ledger, not in the registry: a long note must not
|
|
107
|
+
// bloat accounts.json, and the model has no tool for them.
|
|
108
|
+
const notes = new AccountNotes({ home })
|
|
109
|
+
/** Quote cache lifetime; replaced by the persisted value once the registry loads. */
|
|
110
|
+
let tickMs = DEFAULT_TICK_MS
|
|
71
111
|
|
|
72
112
|
// One mutable slot behind a stable port: the services hold the ports, the
|
|
73
113
|
// FTShare adapter can appear (or disappear) later without rebuilding the
|
|
74
114
|
// services, the route or the tools.
|
|
75
|
-
let market: MarketDataPort = new UnavailableMarketData()
|
|
115
|
+
let market: MarketDataPort = options.marketData ?? new UnavailableMarketData()
|
|
76
116
|
let calendar: TradingCalendarPort = new WeekdayTradingCalendar('未安装 FTShare 数据服务,按工作日估算')
|
|
77
117
|
const data: MarketDataPort = {
|
|
78
118
|
quotes: symbols => market.quotes(symbols),
|
|
@@ -81,6 +121,13 @@ export function apply(ctx: Context): void {
|
|
|
81
121
|
search: (query, limit) => market.search(query, limit),
|
|
82
122
|
marketList: input => market.marketList(input),
|
|
83
123
|
}
|
|
124
|
+
// Every account shares one cache: N accounts holding the same symbol must not
|
|
125
|
+
// cost N upstream calls, and inside one tick they must all see one price.
|
|
126
|
+
const clockNow = options.now
|
|
127
|
+
const cached = new CachedMarketData(data, {
|
|
128
|
+
ttlMs: () => tickMs,
|
|
129
|
+
...(clockNow === undefined ? {} : { now: () => clockNow().getTime() }),
|
|
130
|
+
})
|
|
84
131
|
// Same trick for the calendar: both services take this port once, and the
|
|
85
132
|
// slot behind it is swapped when the FTShare adapter arrives. Handing the
|
|
86
133
|
// slot itself to the stocks service left it on the weekday fallback for the
|
|
@@ -102,12 +149,37 @@ export function apply(ctx: Context): void {
|
|
|
102
149
|
// arrives and flip to "free/configured" when the service appears.
|
|
103
150
|
let dataService = false
|
|
104
151
|
let settings: FtshareSettingsLike | undefined
|
|
105
|
-
|
|
152
|
+
|
|
153
|
+
/** One service per stock account, created on first use and kept forever. */
|
|
154
|
+
const stockServices = new Map<string, PaperService>()
|
|
155
|
+
const stockService = (meta: AccountMeta): PaperService => {
|
|
156
|
+
const existing = stockServices.get(meta.id)
|
|
157
|
+
if (existing !== undefined) return existing
|
|
158
|
+
const accountSettings = meta.initialCashCents === undefined
|
|
159
|
+
? DEFAULT_SETTINGS
|
|
160
|
+
: { ...DEFAULT_SETTINGS, initialCashCents: meta.initialCashCents }
|
|
161
|
+
const service = new PaperService({
|
|
162
|
+
repo: new AccountRepo({ home, accountId: meta.id, logger }),
|
|
163
|
+
data: cached,
|
|
164
|
+
calendar: calendarPort,
|
|
165
|
+
shortlist,
|
|
166
|
+
settings: accountSettings,
|
|
167
|
+
accountId: meta.id,
|
|
168
|
+
logger,
|
|
169
|
+
...(options.now === undefined ? {} : { now: options.now }),
|
|
170
|
+
// Read the registry, not this meta: `accounts/lock` mutates the live
|
|
171
|
+
// entry, and the service map is shared with the scheduler's copies.
|
|
172
|
+
isLocked: () => registry.lockedSync(meta.id),
|
|
173
|
+
isArchived: () => registry.archivedSync(meta.id),
|
|
174
|
+
})
|
|
175
|
+
stockServices.set(meta.id, service)
|
|
176
|
+
return service
|
|
177
|
+
}
|
|
106
178
|
|
|
107
179
|
// Futures: separate ledger, separate service, same route. The market-data
|
|
108
180
|
// port stays on the degraded stand-in until the FTShare futures adapter is
|
|
109
181
|
// wired in; the ledger and the tools must work without it.
|
|
110
|
-
let futuresMarket: FuturesMarketDataPort = new UnavailableFuturesMarketData()
|
|
182
|
+
let futuresMarket: FuturesMarketDataPort = options.futuresMarketData ?? new UnavailableFuturesMarketData()
|
|
111
183
|
const futuresRepo = new FuturesRepo({ home, logger })
|
|
112
184
|
const futuresService = new FuturesService({
|
|
113
185
|
repo: futuresRepo,
|
|
@@ -120,28 +192,67 @@ export function apply(ctx: Context): void {
|
|
|
120
192
|
},
|
|
121
193
|
calendar: calendarPort,
|
|
122
194
|
logger,
|
|
195
|
+
...(options.now === undefined ? {} : { now: options.now }),
|
|
196
|
+
isLocked: () => registry.lockedSync(FUTURES_ACCOUNT_ID),
|
|
123
197
|
})
|
|
124
198
|
const futuresHandler = createFuturesRpcHandler(futuresService)
|
|
125
199
|
// The panel header reads one status: credential state plus the latest market
|
|
126
|
-
// failure across
|
|
200
|
+
// failure across every account (they share the data service).
|
|
127
201
|
const dataSource = async (): Promise<DataSourceStatus> => {
|
|
128
202
|
const probe = await probeDataSource({ dataService, settings })
|
|
129
|
-
const problems = [
|
|
203
|
+
const problems = [...stockServices.values()]
|
|
204
|
+
.map(item => item.problem())
|
|
205
|
+
.concat(futuresService.problem())
|
|
130
206
|
.filter((problem): problem is NonNullable<typeof problem> => problem !== undefined)
|
|
131
207
|
.sort((left, right) => right.at.localeCompare(left.at))
|
|
132
208
|
return problems.length === 0 ? probe : { ...probe, problem: problems[0] }
|
|
133
209
|
}
|
|
134
|
-
|
|
135
|
-
//
|
|
136
|
-
|
|
137
|
-
|
|
210
|
+
// Resolve an account id/name to its stock service. A futures account reaching
|
|
211
|
+
// this path is a caller bug, not a silent fallback.
|
|
212
|
+
const resolveStock: PaperRpcResolver = async account => {
|
|
213
|
+
const meta = await registry.resolve(account)
|
|
214
|
+
if (meta.kind !== 'stock') throw new PaperError('INVALID_ARGUMENT', `账户「${meta.name}」不是股票账户`)
|
|
215
|
+
return { service: stockService(meta), meta }
|
|
216
|
+
}
|
|
217
|
+
const paperHandler = createPaperRpcHandler(resolveStock, { dataSource, notes })
|
|
218
|
+
const accountsHandler = createAccountsRpcHandler(registry)
|
|
219
|
+
// The comparison page reads every visible account; archived ones are only
|
|
220
|
+
// reachable by id, so they stay out of the board.
|
|
221
|
+
const compareHandler = createCompareRpcHandler({
|
|
222
|
+
accounts: async () => (await registry.view()).accounts.filter(meta => meta.kind === 'stock'),
|
|
223
|
+
serviceOf: meta => stockService(meta),
|
|
224
|
+
})
|
|
225
|
+
// `futures/*`, `accounts/*` and `compare/*` have their own handlers;
|
|
226
|
+
// everything else keeps the stock handler, so the browser half needs one
|
|
227
|
+
// route only.
|
|
228
|
+
const handler: PaperRpcHandler = (endpoint, payload, signal, account) =>
|
|
138
229
|
endpoint.startsWith('futures/')
|
|
139
230
|
? futuresHandler(endpoint, payload, signal)
|
|
140
|
-
:
|
|
231
|
+
: endpoint.startsWith('accounts/')
|
|
232
|
+
? accountsHandler(endpoint, payload, signal, account)
|
|
233
|
+
: endpoint.startsWith('compare/')
|
|
234
|
+
? compareHandler(endpoint, payload, signal, account)
|
|
235
|
+
: paperHandler(endpoint, payload, signal, account)
|
|
141
236
|
|
|
142
237
|
// Matching and day settlement must not depend on the panel being open: the
|
|
143
|
-
// host fiber drives `tick` even while the browser half is unmounted.
|
|
144
|
-
|
|
238
|
+
// host fiber drives `tick` even while the browser half is unmounted. One
|
|
239
|
+
// scheduler walks every registered account, so a resting order fills for an
|
|
240
|
+
// account the panel never opened; the shared cache keeps the cost flat.
|
|
241
|
+
const scheduler = new PaperScheduler({
|
|
242
|
+
logger,
|
|
243
|
+
tick: async () => {
|
|
244
|
+
// Archived accounts still have orders: archiving is a panel concern, not a
|
|
245
|
+
// reason to stop matching a resting order.
|
|
246
|
+
const view = await registry.view({ includeArchived: true })
|
|
247
|
+
for (const meta of view.accounts) {
|
|
248
|
+
if (meta.kind !== 'stock') continue
|
|
249
|
+
// Orders only: marking positions is display work, and nobody is looking
|
|
250
|
+
// while the panel is closed. An account with no resting order therefore
|
|
251
|
+
// costs zero quote calls.
|
|
252
|
+
await stockService(meta).tick({ includePositions: false })
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
})
|
|
145
256
|
ctx.effect(
|
|
146
257
|
() => {
|
|
147
258
|
scheduler.start()
|
|
@@ -159,8 +270,22 @@ export function apply(ctx: Context): void {
|
|
|
159
270
|
},
|
|
160
271
|
'ft-paper-trading: futures scheduler',
|
|
161
272
|
)
|
|
273
|
+
// Read the persisted tick once; it only tunes the quote cache lifetime.
|
|
274
|
+
ctx.effect(
|
|
275
|
+
() => {
|
|
276
|
+
void registry
|
|
277
|
+
.tickMs()
|
|
278
|
+
.then(value => {
|
|
279
|
+
tickMs = value
|
|
280
|
+
})
|
|
281
|
+
.catch(() => undefined)
|
|
282
|
+
return () => undefined
|
|
283
|
+
},
|
|
284
|
+
'ft-paper-trading: account registry',
|
|
285
|
+
)
|
|
162
286
|
|
|
163
287
|
ctx.inject(['ftshareData'], scope => {
|
|
288
|
+
if (options.marketData !== undefined || options.futuresMarketData !== undefined) return
|
|
164
289
|
const service = scope.get('ftshareData') as unknown as FtshareDataLike
|
|
165
290
|
const adapter = new FtshareMarketData(service)
|
|
166
291
|
const calendarAdapter = new FtshareTradingCalendar(service)
|
|
@@ -169,11 +294,14 @@ export function apply(ctx: Context): void {
|
|
|
169
294
|
calendar = calendarAdapter
|
|
170
295
|
futuresMarket = futuresAdapter
|
|
171
296
|
dataService = true
|
|
297
|
+
// Cached quotes came from the previous adapter (or the stand-in).
|
|
298
|
+
cached.clear()
|
|
172
299
|
scope.effect(
|
|
173
300
|
() => () => {
|
|
174
301
|
if (market === adapter) market = new UnavailableMarketData()
|
|
175
302
|
if (calendar === calendarAdapter) calendar = new WeekdayTradingCalendar('未安装 FTShare 数据服务,按工作日估算')
|
|
176
303
|
if (futuresMarket === futuresAdapter) futuresMarket = new UnavailableFuturesMarketData()
|
|
304
|
+
cached.clear()
|
|
177
305
|
dataService = false
|
|
178
306
|
},
|
|
179
307
|
'ft-paper-trading: FTShare adapter',
|
|
@@ -203,8 +331,28 @@ export function apply(ctx: Context): void {
|
|
|
203
331
|
|
|
204
332
|
ctx.inject(['tools'], scope => {
|
|
205
333
|
const tools = scope.get('tools') as unknown as ToolsLike
|
|
206
|
-
|
|
334
|
+
// Same seven tool names for every account: the tool's `account` argument
|
|
335
|
+
// (name or id, default = the default account) decides which ledger answers.
|
|
336
|
+
const resolveToolService: ServiceResolver = async account => {
|
|
337
|
+
const meta = await registry.resolve(account)
|
|
338
|
+
if (meta.kind !== 'stock') throw new PaperError('INVALID_ARGUMENT', `账户「${meta.name}」不是股票账户`)
|
|
339
|
+
return stockService(meta)
|
|
340
|
+
}
|
|
341
|
+
registerPaperTools(tools, resolveToolService)
|
|
342
|
+
registerAccountTools(tools, { registry })
|
|
207
343
|
registerFuturesTools(tools, futuresService)
|
|
208
|
-
|
|
344
|
+
// Resolve on demand: an eagerly-created service would capture the
|
|
345
|
+
// pre-registry lock flag and ignore later `accounts/lock`. The reference
|
|
346
|
+
// accepts the same forms as every other tool plus the legacy family words.
|
|
347
|
+
registerLedgerTools(tools, {
|
|
348
|
+
resolve: async reference => {
|
|
349
|
+
if (reference === 'futures') {
|
|
350
|
+
return { kind: 'futures', service: futuresService, accountId: FUTURES_ACCOUNT_ID }
|
|
351
|
+
}
|
|
352
|
+
const resolved = await resolveStock(reference === undefined || reference === '' || reference === 'stock' ? undefined : reference)
|
|
353
|
+
if (resolved.meta === undefined) throw new PaperError('INTERNAL', '账户解析缺少元数据')
|
|
354
|
+
return { kind: 'stock', service: resolved.service, accountId: resolved.meta.id }
|
|
355
|
+
},
|
|
356
|
+
})
|
|
209
357
|
})
|
|
210
358
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opening and cash moves, shared by the stock and futures services.
|
|
3
|
+
*
|
|
4
|
+
* Both planes keep the same rules — open once on first read, re-check cash
|
|
5
|
+
* inside the write transaction, and surface a frozen ledger before anything
|
|
6
|
+
* else. The only differences are the engine functions, the state type and the
|
|
7
|
+
* view builder, which each service passes in. After the error-model unification
|
|
8
|
+
* the failure types are identical too, so the logic lives here once.
|
|
9
|
+
* @module @dsh-ft/dsh-fft-paper-trading/service/account-moves
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { DomainError } from './errors.js'
|
|
13
|
+
|
|
14
|
+
export interface MoveCashDeps<S, V, E> {
|
|
15
|
+
sync(): Promise<S>
|
|
16
|
+
transact<T>(build: (state: S) => { events: E[]; value: T } | Promise<{ events: E[]; value: T }>): Promise<{ state: S; value: T }>
|
|
17
|
+
isBlocked(state: S): boolean
|
|
18
|
+
/** Plane-specific "account frozen" error, with its reason. */
|
|
19
|
+
blocked(state: S): Error
|
|
20
|
+
cashCents(state: S): number
|
|
21
|
+
deposit(state: S, amountCents: number, ts: string): { events: E[] }
|
|
22
|
+
withdraw(state: S, amountCents: number, ts: string): { events: E[] }
|
|
23
|
+
viewOf(state: S): V
|
|
24
|
+
ts(): string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Deposit or withdraw cash (amount already converted to cents).
|
|
29
|
+
*
|
|
30
|
+
* The balance is re-checked inside the transaction: a concurrent buy or a
|
|
31
|
+
* margin reservation may have spent the cash between `sync()` and this write.
|
|
32
|
+
*/
|
|
33
|
+
export async function moveCash<S, V, E>(
|
|
34
|
+
deps: MoveCashDeps<S, V, E>,
|
|
35
|
+
kind: 'deposit' | 'withdraw',
|
|
36
|
+
amountCents: number,
|
|
37
|
+
): Promise<V> {
|
|
38
|
+
const state = await deps.sync()
|
|
39
|
+
if (deps.isBlocked(state)) throw deps.blocked(state)
|
|
40
|
+
const outcome = await deps.transact<{ blocked: boolean; insufficient: boolean }>(current => {
|
|
41
|
+
if (deps.isBlocked(current)) return { events: [], value: { blocked: true, insufficient: false } }
|
|
42
|
+
if (kind === 'withdraw' && amountCents > deps.cashCents(current)) {
|
|
43
|
+
return { events: [], value: { blocked: false, insufficient: true } }
|
|
44
|
+
}
|
|
45
|
+
const ts = deps.ts()
|
|
46
|
+
const result = kind === 'deposit' ? deps.deposit(current, amountCents, ts) : deps.withdraw(current, amountCents, ts)
|
|
47
|
+
return { events: result.events, value: { blocked: false, insufficient: false } }
|
|
48
|
+
})
|
|
49
|
+
if (outcome.value.blocked === true) throw deps.blocked(outcome.state)
|
|
50
|
+
if (outcome.value.insufficient === true) throw new DomainError('INSUFFICIENT_CASH', '可提现金不足')
|
|
51
|
+
return deps.viewOf(outcome.state)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface OpenAccountDeps<S, E> {
|
|
55
|
+
transact<T>(build: (state: S) => { events: E[]; value: T } | Promise<{ events: E[]; value: T }>): Promise<{ state: S; value: T }>
|
|
56
|
+
hasAccount(state: S): boolean
|
|
57
|
+
tradeDateForNow(): Promise<string>
|
|
58
|
+
/** Plane-specific genesis: `openAccount` returns the events to append. */
|
|
59
|
+
open(state: S, tradeDate: string, ts: string): { events: E[] }
|
|
60
|
+
now(): Date
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Open the ledger on first read; a no-op afterwards. */
|
|
64
|
+
export async function openAccountOnce<S, E>(deps: OpenAccountDeps<S, E>): Promise<S> {
|
|
65
|
+
const outcome = await deps.transact(async state => {
|
|
66
|
+
if (deps.hasAccount(state)) return { events: [], value: undefined }
|
|
67
|
+
const tradeDate = await deps.tradeDateForNow()
|
|
68
|
+
const result = deps.open(state, tradeDate, deps.now().toISOString())
|
|
69
|
+
return { events: result.events, value: undefined }
|
|
70
|
+
})
|
|
71
|
+
return outcome.state
|
|
72
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `accounts/*` RPC endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Account administration is deliberately kept out of {@link createPaperRpcHandler}:
|
|
5
|
+
* that handler owns trading and never touches the registry file, while these
|
|
6
|
+
* endpoints only edit metadata (create / rename / archive / lock). Both are mounted
|
|
7
|
+
* on the same route, so the browser half still has one door.
|
|
8
|
+
*
|
|
9
|
+
* There is no session endpoint on purpose: this plugin knows nothing about
|
|
10
|
+
* sessions, and every caller addresses an account by id or display name.
|
|
11
|
+
* @module @dsh-ft/dsh-fft-paper-trading/service/accounts-rpc
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { AccountKind } from '../contract.js'
|
|
15
|
+
import type { AccountRegistry } from '../store/accounts.js'
|
|
16
|
+
import { PaperError } from './errors.js'
|
|
17
|
+
import type { PaperRpcHandler } from './rpc.js'
|
|
18
|
+
import { argumentGuards, fail, failure, ok } from './rpc-support.js'
|
|
19
|
+
|
|
20
|
+
const guard = argumentGuards(message => new PaperError('INVALID_ARGUMENT', message))
|
|
21
|
+
const record = guard.record
|
|
22
|
+
const text = guard.text
|
|
23
|
+
|
|
24
|
+
function kindOf(value: unknown): AccountKind | undefined {
|
|
25
|
+
if (value === undefined || value === null) return undefined
|
|
26
|
+
if (value === 'stock' || value === 'futures') return value
|
|
27
|
+
throw new PaperError('INVALID_ARGUMENT', 'kind 必须是 stock 或 futures')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Yuan input from the panel; the registry stores cents like the ledger does. */
|
|
31
|
+
function cashCents(value: unknown): number | undefined {
|
|
32
|
+
if (value === undefined || value === null) return undefined
|
|
33
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
34
|
+
throw new PaperError('INVALID_ARGUMENT', 'initialCash 必须是正数(元)')
|
|
35
|
+
}
|
|
36
|
+
return Math.round(value * 100)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Routes `accounts/*`; every other endpoint is somebody else's. */
|
|
40
|
+
export function createAccountsRpcHandler(registry: AccountRegistry): PaperRpcHandler {
|
|
41
|
+
return async (endpoint, payload) => {
|
|
42
|
+
try {
|
|
43
|
+
const input = record(payload ?? {})
|
|
44
|
+
switch (endpoint) {
|
|
45
|
+
case 'accounts/list': {
|
|
46
|
+
const kind = kindOf(input.kind)
|
|
47
|
+
return ok(await registry.view({
|
|
48
|
+
includeArchived: input.includeArchived === true,
|
|
49
|
+
...(kind === undefined ? {} : { kind }),
|
|
50
|
+
}))
|
|
51
|
+
}
|
|
52
|
+
case 'accounts/create':
|
|
53
|
+
if (kindOf(input.kind) === 'futures') {
|
|
54
|
+
// Futures is still one ledger with its own panel; a second futures
|
|
55
|
+
// entry would be unreachable and fail every stock request.
|
|
56
|
+
throw new PaperError('INVALID_ARGUMENT', 'v1 只支持新建股票账户')
|
|
57
|
+
}
|
|
58
|
+
return ok(await registry.create({
|
|
59
|
+
name: text(input.name, 'name'),
|
|
60
|
+
...(kindOf(input.kind) === undefined ? {} : { kind: kindOf(input.kind) as AccountKind }),
|
|
61
|
+
...(cashCents(input.initialCash) === undefined ? {} : { initialCashCents: cashCents(input.initialCash) as number }),
|
|
62
|
+
}))
|
|
63
|
+
case 'accounts/rename':
|
|
64
|
+
return ok(await registry.rename(text(input.id, 'id'), text(input.name, 'name')))
|
|
65
|
+
case 'accounts/archive':
|
|
66
|
+
return ok(await registry.archive(text(input.id, 'id')))
|
|
67
|
+
case 'accounts/unarchive':
|
|
68
|
+
return ok(await registry.unarchive(text(input.id, 'id')))
|
|
69
|
+
case 'accounts/lock':
|
|
70
|
+
return ok(await registry.lock(text(input.id, 'id')))
|
|
71
|
+
case 'accounts/unlock':
|
|
72
|
+
return ok(await registry.unlock(text(input.id, 'id')))
|
|
73
|
+
default:
|
|
74
|
+
return fail('INVALID_ARGUMENT', `未知端点 ${endpoint}`)
|
|
75
|
+
}
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return failure(error, item => item instanceof PaperError)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `compare/get`: the numbers behind the comparison page.
|
|
3
|
+
*
|
|
4
|
+
* Every visible account is read through its own service — `account()` for the
|
|
5
|
+
* snapshot and `review('all')` for the drawdown and the daily equity curve.
|
|
6
|
+
* Both are read paths: they only fetch quotes when a day boundary is due (the
|
|
7
|
+
* first read after 15:00 or after the next open), so ordinary polling spends no
|
|
8
|
+
* market-data quota but the first read of a new trading day may take one
|
|
9
|
+
* boundary snapshot per account.
|
|
10
|
+
* @module @dsh-ft/dsh-fft-paper-trading/service/compare-rpc
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { AccountMeta, CompareRow, CompareView } from '../contract.js'
|
|
14
|
+
import { PaperError } from './errors.js'
|
|
15
|
+
import type { PaperService } from './paper-service.js'
|
|
16
|
+
import type { PaperRpcHandler } from './rpc.js'
|
|
17
|
+
import { fail, ok } from './rpc-support.js'
|
|
18
|
+
|
|
19
|
+
export interface CompareSource {
|
|
20
|
+
/** Visible (not archived) stock accounts, in registry order. */
|
|
21
|
+
accounts: () => Promise<AccountMeta[]>
|
|
22
|
+
serviceOf: (meta: AccountMeta) => PaperService
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Routes `compare/get`; other endpoints belong to the per-account handlers. */
|
|
26
|
+
export function createCompareRpcHandler(source: CompareSource): PaperRpcHandler {
|
|
27
|
+
return async endpoint => {
|
|
28
|
+
if (endpoint !== 'compare/get') {
|
|
29
|
+
return fail('INVALID_ARGUMENT', `未知端点 ${endpoint}`)
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const accounts: CompareRow[] = []
|
|
33
|
+
for (const meta of await source.accounts()) {
|
|
34
|
+
const service = source.serviceOf(meta)
|
|
35
|
+
try {
|
|
36
|
+
const [account, review] = await Promise.all([service.account(), service.review('all')])
|
|
37
|
+
accounts.push({
|
|
38
|
+
id: meta.id,
|
|
39
|
+
name: meta.name,
|
|
40
|
+
locked: meta.locked === true,
|
|
41
|
+
...(meta.missing === true ? { missing: true } : {}),
|
|
42
|
+
initialCash: account.initialCash,
|
|
43
|
+
equity: account.equity,
|
|
44
|
+
pnl: account.pnl,
|
|
45
|
+
pnlPct: account.pnlPct,
|
|
46
|
+
todayPnl: account.todayPnl,
|
|
47
|
+
maxDrawdownPct: review.maxDrawdownPct,
|
|
48
|
+
tradeCount: review.tradeCount,
|
|
49
|
+
points: review.equityCurve,
|
|
50
|
+
})
|
|
51
|
+
} catch {
|
|
52
|
+
// One broken ledger must not blank the whole board: surface the row
|
|
53
|
+
// as missing instead of failing every other account with it.
|
|
54
|
+
accounts.push({
|
|
55
|
+
id: meta.id,
|
|
56
|
+
name: meta.name,
|
|
57
|
+
locked: meta.locked === true,
|
|
58
|
+
missing: true,
|
|
59
|
+
initialCash: 0,
|
|
60
|
+
equity: 0,
|
|
61
|
+
pnl: 0,
|
|
62
|
+
pnlPct: 0,
|
|
63
|
+
todayPnl: 0,
|
|
64
|
+
maxDrawdownPct: 0,
|
|
65
|
+
tradeCount: 0,
|
|
66
|
+
points: [],
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const view: CompareView = { accounts }
|
|
71
|
+
return ok(view)
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error instanceof PaperError) return { ok: false, error: { code: error.code, message: error.message } }
|
|
74
|
+
return { ok: false, error: { code: 'INTERNAL', message: error instanceof Error ? error.message : String(error) } }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/service/errors.ts
CHANGED
|
@@ -1,12 +1,31 @@
|
|
|
1
1
|
import type { ErrorCode } from '../contract.js'
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
/** Everything a domain error may carry; `INTERNAL` is the only non-domain value. */
|
|
4
|
+
export type DomainErrorCode = ErrorCode | 'INTERNAL'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The futures plane historically declared its own narrower code union; both
|
|
8
|
+
* planes now answer from one closed set, and this alias keeps call sites and
|
|
9
|
+
* tests compiling while the naming is retired gradually.
|
|
10
|
+
*/
|
|
11
|
+
export type FuturesServiceErrorCode = DomainErrorCode
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One typed failure for both trading planes.
|
|
15
|
+
*
|
|
16
|
+
* The RPC envelope always answers HTTP 200 with `{ ok: false, error }`; the
|
|
17
|
+
* error carries the code and message, never an HTTP status (the old `status`
|
|
18
|
+
* field was written at 96 call sites and read by nothing).
|
|
19
|
+
*/
|
|
20
|
+
export class DomainError extends Error {
|
|
4
21
|
constructor(
|
|
5
|
-
readonly code:
|
|
22
|
+
readonly code: DomainErrorCode,
|
|
6
23
|
message: string,
|
|
7
|
-
readonly status = 400,
|
|
8
24
|
) {
|
|
9
25
|
super(message)
|
|
10
|
-
this.name = '
|
|
26
|
+
this.name = 'DomainError'
|
|
11
27
|
}
|
|
12
28
|
}
|
|
29
|
+
|
|
30
|
+
/** Historical per-plane names for the same class; `instanceof` works for both. */
|
|
31
|
+
export { DomainError as PaperError, DomainError as FuturesError }
|