npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

tinkoff-invest-api

v6.0.0

Published

Node.js SDK for Tinkoff Invest API

Downloads

895

Readme

tinkoff-invest-api

Node.js SDK для работы с Tinkoff Invest API.

Установка

npm i tinkoff-invest-api

Использование

Подключение

import { TinkoffInvestApi } from 'tinkoff-invest-api';

// создать клиента с заданным токеном доступа
const api = new TinkoffInvestApi({ token: '<your-token>' });

Как получить токен доступа описано тут.

Unary-запросы

import { PortfolioRequest_CurrencyRequest } from 'tinkoff-invest-api/dist/generated/operations.js';
import { CandleInterval } from 'tinkoff-invest-api/dist/generated/marketdata.js';

// получить список счетов
const { accounts } = await api.users.getAccounts({});

// получить портфель по id счета
const portfolio = await api.operations.getPortfolio({
  accountId: accounts[0].id,
  currency: PortfolioRequest_CurrencyRequest.RUB
});

// получить 1-минутные свечи за последние 5 мин для акций Тинкофф Групп
const { candles } = await api.marketdata.getCandles({
  figi: 'BBG00QPYJ5H0',
  instrumentId: 'BBG00QPYJ5H0',
  interval: CandleInterval.CANDLE_INTERVAL_1_MIN,
  ...api.helpers.fromTo('-5m'), // <- удобный хелпер для получения { from, to }
});

Стримы

Для работы со стримом сделана обертка api.stream:

import { SubscriptionInterval } from 'tinkoff-invest-api/dist/generated/marketdata.js';

// подписка на свечи
const unsubscribe = await api.stream.market.candles({
  instruments: [
    {
      figi: 'BBG00QPYJ5H0',
      instrumentId: 'BBG00QPYJ5H0',
      interval: SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
    }
  ],
  waitingClose: false,
}, candle => console.log(candle));

// отписаться
await unsubscribe();

// обработка дополнительных событий
api.stream.market.on('error', error => console.log('stream error', error));
api.stream.market.on('close', error => console.log('stream closed, reason:', error));

// получить список текущих подписок
const data = await api.stream.market.getMySubscriptions();

// закрыть соединение
await api.stream.market.cancel();

Примечание: со стримом можно работать и напрямую через api.marketdataStream. Но там AsyncIterable, которые менее удобны (имхо)

По умолчанию стрим автоматически переподключается при потере соединения (#4). Чтобы это отключить, установите api.stream.market.options.autoReconnect = false.

Стримы доступны по следующим сущностям:

  • .candles(request, handler)
  • .trades(request, handler)
  • .orderBook(request, handler)
  • .lastPrice(request, handler)
  • .info(request, handler)

Универсальный счет

Для бесшовной работы со счетами в бою и песочнице сделан универсальный интерфейс TinkoffAccount.

import { TinkoffAccount, RealAccount, SandboxAccount } from 'tinkoff-invest-api';
import { OrderDirection, OrderType } from 'tinkoff-invest-api/dist/generated/orders.js';

// создать экземпляр счета: боевого или в песочнице
const account: TinkoffAccount = process.env.USE_REAL_ACCOUNT
    ? new RealAccount(api, '<real-account-id>')
    : new SandboxAccount(api, '<sandbox-account-id>');

// получить портфель
const protfolio = await account.getPortfolio();

// получить список заявок
const { orders } = await account.getOrders();

// создать лимит-заявку на покупку 1 лота по цене 100
const order = await account.postOrder({
  figi: 'BBG00QPYJ5H0',
  quantity: 1,
  price: api.helpers.toQuotation(100),
  direction: OrderDirection.ORDER_DIRECTION_BUY,
  orderType: OrderType.ORDER_TYPE_LIMIT,
  orderId: '<random-id>',
});

Все методы универсального счета можно посмотреть тут.

Кеширование свечей

Кеширование свечей позволяет сократить кол-во запросов к API, а также удобно получать нужное кол-во свечей за любой период времени (в исходном API есть ограничения на диапазоны дат запроса). Для загрузки свечей с учетом кеша используется класс CandlesLoader:

import { TinkoffInvestApi, CandlesLoader } from 'tinkoff-invest-api';
import { CandleInterval } from 'tinkoff-invest-api/dist/generated/marketdata.js';

const api = new TinkoffInvestApi({ token: '<your-token>' });

// создать инстанс загрузчика свечей
const candlesLoader = new CandlesLoader(api, { cacheDir: '.cache' });

// загрузить минимум 100 последних свечей (в понедельник будут использованы данные пятницы, итп)
const { candles } = await candlesLoader.getCandles({
  figi: 'BBG004730N88',
  instrumentId: 'BBG004730N88',
  interval: CandleInterval.CANDLE_INTERVAL_15_MIN,
  minCount: 100, // <- этот параметр позволяет задать кол-во свечей в результате
});
.cache
  candles
    <figi>
      1_min
        2022-05-01.json
        2022-05-02.json
      5_min
        2022-05-01.json
        2022-05-02.json
      15_min
        2022-05-01.json
        2022-05-02.json
      hour
        2022-05-01.json
        2022-05-02.json
      day
        2020.json
        2021.json
        2022.json

Хелперы

Для более удобной работы есть несколько хелперов:

import { Helpers } from 'tinkoff-invest-api';

/**
 * Переводит число в Quotation.
 * Пример: 123.4 -> { units: 123, nano: 400000000 }
 */
Helpers.toQuotation(value: number): Quotation;

/**
 * Переводит число в MoneyValue.
 * Пример: (123.4, 'rub') -> { units: 123, nano: 400000000, currency: 'rub' }
 */
Helpers.toMoneyValue(value: number, currency: string): MoneyValue;

/**
 * Переводит MoneyValue в строку.
 * Пример: { units: 123, nano: 400000000, currency: 'rub' } -> '123.4 rub'
 */
Helpers.toMoneyString(value: MoneyValue | undefined): string;

/**
 * Переводит Quotation или MoneyValue в число.
 * Пример: { units: 123, nano: 400000000 } -> 123.4
 */
Helpers.toNumber(value: Quotation | MoneyValue): number;

/**
 * Возвращает интервал времени в формате { from, to } по заданному смещению и базовой дате.
 * Для смещения можно использовать кол-во миллисекунд или строку в формате из https://github.com/vercel/ms.
 * Пример: получить { from, to } за последние 5 минут -> fromTo('-5m')
 */
Helpers.fromTo(offset: string | number, base?: Date): { from: Date; to: Date; };

/**
 * Переводит значения констант в человеко-читаемые строки.
 * Например: CandleInterval.CANDLE_INTERVAL_1_MIN -> '1_MIN'
 */
Helpers.toHuman<T extends Enums>(value: T, values: getEnumType<T>): string;

Отладка

Для отладки используется модуль debug. Чтобы вывести отладочную информацию, нужно указать переменную окружения DEBUG:

DEBUG=tinkoff-invest-api:* node robot.js

Лицензия

MIT @ Vitaliy Potapov