优化完美代码,优化计算盈亏
This commit is contained in:
@@ -128,11 +128,17 @@ class BitmartFuturesTransaction:
|
||||
self.start = 0
|
||||
self.open_avg_price = None
|
||||
self.current_amount = None
|
||||
self.unrealized_pnl = 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 = float(positions[0]['current_amount'])
|
||||
self.position_cross = positions[0]["position_cross"]
|
||||
pos = positions[0]
|
||||
self.start = 1 if pos['position_type'] == 1 else -1
|
||||
self.open_avg_price = float(pos['open_avg_price'])
|
||||
self.current_amount = float(pos['current_amount'])
|
||||
self.position_cross = pos["position_cross"]
|
||||
# 直接从API获取未实现盈亏(Bitmart返回的是 unrealized_value 字段)
|
||||
self.unrealized_pnl = float(pos.get('unrealized_value', 0))
|
||||
logger.debug(f"持仓详情: 方向={self.start}, 开仓均价={self.open_avg_price}, "
|
||||
f"持仓量={self.current_amount}, 未实现盈亏={self.unrealized_pnl:.2f}")
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
@@ -140,18 +146,13 @@ class BitmartFuturesTransaction:
|
||||
logger.error(f"持仓查询异常: {e}")
|
||||
return False
|
||||
|
||||
def get_unrealized_pnl_usd(self, current_price):
|
||||
def get_unrealized_pnl_usd(self):
|
||||
"""
|
||||
计算当前持仓未实现盈亏(美元)
|
||||
多仓: (当前价 - 开仓均价) * 持仓量(ETH) = USDT
|
||||
空仓: (开仓均价 - 当前价) * 持仓量(ETH) = USDT
|
||||
获取当前持仓未实现盈亏(美元),直接使用API返回值
|
||||
"""
|
||||
if self.start == 0 or self.open_avg_price is None or self.current_amount is None:
|
||||
if self.start == 0 or self.unrealized_pnl 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
|
||||
return self.unrealized_pnl
|
||||
|
||||
def set_leverage(self):
|
||||
"""程序启动时设置全仓 + 高杠杆"""
|
||||
@@ -575,7 +576,7 @@ class BitmartFuturesTransaction:
|
||||
|
||||
# 3.5 止盈:仓位盈利达到 take_profit_usd 则平仓,下一轮循环再根据K线信号开仓
|
||||
if self.start != 0:
|
||||
pnl_usd = self.get_unrealized_pnl_usd(current_price)
|
||||
pnl_usd = self.get_unrealized_pnl_usd()
|
||||
if pnl_usd is not None and pnl_usd >= self.take_profit_usd:
|
||||
logger.info(f"仓位盈利 {pnl_usd:.2f} 美元 >= {self.take_profit_usd} 美元,执行止盈平仓")
|
||||
self.平仓()
|
||||
|
||||
Reference in New Issue
Block a user