Recover a stream of closed candles
Use this example when a stream disconnect must not skip closed one-minute candles. The application resubscribes, backfills history through GetCandles, and saves a checkpoint after writing each candle. It resumes from the last saved position and emits only closed candles.
The application manages reconnection using public SDK methods. Both the SDK facade and stream run leave reconnection to the caller.
Recover after a disconnect
- Open a stream and wait for successful subscription confirmation with
waitingClose: true. - Read history through
GetCandlesfrom the first unprocessed minute to the start of the current minute. - Treat subsequent candles from the stream as notifications of new closed intervals and backfill them through
GetCandles. - Save the current candle and the checkpoint for resuming before processing the next candle.
- After a transport
UNAVAILABLEor normal stream closure, resubscribe with a bounded delay between attempts.
Persisted data always comes from the historical method with one source and interval. Open the subscription before backfilling and then read notifications queued during the backfill. Overlapping requests skip already processed candles. Only closed candles are emitted.
This example recovers candle history. Trades, order books, and portfolios need their own snapshot and reconciliation rules. A common read position cannot reproduce every exchange event in a stream.
Corrections to published history and delays in its appearance require periodic reconciliation by the application. See the official documentation for GetCandles time-range limits.
Split the example into files
Put the four files in one directory. read-candle-history.ts reads history, watch-candle-updates.ts opens a subscription, recover-closed-candles.ts coordinates recovery, and main.ts saves the data and manages the SDK lifetime.
The example assumes the API returns valid data for the requested parameters.
Backfill history
The function takes the start time from and end time until in UTC milliseconds. It reads history in windows of up to a day. limit: 2400 covers the one-minute candles in one window. It sorts the candles, skips duplicates, and stops at the first incomplete candle. It yields the candle's start time so the checkpoint can advance.
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;
}
}
Receive notifications
The function opens one subscription and yields the time to backfill up to in UTC milliseconds. After the subscription is confirmed, this is the start of the current minute. When a candle arrives, it is the end of the candle's interval. Errors and stream closure propagate to the recovery coordinator.
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;
}
}
}
Resume reading
from is the start of the first unprocessed UTC minute. The coordinator backfills up to the time sent by the subscription and yields candles to the consumer. It keeps nextMinute across connections and resets the failure counter after processing a candle. It advances the checkpoint after resuming from yield so the consumer can save the candle first.
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;
}
}
}
After five consecutive failed reconnections, the generator fails. Successfully processing a new candle resets the counter. TLS, authorization, quota, subscription, data, and local configuration errors propagate immediately.
The shared AbortSignal cancels the wait before retrying. Normal stream closure also triggers reconnection. The coordinator cancels the completed attempt before opening the next one.
The example calls GetCandles on every notification because a closed candle can arrive in the stream before its historical record is available. If history still lacks the closed candle, its checkpoint stays put and the next notification or reconnection retries the read. If notifications stop for a long time, the application should arrange periodic backfills and ping checks.
Save candles and stop
The demonstration stores data and its checkpoint in memory. In an application, replace the Map and checkpoint updates with one storage transaction and load the checkpoint before startup. Include the instrument, interval, source, and candle time in the record key, and make repeated writes under the same key safe.
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();
}
The generator advances its checkpoint after resuming from yield. In the shown for await loop, that happens after the write. If writing throws, the loop closes the generator and cancels the current attempt. The write error propagates to the caller without triggering reconnection. On restart, use only a checkpoint for successfully stored data.
The scenario requires a UID from sdk.instruments. Supply that UID in YOUR_INSTRUMENT_UID and replace YOUR_TOKEN with your own token.
The example's limiter applies to unary backfill calls in one process. Account for quotas across processes and for streaming connections separately. API limits
See Streams and cancellation for cancellation and cleanup and Errors and lifecycle for error classification.
Use test services from public exports to test without connecting to the broker. Test disconnects after subscription confirmation, backfill errors, repeated candles, rejected subscriptions, exhausted attempts, and cancellation while waiting to reconnect.