@dsh-ft/dsh-fft-paper-trading 0.6.0 → 0.6.1
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/lib/client.js +1 -1
- package/lib/data/ftshare-trading-calendar.d.ts +47 -12
- package/lib/data/ftshare-trading-calendar.d.ts.map +1 -1
- package/lib/data/ftshare-trading-calendar.js +156 -44
- package/lib/data/ftshare-trading-calendar.js.map +1 -1
- package/package.json +2 -2
- package/src/data/ftshare-trading-calendar.ts +184 -45
package/lib/client.js
CHANGED
|
@@ -9,7 +9,7 @@ window.__ModuleLoader__.load({
|
|
|
9
9
|
|
|
10
10
|
const ROUTE = '/api/ft-paper-trading'
|
|
11
11
|
/** Release number stamped into the Feedback link title at build time. */
|
|
12
|
-
const PAPER_VERSION = '0.6.
|
|
12
|
+
const PAPER_VERSION = '0.6.1'
|
|
13
13
|
/** Public repository; the panel links out and collects nothing itself. */
|
|
14
14
|
const ISSUE_NEW = 'https://github.com/gigaflw/dsh-fft-paper-trading/issues/new'
|
|
15
15
|
/**
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import type { CalendarStatus } from '../contract.js';
|
|
2
2
|
import type { TradingCalendarPort } from './trading-calendar-port.js';
|
|
3
3
|
import type { FtshareDataLike } from './ftshare-market-data.js';
|
|
4
|
-
/**
|
|
4
|
+
/** First gap between two upstream attempts after a failure; doubles per failure. */
|
|
5
5
|
export declare const CALENDAR_RETRY_MS = 60000;
|
|
6
|
+
/** Ceiling of the failure backoff. */
|
|
7
|
+
export declare const CALENDAR_RETRY_MAX_MS = 600000;
|
|
6
8
|
export interface FtshareTradingCalendarOptions {
|
|
7
|
-
/** Clock for the
|
|
9
|
+
/** Clock for the year cache, the backoff and the natural-day reset. */
|
|
8
10
|
now?: () => Date;
|
|
9
|
-
/**
|
|
11
|
+
/** First retry gap after a failure; defaults to {@link CALENDAR_RETRY_MS}. */
|
|
10
12
|
retryMs?: number;
|
|
13
|
+
/** Backoff ceiling; defaults to {@link CALENDAR_RETRY_MAX_MS}. */
|
|
14
|
+
retryMaxMs?: number;
|
|
11
15
|
}
|
|
12
16
|
/**
|
|
13
17
|
* Trading calendar over FTShare's `ft_v1_time_trading_calendar`.
|
|
@@ -15,26 +19,57 @@ export interface FtshareTradingCalendarOptions {
|
|
|
15
19
|
* The upstream schema takes YYYYMMDD integers and returns an integer
|
|
16
20
|
* `trade_dates` array; this adapter is the only place that converts them.
|
|
17
21
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
+
* **Cached per calendar year, not per query.** An exchange calendar changes once
|
|
23
|
+
* a year, so the first question fetches the whole year once and every later
|
|
24
|
+
* question — any range, any caller, the 5 s match tick included — is answered
|
|
25
|
+
* from that memory. The previous version cached per exact `from:to` range and
|
|
26
|
+
* re-asked upstream after every failure, which let two 5 s schedulers issue
|
|
27
|
+
* ~120 calls/hour against an endpoint with a daily quota.
|
|
28
|
+
*
|
|
29
|
+
* **Failures are remembered too.** A failure falls back to weekdays, records
|
|
30
|
+
* why, and suppresses further attempts with an exponential backoff (1, 2, 4 …
|
|
31
|
+
* ≤ {@link CALENDAR_RETRY_MAX_MS}). A quota answer is not retried at all until
|
|
32
|
+
* the next Shanghai natural day, because retrying it only spends what is left of
|
|
33
|
+
* the window. Concurrent ticks share one in-flight question.
|
|
34
|
+
*
|
|
35
|
+
* The degradation is never silent: {@link source} stays `fallback` and
|
|
36
|
+
* {@link status} carries the upstream reason.
|
|
22
37
|
*/
|
|
23
38
|
export declare class FtshareTradingCalendar implements TradingCalendarPort {
|
|
24
39
|
private readonly service;
|
|
25
40
|
private readonly fallback;
|
|
26
41
|
private readonly now;
|
|
27
42
|
private readonly retryMs;
|
|
28
|
-
private readonly
|
|
29
|
-
|
|
30
|
-
private
|
|
31
|
-
|
|
32
|
-
private
|
|
43
|
+
private readonly retryMaxMs;
|
|
44
|
+
/** `YYYY` → that year's answer. */
|
|
45
|
+
private readonly years;
|
|
46
|
+
/** `YYYY` → in-flight upstream question, so parallel ticks share one call. */
|
|
47
|
+
private readonly inflight;
|
|
48
|
+
private latest;
|
|
33
49
|
constructor(service: FtshareDataLike, options?: FtshareTradingCalendarOptions);
|
|
50
|
+
/** Which source answered the latest calendar question. */
|
|
34
51
|
get source(): 'ftshare' | 'fallback';
|
|
35
52
|
get status(): CalendarStatus;
|
|
36
53
|
tradingDays(from: string, to: string): Promise<string[]>;
|
|
37
54
|
isTradingDay(date: string): Promise<boolean>;
|
|
38
55
|
nextTradingDay(date: string): Promise<string>;
|
|
56
|
+
/**
|
|
57
|
+
* Answer one calendar year from memory, upstream, or the weekday estimate.
|
|
58
|
+
* @param year - `YYYY`.
|
|
59
|
+
* @returns That year's trading days; empty only if the estimate is empty too.
|
|
60
|
+
*/
|
|
61
|
+
private daysOfYear;
|
|
62
|
+
/** Whether a failed year must not be asked again yet. */
|
|
63
|
+
private suppressed;
|
|
64
|
+
/** Exponential backoff by consecutive failures, capped at {@link retryMaxMs}. */
|
|
65
|
+
private retryGap;
|
|
66
|
+
/** `/^YYYY-MM-DD/` of a natural day in Shanghai. */
|
|
67
|
+
private naturalDay;
|
|
68
|
+
private naturalDayOf;
|
|
69
|
+
private estimate;
|
|
70
|
+
/** Ask upstream for the whole year once, then remember the outcome. */
|
|
71
|
+
private ask;
|
|
72
|
+
/** One upstream question; classifies the answer without touching the cache. */
|
|
73
|
+
private fetch;
|
|
39
74
|
}
|
|
40
75
|
//# sourceMappingURL=ftshare-trading-calendar.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ftshare-trading-calendar.d.ts","sourceRoot":"","sources":["../../src/data/ftshare-trading-calendar.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAEpD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA;AAErE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,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AAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAKxD,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAI5C,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAKnD;;;;OAIG;YACW,UAAU;IAWxB,yDAAyD;IACzD,OAAO,CAAC,UAAU;IASlB,iFAAiF;IACjF,OAAO,CAAC,QAAQ;IAIhB,oDAAoD;IACpD,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,YAAY;YAIN,QAAQ;IAItB,uEAAuE;YACzD,GAAG;IA2BjB,+EAA+E;YACjE,KAAK;CAkCpB"}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { addDays } from '../core/calendar.js';
|
|
2
2
|
import { WeekdayTradingCalendar } from './trading-calendar-port.js';
|
|
3
|
-
/**
|
|
3
|
+
/** First gap between two upstream attempts after a failure; doubles per failure. */
|
|
4
4
|
export const CALENDAR_RETRY_MS = 60_000;
|
|
5
|
+
/** Ceiling of the failure backoff. */
|
|
6
|
+
export const CALENDAR_RETRY_MAX_MS = 600_000;
|
|
5
7
|
/** Longest reason kept for display; upstream errors can be paragraphs. */
|
|
6
8
|
const REASON_MAX_LENGTH = 120;
|
|
9
|
+
const SHANGHAI_OFFSET_MS = 8 * 3_600_000;
|
|
7
10
|
function apiDate(date) {
|
|
8
11
|
return Number(date.replaceAll('-', ''));
|
|
9
12
|
}
|
|
@@ -18,88 +21,197 @@ function reasonOf(error) {
|
|
|
18
21
|
const flat = text.replace(/\s+/g, ' ').trim();
|
|
19
22
|
return flat.length <= REASON_MAX_LENGTH ? flat : `${flat.slice(0, REASON_MAX_LENGTH)}…`;
|
|
20
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* Whether an answer is a quota answer, where retrying only burns the window.
|
|
26
|
+
*
|
|
27
|
+
* The gateway reports its daily ceiling as `UPSTREAM_UNAVAILABLE` with the quota
|
|
28
|
+
* in the text (`最近 1 天最多访问 500 次`), so the code alone does not identify it.
|
|
29
|
+
*/
|
|
30
|
+
function isQuota(text, retryable) {
|
|
31
|
+
if (retryable === false && /UPSTREAM_UNAVAILABLE/u.test(text))
|
|
32
|
+
return true;
|
|
33
|
+
return /(最多访问|访问次数|调用次数|频率|限流|配额|quota|rate limit|too many requests)/iu.test(text);
|
|
34
|
+
}
|
|
35
|
+
/** The years a `YYYY-MM-DD` range touches, ascending. */
|
|
36
|
+
function yearsOf(from, to) {
|
|
37
|
+
const first = Number(from.slice(0, 4));
|
|
38
|
+
const last = Number(to.slice(0, 4));
|
|
39
|
+
if (!Number.isFinite(first) || !Number.isFinite(last) || last < first)
|
|
40
|
+
return [from.slice(0, 4)];
|
|
41
|
+
const years = [];
|
|
42
|
+
for (let year = first; year <= last && years.length < 8; year += 1)
|
|
43
|
+
years.push(String(year));
|
|
44
|
+
return years;
|
|
45
|
+
}
|
|
21
46
|
/**
|
|
22
47
|
* Trading calendar over FTShare's `ft_v1_time_trading_calendar`.
|
|
23
48
|
*
|
|
24
49
|
* The upstream schema takes YYYYMMDD integers and returns an integer
|
|
25
50
|
* `trade_dates` array; this adapter is the only place that converts them.
|
|
26
51
|
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
52
|
+
* **Cached per calendar year, not per query.** An exchange calendar changes once
|
|
53
|
+
* a year, so the first question fetches the whole year once and every later
|
|
54
|
+
* question — any range, any caller, the 5 s match tick included — is answered
|
|
55
|
+
* from that memory. The previous version cached per exact `from:to` range and
|
|
56
|
+
* re-asked upstream after every failure, which let two 5 s schedulers issue
|
|
57
|
+
* ~120 calls/hour against an endpoint with a daily quota.
|
|
58
|
+
*
|
|
59
|
+
* **Failures are remembered too.** A failure falls back to weekdays, records
|
|
60
|
+
* why, and suppresses further attempts with an exponential backoff (1, 2, 4 …
|
|
61
|
+
* ≤ {@link CALENDAR_RETRY_MAX_MS}). A quota answer is not retried at all until
|
|
62
|
+
* the next Shanghai natural day, because retrying it only spends what is left of
|
|
63
|
+
* the window. Concurrent ticks share one in-flight question.
|
|
64
|
+
*
|
|
65
|
+
* The degradation is never silent: {@link source} stays `fallback` and
|
|
66
|
+
* {@link status} carries the upstream reason.
|
|
31
67
|
*/
|
|
32
68
|
export class FtshareTradingCalendar {
|
|
33
69
|
service;
|
|
34
70
|
fallback = new WeekdayTradingCalendar();
|
|
35
71
|
now;
|
|
36
72
|
retryMs;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
73
|
+
retryMaxMs;
|
|
74
|
+
/** `YYYY` → that year's answer. */
|
|
75
|
+
years = new Map();
|
|
76
|
+
/** `YYYY` → in-flight upstream question, so parallel ticks share one call. */
|
|
77
|
+
inflight = new Map();
|
|
78
|
+
latest;
|
|
42
79
|
constructor(service, options = {}) {
|
|
43
80
|
this.service = service;
|
|
44
81
|
this.now = options.now ?? (() => new Date());
|
|
45
82
|
this.retryMs = options.retryMs ?? CALENDAR_RETRY_MS;
|
|
83
|
+
this.retryMaxMs = options.retryMaxMs ?? CALENDAR_RETRY_MAX_MS;
|
|
46
84
|
}
|
|
85
|
+
/** Which source answered the latest calendar question. */
|
|
47
86
|
get source() {
|
|
48
|
-
return this.
|
|
87
|
+
return this.latest?.source ?? 'fallback';
|
|
49
88
|
}
|
|
50
89
|
get status() {
|
|
90
|
+
const latest = this.latest;
|
|
91
|
+
if (latest === undefined)
|
|
92
|
+
return this.fallback.status;
|
|
51
93
|
return {
|
|
52
|
-
source:
|
|
53
|
-
...
|
|
54
|
-
|
|
94
|
+
source: latest.source,
|
|
95
|
+
...latest.reason !== undefined ? { reason: latest.reason } : {},
|
|
96
|
+
checkedAt: latest.checkedAt,
|
|
55
97
|
};
|
|
56
98
|
}
|
|
57
99
|
async tradingDays(from, to) {
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
100
|
+
const answers = await Promise.all(yearsOf(from, to).map(year => this.daysOfYear(year)));
|
|
101
|
+
return answers.flat().filter(day => day >= from && day <= to).sort();
|
|
102
|
+
}
|
|
103
|
+
async isTradingDay(date) {
|
|
104
|
+
return (await this.tradingDays(date, date)).includes(date);
|
|
105
|
+
}
|
|
106
|
+
async nextTradingDay(date) {
|
|
107
|
+
const days = await this.tradingDays(addDays(date, 1), addDays(date, 30));
|
|
108
|
+
return days[0] ?? (await this.fallback.nextTradingDay(date));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Answer one calendar year from memory, upstream, or the weekday estimate.
|
|
112
|
+
* @param year - `YYYY`.
|
|
113
|
+
* @returns That year's trading days; empty only if the estimate is empty too.
|
|
114
|
+
*/
|
|
115
|
+
async daysOfYear(year) {
|
|
116
|
+
const entry = this.years.get(year);
|
|
117
|
+
if (entry?.source === 'ftshare' && entry.days !== undefined)
|
|
118
|
+
return entry.days;
|
|
119
|
+
if (entry?.source === 'fallback' && this.suppressed(entry))
|
|
120
|
+
return await this.estimate(year);
|
|
121
|
+
const pending = this.inflight.get(year);
|
|
122
|
+
if (pending !== undefined)
|
|
123
|
+
return pending;
|
|
124
|
+
const question = this.ask(year).finally(() => { this.inflight.delete(year); });
|
|
125
|
+
this.inflight.set(year, question);
|
|
126
|
+
return question;
|
|
127
|
+
}
|
|
128
|
+
/** Whether a failed year must not be asked again yet. */
|
|
129
|
+
suppressed(entry) {
|
|
62
130
|
const now = this.now();
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
131
|
+
// A quota answer is final until the next Shanghai natural day: asking again
|
|
132
|
+
// inside the same window only spends calls the window no longer has.
|
|
133
|
+
if (entry.final)
|
|
134
|
+
return this.naturalDay(now) <= this.naturalDayOf(entry.checkedAt);
|
|
135
|
+
if (entry.failedAt === undefined)
|
|
136
|
+
return false;
|
|
137
|
+
return now.getTime() - entry.failedAt < this.retryGap(entry.failures);
|
|
138
|
+
}
|
|
139
|
+
/** Exponential backoff by consecutive failures, capped at {@link retryMaxMs}. */
|
|
140
|
+
retryGap(failures) {
|
|
141
|
+
return Math.min(this.retryMs * 2 ** Math.max(0, failures - 1), this.retryMaxMs);
|
|
142
|
+
}
|
|
143
|
+
/** `/^YYYY-MM-DD/` of a natural day in Shanghai. */
|
|
144
|
+
naturalDay(now) {
|
|
145
|
+
return new Date(now.getTime() + SHANGHAI_OFFSET_MS).toISOString().slice(0, 10);
|
|
146
|
+
}
|
|
147
|
+
naturalDayOf(iso) {
|
|
148
|
+
return iso === undefined ? '' : this.naturalDay(new Date(iso));
|
|
149
|
+
}
|
|
150
|
+
async estimate(year) {
|
|
151
|
+
return await this.fallback.tradingDays(`${year}-01-01`, `${year}-12-31`);
|
|
152
|
+
}
|
|
153
|
+
/** Ask upstream for the whole year once, then remember the outcome. */
|
|
154
|
+
async ask(year) {
|
|
155
|
+
const now = this.now();
|
|
156
|
+
const from = `${year}-01-01`;
|
|
157
|
+
const to = `${year}-12-31`;
|
|
158
|
+
const outcome = await this.fetch(from, to);
|
|
159
|
+
if (outcome.ok) {
|
|
160
|
+
const entry = { source: 'ftshare', days: outcome.days, checkedAt: now.toISOString(), failures: 0, final: false };
|
|
161
|
+
this.years.set(year, entry);
|
|
162
|
+
this.latest = entry;
|
|
163
|
+
return outcome.days;
|
|
68
164
|
}
|
|
165
|
+
const previous = this.years.get(year);
|
|
166
|
+
const failures = (previous?.source === 'fallback' ? previous.failures : 0) + 1;
|
|
167
|
+
const reason = reasonOf(outcome.error);
|
|
168
|
+
const entry = {
|
|
169
|
+
source: 'fallback',
|
|
170
|
+
reason: outcome.final ? `${reason}(本自然日不再重试)` : reason,
|
|
171
|
+
checkedAt: now.toISOString(),
|
|
172
|
+
failedAt: now.getTime(),
|
|
173
|
+
failures,
|
|
174
|
+
final: outcome.final,
|
|
175
|
+
};
|
|
176
|
+
this.years.set(year, entry);
|
|
177
|
+
this.latest = entry;
|
|
178
|
+
return await this.estimate(year);
|
|
179
|
+
}
|
|
180
|
+
/** One upstream question; classifies the answer without touching the cache. */
|
|
181
|
+
async fetch(from, to) {
|
|
69
182
|
try {
|
|
70
183
|
const result = await this.service.call('ft_v1_time_trading_calendar', {
|
|
71
184
|
market: 'cn',
|
|
72
185
|
start_date: apiDate(from),
|
|
73
186
|
end_date: apiDate(to),
|
|
74
187
|
});
|
|
75
|
-
if (result.state === 'denied' || result.state === 'failed')
|
|
76
|
-
|
|
188
|
+
if (result.state === 'denied' || result.state === 'failed') {
|
|
189
|
+
const text = `${result.notice?.code ?? ''} ${result.notice?.message ?? result.state}`.trim();
|
|
190
|
+
return {
|
|
191
|
+
ok: false,
|
|
192
|
+
error: new Error(result.notice?.message ?? result.state),
|
|
193
|
+
// The quota text is the only quota fact this port carries; `retryable`
|
|
194
|
+
// is passed through only by adapters that keep it.
|
|
195
|
+
final: result.state === 'denied' || isQuota(text, undefined),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
77
198
|
const rows = Array.isArray(result.rows) ? result.rows : [];
|
|
78
199
|
const raw = rows[0]?.trade_dates;
|
|
79
200
|
const days = (Array.isArray(raw) ? raw : [])
|
|
80
201
|
.map(isoDate)
|
|
81
|
-
.filter((value) => value !== undefined)
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
202
|
+
.filter((value) => value !== undefined)
|
|
203
|
+
.sort();
|
|
204
|
+
if (days.length === 0) {
|
|
205
|
+
// An empty year is not an answer: caching it would read as "no trading
|
|
206
|
+
// day ever" and freeze settlement, so it counts as a failure instead.
|
|
207
|
+
return { ok: false, error: new Error(`上游未返回 ${from.slice(0, 4)} 年交易日历`), final: false };
|
|
208
|
+
}
|
|
209
|
+
return { ok: true, days };
|
|
88
210
|
}
|
|
89
211
|
catch (error) {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
this.failedAt = now.getTime();
|
|
93
|
-
this.checkedAt = now.toISOString();
|
|
94
|
-
return this.fallback.tradingDays(from, to);
|
|
212
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
213
|
+
return { ok: false, error, final: isQuota(text, undefined) };
|
|
95
214
|
}
|
|
96
215
|
}
|
|
97
|
-
async isTradingDay(date) {
|
|
98
|
-
return (await this.tradingDays(date, date)).includes(date);
|
|
99
|
-
}
|
|
100
|
-
async nextTradingDay(date) {
|
|
101
|
-
const days = await this.tradingDays(addDays(date, 1), addDays(date, 30));
|
|
102
|
-
return days[0] ?? (await this.fallback.nextTradingDay(date));
|
|
103
|
-
}
|
|
104
216
|
}
|
|
105
217
|
//# sourceMappingURL=ftshare-trading-calendar.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ftshare-trading-calendar.js","sourceRoot":"","sources":["../../src/data/ftshare-trading-calendar.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAE7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAA;AAGnE,
|
|
1
|
+
{"version":3,"file":"ftshare-trading-calendar.js","sourceRoot":"","sources":["../../src/data/ftshare-trading-calendar.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAE7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAA;AAGnE,oFAAoF;AACpF,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAA;AAEvC,sCAAsC;AACtC,MAAM,CAAC,MAAM,qBAAqB,GAAG,OAAO,CAAA;AAE5C,0EAA0E;AAC1E,MAAM,iBAAiB,GAAG,GAAG,CAAA;AAE7B,MAAM,kBAAkB,GAAG,CAAC,GAAG,SAAS,CAAA;AAsBxC,SAAS,OAAO,CAAC,IAAY;IAC3B,OAAO,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAA;AACzC,CAAC;AAED,SAAS,OAAO,CAAC,KAAc;IAC7B,MAAM,MAAM,GAAG,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AAK,CAAC,SAAS,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA;YACzF,CAAC;YACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACnE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,CAAA;QAC9D,CAAC;IACH,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dsh-ft/dsh-fft-paper-trading",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "A-share and commodity futures paper trading for DeepSeek Harness: local ledger, batch orders, review, and FTShare quotes.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"@dsh-ft/dsh-fft-settings": "^0.5.0",
|
|
53
|
-
"@dsh-ft/dsh-fft-ftshare": "^0.
|
|
53
|
+
"@dsh-ft/dsh-fft-ftshare": "^0.4.0",
|
|
54
54
|
"@ftshare-lab/dsh-kline": "0.4.0"
|
|
55
55
|
},
|
|
56
56
|
"bundledDependencies": [
|
|
@@ -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
|
-
/**
|
|
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
|
|
76
|
+
/** Clock for the year cache, the backoff and the natural-day reset. */
|
|
31
77
|
now?: () => Date
|
|
32
|
-
/**
|
|
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
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
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
|
|
52
|
-
|
|
53
|
-
private
|
|
54
|
-
|
|
55
|
-
private
|
|
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.
|
|
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:
|
|
69
|
-
...
|
|
70
|
-
|
|
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
|
|
76
|
-
|
|
77
|
-
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (
|
|
83
|
-
|
|
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')
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
-
|
|
105
|
-
|
|
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
|
}
|