koishi-plugin-rina-currency 0.0.1 → 0.0.3
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/config.d.ts +2 -0
- package/lib/index.js +121 -46
- package/lib/providers/boc.d.ts +3 -1
- package/lib/providers/common.d.ts +5 -1
- package/lib/providers/icbc.d.ts +3 -1
- package/lib/scheduler.d.ts +5 -0
- package/lib/service.d.ts +8 -2
- package/lib/types.d.ts +2 -0
- package/package.json +1 -1
- package/readme.md +5 -1
package/lib/config.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -72,6 +72,8 @@ var Config = import_koishi.Schema.object({
|
|
|
72
72
|
defaultBank: BankSchema.default("boc").description("购汇成本与单银行趋势的默认参考银行"),
|
|
73
73
|
defaultRateType: RateTypeSchema.default("spotSell").description("默认牌价类型"),
|
|
74
74
|
requestTimeout: import_koishi.Schema.number().min(1e3).max(6e4).default(15e3).description("银行接口请求超时(毫秒)"),
|
|
75
|
+
requestAttempts: import_koishi.Schema.number().min(1).max(10).default(3).description("每个银行接口请求的总尝试次数(含首次请求)"),
|
|
76
|
+
requestRetryDelay: import_koishi.Schema.number().min(100).max(3e4).default(1500).description("请求失败后的首次重试等待时间(毫秒),后续等待时间线性递增"),
|
|
75
77
|
collectIntervalMinutes: import_koishi.Schema.number().min(10).max(1440).default(60).description("牌价采集间隔(分钟)"),
|
|
76
78
|
collectOnStart: import_koishi.Schema.boolean().default(true).description("插件启动后立即采集一次"),
|
|
77
79
|
chartWidth: import_koishi.Schema.number().min(600).max(2e3).default(1200).description("趋势图宽度"),
|
|
@@ -213,32 +215,43 @@ async function renderTrendChart(metrics, rateType, options) {
|
|
|
213
215
|
const padding = { top: 184, right: 72, bottom: 76, left: 88 };
|
|
214
216
|
const plotWidth = width - padding.left - padding.right;
|
|
215
217
|
const plotHeight = height - padding.top - padding.bottom;
|
|
216
|
-
const
|
|
218
|
+
const rangeStart = metrics.rangeStart.getTime();
|
|
219
|
+
const rangeEnd = metrics.rangeEnd.getTime();
|
|
220
|
+
const chartPoints = metrics.points.map((point) => ({
|
|
221
|
+
...point,
|
|
222
|
+
collectedAt: new Date(Math.max(point.collectedAt.getTime(), rangeStart))
|
|
223
|
+
}));
|
|
224
|
+
const lastPoint = chartPoints.at(-1);
|
|
225
|
+
if (lastPoint.collectedAt.getTime() < rangeEnd) {
|
|
226
|
+
chartPoints.push({ ...metrics.latest, collectedAt: new Date(rangeEnd) });
|
|
227
|
+
}
|
|
228
|
+
const values = chartPoints.map((point) => point[rateType]);
|
|
217
229
|
const min = Math.min(...values);
|
|
218
230
|
const max = Math.max(...values);
|
|
219
231
|
const spread = Math.max(max - min, Math.max(max, 1) * 2e-3);
|
|
220
232
|
const lower = min - spread * 0.14;
|
|
221
233
|
const upper = max + spread * 0.14;
|
|
222
234
|
const range = upper - lower;
|
|
223
|
-
const
|
|
224
|
-
const
|
|
225
|
-
const timeRange = Math.max(lastTime - firstTime, 1);
|
|
226
|
-
const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - firstTime) / timeRange * plotWidth, "xFor");
|
|
235
|
+
const timeRange = Math.max(rangeEnd - rangeStart, 1);
|
|
236
|
+
const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - rangeStart) / timeRange * plotWidth, "xFor");
|
|
227
237
|
const yFor = /* @__PURE__ */ __name((value) => padding.top + (upper - value) / range * plotHeight, "yFor");
|
|
228
|
-
const coordinates =
|
|
229
|
-
const latestX = xFor(
|
|
238
|
+
const coordinates = chartPoints.map((point) => `${xFor(point.collectedAt.getTime()).toFixed(1)},${yFor(point[rateType]).toFixed(1)}`).join(" ");
|
|
239
|
+
const latestX = xFor(rangeEnd);
|
|
230
240
|
const latestY = yFor(metrics.latest[rateType]);
|
|
231
241
|
const highPoint = metrics.points.reduce((best, point) => point[rateType] > best[rateType] ? point : best);
|
|
232
242
|
const lowPoint = metrics.points.reduce((best, point) => point[rateType] < best[rateType] ? point : best);
|
|
233
|
-
const highX = xFor(highPoint.
|
|
243
|
+
const highX = xFor(Math.max(highPoint.collectedAt.getTime(), rangeStart));
|
|
234
244
|
const highY = yFor(highPoint[rateType]);
|
|
235
|
-
const lowX = xFor(lowPoint.
|
|
245
|
+
const lowX = xFor(Math.max(lowPoint.collectedAt.getTime(), rangeStart));
|
|
236
246
|
const lowY = yFor(lowPoint[rateType]);
|
|
237
247
|
const change = metrics.change == null ? "暂无前日数据" : `${metrics.change >= 0 ? "+" : ""}${formatRate(metrics.change)} ${metrics.changePercent >= 0 ? "+" : ""}${metrics.changePercent.toFixed(2)}%`;
|
|
238
248
|
const changeColor = metrics.change == null ? "#94a3b8" : metrics.change > 0 ? "#fb7185" : "#34d399";
|
|
239
249
|
const ticks = Array.from({ length: 4 }, (_, index) => lower + (upper - lower) * index / 3);
|
|
240
|
-
const
|
|
241
|
-
|
|
250
|
+
const labels = [
|
|
251
|
+
new Date(rangeStart),
|
|
252
|
+
new Date((rangeStart + rangeEnd) / 2),
|
|
253
|
+
new Date(rangeEnd)
|
|
254
|
+
];
|
|
242
255
|
const grid = ticks.map((value) => {
|
|
243
256
|
const y = yFor(value);
|
|
244
257
|
return `<line x1="${padding.left}" x2="${width - padding.right}" y1="${y}" y2="${y}" stroke="#26334a" stroke-width="1" />
|
|
@@ -246,7 +259,7 @@ async function renderTrendChart(metrics, rateType, options) {
|
|
|
246
259
|
}).join("");
|
|
247
260
|
const xLabels = labels.map((point, index) => {
|
|
248
261
|
const anchor = index === 0 ? "start" : index === labels.length - 1 ? "end" : "middle";
|
|
249
|
-
return `<text x="${xFor(point.
|
|
262
|
+
return `<text x="${xFor(point.getTime())}" y="${height - 30}" text-anchor="${anchor}" class="axis">${dateLabel(point)}</text>`;
|
|
250
263
|
}).join("");
|
|
251
264
|
const title = `${BANK_LABELS[metrics.latest.bank]} · 日元${RATE_TYPE_LABELS[rateType]}走势`;
|
|
252
265
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
|
|
@@ -392,18 +405,28 @@ __name(extendModel, "extendModel");
|
|
|
392
405
|
// src/providers/common.ts
|
|
393
406
|
var BOC_SOURCE_URL = "https://www.boc.cn/sourcedb/whpj/index.html";
|
|
394
407
|
var ICBC_SOURCE_URL = "http://papi.icbc.com.cn/exchanges/ns/getLatest";
|
|
395
|
-
async function fetchText(url, timeoutMs, init = {}) {
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
const
|
|
400
|
-
|
|
401
|
-
|
|
408
|
+
async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retryDelay: 0 }) {
|
|
409
|
+
let lastError;
|
|
410
|
+
for (let attempt = 1; attempt <= retry.attempts; attempt++) {
|
|
411
|
+
const controller = new AbortController();
|
|
412
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
413
|
+
try {
|
|
414
|
+
const response = await fetch(url, { ...init, signal: controller.signal });
|
|
415
|
+
if (!response.ok) {
|
|
416
|
+
throw new Error(`${response.status} ${response.statusText}`);
|
|
417
|
+
}
|
|
418
|
+
return await response.text();
|
|
419
|
+
} catch (error) {
|
|
420
|
+
lastError = error;
|
|
421
|
+
} finally {
|
|
422
|
+
clearTimeout(timer);
|
|
423
|
+
}
|
|
424
|
+
if (attempt < retry.attempts) {
|
|
425
|
+
await new Promise((resolve) => setTimeout(resolve, retry.retryDelay * attempt));
|
|
402
426
|
}
|
|
403
|
-
return await response.text();
|
|
404
|
-
} finally {
|
|
405
|
-
clearTimeout(timer);
|
|
406
427
|
}
|
|
428
|
+
const reason = lastError instanceof Error ? `${lastError.name}: ${lastError.message}` : String(lastError);
|
|
429
|
+
throw new Error(`请求 ${url} 失败,已尝试 ${retry.attempts} 次:${reason}`);
|
|
407
430
|
}
|
|
408
431
|
__name(fetchText, "fetchText");
|
|
409
432
|
function asRate(value, field) {
|
|
@@ -453,8 +476,10 @@ function parseBocJpy(html, collectedAt = /* @__PURE__ */ new Date()) {
|
|
|
453
476
|
}
|
|
454
477
|
__name(parseBocJpy, "parseBocJpy");
|
|
455
478
|
var BocProvider = class {
|
|
456
|
-
constructor(timeoutMs) {
|
|
479
|
+
constructor(timeoutMs, attempts, retryDelay) {
|
|
457
480
|
this.timeoutMs = timeoutMs;
|
|
481
|
+
this.attempts = attempts;
|
|
482
|
+
this.retryDelay = retryDelay;
|
|
458
483
|
}
|
|
459
484
|
static {
|
|
460
485
|
__name(this, "BocProvider");
|
|
@@ -463,7 +488,7 @@ var BocProvider = class {
|
|
|
463
488
|
async fetch() {
|
|
464
489
|
const html = await fetchText(BOC_SOURCE_URL, this.timeoutMs, {
|
|
465
490
|
headers: { "user-agent": "koishi-plugin-rina-currency/0.1" }
|
|
466
|
-
});
|
|
491
|
+
}, { attempts: this.attempts, retryDelay: this.retryDelay });
|
|
467
492
|
return parseBocJpy(html);
|
|
468
493
|
}
|
|
469
494
|
};
|
|
@@ -489,8 +514,10 @@ function parseIcbcJpy(payload, collectedAt = /* @__PURE__ */ new Date()) {
|
|
|
489
514
|
}
|
|
490
515
|
__name(parseIcbcJpy, "parseIcbcJpy");
|
|
491
516
|
var IcbcProvider = class {
|
|
492
|
-
constructor(timeoutMs) {
|
|
517
|
+
constructor(timeoutMs, attempts, retryDelay) {
|
|
493
518
|
this.timeoutMs = timeoutMs;
|
|
519
|
+
this.attempts = attempts;
|
|
520
|
+
this.retryDelay = retryDelay;
|
|
494
521
|
}
|
|
495
522
|
static {
|
|
496
523
|
__name(this, "IcbcProvider");
|
|
@@ -504,7 +531,7 @@ var IcbcProvider = class {
|
|
|
504
531
|
"user-agent": "koishi-plugin-rina-currency/0.1"
|
|
505
532
|
},
|
|
506
533
|
body: "{}"
|
|
507
|
-
});
|
|
534
|
+
}, { attempts: this.attempts, retryDelay: this.retryDelay });
|
|
508
535
|
return parseIcbcJpy(JSON.parse(body));
|
|
509
536
|
}
|
|
510
537
|
};
|
|
@@ -542,13 +569,56 @@ var Scheduler = class {
|
|
|
542
569
|
__name(this, "Scheduler");
|
|
543
570
|
}
|
|
544
571
|
sentBroadcasts = /* @__PURE__ */ new Set();
|
|
572
|
+
lastCollectionSlot;
|
|
545
573
|
start() {
|
|
546
574
|
this.ctx.on("ready", async () => {
|
|
547
|
-
|
|
548
|
-
|
|
575
|
+
const due = this.getDueCollection();
|
|
576
|
+
if (due) {
|
|
577
|
+
this.lastCollectionSlot = due.key;
|
|
578
|
+
await this.collectAndAlert({
|
|
579
|
+
recordUnchanged: due.isDailyAnchor,
|
|
580
|
+
collectedAt: due.at
|
|
581
|
+
});
|
|
582
|
+
} else if (this.config.collectOnStart) {
|
|
583
|
+
await this.collectAndAlert();
|
|
584
|
+
}
|
|
585
|
+
this.scheduleAlignedCollections();
|
|
549
586
|
this.ctx.setInterval(() => void this.runBroadcasts(), 3e4);
|
|
550
587
|
});
|
|
551
588
|
}
|
|
589
|
+
/** Runs on China-time minute boundaries, with 17:00 as the daily anchor. */
|
|
590
|
+
scheduleAlignedCollections() {
|
|
591
|
+
const now = /* @__PURE__ */ new Date();
|
|
592
|
+
const delay = 6e4 - now.getSeconds() * 1e3 - now.getMilliseconds();
|
|
593
|
+
this.ctx.setTimeout(() => {
|
|
594
|
+
void this.collectIfDue();
|
|
595
|
+
this.ctx.setInterval(() => void this.collectIfDue(), 6e4);
|
|
596
|
+
}, delay);
|
|
597
|
+
}
|
|
598
|
+
getDueCollection(now = /* @__PURE__ */ new Date()) {
|
|
599
|
+
const clock = chinaClock(now);
|
|
600
|
+
const minutesSinceMidnight = clock.hour * 60 + clock.minute;
|
|
601
|
+
const dailyAnchor = 17 * 60;
|
|
602
|
+
const minutesSinceAnchor = minutesSinceMidnight >= dailyAnchor ? minutesSinceMidnight - dailyAnchor : minutesSinceMidnight + 24 * 60 - dailyAnchor;
|
|
603
|
+
const isDailyAnchor = minutesSinceMidnight === dailyAnchor;
|
|
604
|
+
if (!isDailyAnchor && minutesSinceAnchor % this.config.collectIntervalMinutes !== 0) return;
|
|
605
|
+
const at = new Date(now);
|
|
606
|
+
at.setSeconds(0, 0);
|
|
607
|
+
return {
|
|
608
|
+
key: `${clock.date}:${clock.hour}:${clock.minute}`,
|
|
609
|
+
at,
|
|
610
|
+
isDailyAnchor
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
async collectIfDue() {
|
|
614
|
+
const due = this.getDueCollection();
|
|
615
|
+
if (!due || due.key === this.lastCollectionSlot) return;
|
|
616
|
+
this.lastCollectionSlot = due.key;
|
|
617
|
+
await this.collectAndAlert({
|
|
618
|
+
recordUnchanged: due.isDailyAnchor,
|
|
619
|
+
collectedAt: due.at
|
|
620
|
+
});
|
|
621
|
+
}
|
|
552
622
|
getBot(target) {
|
|
553
623
|
return this.ctx.bots.find((bot) => bot.platform === target.platform && bot.selfId === target.selfId);
|
|
554
624
|
}
|
|
@@ -561,9 +631,9 @@ var Scheduler = class {
|
|
|
561
631
|
await bot.sendMessage(target.channelId, content);
|
|
562
632
|
if (image) await bot.sendMessage(target.channelId, import_koishi3.h.image(image, "image/png"));
|
|
563
633
|
}
|
|
564
|
-
async collectAndAlert() {
|
|
634
|
+
async collectAndAlert(options = {}) {
|
|
565
635
|
try {
|
|
566
|
-
const result = await this.service.collect();
|
|
636
|
+
const result = await this.service.collect(options);
|
|
567
637
|
await Promise.all(result.collected.map((item) => this.maybeAlert(item)));
|
|
568
638
|
} catch (error) {
|
|
569
639
|
this.logger.warn(`定时采集日元牌价失败:${String(error)}`);
|
|
@@ -630,10 +700,10 @@ function toQuote(record) {
|
|
|
630
700
|
return { ...record };
|
|
631
701
|
}
|
|
632
702
|
__name(toQuote, "toQuote");
|
|
633
|
-
function
|
|
634
|
-
return records.sort((left, right) => left.
|
|
703
|
+
function sortByCollectedAt(records) {
|
|
704
|
+
return records.sort((left, right) => left.collectedAt.getTime() - right.collectedAt.getTime());
|
|
635
705
|
}
|
|
636
|
-
__name(
|
|
706
|
+
__name(sortByCollectedAt, "sortByCollectedAt");
|
|
637
707
|
var RateService = class {
|
|
638
708
|
constructor(ctx, logger, providers) {
|
|
639
709
|
this.ctx = ctx;
|
|
@@ -643,11 +713,12 @@ var RateService = class {
|
|
|
643
713
|
static {
|
|
644
714
|
__name(this, "RateService");
|
|
645
715
|
}
|
|
646
|
-
async collect() {
|
|
716
|
+
async collect(options = {}) {
|
|
647
717
|
const settled = await Promise.allSettled(this.providers.map(async (provider) => {
|
|
648
718
|
const previous = await this.getLatest(provider.id);
|
|
649
719
|
const quote = await provider.fetch();
|
|
650
|
-
if (
|
|
720
|
+
if (options.collectedAt) quote.collectedAt = options.collectedAt;
|
|
721
|
+
if (previous?.publishedAt.getTime() === quote.publishedAt.getTime() && !options.recordUnchanged) {
|
|
651
722
|
return { quote: previous, previous, isNew: false };
|
|
652
723
|
}
|
|
653
724
|
await this.ctx.database.create("rina_currency_rate", quote);
|
|
@@ -669,7 +740,7 @@ var RateService = class {
|
|
|
669
740
|
async getLatest(bank) {
|
|
670
741
|
const rows = await this.ctx.database.get("rina_currency_rate", { bank, currency: "JPY" });
|
|
671
742
|
if (!rows.length) return;
|
|
672
|
-
return
|
|
743
|
+
return sortByCollectedAt(rows.map(toQuote)).at(-1);
|
|
673
744
|
}
|
|
674
745
|
async getLatestAll() {
|
|
675
746
|
const entries = await Promise.all(["boc", "icbc"].map(async (bank) => [bank, await this.getLatest(bank)]));
|
|
@@ -682,18 +753,20 @@ var RateService = class {
|
|
|
682
753
|
snapshot = await this.getLatestAll();
|
|
683
754
|
return snapshot;
|
|
684
755
|
}
|
|
685
|
-
async getTrend(bank, rateType, days) {
|
|
686
|
-
const since = new Date(
|
|
756
|
+
async getTrend(bank, rateType, days, now = /* @__PURE__ */ new Date()) {
|
|
757
|
+
const since = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
|
|
687
758
|
const rows = await this.ctx.database.get("rina_currency_rate", {
|
|
688
759
|
bank,
|
|
689
|
-
currency: "JPY"
|
|
690
|
-
publishedAt: { $gte: since }
|
|
760
|
+
currency: "JPY"
|
|
691
761
|
});
|
|
692
|
-
const
|
|
762
|
+
const history = sortByCollectedAt(rows.map(toQuote));
|
|
763
|
+
const prior = [...history].reverse().find((point) => point.collectedAt.getTime() < since.getTime());
|
|
764
|
+
const points = history.filter((point) => point.collectedAt.getTime() >= since.getTime());
|
|
765
|
+
if (prior) points.unshift(prior);
|
|
693
766
|
if (!points.length) return;
|
|
694
767
|
const latest = points.at(-1);
|
|
695
|
-
const dayBefore =
|
|
696
|
-
const previous = [...
|
|
768
|
+
const dayBefore = now.getTime() - 24 * 60 * 60 * 1e3;
|
|
769
|
+
const previous = [...history].reverse().find((point) => point.collectedAt.getTime() <= dayBefore);
|
|
697
770
|
const values = points.map((point) => point[rateType]);
|
|
698
771
|
const change = previous ? latest[rateType] - previous[rateType] : void 0;
|
|
699
772
|
return {
|
|
@@ -703,7 +776,9 @@ var RateService = class {
|
|
|
703
776
|
changePercent: change == null ? void 0 : change / previous[rateType] * 100,
|
|
704
777
|
high: Math.max(...values),
|
|
705
778
|
low: Math.min(...values),
|
|
706
|
-
points
|
|
779
|
+
points,
|
|
780
|
+
rangeStart: since,
|
|
781
|
+
rangeEnd: now
|
|
707
782
|
};
|
|
708
783
|
}
|
|
709
784
|
};
|
|
@@ -716,8 +791,8 @@ function apply(ctx, config) {
|
|
|
716
791
|
extendModel(ctx);
|
|
717
792
|
const logger = ctx.logger(name);
|
|
718
793
|
const service = new RateService(ctx, logger, [
|
|
719
|
-
new BocProvider(config.requestTimeout),
|
|
720
|
-
new IcbcProvider(config.requestTimeout)
|
|
794
|
+
new BocProvider(config.requestTimeout, config.requestAttempts, config.requestRetryDelay),
|
|
795
|
+
new IcbcProvider(config.requestTimeout, config.requestAttempts, config.requestRetryDelay)
|
|
721
796
|
]);
|
|
722
797
|
registerCommands(ctx, service, config);
|
|
723
798
|
new Scheduler(ctx, logger, service, config).start();
|
package/lib/providers/boc.d.ts
CHANGED
|
@@ -4,7 +4,9 @@ import { ExchangeRateQuote } from '../types';
|
|
|
4
4
|
export declare function parseBocJpy(html: string, collectedAt?: Date): ExchangeRateQuote;
|
|
5
5
|
export declare class BocProvider implements RateProvider {
|
|
6
6
|
private timeoutMs;
|
|
7
|
+
private attempts;
|
|
8
|
+
private retryDelay;
|
|
7
9
|
readonly id: "boc";
|
|
8
|
-
constructor(timeoutMs: number);
|
|
10
|
+
constructor(timeoutMs: number, attempts: number, retryDelay: number);
|
|
9
11
|
fetch(): Promise<ExchangeRateQuote>;
|
|
10
12
|
}
|
|
@@ -5,6 +5,10 @@ export interface RateProvider {
|
|
|
5
5
|
readonly id: ExchangeRateQuote['bank'];
|
|
6
6
|
fetch(): Promise<ExchangeRateQuote>;
|
|
7
7
|
}
|
|
8
|
-
export
|
|
8
|
+
export interface RetryOptions {
|
|
9
|
+
attempts: number;
|
|
10
|
+
retryDelay: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function fetchText(url: string, timeoutMs: number, init?: RequestInit, retry?: RetryOptions): Promise<string>;
|
|
9
13
|
export declare function asRate(value: unknown, field: string): number;
|
|
10
14
|
export declare function chinaTime(date: string, time?: string): Date;
|
package/lib/providers/icbc.d.ts
CHANGED
|
@@ -16,8 +16,10 @@ interface IcbcResponse {
|
|
|
16
16
|
export declare function parseIcbcJpy(payload: IcbcResponse, collectedAt?: Date): ExchangeRateQuote;
|
|
17
17
|
export declare class IcbcProvider implements RateProvider {
|
|
18
18
|
private timeoutMs;
|
|
19
|
+
private attempts;
|
|
20
|
+
private retryDelay;
|
|
19
21
|
readonly id: "icbc";
|
|
20
|
-
constructor(timeoutMs: number);
|
|
22
|
+
constructor(timeoutMs: number, attempts: number, retryDelay: number);
|
|
21
23
|
fetch(): Promise<ExchangeRateQuote>;
|
|
22
24
|
}
|
|
23
25
|
export {};
|
package/lib/scheduler.d.ts
CHANGED
|
@@ -7,8 +7,13 @@ export declare class Scheduler {
|
|
|
7
7
|
private service;
|
|
8
8
|
private config;
|
|
9
9
|
private sentBroadcasts;
|
|
10
|
+
private lastCollectionSlot?;
|
|
10
11
|
constructor(ctx: Context, logger: Logger, service: RateService, config: Config);
|
|
11
12
|
start(): void;
|
|
13
|
+
/** Runs on China-time minute boundaries, with 17:00 as the daily anchor. */
|
|
14
|
+
private scheduleAlignedCollections;
|
|
15
|
+
private getDueCollection;
|
|
16
|
+
private collectIfDue;
|
|
12
17
|
private getBot;
|
|
13
18
|
private send;
|
|
14
19
|
private collectAndAlert;
|
package/lib/service.d.ts
CHANGED
|
@@ -13,14 +13,20 @@ export interface CollectionResult {
|
|
|
13
13
|
error: unknown;
|
|
14
14
|
}>;
|
|
15
15
|
}
|
|
16
|
+
export interface CollectOptions {
|
|
17
|
+
/** Store an unchanged quote as a scheduled confirmation point. */
|
|
18
|
+
recordUnchanged?: boolean;
|
|
19
|
+
/** The scheduler slot represented by this collection. */
|
|
20
|
+
collectedAt?: Date;
|
|
21
|
+
}
|
|
16
22
|
export declare class RateService {
|
|
17
23
|
private ctx;
|
|
18
24
|
private logger;
|
|
19
25
|
private providers;
|
|
20
26
|
constructor(ctx: Context, logger: Logger, providers: RateProvider[]);
|
|
21
|
-
collect(): Promise<CollectionResult>;
|
|
27
|
+
collect(options?: CollectOptions): Promise<CollectionResult>;
|
|
22
28
|
getLatest(bank: BankId): Promise<ExchangeRateQuote | undefined>;
|
|
23
29
|
getLatestAll(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
|
|
24
30
|
ensureSnapshot(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
|
|
25
|
-
getTrend(bank: BankId, rateType: RateType, days: number): Promise<TrendMetrics | undefined>;
|
|
31
|
+
getTrend(bank: BankId, rateType: RateType, days: number, now?: Date): Promise<TrendMetrics | undefined>;
|
|
26
32
|
}
|
package/lib/types.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export interface TrendMetrics {
|
|
|
21
21
|
high: number;
|
|
22
22
|
low: number;
|
|
23
23
|
points: ExchangeRateQuote[];
|
|
24
|
+
rangeStart: Date;
|
|
25
|
+
rangeEnd: Date;
|
|
24
26
|
}
|
|
25
27
|
export declare const BANK_LABELS: Record<BankId, string>;
|
|
26
28
|
export declare const RATE_TYPE_LABELS: Record<RateType, string>;
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -30,7 +30,7 @@ plugins:
|
|
|
30
30
|
|
|
31
31
|
## 采集和来源
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
插件启动时可立即采集,之后按北京时间以每日 17:00 为基准、按 `collectIntervalMinutes` 分钟间隔采集,不受插件启动时刻影响。趋势图按采样时间绘制并始终延伸至查询当下;周末等未更新时会保持水平线。若每日 17:00 的牌价与上一次相同,仍会保存一条确认采样点,表示此前一天内牌价未变。
|
|
34
34
|
|
|
35
35
|
- 中国银行:公开外汇牌价页面(HTML 表格)
|
|
36
36
|
- 中国工商银行:公开最新牌价接口(JSON)
|
|
@@ -46,6 +46,8 @@ plugins:
|
|
|
46
46
|
rina-currency:
|
|
47
47
|
defaultBank: boc
|
|
48
48
|
defaultRateType: spotSell
|
|
49
|
+
requestAttempts: 3
|
|
50
|
+
requestRetryDelay: 1500
|
|
49
51
|
collectIntervalMinutes: 60
|
|
50
52
|
broadcasts:
|
|
51
53
|
- platform: onebot
|
|
@@ -64,6 +66,8 @@ plugins:
|
|
|
64
66
|
channelId: '987654'
|
|
65
67
|
```
|
|
66
68
|
|
|
69
|
+
每个来源请求默认总共尝试 3 次(包含首次请求),失败后分别等待 1.5 秒和 3 秒再试;可通过 `requestAttempts` 和 `requestRetryDelay` 调整。连续失败时,最终日志会包含来源地址、尝试次数和最后一次错误。
|
|
70
|
+
|
|
67
71
|
定时播报按北京时间执行。阈值提醒按相邻真实采样点的绝对涨跌幅触发:`changePercent: 0.5` 表示上涨或下跌至少 0.5%。比较周期由 `collectIntervalMinutes` 自然决定;同方向只提醒一次,波动回到阈值内或反向越过阈值后才会重新提醒。
|
|
68
72
|
|
|
69
73
|
## 开发
|