Path: blob/master/ invest-robot-contest_TinkoffInvestBot-main/functions.py
5925 views
import tinkoff.invest as ti1import pandas as pd2from datetime import datetime, timedelta3from ta.momentum import stoch, stoch_signal456CONTRACT_PREFIX = 'tinkoff.public.invest.api.contract.v1.'7INSTRUMENT_TICKER = 'GAZP'8WINDOW = 149SMOOTH_WINDOW = 3101112# Преобразование цены (https://azzrael.ru/api-v2-tinkoff-invest-get-candles-python)13def convert_price(p):14return p.units + p.nano / 1e9151617# Сохранение свеч в датафрейм (https://azzrael.ru/api-v2-tinkoff-invest-get-candles-python)18def create_df(candles: [ti.HistoricCandle]):19df = pd.DataFrame([{20'time': c.time,21'volume': c.volume,22'open': convert_price(c.open),23'close': convert_price(c.close),24'high': convert_price(c.high),25'low': convert_price(c.low),26} for c in candles])27return df282930def create_df_from_stream(c):31df = pd.DataFrame({32'time': [c.time],33'volume': [c.volume],34'open': [convert_price(c.open)],35'close': [convert_price(c.close)],36'high': [convert_price(c.high)],37'low': [convert_price(c.low)]38})39return df404142# Получение FIGI для акций на Мосбирже43def get_shares_figi(cl, sharesticker):44result = cl.instruments.share_by(id_type=ti.InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER, class_code='TQBR',45id=sharesticker)46return result.instrument.figi474849def get_shares_lot_size(cl, sharesticker):50result = cl.instruments.share_by(id_type=ti.InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER, class_code='TQBR',51id=sharesticker)52return result.instrument.lot535455def recalculate_time_series(df1, df2):56del df1['%K']57del df1['%D']58result = pd.concat([df1, df2])59result.sort_values(by='time', inplace=True)60result = result.reset_index(drop=True)61result['%K'] = stoch(result['high'], result['low'], result['close'], window=WINDOW, smooth_window=SMOOTH_WINDOW,62fillna=True)63result['%D'] = stoch_signal(result['high'], result['low'], result['close'], window=WINDOW,64smooth_window=SMOOTH_WINDOW, fillna=True)65# print(result.tail())66return result676869def get_sandbox_account_id(cl):70accounts = cl.sandbox.get_sandbox_accounts()71if len(accounts.accounts) > 0:72result = accounts.accounts[0].id73print(cl.sandbox.get_sandbox_positions(account_id=result))74# cl.sandbox.close_sandbox_account(account_id=result)75else:76acc = cl.sandbox.open_sandbox_account()77result = acc.account_id78cl.sandbox.sandbox_pay_in(account_id=result, amount=ti.MoneyValue(currency='rub', units=10000, nano=0))79print(cl.sandbox.get_sandbox_positions(account_id=result))80return result818283def get_time_series(cl, figi):84starttime = datetime.now() - timedelta(days=1)85finishtime = datetime.now()86result = pd.DataFrame(data=None, columns=['time', 'volume', 'open', 'close', 'high', 'low'])87while result.shape[0] < 1000:88historiccandles = cl.market_data.get_candles(figi=figi, from_=starttime, to=finishtime,89interval=ti.CandleInterval.CANDLE_INTERVAL_5_MIN)90tempdf = create_df(historiccandles.candles)91result = pd.concat([result, tempdf])92starttime = starttime - timedelta(days=1)93finishtime = finishtime - timedelta(days=1)94result.sort_values(by='time', inplace=True)95result = result.reset_index(drop=True)96result['%K'] = stoch(result['high'], result['low'], result['close'], window=WINDOW, smooth_window=SMOOTH_WINDOW,97fillna=True)98result['%D'] = stoch_signal(result['high'], result['low'], result['close'], window=WINDOW,99smooth_window=SMOOTH_WINDOW, fillna=True)100return result101102103def get_account_id(cl):104result = 0105accounts = cl.users.get_accounts()106if len(accounts.accounts) > 0:107for account in accounts.accounts:108if account.access_level == ti.AccessLevel.ACCOUNT_ACCESS_LEVEL_FULL_ACCESS:109response = cl.operations.get_positions(account_id=account.id)110if response.money[0].units > 0:111result = account.id112if result == 0:113print('Нет аккаунтов с полным доступом или ненулевым балансом')114return result115116117