Path: blob/master/ invest-robot-contest_trading_bot-master/trading/trade_help.py
5932 views
from config.personal_data import get_token, get_account, get_account_type1import math2from tinkoff.invest import Client, Quotation, CandleInterval3from datetime import datetime, timedelta4from pycbrf.toolbox import ExchangeRates56"""78Тут представлены все небольшие вспомогательные функции910"""1112'''13Функция для расчёта полной стоимости актива / общего количества средств14Тинькофф возвращает стоимость в units и nano15units - целая часть16nano - дробная (9 знаков после запятой)17'''181920def quotation_to_float(quotation: Quotation):21sum = quotation.units + (quotation.nano * 1e-9)22return sum232425'''26Функция для перевода дробного числа в Quotation27Тинькофф получает стоимость в units и nano28units - целая часть29nano - дробная (9 знаков после запятой)30'''313233def to_quotation(price):34quotation = Quotation()35quotation.units = int(math.modf(price)[1])36quotation.nano = int(round(math.modf(price)[0] * 1e9))37return quotation383940'''41Позволяет узнать количество бумаг в одном лоте по FIGI42'''434445def in_lot_figi(figi, user_id):46with Client(get_token(user_id)) as client:47in_lot = client.instruments.get_instrument_by(id_type=1, id=figi).instrument.lot4849return int(in_lot)505152'''53Позволяет узнать, есть ли такой инструмент в портфеле54Сравнение идёт по FIGI55'''565758def is_in_portfolio(figi, user_id, account_id="", account_type=""):59with Client(get_token(user_id)) as client:6061if account_id == "":62account_id = get_account(user_id=user_id)6364if account_type == "":65account_type = get_account_type(user_id=user_id)6667if account_type == "sandbox":68portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)69else:70portfolio = client.operations.get_portfolio(account_id=account_id)71for i in portfolio.positions:72if i.figi == figi:73return True7475return False767778'''79Функция для получения средней цены акции по свече8081В API Tinkoff нет функции, которая позволит узнать стоимость бумаги по FIGI82По этой причине было решено получить свечки за неделю и взять последнюю доступную.83Такое решение связано с тем, что торги не проходят в выходные дни, поэтому наилучшим решением будет выбрать84большой интервал времени для избежания ошибок.85'''868788def get_price_figi(figi, user_id):89with Client(get_token(user_id)) as client:90try:91candle = client.market_data.get_candles(92figi=figi,93from_=datetime.utcnow() - timedelta(days=7),94to=datetime.utcnow(),95interval=CandleInterval.CANDLE_INTERVAL_HOUR)96# Выбираем последнюю доступную свечку97# Получаем среднюю стоимость бумаги путём складывания самой высокой и самой низкой цен98average_price = ((quotation_to_float(candle.candles[-1].high) + quotation_to_float(candle.candles[-1].low)) / 2)99return average_price100except:101return 0.0102103104'''105Функция для получения знака валюты106'''107108109def get_currency_sing(currency):110if currency == "try":111sign = "₺"112elif currency == "eur":113sign = "€"114elif currency == "kzt":115sign = "₸"116elif currency == "byn":117sign = "Br"118elif currency == "hkd":119sign = "HK$"120elif currency == "cny":121sign = "¥"122elif currency == "rub":123sign = "₽"124elif currency == "usd":125sign = "$"126elif currency == "jpy":127sign = "¥"128elif currency == "chf":129sign = "₣"130elif currency == "gbp":131sign = "£"132else:133sign = currency134135return sign136137138'''139Функция для получения курса валюты по отношению к рублю140Используется библиотека ЦБ РФ141'''142143144def get_exchange_rate(currency):145rates = ExchangeRates()146exchange = rates[f'{currency.upper()}']147148if exchange is not None:149exchange_rate = exchange.rate150elif currency.upper() == "RUB":151exchange_rate = 1152else:153exchange_rate = 0154155return float(exchange_rate)156157158