2
0
forked from kodorvan/stcs
Files
stcs/app/telegram/handlers/stop_trading.py

74 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import logging.config
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery
import app.telegram.keyboards.inline as kbi
import database.request as rq
from app.bybit.close_positions import cancel_order, close_position
from logger_helper.logger_helper import LOGGING_CONFIG
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("stop_trading")
router_stop_trading = Router(name="stop_trading")
user_trade_tasks = {}
@router_stop_trading.callback_query(F.data == "stop_trading")
async def stop_trading(callback_query: CallbackQuery, state: FSMContext):
try:
await state.clear()
if callback_query.from_user.id in user_trade_tasks:
task = user_trade_tasks[callback_query.from_user.id]
if not task.done():
task.cancel()
del user_trade_tasks[callback_query.from_user.id]
conditional_data = await rq.get_user_conditional_settings(
tg_id=callback_query.from_user.id
)
timer_end = conditional_data.timer_end
symbols = await rq.get_all_symbols(tg_id=callback_query.from_user.id)
async def delay_start():
if timer_end > 0:
await callback_query.message.edit_text(
text=f"Торговля будет остановлена с задержкой {timer_end} мин.",
reply_markup=kbi.cancel_timer,
)
await asyncio.sleep(timer_end * 60)
for symbol in symbols:
auto_trading_data = await rq.get_user_auto_trading(
tg_id=callback_query.from_user.id, symbol=symbol
)
if auto_trading_data is not None and auto_trading_data.auto_trading:
await close_position(tg_id=callback_query.from_user.id, symbol=symbol)
await cancel_order(tg_id=callback_query.from_user.id, symbol=symbol)
await rq.set_auto_trading(
tg_id=callback_query.from_user.id, symbol=symbol, auto_trading=False
)
await callback_query.answer(text="Торговля остановлена")
await rq.set_stop_timer(tg_id=callback_query.from_user.id, timer_end=0)
task = asyncio.create_task(delay_start())
user_trade_tasks[callback_query.from_user.id] = task
logger.debug(
"Command stop_trading processed successfully for user: %s",
callback_query.from_user.id,
)
except Exception as e:
await callback_query.answer(text="Произошла ошибка при остановке торговли")
logger.error(
"Error processing command stop_trading for user %s: %s",
callback_query.from_user.id,
e,
)