This commit is contained in:
algizn97
2025-10-04 09:34:11 +05:00
parent 163f4dcba9
commit 220c45d54c
3 changed files with 51 additions and 18 deletions

View File

@@ -70,15 +70,19 @@ class TelegramMessageHandler:
text = ( text = (
f"{status_text}:\n" f"{status_text}:\n"
f"Торговая пара: {symbol}\n" f"Торговая пара: {symbol}\n"
f"Цена: {price}\n"
f"Режим позиции: {position_idx_rus}\n" f"Режим позиции: {position_idx_rus}\n"
f"Количество: {qty}\n" f"Количество: {qty}\n"
f"Тип ордера: {order_type_rus}\n" f"Тип ордера: {order_type_rus}\n"
f"Движение: {side_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( await self.telegram_bot.send_message(
chat_id=tg_id, text=text, reply_markup=kbi.profile_bybit chat_id=tg_id, text=text, reply_markup=kbi.profile_bybit
@@ -111,9 +115,12 @@ class TelegramMessageHandler:
await rq.set_fee_user_auto_trading( await rq.set_fee_user_auto_trading(
tg_id=tg_id, symbol=symbol, side=side, fee=safe_float(exec_fee) 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( 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: if user_auto_trading is not None and user_auto_trading.fee is not None:
@@ -175,6 +182,9 @@ class TelegramMessageHandler:
else: else:
r_side = "Buy" r_side = "Buy"
await rq.set_auto_trading(tg_id=tg_id, symbol=symbol, auto_trading=False, side=r_side) 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: else:
open_order_text = "\n❗️ Сделка закрылась в минус, открываю новую сделку с увеличенной ставкой.\n" open_order_text = "\n❗️ Сделка закрылась в минус, открываю новую сделку с увеличенной ставкой.\n"
await self.telegram_bot.send_message( await self.telegram_bot.send_message(
@@ -192,6 +202,7 @@ class TelegramMessageHandler:
"Risk is too high for this trade": "❗️ Риск сделки слишком высок для продолжения", "Risk is too high for this trade": "❗️ Риск сделки слишком высок для продолжения",
"ab not enough for new order": "❗️ Недостаточно средств для продолжения торговли", "ab not enough for new order": "❗️ Недостаточно средств для продолжения торговли",
"InvalidRequestError": "❗️ Недостаточно средств для размещения нового ордера с заданным количеством и плечом.", "InvalidRequestError": "❗️ Недостаточно средств для размещения нового ордера с заданным количеством и плечом.",
"The number of contracts exceeds maximum limit allowed": "❗️ Количество контрактов превышает допустимое максимальное количество контрактов",
} }
error_text = errors.get( error_text = errors.get(
res, "❗️ Не удалось открыть новую сделку" res, "❗️ Не удалось открыть новую сделку"
@@ -203,6 +214,11 @@ class TelegramMessageHandler:
await rq.set_auto_trading( await rq.set_auto_trading(
tg_id=tg_id, symbol=symbol, auto_trading=False, side=r_side 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( await self.telegram_bot.send_message(
chat_id=tg_id, chat_id=tg_id,
text=error_text, text=error_text,

View File

@@ -39,7 +39,7 @@ main_menu = InlineKeyboardMarkup(
[InlineKeyboardButton(text="Начать торговлю", callback_data="start_trading")], [InlineKeyboardButton(text="Начать торговлю", callback_data="start_trading")],
[ [
InlineKeyboardButton( 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() 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( return InlineKeyboardMarkup(
inline_keyboard=[ inline_keyboard=[
[ [
InlineKeyboardButton( 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( 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() builder = InlineKeyboardBuilder()
for order, side in orders: for order, side in orders:
builder.button(text=f"{order}", callback_data=f"get_order_{order}_{side}") 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=[ inline_keyboard=[
[ [
InlineKeyboardButton( 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( cancel_timer_merged = InlineKeyboardMarkup(
inline_keyboard=[ inline_keyboard=[
[InlineKeyboardButton(text="Отменить таймер", callback_data="cancel_timer_merged")], [
InlineKeyboardButton(
text="Отменить таймер", callback_data="cancel_timer_merged"
)
],
[ [
InlineKeyboardButton(text="На главную", callback_data="profile_bybit"), InlineKeyboardButton(text="На главную", callback_data="profile_bybit"),
], ],
@@ -448,7 +457,11 @@ cancel_timer_merged = InlineKeyboardMarkup(
cancel_timer_switch = InlineKeyboardMarkup( cancel_timer_switch = InlineKeyboardMarkup(
inline_keyboard=[ inline_keyboard=[
[InlineKeyboardButton(text="Отменить таймер", callback_data="cancel_timer_switch")], [
InlineKeyboardButton(
text="Отменить таймер", callback_data="cancel_timer_switch"
)
],
[ [
InlineKeyboardButton(text="На главную", callback_data="profile_bybit"), InlineKeyboardButton(text="На главную", callback_data="profile_bybit"),
], ],
@@ -459,9 +472,13 @@ cancel_timer_switch = InlineKeyboardMarkup(
cancel_timer_stop = InlineKeyboardMarkup( cancel_timer_stop = InlineKeyboardMarkup(
inline_keyboard=[ inline_keyboard=[
[InlineKeyboardButton(text="Отменить таймер", callback_data="cancel_timer_stop")], [
InlineKeyboardButton(
text="Отменить таймер", callback_data="cancel_timer_stop"
)
],
[ [
InlineKeyboardButton(text="На главную", callback_data="profile_bybit"), InlineKeyboardButton(text="На главную", callback_data="profile_bybit"),
], ],
] ]
) )

View File

@@ -1268,7 +1268,7 @@ async def get_all_user_auto_trading(tg_id: int):
return [] 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.""" """Get user auto trading from the database asynchronously."""
try: try:
async with async_session() as session: async with async_session() as session:
@@ -1278,7 +1278,7 @@ async def get_user_auto_trading(tg_id: int, symbol: str):
return None return None
result_auto_trading = await session.execute( 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() auto_trading = result_auto_trading.scalars().first()
return auto_trading return auto_trading