恢复已收盘 K 线流
如果流式连接中断时仍需保证已收盘的一分钟 K 线不被遗漏,请使用此示例。应用重新订阅,通过 GetCandles 补齐历史数据,并在写入每根 K 线之后保存检查点。应用会从上次保存的位置恢复,只输出已收盘的 K 线。
应用通过公开的 SDK 方法管理重连。SDK 门面和 stream run 都由调用方负责重连。
连接中断后恢复
- 打开流,等待带有
waitingClose: true的订阅成功确认。 - 通过
GetCandles读取历史数据,从第一个尚未处理的分钟开始,直到当前分钟的起点。 - 将后续从流收到的 K 线作为新时间段收盘的通知,并通过
GetCandles补齐。 - 处理下一根 K 线之前,保存当前 K 线及用于恢复读取的检查点。
- 传输层返回
UNAVAILABLE或流正常结束后,以有上限的间隔尝试重新订阅。
持久化数据始终来自同一个数据来源和时间间隔的历史查询。先打开订阅,再补齐历史,然后读取补齐期间积累的通知。请求范围重叠时会跳过已处理的 K 线。仅输出已收盘的 K 线。
此示例恢复的是 K 线历史。成交、订单簿和投资组合需要各自的快照和状态核对规则,统一的读取位置无法复原流中的每个交易所事件。
已发布历史数据可能被修正,也可能延迟出现,应用需定期核对。有关 GetCandles 的时间范围限制,请参阅官方文档。
将示例拆分成文件
请将四个文件放在同一目录。read-candle-history.ts 读取历史,watch-candle-updates.ts 打开一个订阅,recover-closed-candles.ts 协调恢复,main.ts 保存数据并管理 SDK 的生命周期。
示例假设 API 会为请求参数返回有效数据。
补齐历史数据
函数接收以 UTC 毫秒表示的开始时间 from 和结束时间 until。函数按不超过一天的窗口读取历史。limit: 2400 足以覆盖一个窗口内的一分钟 K 线。函数对 K 线排序、跳过重复项,并在第一根未收盘的 K 线处停止。函数会同时产出 K 线的开始时间,用于推进检查点。
import {
CandleInterval,
GetCandlesRequest_CandleSource,
type HistoricCandle,
type TInvestNodeSDK
} from '@woodger/t-invest-node-sdk';
const minuteMs = 60_000;
const dayMs = 24 * 60 * minuteMs;
export async function* readCandleHistory(
sdk: Pick<TInvestNodeSDK, 'marketData'>,
instrumentUid: string,
from: number,
until: number,
signal: AbortSignal
): AsyncGenerator<{ candle: HistoricCandle; time: number }> {
let cursor = from;
let windowStart = from;
while (windowStart < until) {
signal.throwIfAborted();
const windowEnd = Math.min(windowStart + dayMs, until);
const { candles } = await sdk.marketData.getCandles({
instrumentId: instrumentUid,
from: new Date(windowStart),
to: new Date(windowEnd),
interval: CandleInterval.CANDLE_INTERVAL_1_MIN,
candleSourceType: GetCandlesRequest_CandleSource.CANDLE_SOURCE_EXCHANGE,
limit: 2400
}, { signal });
const ordered = candles.map((candle) => {
const time = candle.time?.getTime();
if (time === undefined) {
throw new Error('Missing candle time');
}
return { candle, time };
}).sort((a, b) => a.time - b.time);
for (const { candle, time } of ordered) {
signal.throwIfAborted();
if (time < cursor || time >= until) {
continue;
}
if (!candle.isComplete) {
return;
}
yield { candle, time };
cursor = time + minuteMs;
}
windowStart = windowEnd;
}
}
接收通知
函数开启一个订阅,并给出应补齐历史数据的结束时间,单位为 UTC 毫秒。订阅确认后,此时间为当前分钟的起点。收到 K 线后,此时间为该 K 线时段的结束时间。错误或流结束会传给恢复协调器。
import {
GetCandlesRequest_CandleSource,
SubscriptionAction,
SubscriptionInterval,
SubscriptionStatus,
type TInvestNodeSDK
} from '@woodger/t-invest-node-sdk';
const minuteMs = 60_000;
export async function* watchCandleUpdates(
sdk: Pick<TInvestNodeSDK, 'marketdataStream'>,
instrumentUid: string,
signal: AbortSignal
): AsyncGenerator<number> {
let subscribed = false;
const responses = sdk.marketdataStream.marketDataServerSideStream({
subscribeCandlesRequest: {
subscriptionAction: SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
instruments: [{
instrumentId: instrumentUid,
interval: SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
}],
waitingClose: true,
candleSourceType: GetCandlesRequest_CandleSource.CANDLE_SOURCE_EXCHANGE
}
}, { signal });
for await (const response of responses) {
signal.throwIfAborted();
if (!subscribed && response.subscribeCandlesResponse) {
const subscription = response.subscribeCandlesResponse.candlesSubscriptions.find(
(item) => item.instrumentUid === instrumentUid
&& item.interval === SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
);
if (subscription?.subscriptionStatus !== SubscriptionStatus.SUBSCRIPTION_STATUS_SUCCESS
|| !subscription.waitingClose) {
throw new Error('Closed-candle subscription was rejected');
}
subscribed = true;
yield Math.floor(Date.now() / minuteMs) * minuteMs;
}
if (response.candle) {
if (!subscribed) {
throw new Error('Candle received before subscription confirmation');
}
const time = response.candle.time?.getTime();
if (time === undefined) {
throw new Error('Missing candle time');
}
yield time + minuteMs;
}
}
}
恢复读取
from 是第一个尚未处理的 UTC 分钟的起点。协调器将历史补齐到订阅给出的时间,并向使用方产出 K 线。它跨连接保留 nextMinute,并在处理 K 线后重置失败计数。检查点在从 yield 恢复后才会前进,以便使用方先保存 K 线。
import { setTimeout as delay } from 'node:timers/promises';
import {
isSdkError,
SdkErrorCode,
type HistoricCandle,
type TInvestNodeSDK
} from '@woodger/t-invest-node-sdk';
import { readCandleHistory } from './read-candle-history.js';
import { watchCandleUpdates } from './watch-candle-updates.js';
const minuteMs = 60_000;
export async function* recoverClosedCandles(
sdk: Pick<TInvestNodeSDK, 'marketData' | 'marketdataStream'>,
instrumentUid: string,
from: Date,
signal: AbortSignal
): AsyncGenerator<HistoricCandle> {
let nextMinute = from.getTime();
let failures = 0;
const maxRetries = 5;
if (!Number.isFinite(nextMinute) || nextMinute % minuteMs !== 0) {
throw new Error('from must identify a UTC minute boundary');
}
while (!signal.aborted) {
const attempt = new AbortController();
const attemptSignal = AbortSignal.any([signal, attempt.signal]);
try {
for await (const until of watchCandleUpdates(sdk, instrumentUid, attemptSignal)) {
for await (const { candle, time } of readCandleHistory(
sdk, instrumentUid, nextMinute, until, attemptSignal
)) {
yield candle;
nextMinute = time + minuteMs;
failures = 0;
}
}
}
catch (error: unknown) {
if (signal.aborted && (error === signal.reason
|| (isSdkError(error, SdkErrorCode.Cancelled) && error.source === 'abort'))) {
return;
}
if (!isSdkError(error, SdkErrorCode.Unavailable)
|| error.source !== 'grpc' || failures >= maxRetries) {
throw error;
}
}
finally {
attempt.abort();
}
if (signal.aborted) {
return;
}
if (failures >= maxRetries) {
throw new Error('Stream recovery attempts exhausted');
}
const backoffMs = Math.min(30_000, 1000 * 2 ** failures);
failures += 1;
try {
await delay(backoffMs * (0.5 + Math.random() * 0.5), undefined, { signal });
}
catch (error: unknown) {
if (!signal.aborted) {
throw error;
}
return;
}
}
}
连续五次重连失败后,生成器以错误结束。成功处理新的 K 线会重置计数。TLS、授权、配额、订阅、数据和本地配置错误会立即传递给调用方。
共享的 AbortSignal 可以取消下次重试前的等待。流正常结束也会触发重连。开启下一次尝试之前,协调器会取消已结束的尝试。
示例刻意在收到通知时调用 GetCandles,因为流中的已收盘 K 线可能先于相应的历史记录出现。如果历史中还没有该根已收盘 K 线,检查点会保留原位,并在下一个通知或重连时重新读取。如果长时间没有新通知,应用需安排定期补齐和 ping 检查。
保存 K 线并结束
演示将数据和检查点保存在内存中。在实际应用中,请用同一个存储事务替换对 Map 和检查点的更新,并在启动前加载检查点。记录键应包含标的、时间间隔、数据来源和 K 线时间,且同键重复写入应是安全的。
import {
createInMemoryUnaryLimiter,
TInvestNodeSDK,
type HistoricCandle
} from '@woodger/t-invest-node-sdk';
import { recoverClosedCandles } from './recover-closed-candles.js';
const instrumentUid = 'YOUR_INSTRUMENT_UID';
const sdk = new TInvestNodeSDK({
token: 'YOUR_TOKEN',
endpoint: 'invest-public-api.tbank.ru:443',
unaryLimiter: createInMemoryUnaryLimiter()
});
const shutdown = new AbortController();
const requestShutdown = () => shutdown.abort();
const stored = new Map<string, HistoricCandle>();
let checkpoint = new Date(Math.floor(Date.now() / 60_000) * 60_000 - 3_600_000);
process.once('SIGINT', requestShutdown);
process.once('SIGTERM', requestShutdown);
try {
for await (const candle of recoverClosedCandles(
sdk, instrumentUid, checkpoint, shutdown.signal
)) {
const time = candle.time?.getTime();
if (time === undefined) {
throw new Error('Missing candle time');
}
const key = `${instrumentUid}:1min:exchange:${time}`;
stored.set(key, candle);
checkpoint = new Date(time + 60_000);
console.log({ key, candle, nextMinute: checkpoint });
}
}
finally {
process.off('SIGINT', requestShutdown);
process.off('SIGTERM', requestShutdown);
shutdown.abort();
sdk.close();
}
生成器从 yield 恢复后才会推进检查点。在此处的 for await 循环中,这发生在写入之后。写入出错时,循环会关闭生成器并取消当前尝试。写入错误会传给调用方,无需触发重连。再次运行时,只应使用已成功保存的数据所对应的检查点。
此场景需要通过 sdk.instruments 获取的 UID。请在 YOUR_INSTRUMENT_UID 中填入该 UID,并将 YOUR_TOKEN 替换为应用自己的令牌。
示例中的限流器管理单个进程内的一元补齐请求。跨进程的配额和流式连接的配额需要单独考虑。API 限额
要在无需连接券商的情况下验证此场景,请使用公开导出中的测试服务。请覆盖订阅确认后断开、补齐失败、重复 K 线、订阅被拒绝、耗尽重试次数及等待重连时取消的情况。