from typing import List, Dict, Union
def calculate_profit_factor(closed_trades: List[Dict], account_state: Dict) -> Union[float, str]:
"""
基于JS文件 (Ee 函数) 解析的盈亏比 (Profit Factor) 算法。
计算公式: (已实现盈利 + 未实现盈利) / (已实现亏损绝对值 + 未实现亏损绝对值)
Args:
closed_trades: 已平仓交易的列表。每个元素至少包含 "closedPnl"。
account_state: 账户状态,包含 "clearinghouseState.assetPositions" (未平仓位)。
Returns:
盈亏比数值 (float) 或字符串 "1000+"。
"""
gross_profit = 0.0 # 总盈利之和 (GP)
gross_loss_abs = 0.0 # 总亏损绝对值之和 (GL)
# 1. 计算已平仓交易盈亏 (closedPnl)
for trade in closed_trades:
# 确保 PnL 存在且可转换为浮点数
try:
pnl = float(trade.get("closedPnl", 0.0))
except (ValueError, TypeError):
pnl = 0.0
if pnl > 0:
gross_profit += pnl
else:
gross_loss_abs += abs(pnl)
# 2. 计算未平仓资产浮动盈亏 (unrealizedPnl)
asset_positions = account_state.get("clearinghouseState", {}).get("assetPositions", [])
for position_data in asset_positions:
# 确保 unrealizedPnl 存在且可转换为浮点数
try:
unrealized_pnl = float(position_data.get("position", {}).get("unrealizedPnl", 0.0))
except (ValueError, TypeError):
unrealized_pnl = 0.0
if unrealized_pnl > 0:
gross_profit += unrealized_pnl
else:
gross_loss_abs += abs(unrealized_pnl)
# 3. 计算盈亏比并处理特殊情况
if gross_loss_abs != 0:
return gross_profit / gross_loss_abs
elif gross_profit > 0:
# JS 代码中的 "1000+"
return "1000+"
else:
# gross_loss_abs == 0 and gross_profit == 0
return 0.0
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)