Path: blob/master/ invest-robot-contest_tinkoff-contest-python-main/src/service/config.py
5935 views
from typing import Optional12import tinkoff.invest3from tinkoff.invest import AccessLevel, AccountStatus, InstrumentIdType4from tinkoff.invest.async_services import AsyncServices56from src import settings7from src.containers.config import TraderConfig8from src.service.errors import ConfigError91011async def prepare_trader_config(config: dict) -> TraderConfig:12ticker = config["ticker"]13class_code = config["class_code"]1415async with tinkoff.invest.AsyncClient(16settings.INVEST_TOKEN, sandbox_token=settings.SANDBOX_TOKEN, app_name=settings.APP_NAME17) as services:18# get id of the user account19account_id = await _fetch_user_account_id(services, target_account_id=settings.ACCOUNT_ID)2021# TODO: check schedule, buy, sell and api trade flags (MarketDataService.GetTradingStatus first)22# check that the instrument is currently available for trading23instrument_data = (24await services.instruments.get_instrument_by(25id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER, id=ticker, class_code=class_code26)27).instrument28# schedule = await services.instruments.trading_schedules(29# from_=datetime.datetime.utcnow(),30# to=datetime.datetime.utcnow() + datetime.timedelta(days=5),31# exchange=instrument_data.exchange,32# )3334instrument_figi = instrument_data.figi3536return TraderConfig(account_id=account_id, instrument_figi=instrument_figi, config=config)373839async def _fetch_user_account_id(services: AsyncServices, *, target_account_id: Optional[str]) -> str:40accounts = (await services.users.get_accounts()).accounts41if target_account_id is not None:42try:43account = next(acc for acc in accounts if acc.id == target_account_id)44except StopIteration:45raise ConfigError("Specified account id is not found for the given token")46else:47if len(accounts) > 1:48raise ConfigError(49"Multiple accounts found for the token. "50"Please, specify the concrete one with the ACCOUNT_ID env variable."51)52account = accounts[0]5354# verify rights on the account55if account.access_level != AccessLevel.ACCOUNT_ACCESS_LEVEL_FULL_ACCESS:56raise ConfigError("The access token does not have full access to the account")57if account.status != AccountStatus.ACCOUNT_STATUS_OPEN:58raise ConfigError("Can not operate on the account with incorrect status")5960return account.id616263