diff --git a/app/bybit/close_positions.py b/app/bybit/close_positions.py index 47a9687..bcb57c9 100644 --- a/app/bybit/close_positions.py +++ b/app/bybit/close_positions.py @@ -7,25 +7,25 @@ logging.config.dictConfig(LOGGING_CONFIG) logger = logging.getLogger("close_positions") -async def close_position( - tg_id: int, symbol: str, side: str, position_idx: int, qty: float +async def close_position_by_symbol( + tg_id: int, symbol: str ) -> bool: """ Closes all positions :param tg_id: Telegram user ID :param symbol: symbol - :param side: side - :param position_idx: position index - :param qty: quantity :return: bool """ try: client = await get_bybit_client(tg_id) - if side == "Buy": - r_side = "Sell" - else: - r_side = "Buy" + response = client.get_positions( + category="linear", symbol=symbol + ) + positions = response.get("result", {}).get("list", []) + r_side = "Sell" if positions[0].get("side") == "Buy" else "Buy" + qty = positions[0].get("size") + position_idx = positions[0].get("positionIdx") response = client.place_order( category="linear", @@ -37,16 +37,16 @@ async def close_position( positionIdx=position_idx, ) if response["retCode"] == 0: - logger.info("All positions closed for %s for user %s", symbol, tg_id) + logger.info("Positions closed for %s for user %s", symbol, tg_id) return True else: logger.error( - "Error closing all positions for %s for user %s", symbol, tg_id + "Error closing position for %s for user %s", symbol, tg_id ) return False except Exception as e: logger.error( - "Error closing all positions for %s for user %s: %s", symbol, tg_id, e + "Error closing positions for %s for user %s: %s", symbol, tg_id, e ) return False diff --git a/app/bybit/open_positions.py b/app/bybit/open_positions.py index d4dee4a..bf7e675 100644 --- a/app/bybit/open_positions.py +++ b/app/bybit/open_positions.py @@ -90,7 +90,6 @@ async def start_trading_cycle( await rq.set_user_deal( tg_id=tg_id, symbol=symbol, - last_side=side, current_step=1, trade_mode=trade_mode, side_mode=switch_side, @@ -179,7 +178,6 @@ async def trading_cycle_profit( await rq.set_user_deal( tg_id=tg_id, symbol=symbol, - last_side=side, current_step=1, trade_mode=trade_mode, side_mode=side_mode, @@ -246,10 +244,18 @@ async def trading_cycle( leverage=leverage, ) + if trade_mode == "Switch": + if side == "Buy": + r_side = "Sell" + else: + r_side = "Buy" + else: + r_side = side + res = await open_positions( tg_id=tg_id, symbol=symbol, - side=side, + side=r_side, order_quantity=next_quantity, trigger_price=trigger_price, margin_type=margin_type, @@ -263,7 +269,6 @@ async def trading_cycle( await rq.set_user_deal( tg_id=tg_id, symbol=symbol, - last_side=side, current_step=current_step, trade_mode=trade_mode, side_mode=side_mode, diff --git a/app/bybit/telegram_message_handler.py b/app/bybit/telegram_message_handler.py index ff85da3..bb95435 100644 --- a/app/bybit/telegram_message_handler.py +++ b/app/bybit/telegram_message_handler.py @@ -141,8 +141,6 @@ class TelegramMessageHandler: tg_id=tg_id, symbol=symbol, total_fee=total_fee ) text += f"Текущая ставка: {user_deals_data.order_quantity} USDT\n" - else: - text += f"Количество: {exec_qty}\n" text += ( f"Цена исполнения: {exec_price}\n" diff --git a/app/telegram/handlers/close_orders.py b/app/telegram/handlers/close_orders.py index 887ecdc..4948d16 100644 --- a/app/telegram/handlers/close_orders.py +++ b/app/telegram/handlers/close_orders.py @@ -4,9 +4,6 @@ from aiogram import Router from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery -import database.request as rq -from app.bybit.close_positions import cancel_order, close_position -from app.helper_functions import safe_float from logger_helper.logger_helper import LOGGING_CONFIG logging.config.dictConfig(LOGGING_CONFIG) @@ -28,31 +25,6 @@ async def close_position_handler( :return: None """ try: - data = callback_query.data - parts = data.split("_") - symbol = parts[2] - side = parts[3] - position_idx = int(parts[4]) - qty = safe_float(parts[5]) - await rq.set_auto_trading( - tg_id=callback_query.from_user.id, - symbol=symbol, - auto_trading=False, - side=side, - ) - res = await close_position( - tg_id=callback_query.from_user.id, - symbol=symbol, - side=side, - position_idx=position_idx, - qty=qty, - ) - - if not res: - await callback_query.answer(text="Произошла ошибка при закрытии позиции.") - return - - await callback_query.answer(text="Позиция успешно закрыта.") logger.debug( "Command close_position processed successfully for user: %s", callback_query.from_user.id, @@ -81,19 +53,6 @@ async def cancel_order_handler( :return: None """ try: - data = callback_query.data - parts = data.split("_") - symbol = parts[2] - order_id = parts[3] - res = await cancel_order( - tg_id=callback_query.from_user.id, symbol=symbol, order_id=order_id - ) - - if not res: - await callback_query.answer(text="Произошла ошибка при закрытии ордера.") - return - - await callback_query.answer(text="Ордер успешно закрыт.") logger.debug( "Command close_order processed successfully for user: %s", callback_query.from_user.id, diff --git a/app/telegram/handlers/stop_trading.py b/app/telegram/handlers/stop_trading.py index 64e21e0..719dfa1 100644 --- a/app/telegram/handlers/stop_trading.py +++ b/app/telegram/handlers/stop_trading.py @@ -5,6 +5,7 @@ from aiogram import F, Router from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery +from app.bybit.close_positions import close_position_by_symbol import app.telegram.keyboards.inline as kbi import database.request as rq from app.telegram.tasks.tasks import add_stop_task, cancel_stop_task @@ -27,6 +28,7 @@ async def stop_all_trading(callback_query: CallbackQuery, state: FSMContext): tg_id=callback_query.from_user.id ) timer_end = conditional_data.timer_end + symbol = await rq.get_user_symbol(tg_id=callback_query.from_user.id) async def delay_start(): if timer_end > 0: @@ -37,30 +39,21 @@ async def stop_all_trading(callback_query: CallbackQuery, state: FSMContext): await rq.set_stop_timer(tg_id=callback_query.from_user.id, timer_end=0) await asyncio.sleep(timer_end * 60) - user_auto_trading_list = await rq.get_all_user_auto_trading( - tg_id=callback_query.from_user.id + user_auto_trading = await rq.get_user_auto_trading( + tg_id=callback_query.from_user.id, symbol=symbol ) - if any(item.auto_trading for item in user_auto_trading_list): - for active_auto_trading in user_auto_trading_list: - if active_auto_trading.auto_trading: - symbol = active_auto_trading.symbol - req = await rq.set_auto_trading( - tg_id=callback_query.from_user.id, - symbol=symbol, - auto_trading=False, - ) - if not req: - await callback_query.message.edit_text( - text="Произошла ошибка при остановке торговли", - reply_markup=kbi.profile_bybit, - ) - return - await callback_query.message.edit_text( - text="Торговля остановлена", reply_markup=kbi.profile_bybit + if user_auto_trading and user_auto_trading.auto_trading: + await rq.set_auto_trading( + tg_id=callback_query.from_user.id, + symbol=symbol, + auto_trading=False, ) + await close_position_by_symbol( + tg_id=callback_query.from_user.id, symbol=symbol) + await callback_query.message.edit_text(text=f"Торговля для {symbol} остановлена", reply_markup=kbi.profile_bybit) else: - await callback_query.message.edit_text(text="Нет активной торговли") + await callback_query.message.edit_text(text=f"Нет активной торговли для {symbol}", reply_markup=kbi.profile_bybit) task = asyncio.create_task(delay_start()) await add_stop_task(user_id=callback_query.from_user.id, task=task) diff --git a/app/telegram/keyboards/inline.py b/app/telegram/keyboards/inline.py index 2bc7d62..9f70820 100644 --- a/app/telegram/keyboards/inline.py +++ b/app/telegram/keyboards/inline.py @@ -36,6 +36,7 @@ main_menu = InlineKeyboardMarkup( ) ], [InlineKeyboardButton(text="Начать торговлю", callback_data="start_trading")], + [InlineKeyboardButton(text="Остановить торговлю", callback_data="stop_trading")], ] ) diff --git a/database/request.py b/database/request.py index 8677bf7..39a6b4b 100644 --- a/database/request.py +++ b/database/request.py @@ -895,7 +895,6 @@ async def set_stop_timer(tg_id: int, timer_end: int) -> bool: async def set_user_deal( tg_id: int, symbol: str, - last_side: str, current_step: int, trade_mode: str, side_mode: str, @@ -913,7 +912,6 @@ async def set_user_deal( Set the user deal in the database. :param tg_id: Telegram user ID :param symbol: Symbol - :param last_side: Last side :param current_step: Current step :param trade_mode: Trade mode :param side_mode: Side mode @@ -943,7 +941,6 @@ async def set_user_deal( if deal: # Updating existing record - deal.last_side = last_side deal.current_step = current_step deal.trade_mode = trade_mode deal.side_mode = side_mode @@ -961,7 +958,6 @@ async def set_user_deal( new_deal = UserDeals( user=user, symbol=symbol, - last_side=last_side, current_step=current_step, trade_mode=trade_mode, side_mode=side_mode,