Path: blob/master/ invest-robot-contest_trading_bot-master/trading/place_order.py
5933 views
from tinkoff.invest import Client, OrderDirection, OrderType1from trading import trade_help2from config.personal_data import get_token, get_account, get_account_type3from trading.trade_help import quotation_to_float4import sqlite3 as sl5from datetime import datetime6from trading.get_securities import security_name_by_figi7from trading.trade_help import in_lot_figi89"""1011Тут представлены все функции, которые отвечает за размещение ордеров на покупку/продаужу бумаг1213"""1415'''16Функция для покупки ценных бумаг по заданной цене за бумагу17Если цена не задана (равна нулю), то бумаги покупаются по лучшей рыночной цене18'''192021def buy_order(figi, price, quantity_lots, user_id, account_id="", account_type="", via="else"):22with Client(get_token(user_id)) as client:2324if account_id == "":25account_id = get_account(user_id=user_id)2627if account_type == "":28account_type = get_account_type(user_id=user_id)2930if account_type == "sandbox":31if price > 0.0:32order = client.sandbox.post_sandbox_order(33order_id=str(datetime.utcnow().timestamp()),34figi=figi,35price=trade_help.to_quotation(price),36quantity=quantity_lots,37account_id=account_id,38direction=OrderDirection.ORDER_DIRECTION_BUY,39order_type=OrderType.ORDER_TYPE_LIMIT,40)41else:42order = client.sandbox.post_sandbox_order(43order_id=str(datetime.utcnow().timestamp()),44figi=figi,45quantity=quantity_lots,46account_id=account_id,47direction=OrderDirection.ORDER_DIRECTION_BUY,48order_type=OrderType.ORDER_TYPE_MARKET,49)50else:51if price > 0.0:52order = client.orders.post_order(53order_id=str(datetime.utcnow().timestamp()),54figi=figi,55price=trade_help.to_quotation(price),56quantity=quantity_lots,57account_id=account_id,58direction=OrderDirection.ORDER_DIRECTION_BUY,59order_type=OrderType.ORDER_TYPE_LIMIT,60)61else:62order = client.orders.post_order(63order_id=str(datetime.utcnow().timestamp()),64figi=figi,65quantity=quantity_lots,66account_id=account_id,67direction=OrderDirection.ORDER_DIRECTION_BUY,68order_type=OrderType.ORDER_TYPE_MARKET,69)70write_operation(order=order, user_id=user_id, via=via, account_id=account_id, account_type=account_type)7172return order737475'''76Функция для продажи ценных бумаг по заданной цене за бумагу77Если цена не задана (равна нулю), то бумаги продаются по лучшей рыночной цене78'''798081def sell_sfb(figi, price, quantity_lots, user_id, account_id="", account_type="", via="else"):82with Client(get_token(user_id)) as client:8384if account_id == "":85account_id = get_account(user_id=user_id)8687if account_type == "":88account_type = get_account_type(user_id=user_id)8990if account_type == "sandbox":91if price > 0.0:92try:93order = client.sandbox.post_sandbox_order(94order_id=str(datetime.utcnow().timestamp()),95figi=figi,96quantity=quantity_lots,97price=trade_help.to_quotation(price),98account_id=account_id,99direction=OrderDirection.ORDER_DIRECTION_SELL,100order_type=OrderType.ORDER_TYPE_LIMIT,101)102except:103return False104else:105try:106order = client.sandbox.post_sandbox_order(107order_id=str(datetime.utcnow().timestamp()),108figi=figi,109quantity=quantity_lots,110account_id=account_id,111direction=OrderDirection.ORDER_DIRECTION_SELL,112order_type=OrderType.ORDER_TYPE_MARKET,113)114except:115return False116else:117if price > 0.0:118try:119order = client.orders.post_order(120order_id=str(datetime.utcnow().timestamp()),121figi=figi,122quantity=quantity_lots,123price=trade_help.to_quotation(price),124account_id=account_id,125direction=OrderDirection.ORDER_DIRECTION_SELL,126order_type=OrderType.ORDER_TYPE_LIMIT,127)128except:129return False130else:131try:132order = client.orders.post_order(133order_id=str(datetime.utcnow().timestamp()),134figi=figi,135quantity=quantity_lots,136account_id=account_id,137direction=OrderDirection.ORDER_DIRECTION_SELL,138order_type=OrderType.ORDER_TYPE_MARKET,139)140except:141return False142143write_operation(order=order, user_id=user_id, via=via, account_id=account_id, account_type=account_type)144145return order146147148'''149Функция для отмены ордера по его id150'''151152153async def cancel_order(order_id, user_id, account_id="", account_type=""):154with Client(get_token(user_id)) as client:155156if account_id == "":157account_id = get_account(user_id=user_id)158159if account_type == "":160account_type = get_account_type(user_id=user_id)161162if account_type == "sandbox":163state = client.sandbox.get_sandbox_order_state(164order_id=order_id,165account_id=account_id,166)167168order = client.sandbox.cancel_sandbox_order(169order_id=order_id,170account_id=account_id,171)172else:173state = client.orders.get_order_state(174order_id=order_id,175account_id=account_id,176)177178order = client.orders.cancel_order(179order_id=order_id,180account_id=account_id,181)182183connection = sl.connect("db/BotDB.db")184cursor = connection.cursor()185186direction = cursor.execute('SELECT direction FROM operations WHERE order_id=?', (order_id,)).fetchone()[0]187if direction is not None:188quantity_lots = state.lots_executed189price = quotation_to_float(state.executed_order_price)190commission = quotation_to_float(state.executed_commission)191direction += "/canceled"192quantity_total = quantity_lots * in_lot_figi(state.figi, user_id=user_id)193price_total = quantity_total * price194195new_operation = (quantity_lots, quantity_total, price_total, commission, direction, order_id)196197cursor.execute(198'UPDATE OPERATIONS SET quantity_lots = ?, quantity_total = ?, price_total = ?, commission = ?, direction '199'= ? WHERE order_id '200'= ?;',201new_operation)202connection.commit()203204return order205206207def write_operation(order, user_id, account_id, account_type, via="else"):208connection = sl.connect("db/BotDB.db")209cursor = connection.cursor()210211order_id = order.order_id212213date_op = datetime.now().strftime("%d.%m.%Y")214time_op = datetime.now().strftime("%H:%M:%S")215216if order.direction == 2:217direction = "sell"218elif order.direction == 1:219direction = "buy"220else:221direction = "else"222223figi = order.figi224ticker = order.figi # Доделать потом225name = security_name_by_figi(figi=figi, user_id=user_id)226227quantity_lots = order.lots_requested228in_lot = in_lot_figi(figi=figi, user_id=user_id)229quantity_total = quantity_lots * in_lot_figi(figi=figi, user_id=user_id)230231price_position = quotation_to_float(order.initial_order_price)232commission = quotation_to_float(order.initial_commission)233price_total = price_position * quantity_total - commission234235currency = order.initial_order_price.currency236237message = order.message238239operation = (240user_id, account_id, account_type, order_id, date_op, time_op, direction, figi, ticker, name, quantity_lots,241in_lot,242quantity_total, price_position, price_total,243commission, currency, message, via)244cursor.execute("INSERT INTO OPERATIONS (user_id, account_id, account_type, order_id, date_op, time_op, direction, "245"figi, ticker, name, "246"quantity_lots, in_lot, quantity_total, price_position, price_total, commission,currency, message, "247"via) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?);",248operation)249connection.commit()250251252