def __init__(self, token, currency='USD'): self._client = openapi.sandbox_api_client(token) # register new client self._client.sandbox.sandbox_register_post() # clear all orders self._client.sandbox.sandbox_clear_post() # remove balance self._client.sandbox.sandbox_remove_post() self.all_instruments = self.get_all_instruments(currency)
def __init__(self, token): self.__token = token self.__cli_impl = openapi.sandbox_api_client(self.__token) self.__cli_impl.sandbox.sandbox_register_post() self.__cli_impl.sandbox.sandbox_clear_post() self.__cli_impl.sandbox.sandbox_currencies_balance_post( sandbox_set_currency_balance_request={ "currency": "USD", "balance": 1000 })
def get_candles(*args, get_data_task_pk, **kwargs): task = GetDataTask.objects.get(pk=get_data_task_pk) granularity_interval = task.interval to = task.to_time _from = task.from_time figi = task.figi if granularity_interval not in CandleResolution.allowable_values: raise ValueError(f'granularity_interval = {granularity_interval} not in {CandleResolution.allowable_values}') overall_interval = to - _from max_overall_interval = get_max_overall_interval_from_granularity_interval(granularity_interval) sub_intervals_count = math.ceil(overall_interval / max_overall_interval) sub_interval_length = overall_interval / sub_intervals_count time_points = [_from + sub_interval_length * i for i in range(sub_intervals_count)] time_points.append(to) tinkoff_client: SandboxOpenApi = sandbox_api_client(settings.TINKOFF_INVESTMENTS_SANDBOX_OPEN_API_TOKEN) try: instrument = Instrument.objects.get(figi=figi) except Instrument.DoesNotExist: market_search_by_figi_with_retry_on_rate_limits = \ retry_on_rate_limits_exception(tinkoff_client.market.market_search_by_figi_get) response: MarketInstrumentListResponse = market_search_by_figi_with_retry_on_rate_limits(figi) instrument: SearchMarketInstrument = response.payload instrument_serializer = serializers.InstrumentSerializer(data=instrument.to_dict()) instrument_serializer.is_valid(raise_exception=True) instrument_serializer.save() instrument = instrument_serializer.instance for start, end in pairwise(time_points): market_candles_get_with_retry_on_rate_limits = \ retry_on_rate_limits_exception(tinkoff_client.market.market_candles_get_with_http_info) response, status, headers = market_candles_get_with_retry_on_rate_limits(figi, start, end, granularity_interval) payload: Candles = response.payload candles: List[Candle] = payload.candles for candle in candles: if not models.Candle.objects.filter(instrument=instrument, time=candle.time, interval=candle.interval): candle_serializer = serializers.CandleSerializer(data=candle.to_dict()) candle_serializer.is_valid(raise_exception=True) candle_serializer.save()
def get_figi(): ticker = 'ALRS' tinkoff_client = sandbox_api_client( TINKOFF_INVESTMENTS_SANDBOX_OPEN_API_TOKEN) response: MarketInstrumentListResponse = tinkoff_client.market.market_search_by_ticker_get( ticker) payload: MarketInstrumentList = response.payload instrument: MarketInstrument = payload.instruments[0] return instrument.figi
def connect(token=None): """ Function that creates connection to Tinkoff API Parameters ---------- token : string API key for either sandbox or prod. Taken from .env file To get your key, log in to you account on tinkoff.ru Go to investment Go to settings Function "deals confirmation by code" should be turned off Issue a token for OpenAPI for sandbox and prod. If system asks you to authorize one more time-it's okay. Copy and paste token (to .env file for example) Token will be shown only once, but you can issue as many tokens as you want. Returns ------- Connector. Client object of clickhouse_driver.client module ping (list of tuples): responce from server """ logger = logging.getLogger(apiname + connect.__name__) logger.info(f"connection to TinkoffAPI is in progress ...") client = openapi.sandbox_api_client(token) try: ping = client.sandbox.sandbox_register_post() client.sandbox.sandbox_clear_post() client.sandbox.sandbox_currencies_balance_post( sandbox_set_currency_balance_request={ "currency": "USD", "balance": 1000 }) # except InterfaceError: # not tested. # print("InterfaceError error is catched.") except Exception as exc: logger.error(f"generated an exception: {exc}") client = None ping = str(exc) else: logger.info("connected to API web service.") return client, ping
def get_instruments(*args, get_data_task_pk, **kwargs): currency = Currency.RUB logging.debug('started get_instruments()') tinkoff_client: SandboxOpenApi = sandbox_api_client(settings.TINKOFF_INVESTMENTS_SANDBOX_OPEN_API_TOKEN) response: MarketInstrumentListResponse = tinkoff_client.market.market_stocks_get() payload: MarketInstrumentList = response.payload instruments: List[MarketInstrument] = payload.instruments instruments = list(filter(lambda i: i.currency == currency, instruments)) for instrument in instruments: data = instrument.to_dict() if not Instrument.objects.filter(figi=instrument.figi): instrument = serializers.InstrumentSerializer(data=data) instrument.is_valid(raise_exception=True) instrument.save() logging.debug('completed get_instruments()')
from openapi_client import openapi token = 'YOUR TOKEN' client = openapi.sandbox_api_client(token) client.sandbox.sandbox_register_post() client.sandbox.sandbox_currencies_balance_post( sandbox_set_currency_balance_request={ "currency": "USD", "balance": 1000 })
def __init__(self, token=utils.TOKEN): self._token = token self._client = openapi.sandbox_api_client( self._token) # Initialize the openapi self._market = self.client.market
import logging import datetime import time import lxml import pandas import requests import telebot from bs4 import BeautifulSoup from openapi_client import openapi # token Telegram token_bot = telebot.TeleBot('token') # token API Тинькофф Инвестиции client_invest = openapi.sandbox_api_client('token') # main keyboard user main_user_keyboard = telebot.types.ReplyKeyboardMarkup(True, False) main_user_keyboard.row('Погода', 'Новости', 'Акции', 'Нефть') main_user_keyboard.row('Погода в другом городе', 'Портфель') # keyboard button back user_keyboard_back = telebot.types.ReplyKeyboardMarkup(True, False) user_keyboard_back.row('Назад') # keyboard button back and request geo-coordinates user_keyboard_geo_back = telebot.types.ReplyKeyboardMarkup(True, False) user_keyboard_geo_back.add( telebot.types.KeyboardButton(text='Отправить местоположение', request_location=True), 'Назад')