tbank_invest

Languages: English · Русский

Unofficial Dart client for T‑Invest (T‑Bank) Invest API — REST (Dio) + dart:io WebSocket helpers. Not an official SDK.

Flutter Web / browser: not supported — the main import pulls in dart:io (see Platform support).


English

Dart client for T‑Invest:

  • REST — thin wrappers over every method from the official OpenAPI (POST + JSON), using Dio.
  • WebSocketWebSocket helper with Authorization and the json subprotocol for streaming endpoints.

Platform support

Where What to expect
Flutter on iOS, Android, macOS, Windows, and Dart CLI on the same desktop OSes Use the package as documented: REST (TinvestClient) and InvestWebSocket both work.
Flutter Web, dart2js, or other browser / JS targets Unsupported today. The default barrel file tbank_invest.dart exports invest_websocket.dart, which imports dart:io, so the project will not compile for web — not only streaming, but the entire import 'package:tbank_invest/tbank_invest.dart' graph. A web-capable build would need a separate entry point without dart:io (not shipped in this version).

Table of contents (EN)

Features

Area Notes
REST One class per gRPC/OpenAPI service (InvestUsersApi, InvestMarketDataApi, …). Each method maps 1:1 to a path in InvestApiPaths.
JSON Responses are JsonMap — map to your own models as needed.
Auth Bearer token on every request; optional x-app-name via InvestConfig.appName.
WebSocket InvestWebSocket.connect builds wss://… URLs from InvestConfig + InvestApiPaths.
Helpers MoneyValue, Quotation, InvestApiException (HTTP status, gRPC code, x-tracking-id when present).

Installation

dependencies:
  tbank_invest: ^0.1.1

Path dependency during development:

dependencies:
  tbank_invest:
    path: packages/tbank_invest

Quick start (REST)

import 'package:tbank_invest/tbank_invest.dart';

Future<void> main() async {
  final client = TinvestClient(
    InvestConfig(
      token: 't.your_token_here',
      environment: InvestEnvironment.sandbox,
    ),
  );

  try {
    final json = await client.users.getAccounts({});
    final accounts = json['accounts'];
  } on InvestApiException catch (e) {
    print(e);
  } finally {
    client.close();
  }
}

Token via CLI:

dart run --define=TBANK_TOKEN=t.xxx bin/your_app.dart
const token = String.fromEnvironment('TBANK_TOKEN', defaultValue: '');

Configuration

Field Purpose
token API token (t.…), without Bearer .
environment production or sandbox — REST/WSS base URLs.
appName Optional x-app-name if registered with T‑Bank.
logHttpTraffic If true, Dio logs bodies (not Authorization). Default false.
Timeouts connectTimeout, receiveTimeout, sendTimeout.

WebSocket

Same path segments as REST (InvestApiPaths), wss://, subprotocol json, Authorization: Bearer <token>. Payloads: official WebSocket / protobuf JSON (asyncapi, WS docs).

Last-price subscribe example:

import 'dart:convert';
import 'dart:io' show WebSocket;

import 'package:tbank_invest/tbank_invest.dart';

Future<void> lastPriceExample(InvestConfig config) async {
  final ws = await InvestWebSocket.connect(
    config: config,
    apiPath: InvestApiPaths.marketDataStreamServiceMarketDataStream,
  );

  ws.add(jsonEncode({
    'subscribeLastPriceRequest': {
      'subscriptionAction': 'SUBSCRIPTION_ACTION_SUBSCRIBE',
      'instruments': [
        {'instrumentId': '<instrument-uuid>'},
      ],
    },
  }));

  await for (final data in ws) {
    final text = data is String ? data : utf8.decode(data as List<int>);
    print(text);
  }
}

Platforms: dart:io WebSocket works on Flutter iOS, Android, desktop; Flutter Web needs another transport.

Errors

  • InvestApiException — optional httpStatusCode, grpcCode, businessCode, trackingId.
  • InvestDecodeException — unexpected JSON.
  • InvestException — generic client error.

Package layout

lib/
  tbank_invest.dart
  src/
    invest_config.dart
    invest_http_client.dart
    invest_websocket.dart
    invest_exception.dart
    api_paths.dart
    json_types.dart
    models/
    services/
    tinvest_client.dart
example/
  example.dart

Limitations

  • No Flutter Web / browser — default import includes dart:io WebSocket; see Platform support.
  • No codegen for all DTOs — use JsonMap or your models.
  • Quotas and stream rules are enforced by T‑Bank.

Example app

dart run --define=TBANK_TOKEN=t.xxx example/example.dart

License

MIT — see LICENSE.


Русский

Неофициальный Dart-клиент для API Т‑Инвест (Т‑Банк):

  • REST — обёртки над методами из OpenAPI (POST + JSON), транспорт Dio.
  • WebSocket — помощник на базе WebSocket из dart:io с заголовком Authorization и подпротоколом json.

Официальным SDK пакет не является; контракты и лимиты — в документации Т‑Банка.

Flutter Web / браузер: не поддерживается — основной импорт тянет dart:io (см. Поддержка платформ).

Поддержка платформ

Где Что ждать
Flutter на iOS, Android, macOS, Windows и Dart CLI на тех же ОС Полный сценарий: REST (TinvestClient) и InvestWebSocket.
Flutter Web, dart2js, браузер / JS Сейчас не поддерживается. Файл tbank_invest.dart реэкспортирует invest_websocket.dart с dart:io, поэтому сборка под веб не проходит — страдает не только стрим, но и любой import 'package:tbank_invest/tbank_invest.dart'. Отдельная точка входа без dart:io в этой версии не поставляется.

Содержание (RU)

Возможности

Область Описание
REST Один класс на сервис OpenAPI (InvestUsersApi, InvestMarketDataApi, …), путь 1:1 с InvestApiPaths.
JSON Ответы — JsonMap; модели можно навесить сами.
Авторизация Bearer на каждый запрос; опционально x-app-name через InvestConfig.appName.
WebSocket InvestWebSocket.connect собирает wss://… из InvestConfig и InvestApiPaths.
Утилиты MoneyValue, Quotation, InvestApiException.

Установка

dependencies:
  tbank_invest: ^0.1.1

Локально из пути:

dependencies:
  tbank_invest:
    path: packages/tbank_invest

Быстрый старт (REST)

import 'package:tbank_invest/tbank_invest.dart';

Future<void> main() async {
  final client = TinvestClient(
    InvestConfig(
      token: 't.ВАШ_ТОКЕН',
      environment: InvestEnvironment.sandbox,
    ),
  );

  try {
    final json = await client.users.getAccounts({});
    final accounts = json['accounts'];
  } on InvestApiException catch (e) {
    print(e);
  } finally {
    client.close();
  }
}

Токен без хардкода:

dart run --define=TBANK_TOKEN=t.xxx bin/your_app.dart
const token = String.fromEnvironment('TBANK_TOKEN', defaultValue: '');

Конфигурация

Поле Назначение
token Токен API (t.…), без префикса Bearer .
environment production или sandbox — базовые URL REST/WSS.
appName Опционально, заголовок x-app-name, если зарегистрировано в Т‑Банке.
logHttpTraffic При true Dio пишет тела запросов/ответов (заголовок Authorization не логируется). По умолчанию false.
Таймауты connectTimeout, receiveTimeout, sendTimeout.

WebSocket (стримы)

Те же сегменты пути, что и у REST (InvestApiPaths), схема wss://, подпротокол json, Authorization: Bearer <token>. Формат тел сообщений — как в asyncapi и документации WS.

Пример подписки на последнюю цену — см. раздел English → WebSocket (тот же код).

Платформы: для Flutter подходят iOS, Android, desktop; веб — другой транспорт.

Ошибки

  • InvestApiException — тело ошибки API, при необходимости httpStatusCode, grpcCode, trackingId.
  • InvestDecodeException — неожиданная форма JSON.
  • InvestException — прочие ошибки клиента.

Структура пакета

lib/
  tbank_invest.dart      # Экспорт
  src/
    invest_config.dart
    invest_http_client.dart
    invest_websocket.dart
    invest_exception.dart
    api_paths.dart       # Константы путей (генерация)
    json_types.dart
    models/
    services/
    tinvest_client.dart
example/
  example.dart

Ограничения

  • Нет Flutter Web / браузера — в дефолтном импорте есть WebSocket на dart:io; см. Поддержка платформ.
  • Нет сгенерированных DTO для всех ответов — работа с JsonMap или своими моделями.
  • Лимиты API и правила стримов задаёт Т‑Банк.

Пример

Из корня пакета:

dart run --define=TBANK_TOKEN=t.xxx example/example.dart

Лицензия

MIT — файл LICENSE.

Libraries

tbank_invest
Dart client for the T-Invest REST API and WebSocket streams.