From 220c45d54ca81def8201b779390257aa8eded4ad Mon Sep 17 00:00:00 2001 From: algizn97 Date: Sat, 4 Oct 2025 09:34:11 +0500 Subject: [PATCH] Fixed --- app/bybit/telegram_message_handler.py | 28 +++++++++++++++----- app/telegram/keyboards/inline.py | 37 +++++++++++++++++++-------- database/request.py | 4 +-- 3 files changed, 51 insertions(+), 18 deletions(-) diff --git a/app/bybit/telegram_message_handler.py b/app/bybit/telegram_message_handler.py index 6335567..15b8d00 100644 --- a/app/bybit/telegram_message_handler.py +++ b/app/bybit/telegram_message_handler.py @@ -70,15 +70,19 @@ class TelegramMessageHandler: text = ( f"{status_text}:\n" f"Торговая пара: {symbol}\n" - f"Цена: {price}\n" f"Режим позиции: {position_idx_rus}\n" f"Количество: {qty}\n" f"Тип ордера: {order_type_rus}\n" f"Движение: {side_rus}\n" - f"Триггер цена: {trigger_price}\n" - f"Тейк-профит: {take_profit}\n" - f"Стоп-лосс: {stop_loss}\n" ) + if price and price != "0": + text += f"Цена: {price}\n" + if take_profit and take_profit != "Нет данных": + text += f"Тейк-профит: {take_profit}\n" + if stop_loss and stop_loss != "Нет данных": + text += f"Стоп-лосс: {stop_loss}\n" + if trigger_price and trigger_price != "Нет данных": + text += f"Триггер цена: {trigger_price}\n" await self.telegram_bot.send_message( chat_id=tg_id, text=text, reply_markup=kbi.profile_bybit @@ -111,9 +115,12 @@ class TelegramMessageHandler: await rq.set_fee_user_auto_trading( tg_id=tg_id, symbol=symbol, side=side, fee=safe_float(exec_fee) ) - + if side == "Buy": + res_side = "Sell" + else: + res_side = "Buy" user_auto_trading = await rq.get_user_auto_trading( - tg_id=tg_id, symbol=symbol + tg_id=tg_id, symbol=symbol, side=res_side ) if user_auto_trading is not None and user_auto_trading.fee is not None: @@ -175,6 +182,9 @@ class TelegramMessageHandler: else: r_side = "Buy" await rq.set_auto_trading(tg_id=tg_id, symbol=symbol, auto_trading=False, side=r_side) + user_deals_data = await rq.get_user_deal_by_symbol(tg_id=tg_id, symbol=symbol) + if user_deals_data and user_deals_data.switch_side_mode: + await rq.set_auto_trading(tg_id=tg_id, symbol=symbol, auto_trading=False, side=side) else: open_order_text = "\n❗️ Сделка закрылась в минус, открываю новую сделку с увеличенной ставкой.\n" await self.telegram_bot.send_message( @@ -192,6 +202,7 @@ class TelegramMessageHandler: "Risk is too high for this trade": "❗️ Риск сделки слишком высок для продолжения", "ab not enough for new order": "❗️ Недостаточно средств для продолжения торговли", "InvalidRequestError": "❗️ Недостаточно средств для размещения нового ордера с заданным количеством и плечом.", + "The number of contracts exceeds maximum limit allowed": "❗️ Количество контрактов превышает допустимое максимальное количество контрактов", } error_text = errors.get( res, "❗️ Не удалось открыть новую сделку" @@ -203,6 +214,11 @@ class TelegramMessageHandler: await rq.set_auto_trading( tg_id=tg_id, symbol=symbol, auto_trading=False, side=r_side ) + user_deals_data = await rq.get_user_deal_by_symbol(tg_id=tg_id, symbol=symbol) + if user_deals_data and user_deals_data.switch_side_mode: + await rq.set_auto_trading( + tg_id=tg_id, symbol=symbol, auto_trading=False, side=side + ) await self.telegram_bot.send_message( chat_id=tg_id, text=error_text, diff --git a/app/telegram/keyboards/inline.py b/app/telegram/keyboards/inline.py index 13069cd..7c1f559 100644 --- a/app/telegram/keyboards/inline.py +++ b/app/telegram/keyboards/inline.py @@ -39,7 +39,7 @@ main_menu = InlineKeyboardMarkup( [InlineKeyboardButton(text="Начать торговлю", callback_data="start_trading")], [ InlineKeyboardButton( - text="Остановить торговлю", callback_data="trading_stop" + text="Остановить торговлю", callback_data="stop_trading" ) ], ] @@ -337,17 +337,21 @@ def create_active_positions_keyboard(symbols: list): return builder.as_markup() -def make_close_position_keyboard(symbol_pos: str, side: str, position_idx: int, qty: int): +def make_close_position_keyboard( + symbol_pos: str, side: str, position_idx: int, qty: int +): return InlineKeyboardMarkup( inline_keyboard=[ [ InlineKeyboardButton( - text="Закрыть позицию", callback_data=f"close_position_{symbol_pos}_{side}_{position_idx}_{qty}" + text="Закрыть позицию", + callback_data=f"close_position_{symbol_pos}_{side}_{position_idx}_{qty}", ) ], [ InlineKeyboardButton( - text="Установить TP/SL", callback_data=f"pos_tp_sl_{symbol_pos}_{position_idx}" + text="Установить TP/SL", + callback_data=f"pos_tp_sl_{symbol_pos}_{position_idx}", ) ], [ @@ -358,7 +362,7 @@ def make_close_position_keyboard(symbol_pos: str, side: str, position_idx: int, ) -def create_active_orders_keyboard(orders:list): +def create_active_orders_keyboard(orders: list): builder = InlineKeyboardBuilder() for order, side in orders: builder.button(text=f"{order}", callback_data=f"get_order_{order}_{side}") @@ -373,7 +377,8 @@ def make_close_orders_keyboard(symbol_order: str, order_id: str): inline_keyboard=[ [ InlineKeyboardButton( - text="Закрыть ордер", callback_data=f"close_order_{symbol_order}_{order_id}" + text="Закрыть ордер", + callback_data=f"close_order_{symbol_order}_{order_id}", ) ], [ @@ -439,7 +444,11 @@ back_to_start_trading = InlineKeyboardMarkup( cancel_timer_merged = InlineKeyboardMarkup( inline_keyboard=[ - [InlineKeyboardButton(text="Отменить таймер", callback_data="cancel_timer_merged")], + [ + InlineKeyboardButton( + text="Отменить таймер", callback_data="cancel_timer_merged" + ) + ], [ InlineKeyboardButton(text="На главную", callback_data="profile_bybit"), ], @@ -448,7 +457,11 @@ cancel_timer_merged = InlineKeyboardMarkup( cancel_timer_switch = InlineKeyboardMarkup( inline_keyboard=[ - [InlineKeyboardButton(text="Отменить таймер", callback_data="cancel_timer_switch")], + [ + InlineKeyboardButton( + text="Отменить таймер", callback_data="cancel_timer_switch" + ) + ], [ InlineKeyboardButton(text="На главную", callback_data="profile_bybit"), ], @@ -459,9 +472,13 @@ cancel_timer_switch = InlineKeyboardMarkup( cancel_timer_stop = InlineKeyboardMarkup( inline_keyboard=[ - [InlineKeyboardButton(text="Отменить таймер", callback_data="cancel_timer_stop")], + [ + InlineKeyboardButton( + text="Отменить таймер", callback_data="cancel_timer_stop" + ) + ], [ InlineKeyboardButton(text="На главную", callback_data="profile_bybit"), ], ] -) \ No newline at end of file +) diff --git a/database/request.py b/database/request.py index f6402c9..78c401f 100644 --- a/database/request.py +++ b/database/request.py @@ -1268,7 +1268,7 @@ async def get_all_user_auto_trading(tg_id: int): return [] -async def get_user_auto_trading(tg_id: int, symbol: str): +async def get_user_auto_trading(tg_id: int, symbol: str, side: str): """Get user auto trading from the database asynchronously.""" try: async with async_session() as session: @@ -1278,7 +1278,7 @@ async def get_user_auto_trading(tg_id: int, symbol: str): return None result_auto_trading = await session.execute( - select(UserAutoTrading).filter_by(user_id=user.id, symbol=symbol) + select(UserAutoTrading).filter_by(user_id=user.id, symbol=symbol, side=side) ) auto_trading = result_auto_trading.scalars().first() return auto_trading