2
0
forked from kodorvan/stcs

The stop trading button has been added, and the switch mode has been fixed

This commit is contained in:
algizn97
2025-10-23 11:28:44 +05:00
parent ddfa3a7360
commit 3df88d07ab
7 changed files with 35 additions and 83 deletions

View File

@@ -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

View File

@@ -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,

View File

@@ -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"

View File

@@ -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,

View File

@@ -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="Торговля остановлена", reply_markup=kbi.profile_bybit)
else:
await callback_query.message.edit_text(text="Нет активной торговли")
await callback_query.message.edit_text(text="Нет активной торговли", reply_markup=kbi.profile_bybit)
task = asyncio.create_task(delay_start())
await add_stop_task(user_id=callback_query.from_user.id, task=task)

View File

@@ -36,6 +36,7 @@ main_menu = InlineKeyboardMarkup(
)
],
[InlineKeyboardButton(text="Начать торговлю", callback_data="start_trading")],
[InlineKeyboardButton(text="Остановить торговлю", callback_data="stop_trading")],
]
)