forked from kodorvan/stcs
Fixed and updated tasks
This commit is contained in:
@@ -98,7 +98,7 @@ async def handle_execution_message(message, msg: dict) -> None:
|
|||||||
Обработчик сообщений об исполнении сделки.
|
Обработчик сообщений об исполнении сделки.
|
||||||
Логирует событие и проверяет условия для мартингейла и TP.
|
Логирует событие и проверяет условия для мартингейла и TP.
|
||||||
"""
|
"""
|
||||||
logger.info(f"Исполнена сделка:\n{json.dumps(msg, indent=4, ensure_ascii=False)}")
|
# logger.info(f"Исполнена сделка:\n{json.dumps(msg, indent=4, ensure_ascii=False)}")
|
||||||
|
|
||||||
pnl = parse_pnl_from_msg(msg)
|
pnl = parse_pnl_from_msg(msg)
|
||||||
tg_id = message.from_user.id
|
tg_id = message.from_user.id
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging.config
|
import logging.config
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from app.services.Bybit.functions.Futures import close_trade_after_delay, trading_cycle
|
from app.services.Bybit.functions.Futures import close_trade_after_delay, trading_cycle, open_position
|
||||||
from logger_helper.logger_helper import LOGGING_CONFIG
|
from logger_helper.logger_helper import LOGGING_CONFIG
|
||||||
|
|
||||||
logging.config.dictConfig(LOGGING_CONFIG)
|
logging.config.dictConfig(LOGGING_CONFIG)
|
||||||
@@ -9,16 +9,17 @@ logger = logging.getLogger("tasks")
|
|||||||
|
|
||||||
active_start_tasks = {}
|
active_start_tasks = {}
|
||||||
active_close_tasks = {}
|
active_close_tasks = {}
|
||||||
|
active_start_tasks_timer = {}
|
||||||
|
|
||||||
lock_start_tasks = asyncio.Lock()
|
lock_start_tasks = asyncio.Lock()
|
||||||
lock_close_tasks = asyncio.Lock()
|
lock_close_tasks = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
def start_trading_cycle(tg_id, message) -> None:
|
def start_trading_cycle(tg_id, message, side: str, margin_mode: str, tpsl_mode='Full') -> None:
|
||||||
"""
|
"""
|
||||||
Запускает асинхронную задачу торгового цикла для пользователя с указанным tg_id.
|
Запускает асинхронную задачу торгового цикла для пользователя с указанным tg_id.
|
||||||
"""
|
"""
|
||||||
task = asyncio.create_task(trading_cycle(tg_id, message))
|
task = asyncio.create_task(open_position(tg_id, message, side, margin_mode, tpsl_mode))
|
||||||
active_start_tasks[tg_id] = task
|
active_start_tasks[tg_id] = task
|
||||||
|
|
||||||
|
|
||||||
@@ -31,6 +32,17 @@ def stop_trading_cycle(tg_id) -> None:
|
|||||||
task.cancel()
|
task.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
def start_trading_for_timer(tg_id, message, side: str, margin_mode: str, tpsl_mode='Full') -> None:
|
||||||
|
# Старт с задержкой (trading_cycle)
|
||||||
|
task = asyncio.create_task(trading_cycle(tg_id, message))
|
||||||
|
active_start_tasks_timer[tg_id] = task
|
||||||
|
|
||||||
|
def stop_trading_for_timer(tg_id) -> None:
|
||||||
|
task: Optional[asyncio.Task] = active_start_tasks_timer.pop(tg_id, None)
|
||||||
|
if task:
|
||||||
|
task.cancel()
|
||||||
|
|
||||||
|
|
||||||
def start_close_trade_task(tg_id, message, symbol, delay_sec) -> None:
|
def start_close_trade_task(tg_id, message, symbol, delay_sec) -> None:
|
||||||
"""
|
"""
|
||||||
Запускает асинхронную задачу автоматического закрытия сделки после задержки.
|
Запускает асинхронную задачу автоматического закрытия сделки после задержки.
|
||||||
@@ -48,11 +60,22 @@ def stop_close_trade_task(tg_id) -> None:
|
|||||||
task.cancel()
|
task.cancel()
|
||||||
|
|
||||||
|
|
||||||
async def handle_start_trading(tg_id: int, message):
|
async def handle_start_trading(tg_id: int, message, side: str, margin_mode: str, tpsl_mode='Full', use_timer=False):
|
||||||
"""
|
"""
|
||||||
Запускает торговый цикл. Если уже есть запущенная задача, отменяет её.
|
Запускает торговый цикл. Если уже есть запущенная задача, отменяет её.
|
||||||
"""
|
"""
|
||||||
async with lock_start_tasks:
|
async with lock_start_tasks:
|
||||||
|
if use_timer:
|
||||||
|
old_task = active_start_tasks_timer.get(tg_id)
|
||||||
|
if old_task and not old_task.done():
|
||||||
|
old_task.cancel()
|
||||||
|
try:
|
||||||
|
await old_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info(f"Старая задача торговли с таймером для пользователя {tg_id} отменена")
|
||||||
|
start_trading_for_timer(tg_id, message, side, margin_mode, tpsl_mode)
|
||||||
|
logger.info(f"Новая задача торговли с таймером запущена для пользователя {tg_id}")
|
||||||
|
else:
|
||||||
old_task = active_start_tasks.get(tg_id)
|
old_task = active_start_tasks.get(tg_id)
|
||||||
if old_task and not old_task.done():
|
if old_task and not old_task.done():
|
||||||
old_task.cancel()
|
old_task.cancel()
|
||||||
@@ -60,15 +83,19 @@ async def handle_start_trading(tg_id: int, message):
|
|||||||
await old_task
|
await old_task
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
logger.info(f"Старая задача торговли для пользователя {tg_id} отменена")
|
logger.info(f"Старая задача торговли для пользователя {tg_id} отменена")
|
||||||
start_trading_cycle(tg_id, message)
|
start_trading_cycle(tg_id, message, side, margin_mode, tpsl_mode)
|
||||||
logger.info(f"Новая задача торговли запущена для пользователя {tg_id}")
|
logger.info(f"Новая задача торговли запущена для пользователя {tg_id}")
|
||||||
|
|
||||||
|
|
||||||
async def handle_stop_trading(tg_id: int):
|
async def handle_stop_trading(tg_id: int, use_timer=False):
|
||||||
"""
|
"""
|
||||||
Останавливает торговую задачу пользователя, если она активна.
|
Останавливает торговую задачу пользователя, если она активна.
|
||||||
"""
|
"""
|
||||||
async with lock_start_tasks:
|
async with lock_start_tasks:
|
||||||
|
if use_timer:
|
||||||
|
stop_trading_for_timer(tg_id)
|
||||||
|
logger.info(f"Задача торговли с таймером остановлена для пользователя {tg_id}")
|
||||||
|
else:
|
||||||
stop_trading_cycle(tg_id)
|
stop_trading_cycle(tg_id)
|
||||||
logger.info(f"Задача торговли остановлена для пользователя {tg_id}")
|
logger.info(f"Задача торговли остановлена для пользователя {tg_id}")
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user