@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,67 @@
1
+ /* 70 · plugin — sidebar glyph, cordis apply and the exported surface. */
2
+
3
+ const PANEL_ID = 'ft-paper-trading'
4
+
5
+ /** Candlestick glyph; the sidebar owns the button, label and tooltip. */
6
+ function PaperGlyph({ size }) {
7
+ const edge = Number(size) > 0 ? Number(size) : 16
8
+ return h('svg', {
9
+ width: edge, height: edge, viewBox: '0 0 16 16', 'aria-hidden': 'true',
10
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round',
11
+ },
12
+ h('path', { d: 'M2 13.5V10M5.5 13.5V6M9 13.5V8.5M12.5 13.5V3.5' }),
13
+ h('path', { d: 'M1.5 2.5h13', opacity: 0.35 }),
14
+ )
15
+ }
16
+
17
+ function apply(ctx) {
18
+ // The sidebar renders this row, so its text is host chrome and follows the
19
+ // host interface language — not the panel copy, which stays Chinese. The
20
+ // host re-reads `label` on every locale change, so a thunk is enough; the
21
+ // two product names match `locale/zh.json` and `locale/en.json`, which
22
+ // carry the same names into the plugin list.
23
+ let hostLocale
24
+ const panelLabel = () => {
25
+ let active
26
+ try {
27
+ active = hostLocale?.getLocale?.().active
28
+ } catch {
29
+ active = undefined
30
+ }
31
+ const tag = active ?? (typeof navigator === 'undefined' ? '' : navigator.language)
32
+ return String(tag).toLowerCase().startsWith('zh') ? '模拟交易' : 'Paper Trading'
33
+ }
34
+ // Optional: hosts without the locale service keep browser-language naming
35
+ // instead of losing the whole client half to an unmet injection.
36
+ ctx.inject(['locale'], scope => {
37
+ const locale = scope.get('locale')
38
+ if (locale === undefined) return () => {}
39
+ hostLocale = locale
40
+ return () => { if (hostLocale === locale) hostLocale = undefined }
41
+ })
42
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
43
+ name: 'sidebar.panellist',
44
+ id: PANEL_ID,
45
+ order: 30,
46
+ label: panelLabel,
47
+ }, PaperGlyph))
48
+ ctx.slots.inject('main', () => ctx.slots.register({
49
+ name: 'main',
50
+ key: PANEL_ID,
51
+ children: {
52
+ 'paperTrading.kline': { kind: 'single', scope: 'root' },
53
+ },
54
+ }, Dashboard))
55
+ // The declared slot stays empty until dsh_kline fills it through its
56
+ // optional host contract; without that plugin (or on an older chart) the
57
+ // rail keeps its built-in simplified chart instead.
58
+ ctx.inject(['klinePanels'], scope => {
59
+ const panels = scope.get('klinePanels')
60
+ if (panels === undefined) return () => {}
61
+ return panels.mount('paperTrading.kline')
62
+ })
63
+ }
64
+
65
+ const inject = ['slots']
66
+ exports.apply = apply
67
+ exports.inject = inject
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Account registry and comparison shapes (multi-account).
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/accounts
4
+ */
5
+
6
+ import type { EquityPoint } from './domain.js'
7
+
8
+ /** Asset families that own their own ledger. v1 only grows `stock`. */
9
+ export type AccountKind = 'stock' | 'futures'
10
+
11
+ /**
12
+ * One account's free-form notes.
13
+ *
14
+ * A single large text block the human rewrites however they like — not a log,
15
+ * no timestamps, never written by the model. Stored beside the ledger so the
16
+ * registry file stays small.
17
+ */
18
+ export interface NoteView {
19
+ text: string
20
+ /** ISO time of the last write, absent when the account has no note yet. */
21
+ updatedAt?: string
22
+ bytes: number
23
+ maxBytes: number
24
+ }
25
+
26
+ /**
27
+ * Registry entry for one ledger directory.
28
+ *
29
+ * `id` is the on-disk directory name and never changes; `name` is the
30
+ * user-editable display name and may repeat — `id` is the only reliable handle.
31
+ * `initialCashCents` is a creation intent kept until the account's first
32
+ * `account.opened` event has recorded it in the ledger.
33
+ *
34
+ * There is deliberately no session, model or owner field: this plugin knows
35
+ * nothing about sessions, and any caller may address any account.
36
+ */
37
+ export interface AccountMeta {
38
+ id: string
39
+ kind: AccountKind
40
+ name: string
41
+ createdAt: string
42
+ /**
43
+ * Archived: hidden from the picker and the comparison page, and frozen like a
44
+ * locked account. The ledger and registry entry stay; archiving is reversible.
45
+ */
46
+ archived: boolean
47
+ /** Locked accounts refuse state changes (orders, reset, cash, ledger restore). */
48
+ locked: boolean
49
+ initialCashCents?: number
50
+ /** The ledger directory vanished while the registry still lists the entry. */
51
+ missing?: boolean
52
+ }
53
+
54
+ /** One row of the comparison page: enough to draw a curve and rank by return. */
55
+ export interface CompareRow {
56
+ id: string
57
+ name: string
58
+ locked: boolean
59
+ missing?: boolean
60
+ initialCash: number
61
+ equity: number
62
+ pnl: number
63
+ pnlPct: number
64
+ todayPnl: number
65
+ maxDrawdownPct: number
66
+ tradeCount: number
67
+ /** Daily equity snapshots, oldest first; the client normalises before plotting. */
68
+ points: EquityPoint[]
69
+ }
70
+
71
+ /** `compare/get` payload: one row per visible account, unsorted. */
72
+ export interface CompareView {
73
+ accounts: CompareRow[]
74
+ }
75
+
76
+ /** `accounts/list` payload: the registry plus the defaults the panel needs. */
77
+ export interface AccountsView {
78
+ accounts: AccountMeta[]
79
+ /** Default account id per kind, e.g. `{ stock: 'default', futures: 'futures' }`. */
80
+ defaultIds: Record<AccountKind, string>
81
+ tickMs: number
82
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Cross-plane contract, common stock-domain shapes.
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/common
4
+ */
5
+
6
+ /**
7
+ * Cross-plane contract for the paper-trading plugin.
8
+ *
9
+ * Browser half and host half compile against these shapes; this module must stay
10
+ * free of runtime dependencies so both sides can import it as types.
11
+ * @module @dsh-ft/dsh-fft-paper-trading/contract
12
+ */
13
+
14
+ /** Exact Fetch route used by the browser half. */
15
+ export const PAPER_ROUTE = '/api/ft-paper-trading' as const
16
+ /** Request body cap; the route rejects anything larger before parsing. */
17
+ export const PAPER_MAX_BODY_BYTES = 256 * 1024
18
+ /**
19
+ * Ledger schema version. v4 stores every security as its canonical
20
+ * `code.exchange` id; older ledgers used the raw input and are incompatible.
21
+ */
22
+ export const PAPER_LEDGER_VERSION = 4
23
+
24
+ export type Side = 'buy' | 'sell'
25
+ export type OrderType = 'market' | 'limit'
26
+ export type OrderStatus = 'queued' | 'pending' | 'partially_filled' | 'filled' | 'canceled' | 'rejected' | 'expired'
27
+ export type DataState = 'ok' | 'stale' | 'denied' | 'failed'
28
+ export type Period = '7d' | '30d' | 'all'
29
+
30
+ /** Trading phase in Asia/Shanghai; the session table lives in core/session.ts. */
31
+ export type SessionPhase =
32
+ | 'pre_open'
33
+ | 'continuous_am'
34
+ | 'lunch'
35
+ | 'continuous_pm'
36
+ | 'auction_close'
37
+ | 'closed'
38
+
39
+ export interface PaperSettings {
40
+ /** Starting cash in cents. */
41
+ initialCashCents: number
42
+ commissionRate: number
43
+ minCommissionCents: number
44
+ stampDutyRate: number
45
+ transferFeeRate: number
46
+ enableT1: boolean
47
+ maxOrderNotionalCents: number
48
+ }
49
+
50
+ export const DEFAULT_SETTINGS: PaperSettings = {
51
+ // 100 万,A 股模拟盘的常规默认值:1 手贵州茅台(约 14.5 万)也能买,
52
+ // 10 万会让新账户连一手高价股都下不了单。
53
+ initialCashCents: 100_000_000,
54
+ commissionRate: 0.00025,
55
+ minCommissionCents: 500,
56
+ stampDutyRate: 0.0005,
57
+ transferFeeRate: 0.00001,
58
+ enableT1: true,
59
+ maxOrderNotionalCents: 0,
60
+ }
61
+
62
+ export interface Quote {
63
+ /** Canonical id, e.g. `000001.SZ`. */
64
+ symbol: string
65
+ name?: string
66
+ last: number
67
+ prevClose?: number
68
+ /** Market time of the quote/bar; null means it cannot fill. */
69
+ marketTs?: string | null
70
+ /** Fetch time, for latency display only. */
71
+ fetchedAt?: string
72
+ st?: boolean
73
+ status?: string
74
+ source?: string
75
+ }
76
+
77
+ export interface Bar {
78
+ time: string
79
+ open: number
80
+ high: number
81
+ low: number
82
+ close: number
83
+ volume?: number
84
+ }
85
+
86
+ export interface OrderDraft {
87
+ /** Canonical id, e.g. `000001.SZ`. */
88
+ symbol: string
89
+ side: Side
90
+ type: OrderType
91
+ qty: number
92
+ limitPrice?: number
93
+ /** Manual fallback when no quote is available (market orders only). */
94
+ price?: number
95
+ /** Optional journal note shown in the review view. */
96
+ note?: string
97
+ }
98
+
99
+ export interface OrderView {
100
+ id: string
101
+ requestId: string
102
+ /** Canonical id, e.g. `000001.SZ`. */
103
+ symbol: string
104
+ name?: string
105
+ side: Side
106
+ type: OrderType
107
+ qty: number
108
+ limitPrice?: number
109
+ status: OrderStatus
110
+ reason?: string
111
+ note?: string
112
+ createdAt: string
113
+ updatedAt: string
114
+ filledAt?: string
115
+ fillPrice?: number
116
+ filledQty?: number
117
+ remainingQty?: number
118
+ avgFillPrice?: number
119
+ amountCents?: number
120
+ feesCents?: number
121
+ }
122
+
123
+ export interface FillView {
124
+ id: string
125
+ orderId: string
126
+ /** Canonical id, e.g. `000001.SZ`. */
127
+ symbol: string
128
+ name?: string
129
+ side: Side
130
+ price: number
131
+ qty: number
132
+ amountCents: number
133
+ feesCents: number
134
+ ts: string
135
+ tradeDate: string
136
+ }
137
+
138
+ export interface PositionView {
139
+ /** Canonical id, e.g. `000001.SZ`. */
140
+ symbol: string
141
+ name?: string
142
+ qty: number
143
+ available: number
144
+ avgCost: number
145
+ lastPrice?: number
146
+ marketValueCents?: number
147
+ unrealizedPnlCents?: number
148
+ unrealizedPnlPct?: number
149
+ }
150
+
151
+ export interface AccountView {
152
+ accountId: string
153
+ currency: 'CNY'
154
+ initialCash: number
155
+ cash: number
156
+ marketValue: number
157
+ equity: number
158
+ pnl: number
159
+ pnlPct: number
160
+ todayPnl: number
161
+ /** Deposits minus withdrawals after the account opened, in yuan. */
162
+ netCashFlow: number
163
+ tradeDate: string
164
+ blocked: boolean
165
+ /** Why the account is locked, copied from the last `ledger.violation`. */
166
+ blockedReason?: string
167
+ /** Absolute path of `events.jsonl`, so a locked account can be repaired. */
168
+ ledgerPath?: string
169
+ positions: PositionView[]
170
+ settings: PaperSettings
171
+ }
172
+
173
+ export const DEFAULT_ACCOUNT_ID = 'default'
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Stock trading views: ticket, orders, positions, review, market, symbols.
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/domain
4
+ */
5
+
6
+ import type { DataState, OrderType, OrderView, PositionView, Quote, SessionPhase, Side } from './common.js'
7
+
8
+ export interface PreviewView {
9
+ symbol: string
10
+ side: Side
11
+ type: OrderType
12
+ qty: number
13
+ price: number
14
+ amountCents: number
15
+ commissionCents: number
16
+ stampCents: number
17
+ transferCents: number
18
+ totalFeesCents: number
19
+ cashAfterCents: number
20
+ availableQty: number
21
+ maxBuyQty: number
22
+ quote?: Quote
23
+ priceLimit?: PriceLimit
24
+ session?: MarketStatus
25
+ warnings: string[]
26
+ }
27
+
28
+ /**
29
+ * One-row outcome of a basket allocation.
30
+ *
31
+ * `ok` means the row can be bought with the computed `qty > 0`; every other
32
+ * status explains why nothing was allocated, so the client can show the row
33
+ * without inventing text of its own.
34
+ */
35
+ export type BasketRowStatus = 'ok' | 'zero_lot' | 'no_quote' | 'suspended'
36
+
37
+ /** A CSV problem; `line` is 1-based, 0 means the whole file. */
38
+ export interface BasketIssue {
39
+ line: number
40
+ message: string
41
+ }
42
+
43
+ /** One allocated row of `basket/preview`; the client renders this verbatim. */
44
+ export interface BasketPlanRow {
45
+ /** Canonical id, e.g. `000001.SZ`. */
46
+ symbol: string
47
+ name?: string
48
+ /** Normalised weight, 0..1. */
49
+ weight: number
50
+ /** `floor(budgetCents * weight)`, before the fee buy-back. */
51
+ targetCents: number
52
+ price?: number
53
+ qty: number
54
+ amountCents: number
55
+ feesCents: number
56
+ /** `amountCents / budgetCents`; rows without allocation report 0. */
57
+ actualWeight: number
58
+ status: BasketRowStatus
59
+ warning?: string
60
+ }
61
+
62
+ /** `basket/preview`: parse + allocation, read-only. */
63
+ export interface BasketPreview {
64
+ /** Effective budget: min(user input, available cash). */
65
+ budgetCents: number
66
+ /** Available cash before the basket. */
67
+ cashCents: number
68
+ rows: BasketPlanRow[]
69
+ issues: BasketIssue[]
70
+ warnings: string[]
71
+ totalAmountCents: number
72
+ totalFeesCents: number
73
+ /** `budgetCents - totalAmountCents - totalFeesCents`. */
74
+ residualCents: number
75
+ /** `cashCents - totalAmountCents - totalFeesCents`. */
76
+ cashAfterCents: number
77
+ session: MarketStatus
78
+ }
79
+
80
+ /** One confirmed row of a basket order; the caller sends back preview quantities. */
81
+ export interface BasketOrderInput {
82
+ /** Canonical id, e.g. `000001.SZ`. */
83
+ symbol: string
84
+ /** 100-share multiple, > 0. */
85
+ qty: number
86
+ }
87
+
88
+ export interface BasketOrderRowResult {
89
+ symbol: string
90
+ order?: OrderView
91
+ /** Present when the row was rejected; the readable reason, not just a code. */
92
+ error?: string
93
+ }
94
+
95
+ /** `basket/place`: per-row outcome plus the cash left after the whole batch. */
96
+ export interface BasketOrderResult {
97
+ batchId: string
98
+ rows: BasketOrderRowResult[]
99
+ cashAfterCents: number
100
+ }
101
+
102
+ export interface EquityPoint {
103
+ date: string
104
+ equity: number
105
+ cash: number
106
+ }
107
+
108
+ export interface ReviewView {
109
+ equityCurve: EquityPoint[]
110
+ maxDrawdownPct: number
111
+ tradeCount: number
112
+ buyCount: number
113
+ sellCount: number
114
+ totalFees: number
115
+ realizedPnl: number
116
+ days: number
117
+ }
118
+
119
+ export interface TickView {
120
+ tradeDate: string
121
+ filled: OrderView[]
122
+ expired: OrderView[]
123
+ quotes: Quote[]
124
+ notices: string[]
125
+ }
126
+
127
+ /**
128
+ * Which trading-day source answered, and why it degraded.
129
+ *
130
+ * `fallback` means Monday–Friday is being used instead of the exchange
131
+ * calendar, so holidays are treated as trading days until the source recovers.
132
+ */
133
+ export interface CalendarStatus {
134
+ source: 'ftshare' | 'fallback'
135
+ /** Why the fallback is in use; present only while degraded. */
136
+ reason?: string
137
+ /** ISO-8601 of the last check against the source. */
138
+ checkedAt?: string
139
+ }
140
+
141
+ export interface MarketStatus {
142
+ phase: SessionPhase
143
+ tradeDate: string
144
+ canSubmit: boolean
145
+ canMatch: boolean
146
+ /** ISO-8601 of the next phase boundary. */
147
+ nextBoundary?: string
148
+ reason?: string
149
+ /** Trading-day source; `fallback` means the session table is a weekday estimate. */
150
+ calendar?: CalendarStatus
151
+ }
152
+
153
+ export interface PriceLimit {
154
+ upper: number
155
+ lower: number
156
+ ratio: number
157
+ source: 'prev-close' | 'limit-list' | 'unknown'
158
+ }
159
+
160
+ export interface SymbolHit {
161
+ /** Canonical id, e.g. `000001.SZ`. */
162
+ symbol: string
163
+ name: string
164
+ }
165
+
166
+ export interface MarketListResult {
167
+ state: DataState
168
+ quotes: Quote[]
169
+ page: number
170
+ total?: number
171
+ notice?: string
172
+ /** Upstream error code (e.g. `route_not_allowed`), for the banner reason. */
173
+ noticeCode?: string
174
+ }
175
+
176
+ export interface DayReport {
177
+ date: string
178
+ equity: number
179
+ cash: number
180
+ dayPnl: number
181
+ fees: number
182
+ available: number
183
+ positions: PositionView[]
184
+ gaps: Record<string, number>
185
+ closeSource: 'daily' | 'last' | 'missing'
186
+ }
187
+
188
+ export interface CashFlowEntry {
189
+ ts: string
190
+ type: 'open' | 'reset' | 'buy' | 'sell' | 'deposit' | 'withdraw'
191
+ amount: number
192
+ balance: number
193
+ ref?: string
194
+ }
195
+
196
+ export interface ShortlistView {
197
+ symbols: string[]
198
+ }
199
+
200
+ export interface RoundTrip {
201
+ symbol: string
202
+ name?: string
203
+ qty: number
204
+ cost: number
205
+ proceeds: number
206
+ pnl: number
207
+ holdingDays: number
208
+ }
209
+
210
+ /**
211
+ * Which data source the panel is pricing against.
212
+ *
213
+ * `configured` — an FTShare API key is configured and usable.
214
+ * `free` — no key: the anonymous free tier (daily-close quotes, 500/day).
215
+ * `none` — the FTShare data service is not installed.
216
+ * `invalid` — a key exists but cannot be used (rejected or unreadable).
217
+ */
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Error codes surfaced through RpcFailure and the agent tools.
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/errors
4
+ */
5
+
6
+ export type ErrorCode =
7
+ | 'ACCOUNT_BLOCKED'
8
+ | 'INVALID_ARGUMENT'
9
+ | 'INVALID_SYMBOL'
10
+ | 'INVALID_QTY'
11
+ | 'INVALID_LOT'
12
+ | 'INSUFFICIENT_CASH'
13
+ | 'INSUFFICIENT_POSITION'
14
+ | 'T1_LOCKED'
15
+ | 'MAX_NOTIONAL'
16
+ | 'ORDER_NOT_FOUND'
17
+ | 'ORDER_NOT_PENDING'
18
+ | 'QUOTE_UNAVAILABLE'
19
+ | 'SESSION_CLOSED'
20
+ | 'AUCTION_ONLY'
21
+ | 'PRICE_LIMIT'
22
+ | 'SUSPENDED'
23
+ | 'UNSUPPORTED_INSTRUMENT'
24
+ | 'LEDGER_RESTORE_FAILED'
25
+ | 'ACCOUNT_NOT_FOUND'
26
+ | 'ACCOUNT_LIMIT'
27
+ | 'ACCOUNT_LOCKED'
28
+ | 'ACCOUNT_ARCHIVED'
29
+ | 'INSUFFICIENT_MARGIN'
30
+ | 'CONTRACT_NOT_FOUND'
31
+ | 'CONTRACT_EXPIRED'
32
+ | 'NO_VOLUME'
33
+ | 'LIMIT_UNAVAILABLE'
34
+ | 'MARGIN_UNAVAILABLE'
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The paper-trading contract, split by domain.
3
+ *
4
+ * Consumers keep importing `../contract.js` (a barrel); a module that only
5
+ * needs one area can import it directly from here.
6
+ * @module @dsh-ft/dsh-fft-paper-trading/contract
7
+ */
8
+
9
+ export * from './common.js'
10
+ export * from './accounts.js'
11
+ export * from './domain.js'
12
+ export * from './ledger.js'
13
+ export * from './market.js'
14
+ export * from './rpc.js'
15
+ export * from './errors.js'
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Ledger recovery views (export, snapshots).
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/ledger
4
+ */
5
+
6
+ /** `account/export`: the raw ledger file, so a locked account can be inspected. */
7
+ export interface LedgerExport {
8
+ /** Absolute path of `events.jsonl`. */
9
+ path: string
10
+ /** False when no ledger file exists yet. */
11
+ exists: boolean
12
+ /** Raw JSONL text; omitted when `exists` is false. */
13
+ content?: string
14
+ notice?: string
15
+ }
16
+
17
+ /** One ledger snapshot as listed to the panel, an agent, or a human. */
18
+ export interface LedgerSnapshotView {
19
+ name: string
20
+ createdAt: string
21
+ bytes: number
22
+ /** Version stored in the snapshot, before any migration. */
23
+ ledgerVersion: number
24
+ lastSeq: number
25
+ tradeDate: string
26
+ /** Free cash at that point, in yuan. */
27
+ cash: number
28
+ /** Replays cleanly at the current ledger version (after migration). */
29
+ valid: boolean
30
+ /** Needs the loader's migration step before restoring. */
31
+ migratable: boolean
32
+ problem?: string
33
+ }
34
+
35
+ /** `ledger/list`: everything needed to choose a recovery point. */
36
+ export interface LedgerSnapshotsView {
37
+ path: string
38
+ blocked: boolean
39
+ blockedReason?: string
40
+ ledgerVersion?: number
41
+ snapshots: LedgerSnapshotView[]
42
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Round trips and market-data-source state.
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/market
4
+ */
5
+
6
+ export type DataSourceState = 'configured' | 'free' | 'none' | 'invalid'
7
+
8
+ /**
9
+ * Why the last market-data call failed, as a code the UI can act on.
10
+ *
11
+ * The upstream classification (`state` + `notice.code`) decides this. Text is
12
+ * only read for one thing the codes cannot express: a spent quota shares its
13
+ * code with a real outage, so the exhausted wording is matched instead.
14
+ */
15
+ export type DataProblemReason =
16
+ | 'no-key'
17
+ | 'invalid-key'
18
+ | 'plan-denied'
19
+ | 'quota'
20
+ | 'network'
21
+ | 'upstream'
22
+
23
+ /** One observed data failure; the latest one drives the panel banner. */
24
+ export interface DataProblem {
25
+ reason: DataProblemReason
26
+ /** Readable upstream cause, already trimmed for display. */
27
+ message: string
28
+ /** ISO-8601 time of the observation. */
29
+ at: string
30
+ }
31
+
32
+ /** Read-only data-source state for the panel header; never carries the key itself. */
33
+ export interface DataSourceStatus {
34
+ state: DataSourceState
35
+ /** Short, user-facing cause for `invalid` or a degraded `configured`. */
36
+ message?: string
37
+ /** Latest observed data failure, cleared by the next successful quote call. */
38
+ problem?: DataProblem
39
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * RPC envelope shared by the browser and host halves.
3
+ * @module @dsh-ft/dsh-fft-paper-trading/contract/rpc
4
+ */
5
+
6
+ export interface RpcSuccess<T> { ok: true; value: T }
7
+ export interface RpcFailure { ok: false; error: { code: string; message: string; details?: Record<string, unknown> } }
8
+ export type RpcResult<T> = RpcSuccess<T> | RpcFailure
9
+
10
+ export interface RpcRequest {
11
+ endpoint: string
12
+ payload?: unknown
13
+ /** Target account id or display name; omitted means the kind's default account. */
14
+ account?: string
15
+ }