@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
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Free-form notes for one account.
|
|
3
|
+
*
|
|
4
|
+
* A single text block the human rewrites however they like: no entries, no
|
|
5
|
+
* timestamps, no history. It lives beside the ledger (`note.md`) instead of the
|
|
6
|
+
* registry so a long note never bloats `accounts.json`, and the model has no
|
|
7
|
+
* tool for it — this is the human's own space.
|
|
8
|
+
* @module @dsh-ft/dsh-fft-paper-trading/store/notes
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
12
|
+
import type { NoteView } from '../contract.js'
|
|
13
|
+
import { PaperError } from '../service/errors.js'
|
|
14
|
+
import { notePath } from './paths.js'
|
|
15
|
+
import { writeFileAtomic } from './atomic-file.js'
|
|
16
|
+
|
|
17
|
+
/** 100 KB of UTF-8: a very long research note, still cheap to load and save. */
|
|
18
|
+
export const NOTE_MAX_BYTES = 100_000
|
|
19
|
+
|
|
20
|
+
export interface AccountNotesOptions {
|
|
21
|
+
home: string
|
|
22
|
+
maxBytes?: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class AccountNotes {
|
|
26
|
+
private readonly home: string
|
|
27
|
+
private readonly maxBytes: number
|
|
28
|
+
/** Writes to one account must land in order; two quick saves used to race
|
|
29
|
+
* for the same temp file and one of them failed with ENOENT. */
|
|
30
|
+
private readonly queues = new Map<string, Promise<unknown>>()
|
|
31
|
+
|
|
32
|
+
constructor(options: AccountNotesOptions) {
|
|
33
|
+
this.home = options.home
|
|
34
|
+
this.maxBytes = options.maxBytes ?? NOTE_MAX_BYTES
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Read one account's note; a missing file is an empty note, not an error. */
|
|
38
|
+
async read(accountId: string): Promise<NoteView> {
|
|
39
|
+
const file = notePath(this.home, accountId)
|
|
40
|
+
let text: string
|
|
41
|
+
try {
|
|
42
|
+
text = await readFile(file, 'utf8')
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
|
45
|
+
return { text: '', bytes: 0, maxBytes: this.maxBytes }
|
|
46
|
+
}
|
|
47
|
+
throw new PaperError('INTERNAL', `读取笔记失败:${error instanceof Error ? error.message : String(error)}`)
|
|
48
|
+
}
|
|
49
|
+
let updatedAt: string | undefined
|
|
50
|
+
try {
|
|
51
|
+
updatedAt = (await stat(file)).mtime.toISOString()
|
|
52
|
+
} catch {
|
|
53
|
+
updatedAt = undefined
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
text,
|
|
57
|
+
bytes: byteLength(text),
|
|
58
|
+
maxBytes: this.maxBytes,
|
|
59
|
+
...(updatedAt === undefined ? {} : { updatedAt }),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Replace the whole note atomically; an empty string clears it. */
|
|
64
|
+
async write(accountId: string, text: unknown): Promise<NoteView> {
|
|
65
|
+
if (typeof text !== 'string') throw new PaperError('INVALID_ARGUMENT', '笔记内容必须是文本')
|
|
66
|
+
const bytes = byteLength(text)
|
|
67
|
+
if (bytes > this.maxBytes) {
|
|
68
|
+
throw new PaperError('INVALID_ARGUMENT', `笔记不能超过 ${Math.round(this.maxBytes / 1000)} KB(当前 ${Math.round(bytes / 1000)} KB)`)
|
|
69
|
+
}
|
|
70
|
+
const previous = this.queues.get(accountId) ?? Promise.resolve()
|
|
71
|
+
const next = previous.then(async () => {
|
|
72
|
+
try {
|
|
73
|
+
await writeFileAtomic(notePath(this.home, accountId), text)
|
|
74
|
+
} catch (error) {
|
|
75
|
+
throw new PaperError('INTERNAL', `保存笔记失败:${error instanceof Error ? error.message : String(error)}`)
|
|
76
|
+
}
|
|
77
|
+
})
|
|
78
|
+
this.queues.set(accountId, next.catch(() => undefined))
|
|
79
|
+
await next
|
|
80
|
+
return this.read(accountId)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function byteLength(text: string): number {
|
|
85
|
+
return Buffer.byteLength(text, 'utf8')
|
|
86
|
+
}
|
package/src/store/paths.ts
CHANGED
|
@@ -28,3 +28,8 @@ export function eventsPath(home: string, accountId: string): string {
|
|
|
28
28
|
export function backupsDir(home: string, accountId: string): string {
|
|
29
29
|
return join(accountDir(home, accountId), 'backups')
|
|
30
30
|
}
|
|
31
|
+
|
|
32
|
+
/** One account's free-form notes; lives beside the ledger, not in the registry. */
|
|
33
|
+
export function notePath(home: string, accountId: string): string {
|
|
34
|
+
return join(accountDir(home, accountId), 'note.md')
|
|
35
|
+
}
|
package/src/store/repo.ts
CHANGED
|
@@ -1,95 +1,57 @@
|
|
|
1
|
-
import { join, resolve } from 'node:path'
|
|
2
1
|
import type { Quote } from '../contract.js'
|
|
3
|
-
import { applyEvent,
|
|
2
|
+
import { applyEvent, verify } from '../core/ledger.js'
|
|
4
3
|
import { migrateLedger, ledgerVersionOf, MigrationUnavailable } from '../core/migrations.js'
|
|
5
|
-
import { prepareLedger, replay
|
|
4
|
+
import { prepareLedger, replay } from '../core/replay.js'
|
|
6
5
|
import type { AccountState, LedgerEvent } from '../core/types.js'
|
|
7
|
-
import {
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
6
|
+
import { readEventsFile } from './event-store.js'
|
|
7
|
+
import { LedgerRepoBase, type LedgerPlane, type LedgerRepoOptions } from './ledger-repo-base.js'
|
|
8
|
+
import type { AccountStore, LedgerSnapshot } from './port.js'
|
|
9
|
+
import { snapshotPath, writeSnapshot, type SnapshotFile } from './snapshots.js'
|
|
10
|
+
|
|
11
|
+
/** How the stock plane folds its event log; the storage mechanics are shared. */
|
|
12
|
+
const ACCOUNT_PLANE: LedgerPlane<AccountState, LedgerEvent> = {
|
|
13
|
+
label: 'paper-trading',
|
|
14
|
+
prepare: prepareLedger,
|
|
15
|
+
replay: (events, accountId) => replay(events, accountId),
|
|
16
|
+
applyEvent,
|
|
17
|
+
verify,
|
|
18
|
+
summary: state => ({
|
|
19
|
+
lastSeq: state.lastSeq,
|
|
20
|
+
tradeDate: state.tradeDate,
|
|
21
|
+
cashCents: state.cashCents,
|
|
22
|
+
blocked: state.blocked,
|
|
23
|
+
...(state.blockedReason === undefined ? {} : { blockedReason: state.blockedReason }),
|
|
24
|
+
}),
|
|
25
|
+
ledgerVersion: ledgerVersionOf,
|
|
26
|
+
dropEventsWhenBlocked: true,
|
|
22
27
|
}
|
|
23
28
|
|
|
24
29
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* Every write goes through one Promise queue and one sequence invariant, so a
|
|
28
|
-
* concurrent read cannot duplicate a day-boundary event. Repairs and resets use
|
|
29
|
-
* an atomic file replacement; a rejected write never touches the file.
|
|
30
|
+
* The stock account ledger: shared JSONL persistence plus the stock fold.
|
|
30
31
|
*
|
|
31
32
|
* Recovery is a first-class path: a ledger from a known older version is
|
|
32
33
|
* migrated in place (snapshot first), and any snapshot can be restored into the
|
|
33
|
-
* running process without restarting the host.
|
|
34
|
+
* running process without restarting the host. Only the migration chain and the
|
|
35
|
+
* migration-aware snapshot inspection are stock-specific.
|
|
34
36
|
*/
|
|
35
|
-
export class AccountRepo implements AccountStore {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
private loading: Promise<AccountState> | undefined
|
|
39
|
-
private queue: Promise<unknown> = Promise.resolve()
|
|
40
|
-
|
|
41
|
-
constructor(private readonly options: RepoOptions) {
|
|
42
|
-
this.store = new EventStore(eventsPath(options.home, options.accountId))
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Absolute path of `events.jsonl`, surfaced so a locked account is fixable. */
|
|
46
|
-
get ledgerPath(): string {
|
|
47
|
-
return this.store.filePath
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
private backups(): string {
|
|
51
|
-
return backupsDir(this.options.home, this.options.accountId)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
private async ensureLoaded(): Promise<AccountState> {
|
|
55
|
-
if (this.state !== undefined) return this.state
|
|
56
|
-
if (this.loading === undefined) this.loading = this.loadOnce()
|
|
57
|
-
return this.loading
|
|
37
|
+
export class AccountRepo extends LedgerRepoBase<AccountState, LedgerEvent> implements AccountStore {
|
|
38
|
+
constructor(options: LedgerRepoOptions) {
|
|
39
|
+
super(ACCOUNT_PLANE, options)
|
|
58
40
|
}
|
|
59
41
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
// its history. `undefined` means "already current" or "no migration path";
|
|
71
|
-
// only the latter locks, and replay below records the reason.
|
|
72
|
-
const migrated = prepared.issues.length === 0 ? await this.tryMigrate(prepared.events) : undefined
|
|
73
|
-
if (migrated !== undefined) {
|
|
74
|
-
this.state = migrated
|
|
75
|
-
} else {
|
|
76
|
-
const result = replay(source, this.options.accountId)
|
|
77
|
-
this.state = result.state
|
|
78
|
-
const issues = [...prepared.issues, ...result.issues]
|
|
79
|
-
if (issues.length > 0 && !result.state.blocked) {
|
|
80
|
-
await this.recordViolation(issues)
|
|
81
|
-
} else if (prepared.issues.length === 0 && prepared.duplicates > 0) {
|
|
82
|
-
this.state = await this.compact(prepared, result.state)
|
|
42
|
+
/** Refresh the in-memory mark-to-market cache; quote ticks are not ledger events. */
|
|
43
|
+
async markPrices(quotes: readonly Quote[]): Promise<AccountState> {
|
|
44
|
+
return this.enqueue(async () => {
|
|
45
|
+
const state = await this.ensureLoaded()
|
|
46
|
+
for (const quote of quotes) {
|
|
47
|
+
const position = state.positions[quote.symbol]
|
|
48
|
+
if (position !== undefined) {
|
|
49
|
+
position.lastPrice = quote.last
|
|
50
|
+
position.lastTs = quote.marketTs ?? undefined
|
|
51
|
+
}
|
|
83
52
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
// A known-good copy from before this session is what recovery has to fall
|
|
87
|
-
// back on; it is deliberately skipped for a blocked ledger (that file is the
|
|
88
|
-
// evidence, not the backup).
|
|
89
|
-
if (!this.state.blocked) {
|
|
90
|
-
await ensureAutoSnapshot(this.store, this.backups(), { logger: this.options.logger })
|
|
91
|
-
}
|
|
92
|
-
return this.state
|
|
53
|
+
return state
|
|
54
|
+
})
|
|
93
55
|
}
|
|
94
56
|
|
|
95
57
|
/**
|
|
@@ -99,7 +61,7 @@ export class AccountRepo implements AccountStore {
|
|
|
99
61
|
* original file byte for byte, and returning `undefined` lets the normal
|
|
100
62
|
* replay path lock the account with the version reason.
|
|
101
63
|
*/
|
|
102
|
-
|
|
64
|
+
protected override async tryMigrate(events: LedgerEvent[]): Promise<AccountState | undefined> {
|
|
103
65
|
let outcome
|
|
104
66
|
try {
|
|
105
67
|
outcome = migrateLedger(events)
|
|
@@ -139,138 +101,10 @@ export class AccountRepo implements AccountStore {
|
|
|
139
101
|
}
|
|
140
102
|
|
|
141
103
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
* Only reached when every duplicate was byte-equivalent apart from its
|
|
145
|
-
* `recordedAt` stamp, so the account values themselves are untouched.
|
|
146
|
-
*/
|
|
147
|
-
private async compact(prepared: PreparedLedger, state: AccountState): Promise<AccountState> {
|
|
148
|
-
const seq = state.lastSeq + 1
|
|
149
|
-
const event: LedgerEvent = {
|
|
150
|
-
seq,
|
|
151
|
-
id: `evt-${seq}`,
|
|
152
|
-
ts: new Date().toISOString(),
|
|
153
|
-
type: 'ledger.repaired',
|
|
154
|
-
payload: { dropped: prepared.duplicates },
|
|
155
|
-
}
|
|
156
|
-
try {
|
|
157
|
-
await writeSnapshot(this.store, this.backups(), 'repair')
|
|
158
|
-
await this.store.replace([...prepared.events, event])
|
|
159
|
-
applyEvent(state, event)
|
|
160
|
-
this.options.logger?.warn(`paper-trading: dropped ${prepared.duplicates} duplicate ledger event(s)`)
|
|
161
|
-
} catch (error) {
|
|
162
|
-
this.options.logger?.warn(`paper-trading: ledger repair failed, kept in memory only: ${String(error)}`)
|
|
163
|
-
}
|
|
164
|
-
return state
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
private async recordViolation(issues: string[]): Promise<void> {
|
|
168
|
-
const state = this.state
|
|
169
|
-
// A blocked account never grows its ledger: a new violation per tick would
|
|
170
|
-
// bury the original evidence under thousands of identical events.
|
|
171
|
-
if (state === undefined || state.blocked) return
|
|
172
|
-
const seq = state.lastSeq + 1
|
|
173
|
-
const event: LedgerEvent = {
|
|
174
|
-
seq,
|
|
175
|
-
id: `evt-${seq}`,
|
|
176
|
-
ts: new Date().toISOString(),
|
|
177
|
-
type: 'ledger.violation',
|
|
178
|
-
payload: { check: 'replay', expected: 'consistent', actual: issues.join('; ') },
|
|
179
|
-
}
|
|
180
|
-
await this.store.append([event])
|
|
181
|
-
applyEvent(state, event)
|
|
182
|
-
this.state = state
|
|
183
|
-
this.options.logger?.warn(`paper-trading: ledger violation, account blocked: ${issues.join('; ')}`)
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
async current(): Promise<AccountState> {
|
|
187
|
-
return this.ensureLoaded()
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
async transact<T>(build: (state: AccountState) => Transaction<T> | Promise<Transaction<T>>): Promise<TransactionOutcome<T>> {
|
|
191
|
-
return this.enqueue(async () => {
|
|
192
|
-
const state = await this.ensureLoaded()
|
|
193
|
-
const built = await build(state)
|
|
194
|
-
const events = built.events
|
|
195
|
-
if (events.length === 0) return { state, value: built.value, events }
|
|
196
|
-
if (state.blocked) {
|
|
197
|
-
this.options.logger?.warn(`paper-trading: account blocked, dropped ${events.length} event(s)`)
|
|
198
|
-
return { state, value: built.value, events: [] }
|
|
199
|
-
}
|
|
200
|
-
this.assertSequence(state, events)
|
|
201
|
-
await this.store.append(events)
|
|
202
|
-
for (const event of events) applyEvent(state, event)
|
|
203
|
-
const issues = verify(state)
|
|
204
|
-
this.state = state
|
|
205
|
-
if (issues.length > 0) await this.recordViolation(issues)
|
|
206
|
-
return { state: this.state ?? state, value: built.value, events }
|
|
207
|
-
})
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
async append(events: readonly LedgerEvent[]): Promise<AccountState> {
|
|
211
|
-
const outcome = await this.transact(() => ({ events: [...events], value: undefined }))
|
|
212
|
-
return outcome.state
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* Replace the file with a new ledger (reset, compaction).
|
|
217
|
-
*
|
|
218
|
-
* The replacement is validated and replayed before the atomic rename, so a
|
|
219
|
-
* reset never leaves a ledger that would lock the account on the next start.
|
|
104
|
+
* Snapshot inspection for the stock plane: unlike futures, an older snapshot
|
|
105
|
+
* may be migratable, and the reason must be reported before the restore.
|
|
220
106
|
*/
|
|
221
|
-
async
|
|
222
|
-
return this.enqueue(async () => {
|
|
223
|
-
this.assertSequence(emptyState(this.options.accountId), events)
|
|
224
|
-
const result = replay([...events], this.options.accountId)
|
|
225
|
-
if (result.issues.length > 0) {
|
|
226
|
-
throw new Error(`paper-trading: refusing an inconsistent ledger: ${result.issues.join('; ')}`)
|
|
227
|
-
}
|
|
228
|
-
// Settle any in-flight load first: it may still repair or block the old file.
|
|
229
|
-
await this.ensureLoaded()
|
|
230
|
-
await this.store.replace(events)
|
|
231
|
-
this.state = result.state
|
|
232
|
-
this.loading = Promise.resolve(result.state)
|
|
233
|
-
return this.state
|
|
234
|
-
})
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** Refresh the in-memory mark-to-market cache; quote ticks are not ledger events. */
|
|
238
|
-
async markPrices(quotes: readonly Quote[]): Promise<AccountState> {
|
|
239
|
-
return this.enqueue(async () => {
|
|
240
|
-
const state = await this.ensureLoaded()
|
|
241
|
-
for (const quote of quotes) {
|
|
242
|
-
const position = state.positions[quote.symbol]
|
|
243
|
-
if (position !== undefined) {
|
|
244
|
-
position.lastPrice = quote.last
|
|
245
|
-
position.lastTs = quote.marketTs ?? undefined
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
return state
|
|
249
|
-
})
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** Copy the event file into `backups/`, named after the reset timestamp. */
|
|
253
|
-
async backup(label: string): Promise<boolean> {
|
|
254
|
-
return this.enqueue(async () => {
|
|
255
|
-
const stamp = label.replace(/[:.]/g, '-')
|
|
256
|
-
return this.store.backup(`${this.backups()}/events-${stamp}.jsonl`)
|
|
257
|
-
})
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** Raw file text for `account/export`; `content: null` means "not created yet". */
|
|
261
|
-
async readLedger(): Promise<LedgerFile> {
|
|
262
|
-
return { path: resolve(this.store.filePath), content: await this.store.readText() }
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/** List snapshots with replay metadata, newest first. */
|
|
266
|
-
async snapshots(): Promise<LedgerSnapshot[]> {
|
|
267
|
-
const files = await listSnapshotFiles(this.backups())
|
|
268
|
-
const snapshots: LedgerSnapshot[] = []
|
|
269
|
-
for (const file of files) snapshots.push(await this.inspectSnapshot(file))
|
|
270
|
-
return snapshots
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
private async inspectSnapshot(file: SnapshotFile): Promise<LedgerSnapshot> {
|
|
107
|
+
protected override async inspectSnapshot(file: SnapshotFile): Promise<LedgerSnapshot> {
|
|
274
108
|
const base = {
|
|
275
109
|
name: file.name,
|
|
276
110
|
createdAt: new Date(file.mtimeMs).toISOString(),
|
|
@@ -324,13 +158,13 @@ export class AccountRepo implements AccountStore {
|
|
|
324
158
|
}
|
|
325
159
|
|
|
326
160
|
/**
|
|
327
|
-
* Replace the live ledger with one snapshot.
|
|
161
|
+
* Replace the live ledger with one snapshot, migrating it first when needed.
|
|
328
162
|
*
|
|
329
163
|
* Allowed while blocked: a locked account is exactly the case recovery exists
|
|
330
164
|
* for. Validation happens before anything is written, and the current file is
|
|
331
165
|
* snapshotted first so the recovery itself can be undone.
|
|
332
166
|
*/
|
|
333
|
-
async restore(name: string): Promise<AccountState> {
|
|
167
|
+
override async restore(name: string): Promise<AccountState> {
|
|
334
168
|
const file = snapshotPath(this.backups(), name)
|
|
335
169
|
return this.enqueue(async () => {
|
|
336
170
|
// Settle an in-flight load first: it may still repair/block the old file,
|
|
@@ -362,20 +196,4 @@ export class AccountRepo implements AccountStore {
|
|
|
362
196
|
return this.state
|
|
363
197
|
})
|
|
364
198
|
}
|
|
365
|
-
|
|
366
|
-
private assertSequence(state: AccountState, events: readonly LedgerEvent[]): void {
|
|
367
|
-
let expected = state.lastSeq + 1
|
|
368
|
-
for (const event of events) {
|
|
369
|
-
if (!Number.isInteger(event.seq) || event.seq !== expected) {
|
|
370
|
-
throw new Error(`paper-trading: ledger seq mismatch: expected ${expected}, got ${String(event.seq)}`)
|
|
371
|
-
}
|
|
372
|
-
expected += 1
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
private enqueue<T>(task: () => Promise<T>): Promise<T> {
|
|
377
|
-
const run = this.queue.then(task, task)
|
|
378
|
-
this.queue = run.then(() => undefined, () => undefined)
|
|
379
|
-
return run
|
|
380
|
-
}
|
|
381
199
|
}
|
package/src/store/shortlist.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { mkdir, readFile, rename
|
|
1
|
+
import { mkdir, readFile, rename } from 'node:fs/promises'
|
|
2
2
|
import { dirname, join } from 'node:path'
|
|
3
3
|
import { paperRoot } from './paths.js'
|
|
4
|
+
import { writeFileAtomic } from './atomic-file.js'
|
|
4
5
|
|
|
5
6
|
/** UI preference, deliberately not part of the account ledger. */
|
|
6
7
|
export class ShortlistStore {
|
|
@@ -26,10 +27,7 @@ export class ShortlistStore {
|
|
|
26
27
|
|
|
27
28
|
async write(symbols: string[]): Promise<string[]> {
|
|
28
29
|
const clean = [...new Set(symbols.map(symbol => symbol.trim()).filter(Boolean))].slice(0, 200)
|
|
29
|
-
await
|
|
30
|
-
const temporary = `${this.file}.tmp`
|
|
31
|
-
await writeFile(temporary, `${JSON.stringify({ symbols: clean }, null, 2)}\n`, { mode: 0o600 })
|
|
32
|
-
await rename(temporary, this.file)
|
|
30
|
+
await writeFileAtomic(this.file, `${JSON.stringify({ symbols: clean }, null, 2)}\n`)
|
|
33
31
|
return clean
|
|
34
32
|
}
|
|
35
33
|
}
|
package/src/store/snapshots.ts
CHANGED
|
@@ -23,9 +23,6 @@ export interface SnapshotFile {
|
|
|
23
23
|
/** `events-<reason>-<stamp>.jsonl`; the legacy names (`events-<stamp>.jsonl`) also match. */
|
|
24
24
|
const SNAPSHOT_NAME = /^events-[A-Za-z0-9._-]+\.jsonl$/
|
|
25
25
|
export const AUTO_SNAPSHOT_PREFIX = 'events-auto-'
|
|
26
|
-
export const PRE_MIGRATE_PREFIX = 'events-pre-migrate-'
|
|
27
|
-
export const PRE_RESTORE_PREFIX = 'events-pre-restore-'
|
|
28
|
-
export const MANUAL_PREFIX = 'events-manual-'
|
|
29
26
|
|
|
30
27
|
/** Keep only this many automatic snapshots; reset/repair/pre-* files are never pruned. */
|
|
31
28
|
const KEEP_AUTO = 10
|