From 5ad69f3f6d1da4cc8d96a518d0c484b33266661b Mon Sep 17 00:00:00 2001 From: algizn97 Date: Sat, 18 Oct 2025 13:52:20 +0500 Subject: [PATCH] Fixed take profit calculation. Added a position check for the current pair when trying to change the margin. --- app/bybit/open_positions.py | 8 +++--- app/bybit/telegram_message_handler.py | 19 ++++++++++++-- .../main_settings/additional_settings.py | 26 +++++++++++++++++++ app/telegram/handlers/start_trading.py | 11 ++++---- 4 files changed, 53 insertions(+), 11 deletions(-) diff --git a/app/bybit/open_positions.py b/app/bybit/open_positions.py index a7e10f6..07a7d4c 100644 --- a/app/bybit/open_positions.py +++ b/app/bybit/open_positions.py @@ -296,10 +296,10 @@ async def open_positions( if (liq_long > 0 or liq_short > 0) and price_for_cals > 0: if side == "Buy": base_tp = price_for_cals + (price_for_cals - liq_long) - take_profit_price = base_tp + commission_fee_percent + take_profit_price = base_tp + commission_fee_percent / qty_formatted else: base_tp = price_for_cals - (liq_short - price_for_cals) - take_profit_price = base_tp - commission_fee_percent + take_profit_price = base_tp - commission_fee_percent / qty_formatted take_profit_price = max(take_profit_price, 0) else: take_profit_price = None @@ -307,10 +307,10 @@ async def open_positions( stop_loss_price = None else: if side == "Buy": - take_profit_price = price_for_cals * (1 + take_profit_percent / 100) + commission_fee_percent + take_profit_price = price_for_cals * (1 + take_profit_percent / 100) + commission_fee_percent / qty_formatted stop_loss_price = price_for_cals * (1 - stop_loss_percent / 100) else: - take_profit_price = price_for_cals * (1 - take_profit_percent / 100) - commission_fee_percent + take_profit_price = price_for_cals * (1 - take_profit_percent / 100) - commission_fee_percent / qty_formatted stop_loss_price = price_for_cals * (1 + stop_loss_percent / 100) take_profit_price = max(take_profit_price, 0) diff --git a/app/bybit/telegram_message_handler.py b/app/bybit/telegram_message_handler.py index ce9e259..5de198c 100644 --- a/app/bybit/telegram_message_handler.py +++ b/app/bybit/telegram_message_handler.py @@ -41,11 +41,26 @@ class TelegramMessageHandler: if order_status == "Filled" or order_status not in status_map: return None + user_auto_trading = await rq.get_user_auto_trading( + tg_id=tg_id, symbol=symbol + ) + auto_trading = ( + user_auto_trading.auto_trading if user_auto_trading else False + ) + user_deals_data = await rq.get_user_deal_by_symbol( + tg_id=tg_id, symbol=symbol + ) + text = ( f"Торговая пара: {symbol}\n" - f"Количество: {qty}\n" f"Движение: {side_rus}\n" ) + + if user_deals_data is not None and auto_trading: + text += f"Текущая ставка: {user_deals_data.order_quantity}\n" + else: + text += f"Количество: {qty}\n" + if price and price != "0": text += f"Цена: {price}\n" if take_profit and take_profit != "Нет данных": @@ -185,7 +200,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": "❗️ Количество контрактов превышает допустимое максимальное количество контрактов", + "The number of contracts exceeds maximum limit allowed": "❗️ Превышен максимальный лимит ставки", } error_text = errors.get( res, "❗️ Не удалось открыть новую сделку" diff --git a/app/telegram/handlers/main_settings/additional_settings.py b/app/telegram/handlers/main_settings/additional_settings.py index df2d1d9..1f9099e 100644 --- a/app/telegram/handlers/main_settings/additional_settings.py +++ b/app/telegram/handlers/main_settings/additional_settings.py @@ -7,6 +7,7 @@ from aiogram.types import CallbackQuery, Message import app.telegram.keyboards.inline as kbi import database.request as rq from app.bybit.get_functions.get_instruments_info import get_instruments_info +from app.bybit.get_functions.get_positions import get_active_positions_by_symbol, get_active_orders_by_symbol from app.bybit.set_functions.set_leverage import set_leverage from app.bybit.set_functions.set_margin_mode import set_margin_mode from app.helper_functions import is_int, is_number, safe_float @@ -211,6 +212,31 @@ async def settings_for_margin_type( """ try: await state.clear() + symbol = await rq.get_user_symbol(tg_id=callback_query.from_user.id) + deals = await get_active_positions_by_symbol( + tg_id=callback_query.from_user.id, symbol=symbol + ) + position = next((d for d in deals if d.get("symbol") == symbol), None) + + if position: + size = position.get("size", 0) + else: + size = 0 + + if safe_float(size) > 0: + await callback_query.answer( + text="У вас есть активная позиция по текущей паре", + ) + return + + orders = await get_active_orders_by_symbol( + tg_id=callback_query.from_user.id, symbol=symbol) + + if orders is not None: + await callback_query.answer( + text="У вас есть активный ордер по текущей паре", + ) + return await callback_query.message.edit_text( text="Выберите тип маржи:\n\n" "Примечание: Если у вас есть открытые позиции, то маржа примениться ко всем позициям", diff --git a/app/telegram/handlers/start_trading.py b/app/telegram/handlers/start_trading.py index 28a151d..440f35c 100644 --- a/app/telegram/handlers/start_trading.py +++ b/app/telegram/handlers/start_trading.py @@ -47,7 +47,7 @@ async def start_trading(callback_query: CallbackQuery, state: FSMContext) -> Non if safe_float(size) > 0: await callback_query.answer( - text="У вас есть активная позиция", + text="У вас есть активная позиция по текущей паре", ) return @@ -56,7 +56,7 @@ async def start_trading(callback_query: CallbackQuery, state: FSMContext) -> Non if orders is not None: await callback_query.answer( - text="У вас есть активные ордера", + text="У вас есть активный ордер по текущей паре", ) return @@ -94,13 +94,14 @@ async def start_trading(callback_query: CallbackQuery, state: FSMContext) -> Non ) error_messages = { - "Limit price is out min price": "Цена лимитного ордера меньше минимального", - "Limit price is out max price": "Цена лимитного ордера больше максимального", + "Limit price is out min price": "Цена лимитного ордера меньше допустимого", + "Limit price is out max price": "Цена лимитного ордера больше допустимого", "Risk is too high for this trade": "Риск сделки превышает допустимый убыток", "estimated will trigger liq": "Лимитный ордер может вызвать мгновенную ликвидацию. Проверьте параметры ордера.", "ab not enough for new order": "Недостаточно средств для создания нового ордера", "InvalidRequestError": "Произошла ошибка при запуске торговли.", - "Order does not meet minimum order value": "Сумма ставки меньше допустимого для запуска торговли.", + "Order does not meet minimum order value": "Сумма ставки меньше допустимого для запуска торговли. " + "Увеличьте ставку, чтобы запустить торговлю", "position idx not match position mode": "Измените режим позиции, чтобы запустить торговлю", "Qty invalid": "Некорректное значение ставки для данного инструмента", "The number of contracts exceeds maximum limit allowed": "️️Превышен максимальный лимит ставки",