Path: blob/master/ invest-robot-contest_trading_bot-master/trading/get_account_info.py
5932 views
from tinkoff.invest import Client, Quotation1from trading.trade_help import quotation_to_float2import pandas as pd3from config.personal_data import get_token, get_account_type, get_account4import sqlite3 as sl5import dataframe_image as dfi6from trading.trade_help import get_exchange_rate, get_currency_sing7from trading.get_securities import security_name_by_figi89'''1011Тут представлены все функции, которые позволяют получить какую-либо информацию о счёте1213Все данные будут храниться в pandas DataFrame для дальнейшей обработки1415Все значения, где количество или суммы представлены с помощью units (целая часть) и nano (дробная часть),16сразу переводятся в дробные числа для удобства с помощью функции total_quantity.1718'''1920'''21Функция для получения информации о свободной валюте на счёте22'''232425def get_all_currency(user_id, account_id="", account_type=""):26with Client(get_token(user_id)) as client:2728if account_id == "":29account_id = get_account(user_id=user_id)3031if account_type == "":32account_type = get_account_type(user_id=user_id)3334if account_type == "sandbox":35positions = client.sandbox.get_sandbox_positions(account_id=account_id)36else:37positions = client.operations.get_positions(account_id=account_id)3839currency_df = pd.DataFrame(40{41"currency": i.currency,42"name": get_currency_name(user_id=user_id, currency=i.currency),43"sign": get_currency_sing(currency=i.currency),44"exchange_rate": get_exchange_rate(currency=i.currency),45"sum": quotation_to_float(Quotation(units=i.units, nano=i.nano)),46"sum_in_ruble": quotation_to_float(Quotation(units=i.units, nano=i.nano)) * get_exchange_rate(47currency=i.currency),48"units": i.units,49"nano": i.nano,50} for i in positions.money51)5253return currency_df545556'''57Функция для получения названия валюты58Необходима для вывода информации по доступной валюте, так Тинькофф предоставляет только59'''606162def get_currency_name(user_id, currency):63with Client(get_token(user_id)) as client:64pos = client.instruments.currencies()6566for i in pos.instruments:67if i.nominal.currency == currency:68return i.name6970return ""717273'''74Функция для получения информации о всех купленных бумагах75'''767778def get_all_securities(user_id, account_id="", account_type=""):79with Client(get_token(user_id)) as client:8081if account_id == "":82account_id = get_account(user_id=user_id)8384if account_type == "":85account_type = get_account_type(user_id=user_id)8687if account_type == "sandbox":88portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)89else:90portfolio = client.operations.get_portfolio(account_id=account_id)9192portfolio_df = pd.DataFrame(93{94"figi": i.figi,95"instrument": i.instrument_type,96"security_name": security_name_by_figi(figi=i.figi,user_id=user_id),97"quantity": quotation_to_float(i.quantity),98"average_price": quotation_to_float(i.average_position_price),99"exp_yield": quotation_to_float(i.expected_yield),100"nkd": quotation_to_float(i.current_nkd),101"average_price_pt": quotation_to_float(i.average_position_price_pt),102"current_price": quotation_to_float(i.current_price),103"average_price_fifo": quotation_to_float(i.average_position_price_fifo),104"lots": quotation_to_float(i.quantity_lots),105"currency": i.average_position_price.currency,106"currency_sign": get_currency_sing(i.average_position_price.currency)107} for i in portfolio.positions108)109110return portfolio_df111112113'''114Функция для получения статистики по счёту115Суммы по всем активам и предполагаемый доход/убыток116'''117118119def get_all_stat(user_id, account_id="", account_type=""):120with Client(get_token(user_id)) as client:121122if account_id == "":123account_id = get_account(user_id=user_id)124125if account_type == "":126account_type = get_account_type(user_id=user_id)127128if account_type == "sandbox":129portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)130else:131portfolio = client.operations.get_portfolio(account_id=account_id)132133stat_df = pd.DataFrame(134{135"sum_shares": quotation_to_float(portfolio.total_amount_shares),136"sum_bonds": quotation_to_float(portfolio.total_amount_bonds),137"sum_etf": quotation_to_float(portfolio.total_amount_etf),138"sum_curr": quotation_to_float(portfolio.total_amount_currencies),139"sum_fut": quotation_to_float(portfolio.total_amount_futures),140"sum_total": quotation_to_float(portfolio.total_amount_shares) + quotation_to_float(141portfolio.total_amount_bonds) + quotation_to_float(portfolio.total_amount_etf) + quotation_to_float(142portfolio.total_amount_currencies) + quotation_to_float(portfolio.total_amount_futures),143"exp_yield": quotation_to_float(portfolio.expected_yield),144145}, index=[0]146)147148return stat_df149150151'''152Функция для получения информации о количестве доступных лотов по figi153154Данная функция используется для проверки в боте, можно ли продать указанное количество акций155'''156157158def get_lots_portfolio(figi, user_id, account_id="", account_type=""):159with Client(get_token(user_id)) as client:160161if account_id == "":162account_id = get_account(user_id=user_id)163164if account_type == "":165account_type = get_account_type(user_id=user_id)166167if account_type == "sandbox":168portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)169else:170portfolio = client.operations.get_portfolio(account_id=account_id)171172for i in portfolio.positions:173if i.figi == figi:174lots = int(quotation_to_float(i.quantity_lots))175return int(lots)176177return 0178179180'''181Функция для получения информации о цене бумаги в портфеле182'''183184185def get_price_in_portfolio(figi, user_id, account_id="", account_type=""):186with Client(get_token(user_id)) as client:187188if account_id == "":189account_id = get_account(user_id=user_id)190191if account_type == "":192account_type = get_account_type(user_id=user_id)193194if account_type == "sandbox":195portfolio = client.sandbox.get_sandbox_portfolio(account_id=account_id)196else:197portfolio = client.operations.get_portfolio(account_id=account_id)198199for i in portfolio.positions:200if i.figi == figi:201price = quotation_to_float(i.current_price)202if price == 0.0:203price = quotation_to_float(i.average_position_price)204return price205206return 0.0207208209'''210Функция для получения списка открытых ордеров211'''212213214def get_my_order(user_id, account_id="", account_type=""):215with Client(get_token(user_id)) as client:216217if account_id == "":218account_id = get_account(user_id=user_id)219220if account_type == "":221account_type = get_account_type(user_id=user_id)222223if account_type == "sandbox":224orders = client.sandbox.get_sandbox_orders(account_id=account_id).orders225else:226orders = client.orders.get_orders(account_id=account_id).orders227228order_df = pd.DataFrame(229{230"order_id": i.order_id,231"lots_req": i.lots_requested,232"lots_ex": i.lots_executed,233"sum_req": quotation_to_float(i.initial_order_price),234"sum_ex": quotation_to_float(i.executed_order_price),235"sum_total": quotation_to_float(i.total_order_amount), # сумма после всех комиссий236"commission": quotation_to_float(i.initial_commission),237"serv_commission": quotation_to_float(i.service_commission),238"currency": i.currency,239"currency_sign": get_currency_sing(i.currency),240"figi": i.figi,241"direction": i.direction,242"price_one": quotation_to_float(i.initial_security_price),243"order_date": i.order_date,244} for i in orders245)246247return order_df248249250'''251Функция для получения списка всех операций пользователя252'''253254255def get_my_operations(user_id, account_id="", figi=""):256connection = sl.connect("db/BotDB.db")257cursor = connection.cursor()258259if account_id == "":260account_id = get_account(user_id=user_id)261262if figi == "":263operations = cursor.execute(264'SELECT id, user_id, account_id, account_type, order_id, date_op, time_op, direction, figi, name, ticker, '265'quantity_lots, in_lot, quantity_total, price_position, price_total, commission, currency, message, '266'via FROM operations WHERE user_id = ? AND account_id = ?',267(user_id, account_id)).fetchall()268else:269operations = cursor.execute(270'SELECT id, user_id, account_id, account_type, order_id, date_op, time_op, direction, figi, name, ticker, '271'quantity_lots, in_lot, quantity_total, price_position, price_total, commission, currency, message, '272'via FROM operations WHERE user_id = ? AND account_id = ? AND figi = ?',273(user_id, account_id, figi)).fetchall()274275if not operations:276return False277278operations_df = pd.DataFrame(279{280"id": line[0],281"user_id": user_id,282"account_id": account_id,283"account_type": line[3],284"order_id": line[4],285"date": line[5],286"time": line[6],287"direction": line[7],288"figi": line[8],289"name": line[9],290"ticker": line[10],291"quantity_lots": line[11],292"in_lot": line[12],293"quantity_total": line[13],294"price_position": line[14],295"price_total": line[15],296"commission": line[16],297"currency": line[17],298"message": line[18],299"via": line[19]300} for line in operations301)302303style_df = operations_df.drop(['id', 'user_id', 'order_id', 'figi', 'ticker'], axis=1)304# style_df = style_df.style.apply(color_macd)305306dfi.export(style_df, f"img/operations/all_operations_{user_id}.png")307308return True309310311