优化完美代码,加入止盈条件

This commit is contained in:
27942
2026-02-06 00:13:21 +08:00
parent 82c71d2d90
commit c19ae00e84

View File

@@ -38,6 +38,7 @@ class BitmartFuturesTransaction:
self.leverage = "100" # 高杠杆(全仓模式下可开更大仓位)
self.open_type = "cross" # 全仓模式
self.risk_percent = 0.01 # 每次开仓使用可用余额的 1%
self.take_profit_usd = 5 # 仓位盈利达到此金额(美元)时平仓止盈
self.open_avg_price = None # 开仓价格
self.current_amount = None # 持仓量
@@ -125,10 +126,12 @@ class BitmartFuturesTransaction:
positions = response['data']
if not positions:
self.start = 0
self.open_avg_price = None
self.current_amount = None
return True
self.start = 1 if positions[0]['position_type'] == 1 else -1
self.open_avg_price = float(positions[0]['open_avg_price'])
self.current_amount = positions[0]['current_amount']
self.current_amount = float(positions[0]['current_amount'])
self.position_cross = positions[0]["position_cross"]
return True
else:
@@ -137,6 +140,19 @@ class BitmartFuturesTransaction:
logger.error(f"持仓查询异常: {e}")
return False
def get_unrealized_pnl_usd(self, current_price):
"""
计算当前持仓未实现盈亏(美元)
多仓: (当前价 - 开仓均价) * 持仓量(ETH) = USDT
空仓: (开仓均价 - 当前价) * 持仓量(ETH) = USDT
"""
if self.start == 0 or self.open_avg_price is None or self.current_amount is None:
return None
if self.start == 1: # 多
return (current_price - self.open_avg_price) * self.current_amount
else: # 空
return (self.open_avg_price - current_price) * self.current_amount
def set_leverage(self):
"""程序启动时设置全仓 + 高杠杆"""
try:
@@ -557,6 +573,15 @@ class BitmartFuturesTransaction:
logger.debug(f"当前持仓状态: {self.start} (0=无, 1=多, -1=空)")
# 3.5 止盈:仓位盈利达到 take_profit_usd 则平仓下一轮循环再根据K线信号开仓
if self.start != 0:
pnl_usd = self.get_unrealized_pnl_usd(current_price)
if pnl_usd is not None and pnl_usd >= self.take_profit_usd:
logger.info(f"仓位盈利 {pnl_usd:.2f} 美元 >= {self.take_profit_usd} 美元,执行止盈平仓")
self.平仓()
time.sleep(3)
continue # 下一轮循环将无持仓会按K线信号重新判断是否开仓
# 4. 检查信号
signal = self.check_signal(current_price, prev_kline, current_kline)