@dsh-ft/dsh-fft-paper-trading 0.6.0 → 0.6.2

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 (110) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +4 -4
  3. package/lib/agent/format.d.ts.map +1 -1
  4. package/lib/agent/format.js +4 -0
  5. package/lib/agent/format.js.map +1 -1
  6. package/lib/agent/tools.d.ts.map +1 -1
  7. package/lib/agent/tools.js +5 -3
  8. package/lib/agent/tools.js.map +1 -1
  9. package/lib/client.js +76 -13
  10. package/lib/contract.d.ts.map +1 -1
  11. package/lib/contract.js +3 -1
  12. package/lib/contract.js.map +1 -1
  13. package/lib/core/risk.d.ts.map +1 -1
  14. package/lib/core/risk.js +10 -2
  15. package/lib/core/risk.js.map +1 -1
  16. package/lib/core/views.js +2 -2
  17. package/lib/core/views.js.map +1 -1
  18. package/lib/data/ftshare-trading-calendar.d.ts +47 -12
  19. package/lib/data/ftshare-trading-calendar.d.ts.map +1 -1
  20. package/lib/data/ftshare-trading-calendar.js +156 -44
  21. package/lib/data/ftshare-trading-calendar.js.map +1 -1
  22. package/lib/service/paper-service.d.ts +1 -1
  23. package/lib/service/paper-service.d.ts.map +1 -1
  24. package/lib/service/paper-service.js +24 -12
  25. package/lib/service/paper-service.js.map +1 -1
  26. package/lib/service/rpc.d.ts.map +1 -1
  27. package/lib/service/rpc.js +12 -1
  28. package/lib/service/rpc.js.map +1 -1
  29. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +98 -0
  30. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +116 -26
  31. package/node_modules/@ftshare-lab/dsh-kline/README.md +125 -25
  32. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +38 -0
  33. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +3 -9
  34. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +63 -269
  35. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +15 -3
  36. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +99 -0
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +15 -0
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +33 -0
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +12 -3
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +91 -2
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +64 -13
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +3356 -787
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +96 -19
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +18 -0
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +19 -2
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +17 -0
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +55 -0
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +47 -0
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +32 -0
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +2 -0
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +4 -0
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +1 -1
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +2 -0
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +3 -2
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +1 -1
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +1 -0
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +14 -0
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +11 -3
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +2 -2
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -36
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +2 -1
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +35 -4
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +46 -0
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +45 -0
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +21 -36
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +5 -0
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +11 -0
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +3 -0
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +5 -0
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +3 -0
  73. package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -5
  74. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +2 -0
  75. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +27 -0
  76. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +180 -49
  77. package/node_modules/@ftshare-lab/dsh-kline/server.py +300 -34
  78. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +119 -0
  79. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +176 -0
  80. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +260 -0
  81. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +1 -1
  82. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +22 -3
  83. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +141 -16
  84. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +466 -0
  85. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +63 -0
  86. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +3 -0
  87. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +13 -7
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +117 -0
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +58 -3
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +164 -40
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +83 -0
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +78 -21
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +60 -0
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +125 -0
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +165 -0
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +162 -0
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +114 -0
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +170 -0
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +87 -0
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +228 -0
  101. package/package.json +3 -3
  102. package/src/agent/format.ts +3 -0
  103. package/src/agent/tools.ts +5 -3
  104. package/src/client/index.js +75 -12
  105. package/src/contract.ts +3 -1
  106. package/src/core/risk.ts +10 -2
  107. package/src/core/views.ts +2 -2
  108. package/src/data/ftshare-trading-calendar.ts +184 -45
  109. package/src/service/paper-service.ts +22 -19
  110. package/src/service/rpc.ts +12 -1
@@ -4,12 +4,37 @@ import type { TradingCalendarPort } from './trading-calendar-port.js'
4
4
  import { WeekdayTradingCalendar } from './trading-calendar-port.js'
5
5
  import type { FtshareDataLike } from './ftshare-market-data.js'
6
6
 
7
- /** How long a failed lookup is trusted before the adapter tries upstream again. */
7
+ /** First gap between two upstream attempts after a failure; doubles per failure. */
8
8
  export const CALENDAR_RETRY_MS = 60_000
9
9
 
10
+ /** Ceiling of the failure backoff. */
11
+ export const CALENDAR_RETRY_MAX_MS = 600_000
12
+
10
13
  /** Longest reason kept for display; upstream errors can be paragraphs. */
11
14
  const REASON_MAX_LENGTH = 120
12
15
 
16
+ const SHANGHAI_OFFSET_MS = 8 * 3_600_000
17
+
18
+ /** Trading days as `YYYY-MM-DD`, ascending. */
19
+ type DayList = string[]
20
+
21
+ /** One calendar year's worth of answers, as the adapter remembers them. */
22
+ interface YearEntry {
23
+ source: 'ftshare' | 'fallback'
24
+ /** Present when `source` is `ftshare`. */
25
+ days?: DayList
26
+ /** Why the weekday estimate is in use; present when `source` is `fallback`. */
27
+ reason?: string
28
+ /** ISO-8601 of the attempt that produced this entry. */
29
+ checkedAt: string
30
+ /** When the last attempt failed, for the backoff. */
31
+ failedAt?: number
32
+ /** Consecutive failures, so the backoff can double. */
33
+ failures: number
34
+ /** A quota/credential answer: never retried again this natural day. */
35
+ final: boolean
36
+ }
37
+
13
38
  function apiDate(date: string): number {
14
39
  return Number(date.replaceAll('-', ''))
15
40
  }
@@ -26,11 +51,34 @@ function reasonOf(error: unknown): string {
26
51
  return flat.length <= REASON_MAX_LENGTH ? flat : `${flat.slice(0, REASON_MAX_LENGTH)}…`
27
52
  }
28
53
 
54
+ /**
55
+ * Whether an answer is a quota answer, where retrying only burns the window.
56
+ *
57
+ * The gateway reports its daily ceiling as `UPSTREAM_UNAVAILABLE` with the quota
58
+ * in the text (`最近 1 天最多访问 500 次`), so the code alone does not identify it.
59
+ */
60
+ function isQuota(text: string, retryable: boolean | undefined): boolean {
61
+ if (retryable === false && /UPSTREAM_UNAVAILABLE/u.test(text)) return true
62
+ return /(最多访问|访问次数|调用次数|频率|限流|配额|quota|rate limit|too many requests)/iu.test(text)
63
+ }
64
+
65
+ /** The years a `YYYY-MM-DD` range touches, ascending. */
66
+ function yearsOf(from: string, to: string): string[] {
67
+ const first = Number(from.slice(0, 4))
68
+ const last = Number(to.slice(0, 4))
69
+ if (!Number.isFinite(first) || !Number.isFinite(last) || last < first) return [from.slice(0, 4)]
70
+ const years: string[] = []
71
+ for (let year = first; year <= last && years.length < 8; year += 1) years.push(String(year))
72
+ return years
73
+ }
74
+
29
75
  export interface FtshareTradingCalendarOptions {
30
- /** Clock for the retry window; injectable so tests do not wait a minute. */
76
+ /** Clock for the year cache, the backoff and the natural-day reset. */
31
77
  now?: () => Date
32
- /** Retry gap after a failure; defaults to {@link CALENDAR_RETRY_MS}. */
78
+ /** First retry gap after a failure; defaults to {@link CALENDAR_RETRY_MS}. */
33
79
  retryMs?: number
80
+ /** Backoff ceiling; defaults to {@link CALENDAR_RETRY_MAX_MS}. */
81
+ retryMaxMs?: number
34
82
  }
35
83
 
36
84
  /**
@@ -39,82 +87,173 @@ export interface FtshareTradingCalendarOptions {
39
87
  * The upstream schema takes YYYYMMDD integers and returns an integer
40
88
  * `trade_dates` array; this adapter is the only place that converts them.
41
89
  *
42
- * A failure falls back to weekdays and **is not cached**: the adapter retries
43
- * the upstream after {@link retryMs} so a recovered network or a new quota
44
- * window flips {@link status} back instead of keeping the holiday calendar
45
- * degraded for the rest of the day. Only successful answers are cached.
90
+ * **Cached per calendar year, not per query.** An exchange calendar changes once
91
+ * a year, so the first question fetches the whole year once and every later
92
+ * question — any range, any caller, the 5 s match tick included — is answered
93
+ * from that memory. The previous version cached per exact `from:to` range and
94
+ * re-asked upstream after every failure, which let two 5 s schedulers issue
95
+ * ~120 calls/hour against an endpoint with a daily quota.
96
+ *
97
+ * **Failures are remembered too.** A failure falls back to weekdays, records
98
+ * why, and suppresses further attempts with an exponential backoff (1, 2, 4 …
99
+ * ≤ {@link CALENDAR_RETRY_MAX_MS}). A quota answer is not retried at all until
100
+ * the next Shanghai natural day, because retrying it only spends what is left of
101
+ * the window. Concurrent ticks share one in-flight question.
102
+ *
103
+ * The degradation is never silent: {@link source} stays `fallback` and
104
+ * {@link status} carries the upstream reason.
46
105
  */
47
106
  export class FtshareTradingCalendar implements TradingCalendarPort {
48
107
  private readonly fallback = new WeekdayTradingCalendar()
49
108
  private readonly now: () => Date
50
109
  private readonly retryMs: number
51
- private readonly cache = new Map<string, string[]>()
52
- private degraded = false
53
- private lastError: string | undefined
54
- private checkedAt: string | undefined
55
- private failedAt: number | undefined
110
+ private readonly retryMaxMs: number
111
+ /** `YYYY` → that year's answer. */
112
+ private readonly years = new Map<string, YearEntry>()
113
+ /** `YYYY` → in-flight upstream question, so parallel ticks share one call. */
114
+ private readonly inflight = new Map<string, Promise<DayList>>()
115
+ private latest: YearEntry | undefined
56
116
 
57
117
  constructor(private readonly service: FtshareDataLike, options: FtshareTradingCalendarOptions = {}) {
58
118
  this.now = options.now ?? (() => new Date())
59
119
  this.retryMs = options.retryMs ?? CALENDAR_RETRY_MS
120
+ this.retryMaxMs = options.retryMaxMs ?? CALENDAR_RETRY_MAX_MS
60
121
  }
61
122
 
123
+ /** Which source answered the latest calendar question. */
62
124
  get source(): 'ftshare' | 'fallback' {
63
- return this.degraded ? 'fallback' : 'ftshare'
125
+ return this.latest?.source ?? 'fallback'
64
126
  }
65
127
 
66
128
  get status(): CalendarStatus {
129
+ const latest = this.latest
130
+ if (latest === undefined) return this.fallback.status
67
131
  return {
68
- source: this.source,
69
- ...(this.degraded && this.lastError !== undefined ? { reason: this.lastError } : {}),
70
- ...(this.checkedAt === undefined ? {} : { checkedAt: this.checkedAt }),
132
+ source: latest.source,
133
+ ...latest.reason !== undefined ? { reason: latest.reason } : {},
134
+ checkedAt: latest.checkedAt,
71
135
  }
72
136
  }
73
137
 
74
138
  async tradingDays(from: string, to: string): Promise<string[]> {
75
- const key = `${from}:${to}`
76
- const cached = this.cache.get(key)
77
- if (cached !== undefined) return cached
139
+ const answers = await Promise.all(yearsOf(from, to).map(year => this.daysOfYear(year)))
140
+ return answers.flat().filter(day => day >= from && day <= to).sort()
141
+ }
142
+
143
+ async isTradingDay(date: string): Promise<boolean> {
144
+ return (await this.tradingDays(date, date)).includes(date)
145
+ }
146
+
147
+ async nextTradingDay(date: string): Promise<string> {
148
+ const days = await this.tradingDays(addDays(date, 1), addDays(date, 30))
149
+ return days[0] ?? (await this.fallback.nextTradingDay(date))
150
+ }
151
+
152
+ /**
153
+ * Answer one calendar year from memory, upstream, or the weekday estimate.
154
+ * @param year - `YYYY`.
155
+ * @returns That year's trading days; empty only if the estimate is empty too.
156
+ */
157
+ private async daysOfYear(year: string): Promise<DayList> {
158
+ const entry = this.years.get(year)
159
+ if (entry?.source === 'ftshare' && entry.days !== undefined) return entry.days
160
+ if (entry?.source === 'fallback' && this.suppressed(entry)) return await this.estimate(year)
161
+ const pending = this.inflight.get(year)
162
+ if (pending !== undefined) return pending
163
+ const question = this.ask(year).finally(() => { this.inflight.delete(year) })
164
+ this.inflight.set(year, question)
165
+ return question
166
+ }
167
+
168
+ /** Whether a failed year must not be asked again yet. */
169
+ private suppressed(entry: YearEntry): boolean {
170
+ const now = this.now()
171
+ // A quota answer is final until the next Shanghai natural day: asking again
172
+ // inside the same window only spends calls the window no longer has.
173
+ if (entry.final) return this.naturalDay(now) <= this.naturalDayOf(entry.checkedAt)
174
+ if (entry.failedAt === undefined) return false
175
+ return now.getTime() - entry.failedAt < this.retryGap(entry.failures)
176
+ }
177
+
178
+ /** Exponential backoff by consecutive failures, capped at {@link retryMaxMs}. */
179
+ private retryGap(failures: number): number {
180
+ return Math.min(this.retryMs * 2 ** Math.max(0, failures - 1), this.retryMaxMs)
181
+ }
182
+
183
+ /** `/^YYYY-MM-DD/` of a natural day in Shanghai. */
184
+ private naturalDay(now: Date): string {
185
+ return new Date(now.getTime() + SHANGHAI_OFFSET_MS).toISOString().slice(0, 10)
186
+ }
187
+
188
+ private naturalDayOf(iso: string | undefined): string {
189
+ return iso === undefined ? '' : this.naturalDay(new Date(iso))
190
+ }
191
+
192
+ private async estimate(year: string): Promise<DayList> {
193
+ return await this.fallback.tradingDays(`${year}-01-01`, `${year}-12-31`)
194
+ }
195
+
196
+ /** Ask upstream for the whole year once, then remember the outcome. */
197
+ private async ask(year: string): Promise<DayList> {
78
198
  const now = this.now()
79
- // Inside the retry window a failed lookup serves the weekday estimate
80
- // without hitting upstream again, but the result is intentionally not
81
- // cached: the next window gets a real answer.
82
- if (this.degraded && this.failedAt !== undefined && now.getTime() - this.failedAt < this.retryMs) {
83
- return this.fallback.tradingDays(from, to)
199
+ const from = `${year}-01-01`
200
+ const to = `${year}-12-31`
201
+ const outcome = await this.fetch(from, to)
202
+ if (outcome.ok) {
203
+ const entry: YearEntry = { source: 'ftshare', days: outcome.days, checkedAt: now.toISOString(), failures: 0, final: false }
204
+ this.years.set(year, entry)
205
+ this.latest = entry
206
+ return outcome.days
84
207
  }
208
+ const previous = this.years.get(year)
209
+ const failures = (previous?.source === 'fallback' ? previous.failures : 0) + 1
210
+ const reason = reasonOf(outcome.error)
211
+ const entry: YearEntry = {
212
+ source: 'fallback',
213
+ reason: outcome.final ? `${reason}(本自然日不再重试)` : reason,
214
+ checkedAt: now.toISOString(),
215
+ failedAt: now.getTime(),
216
+ failures,
217
+ final: outcome.final,
218
+ }
219
+ this.years.set(year, entry)
220
+ this.latest = entry
221
+ return await this.estimate(year)
222
+ }
223
+
224
+ /** One upstream question; classifies the answer without touching the cache. */
225
+ private async fetch(from: string, to: string): Promise<{ ok: true; days: DayList } | { ok: false; error: unknown; final: boolean }> {
85
226
  try {
86
227
  const result = await this.service.call('ft_v1_time_trading_calendar', {
87
228
  market: 'cn',
88
229
  start_date: apiDate(from),
89
230
  end_date: apiDate(to),
90
231
  })
91
- if (result.state === 'denied' || result.state === 'failed') throw new Error(result.notice?.message ?? result.state)
232
+ if (result.state === 'denied' || result.state === 'failed') {
233
+ const text = `${result.notice?.code ?? ''} ${result.notice?.message ?? result.state}`.trim()
234
+ return {
235
+ ok: false,
236
+ error: new Error(result.notice?.message ?? result.state),
237
+ // The quota text is the only quota fact this port carries; `retryable`
238
+ // is passed through only by adapters that keep it.
239
+ final: result.state === 'denied' || isQuota(text, undefined),
240
+ }
241
+ }
92
242
  const rows = Array.isArray(result.rows) ? result.rows : []
93
243
  const raw = rows[0]?.trade_dates
94
244
  const days = (Array.isArray(raw) ? raw : [])
95
245
  .map(isoDate)
96
246
  .filter((value): value is string => value !== undefined)
97
- this.degraded = false
98
- this.lastError = undefined
99
- this.failedAt = undefined
100
- this.checkedAt = now.toISOString()
101
- this.cache.set(key, days)
102
- return days
247
+ .sort()
248
+ if (days.length === 0) {
249
+ // An empty year is not an answer: caching it would read as "no trading
250
+ // day ever" and freeze settlement, so it counts as a failure instead.
251
+ return { ok: false, error: new Error(`上游未返回 ${from.slice(0, 4)} 年交易日历`), final: false }
252
+ }
253
+ return { ok: true, days }
103
254
  } catch (error) {
104
- this.degraded = true
105
- this.lastError = reasonOf(error)
106
- this.failedAt = now.getTime()
107
- this.checkedAt = now.toISOString()
108
- return this.fallback.tradingDays(from, to)
255
+ const text = error instanceof Error ? error.message : String(error)
256
+ return { ok: false, error, final: isQuota(text, undefined) }
109
257
  }
110
258
  }
111
-
112
- async isTradingDay(date: string): Promise<boolean> {
113
- return (await this.tradingDays(date, date)).includes(date)
114
- }
115
-
116
- async nextTradingDay(date: string): Promise<string> {
117
- const days = await this.tradingDays(addDays(date, 1), addDays(date, 30))
118
- return days[0] ?? (await this.fallback.nextTradingDay(date))
119
- }
120
259
  }
@@ -417,14 +417,12 @@ export class PaperService {
417
417
  const now = this.ts()
418
418
  const phase = this.phaseFor(state, now)
419
419
  const matchable = canMatch(phase)
420
- if (!canSubmit(phase, draft.type)) {
421
- throw new PaperError(
422
- phase === 'closed' ? 'SESSION_CLOSED' : 'AUCTION_ONLY',
423
- phase === 'auction_close'
424
- ? '收盘竞价暂不支持模拟撮合'
425
- : draft.type === 'market' ? '当前时段不接受市价单,请改限价预埋' : '当前时段不接受委托',
426
- 409,
427
- )
420
+ // A market order outside continuous trading cannot fill now, but a real
421
+ // broker still accepts it as an order for the next matching window, so it
422
+ // is taken as a queued order instead of a rejection. The closing auction
423
+ // has no window left today, so it stays rejected.
424
+ if (phase === 'auction_close') {
425
+ throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合', 409)
428
426
  }
429
427
  const quote = await this.quoteFor(draft)
430
428
  const tradeDate = await this.orderDateFor(state, now, phase)
@@ -475,9 +473,10 @@ export class PaperService {
475
473
  })
476
474
  const session = await this.marketStatusAt(state, this.ts())
477
475
  const warnings = [...parsed.warnings, ...allocation.warnings]
478
- // The plan is still readable after the close; the hint is why the client
479
- // must keep the confirm button disabled.
480
- if (!session.canMatch) warnings.push('当前时段不能市价成交,只能预览')
476
+ // The plan is still readable after the close: the rows stay visible, and a
477
+ // confirmed batch is simply planted for the next matching window.
478
+ if (session.phase === 'auction_close') warnings.push('收盘竞价暂不支持模拟撮合,请等收盘后再下单')
479
+ else if (!session.canMatch) warnings.push('当前时段不能立即成交,确认后委托将在下一交易时段撮合')
481
480
  return {
482
481
  budgetCents: budget,
483
482
  cashCents,
@@ -509,12 +508,10 @@ export class PaperService {
509
508
  if (state.blocked) throw this.blocked(state)
510
509
  const now = this.ts()
511
510
  const phase = this.phaseFor(state, now)
512
- if (!canSubmit(phase, 'market')) {
513
- throw new PaperError(
514
- phase === 'closed' ? 'SESSION_CLOSED' : 'AUCTION_ONLY',
515
- '当前时段不接受市价单,请改限价预埋或连续竞价时段重试',
516
- 409,
517
- )
511
+ // Outside continuous trading the batch is queued like a single market
512
+ // order; only the closing auction is rejected because no window follows.
513
+ if (phase === 'auction_close') {
514
+ throw new PaperError('AUCTION_ONLY', '收盘竞价暂不支持模拟撮合', 409)
518
515
  }
519
516
  const matchable = canMatch(phase)
520
517
 
@@ -985,15 +982,21 @@ export class PaperService {
985
982
  * the current defaults, so a legacy account does not inherit its missing
986
983
  * fields. The write is an atomic temp-file rename.
987
984
  */
988
- async reset(confirm: boolean): Promise<AccountView> {
985
+ async reset(confirm: boolean, initialCashCents?: number): Promise<AccountView> {
989
986
  if (confirm !== true) throw new PaperError('INVALID_ARGUMENT', '重置需要 confirm=true', 400)
987
+ if (initialCashCents !== undefined && (!Number.isSafeInteger(initialCashCents) || initialCashCents <= 0)) {
988
+ throw new PaperError('INVALID_ARGUMENT', '初始资金必须是正整数(分)', 400)
989
+ }
990
990
  const ts = this.ts()
991
991
  await this.options.repo.backup(ts)
992
992
  const previous = await this.options.repo.current().catch(error => {
993
993
  this.options.logger?.warn(`paper-trading: reset could not replay the old ledger: ${String(error)}`)
994
994
  return undefined
995
995
  })
996
- const settings = normalizeSettings(previous !== undefined && previous.tradeDate !== '' ? previous.settings : this.settings)
996
+ const merged = normalizeSettings(previous !== undefined && previous.tradeDate !== '' ? previous.settings : this.settings)
997
+ // A reset keeps the previous settings, so an existing 10 万 account would
998
+ // never pick up a new default; the caller may pass the starting cash.
999
+ const settings = initialCashCents === undefined ? merged : { ...merged, initialCashCents }
997
1000
  const tradeDate = previous !== undefined && previous.tradeDate !== '' ? previous.tradeDate : await this.tradeDateForNow()
998
1001
  const genesis: LedgerEvent = {
999
1002
  seq: 1,
@@ -60,6 +60,17 @@ function basketBudget(value: unknown): number | undefined {
60
60
  return value
61
61
  }
62
62
 
63
+ /** Optional reset starting cash, entered in yuan like every other panel amount. */
64
+ function initialCashCents(value: unknown): number | undefined {
65
+ if (value === undefined || value === null) return undefined
66
+ const yuan = num(value, 'initialCash')
67
+ const cents = Math.round(yuan * 100)
68
+ if (!Number.isSafeInteger(cents) || cents <= 0) {
69
+ throw new PaperError('INVALID_ARGUMENT', 'initialCash 必须是正数(元)')
70
+ }
71
+ return cents
72
+ }
73
+
63
74
  function basketRows(value: unknown): BasketOrderInput[] {
64
75
  if (!Array.isArray(value)) throw new PaperError('INVALID_ARGUMENT', 'rows 必须是数组')
65
76
  if (value.length < 1 || value.length > BASKET_MAX_ROWS) {
@@ -104,7 +115,7 @@ export function createPaperRpcHandler(service: PaperService, options: PaperRpcOp
104
115
  return ok(await service.account())
105
116
  case 'account/reset': {
106
117
  const input = record(payload ?? {})
107
- return ok(await service.reset(input.confirm === true))
118
+ return ok(await service.reset(input.confirm === true, initialCashCents(input.initialCash)))
108
119
  }
109
120
  case 'account/deposit':
110
121
  return ok(await service.deposit(num(record(payload).amount, 'amount')))