2
0
forked from kodorvan/stcs
Files
stcs/app/bybit/set_functions/set_tp_sl.py

49 lines
1.5 KiB
Python

import logging.config
from app.bybit import get_bybit_client
from app.bybit.get_functions.get_positions import get_active_positions_by_symbol
from app.bybit.logger_bybit.logger_bybit import LOGGING_CONFIG
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("set_tp_sl")
async def set_tp_sl_for_position(
tg_id: int,
symbol: str,
take_profit_price: float,
stop_loss_price: float,
) -> bool:
"""
Set take profit and stop loss for a symbol.
:param tg_id: Telegram user ID
:param symbol: Symbol to set take profit and stop loss for
:param take_profit_price: Take profit price
:param stop_loss_price: Stop loss price
:return: bool
"""
try:
client = await get_bybit_client(tg_id)
user_positions = await get_active_positions_by_symbol(
tg_id=tg_id, symbol=symbol
)
position_idx = user_positions.get("positionIdx")
resp = client.set_trading_stop(
category="linear",
symbol=symbol,
takeProfit=str(round(take_profit_price, 5)),
stopLoss=str(round(stop_loss_price, 5)),
positionIdx=position_idx,
tpslMode="Full",
)
if resp.get("retCode") == 0:
logger.info("TP/SL for %s has been set", symbol)
return True
else:
logger.error("Error setting TP/SL for %s: %s", symbol, resp.get("retMsg"))
return False
except Exception as e:
logger.error("Error setting TP/SL for %s: %s", symbol, e)
return False