T-Invest Node SDK Node.js
On this page

Read a stream and stop it

Use this example to read T-Invest events until cancellation, an error, or closure by the provider. The application opens a stream, passes it an AbortSignal, and releases its handlers when reading ends. It handles expected cancellation, keeps provider errors visible, and closes the SDK after the stream stops.

Open a server-side stream

The example installs process signal handlers, passes one AbortSignal to the streaming RPC, and handles local cancellation as normal completion. Provider errors propagate to the caller.

server-side-stream.ts
import {
  isSdkError,
  SdkErrorCode,
  SubscriptionAction,
  SubscriptionInterval,
  TInvestNodeSDK
} from '@woodger/t-invest-node-sdk';

const sdk = new TInvestNodeSDK({
  token: 'YOUR_TOKEN',
  endpoint: 'invest-public-api.tbank.ru:443'
});

const shutdown = new AbortController();
const requestShutdown = () => shutdown.abort();

process.once('SIGINT', requestShutdown);
process.once('SIGTERM', requestShutdown);

try {
  const responses = sdk.marketdataStream.marketDataServerSideStream(
    {
      subscribeCandlesRequest: {
        subscriptionAction: SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
        instruments: [
          {
            instrumentId: 'BBG00QPYJ5H0',
            interval: SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
          }
        ],
        waitingClose: false
      }
    },
    { signal: shutdown.signal }
  );

  for await (const response of responses) {
    if (response.candle) {
      console.log(response.candle);
    }
  }
}
catch (error) {
  if (
    !shutdown.signal.aborted
    || !isSdkError(error, SdkErrorCode.Cancelled)
    || error.source !== 'abort'
  ) {
    throw error;
  }
}
finally {
  process.off('SIGINT', requestShutdown);
  process.off('SIGTERM', requestShutdown);

  shutdown.abort();
  sdk.close();
}

Open a bidirectional Market Data stream

A bidirectional RPC takes an asynchronous source of MarketDataRequest requests. With a finite set of initial requests, the source can finish immediately after yield. The response stream stays open until cancellation or closure by the provider.

bidirectional-stream.ts
import {
  SubscriptionAction,
  SubscriptionInterval,
  TInvestNodeSDK
} from '@woodger/t-invest-node-sdk';

async function* initialRequests() {
  yield {
    subscribeCandlesRequest: {
      subscriptionAction:
        SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
      instruments: [
        {
          instrumentId: 'BBG00QPYJ5H0',
          interval:
            SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
        }
      ],
      waitingClose: false
    }
  };
}

export async function runMarketDataStream(sdk: TInvestNodeSDK, signal: AbortSignal): Promise<void> {
  const responses = sdk.marketdataStream.marketDataStream(
    initialRequests(),
    {
      signal
    }
  );

  for await (const response of responses) {
    console.log(response);
  }
}

Create and release sdk and signal as in the full server-side stream example above. If the request source stays active after the initial subscription, have it handle cancellation, stop producing requests, and remove event handlers.

Change a subscription while reading

The request source can stay active and send subscription changes while the application reads responses. The example first subscribes to one-minute candles and sends an unsubscribe request over the same RPC ten seconds later. Subscription and unsubscription acknowledgments arrive in subscribeCandlesResponse and are printed with the other responses.

subscription-changes.ts
import { setTimeout as delay } from 'node:timers/promises';
import {
  SubscriptionAction,
  SubscriptionInterval,
  type TInvestNodeSDK
} from '@woodger/t-invest-node-sdk';

async function* subscriptionChanges(instrumentUid: string, signal: AbortSignal) {
  const subscription = {
    instruments: [{
      instrumentId: instrumentUid,
      interval: SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
    }],
    waitingClose: true
  };
  const subscriptionDurationMs = 10_000;

  signal.throwIfAborted();

  yield {
    subscribeCandlesRequest: {
      ...subscription,
      subscriptionAction: SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE
    }
  };

  await delay(subscriptionDurationMs, undefined, { signal });

  yield {
    subscribeCandlesRequest: {
      ...subscription,
      subscriptionAction: SubscriptionAction.SUBSCRIPTION_ACTION_UNSUBSCRIBE
    }
  };
}

export async function runSubscriptionChanges(
  sdk: Pick<TInvestNodeSDK, 'marketdataStream'>,
  instrumentUid: string,
  signal: AbortSignal
): Promise<void> {
  const session = new AbortController();
  const sessionSignal = AbortSignal.any([signal, session.signal]);

  try {
    const responses = sdk.marketdataStream.marketDataStream(
      subscriptionChanges(instrumentUid, sessionSignal),
      { signal: sessionSignal }
    );

    for await (const response of responses) {
      console.log(response);
    }
  }
  finally {
    session.abort();
  }
}

Pass the UID from the instrument lookup example. Follow the first example on this page to create the SDK, handle local cancellation, and close the channel. The shared signal stops both the RPC and the wait in the request source. If reading ends early, finally cancels the remaining wait.

The response stream stays open after the request source finishes unsubscribing. It runs until cancellation or closure by the provider. Order state streams use a different subscription, shown in the order state example.

Recover a stream after a disconnect

The market data recovery example shows how to resubscribe, backfill closed one-minute candles, and save progress after writing. The application manages recovery. The SDK propagates errors to let the application control retries.

Stop the stream before closing the SDK

The code controlling a long-running operation should follow these steps.

  1. Abort the signal passed to the streaming RPC.
  2. Wait for the current read to end and handle the expected cancellation.
  3. Stop the application's data sources and remove process signal handlers.
  4. Call sdk.close().

You can call sdk.close() repeatedly. For an active stream, first abort reading with your signal and wait for the operation to finish, then close the channel.

Streaming calls bypass TInvestUnaryLimiter. See the limits policy for connection and subscription quotas and the streaming CLI reference for CLI behavior.