Skip to main content

Tinkoff Invest

Project description

T-Invest

Build Status PyPI PyPI - Python Version Codecov GitHub last commit Tinvest

pip install tinvest

Данный проект представляет собой инструментарий на языке Python для работы с OpenAPI Тинькофф Инвестиции, который можно использовать для создания торговых роботов.

Клиент предоставляет синхронный и асинхронный API для взаимодействия с Тинькофф Инвестиции.

Начало работы

Где взять токен аутентификации?

В разделе инвестиций вашего личного кабинета tinkoff . Далее:

  • Перейдите в настройки
  • Проверьте, что функция "Подтверждение сделок кодом" отключена
  • Выпустите токен для торговли на бирже и режима "песочницы" (sandbox)
  • Скопируйте токен и сохраните, токен отображается только один раз, просмотреть его позже не получится, тем не менее вы можете выпускать неограниченное количество токенов

Документация

Документацию непосредственно по OpenAPI можно найти по ссылке.

Быстрый старт

Для непосредственного взаимодействия с OpenAPI нужно создать клиента. Клиенты разделены на streaming и rest.

Примеры использования SDK находятся ниже.

У меня есть вопрос

Основной репозиторий с документацией — в нем вы можете задать вопрос в Issues и получать информацию о релизах в Releases. Если возникают вопросы по данному SDK, нашёлся баг или есть предложения по улучшению, то можно задать его в Issues.

Примеры:

Для работы с данным пакетом вам нужно изучить OpenAPI Тинькофф Инвестиции ссылка

import asyncio
from datetime import datetime

import tinvest

TOKEN = "<TOKEN>"

events = tinvest.StreamingEvents()


@events.candle()
async def handle_candle(
    api: tinvest.StreamingApi,
    payload: tinvest.CandleStreaming,
    server_time: datetime  # [optional] if you want
):
    print(payload)


@events.orderbook()
async def handle_orderbook(
    api: tinvest.StreamingApi, payload: tinvest.OrderbookStreaming
):
    print(payload)


@events.instrument_info()
async def handle_instrument_info(
    api: tinvest.StreamingApi, payload: tinvest.InstrumentInfoStreaming
):
    print(payload)


@events.error()
async def handle_error(
    api: tinvest.StreamingApi, payload: tinvest.ErrorStreaming
):
    print(payload)


@events.startup()
async def startup(api: tinvest.StreamingApi):
    await api.candle.subscribe("BBG0013HGFT4", tinvest.CandleResolution.min1)
    await api.orderbook.subscribe("BBG0013HGFT4", 5, "123ASD1123")
    await api.instrument_info.subscribe("BBG0013HGFT4")


@events.cleanup()
async def cleanup(api: tinvest.StreamingApi):
    await api.candle.unsubscribe("BBG0013HGFT4", "1min")
    await api.orderbook.unsubscribe("BBG0013HGFT4", 5)
    await api.instrument_info.unsubscribe("BBG0013HGFT4")


async def main():
    await tinvest.Streaming(TOKEN, state={"postgres": ...}).add_handlers(events).run()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
import tinvest

TOKEN = "<TOKEN>"

client = tinvest.SyncClient(TOKEN)
api = tinvest.PortfolioApi(client)

response = api.portfolio_get()  # requests.Response
if response.status_code == 200:
    print(response.parse_json())  # tinvest.PortfolioResponse
# Handle error
...
api = tinvest.OperationsApi(client)

response = api.operations_get("", "")
if response.status_code != 200:
    print(response.parse_error())  # tinvest.Error
import asyncio
import tinvest

TOKEN = "<TOKEN>"

client = tinvest.AsyncClient(TOKEN)
api = tinvest.PortfolioApi(client)


async def request():
    async with api.portfolio_get() as response:  # aiohttp.ClientResponse
        if response.status == 200:
            print(await response.parse_json())  # tinvest.PortfolioResponse


loop = asyncio.get_event_loop()
loop.run_until_complete(request())

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tinvest-1.0.20.tar.gz (13.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tinvest-1.0.20-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file tinvest-1.0.20.tar.gz.

File metadata

  • Download URL: tinvest-1.0.20.tar.gz
  • Upload date:
  • Size: 13.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.0.5 CPython/3.7.1 Linux/4.15.0-1028-gcp

File hashes

Hashes for tinvest-1.0.20.tar.gz
Algorithm Hash digest
SHA256 0b3f0b58e160fa3b2e8090a64948262216b0879ff82255637142b6ff25961edf
MD5 90756d85583aa385dcebef02fef982ef
BLAKE2b-256 47e38cefc5da6bb2f7f77f03f64ab1760c567ae6a1d7ed70451fd2a8f37b9581

See more details on using hashes here.

File details

Details for the file tinvest-1.0.20-py3-none-any.whl.

File metadata

  • Download URL: tinvest-1.0.20-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.0.5 CPython/3.7.1 Linux/4.15.0-1028-gcp

File hashes

Hashes for tinvest-1.0.20-py3-none-any.whl
Algorithm Hash digest
SHA256 d1b2f7c59c63d0f71991277a2bbf7996643a68564ddaacf9b38e9d343632b8ea
MD5 4026c4a813e3e8cff299d87b69257d0b
BLAKE2b-256 cf31f34dff7824ceedbd07c31ea4cef56f75744b220685781047326df274299d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page