Contract
exchange.GetPosition()
获取合约持仓信息(仅限合约交易)。
语法
python
positions = exchange.GetPosition()返回值
返回一个列表,每个元素是一个字典:
| 字段 | 类型 | 说明 |
|---|---|---|
| Symbol | str | 合约代码 |
| Type | str | 持仓类型(long/short) |
| Amount | float | 持仓数量 |
| Price | float | 持仓均价 |
| Profit | float | 未实现盈亏 |
| Margin | float | 占用保证金 |
| Info | str | 交易所原始信息(JSON字符串) |
| LiquidationPrice | float | 强平价格 |
| Leverage | int | 杠杆倍数(0表示全仓) |
| InitialMargin | float | 起始保证金 |
示例
基础用法
python
positions = exchange.GetPosition()
if not positions:
Log("当前无持仓")
else:
for pos in positions:
Log(f"持仓类型: {pos['Type']}")
Log(f"持仓量: {pos['Amount']}")
Log(f"持仓均价: {pos['Price']:.2f}")
Log(f"未实现盈亏: {pos['Profit']:.2f}")
Log(f"占用保证金: {pos['Margin']:.2f}")
Log(f"强平价格: {pos['LiquidationPrice']:.2f}")
Log(f"杠杆倍数: {pos['Leverage']}x")查看完整持仓信息
python
positions = exchange.GetPosition()
for pos in positions:
Log(f"========== {pos['Symbol']} ==========")
Log(f"持仓类型: {pos['Type']}")
Log(f"持仓数量: {pos['Amount']}")
Log(f"持仓均价: {pos['Price']:.2f}")
Log(f"未实现盈亏: {pos['Profit']:.2f} USDT")
Log(f"占用保证金: {pos['Margin']:.2f} USDT")
Log(f"起始保证金: {pos['InitialMargin']:.2f} USDT")
Log(f"强平价格: {pos['LiquidationPrice']:.2f}")
Log(f"杠杆倍数: {pos['Leverage']}x ({'全仓' if pos['Leverage'] == 0 else '逐仓'})")
# 解析原始信息(如需要)
if pos['Info']:
import json
info = json.loads(pos['Info'])
Log(f"原始信息: {info}")plaintext
### 计算持仓盈亏率
```python
def calculate_profit_rate():
"""计算持仓盈亏率"""
positions = exchange.GetPosition()
for pos in positions:
if pos['Margin'] > 0:
profit_rate = (pos['Profit'] / pos['Margin']) * 100
Log(f"{pos['Type']} 持仓盈亏率: {profit_rate:+.2f}%")
calculate_profit_rate()检查持仓方向
python
def get_position_direction():
"""获取当前持仓方向"""
positions = exchange.GetPosition()
if not positions:
return "none"
# 只考虑第一个持仓
return positions[0]['Type']
direction = get_position_direction()
if direction == "long":
Log("当前持有多单")
elif direction == "short":
Log("当前持有空单")
else:
Log("当前无持仓")止盈止损检查
python
def check_stop_loss_take_profit(stop_loss_percent=5, take_profit_percent=10):
"""检查止盈止损"""
positions = exchange.GetPosition()
for pos in positions:
if pos['Margin'] == 0:
continue
profit_rate = (pos['Profit'] / pos['Margin']) * 100
if profit_rate <= -stop_loss_percent:
Log(f"触发止损!盈亏率: {profit_rate:.2f}%")
# 平仓逻辑
close_position(pos)
elif profit_rate >= take_profit_percent:
Log(f"触发止盈!盈亏率: {profit_rate:.2f}%")
# 平仓逻辑
close_position(pos)
def close_position(pos):
"""平仓"""
if pos['Type'] == 'long':
# 多单平仓:卖出
exchange.SetDirection("closebuy")
exchange.Sell(-1, pos['Amount'])
else:
# 空单平仓:买入
exchange.SetDirection("closesell")
exchange.Buy(-1, pos['Amount'])
# 5%止损,10%止盈
check_stop_loss_take_profit(5, 10)强平价格风控
python
def check_liquidation_risk():
"""检查强平风险"""
positions = exchange.GetPosition()
ticker = exchange.GetTicker()
current_price = ticker['Last']
for pos in positions:
if pos['LiquidationPrice'] == 0:
continue
if pos['Type'] == 'long':
# 多单:当前价格距离强平价格的百分比
distance = (current_price - pos['LiquidationPrice']) / current_price * 100
Log(f"多单距离强平: {distance:.2f}%")
if distance < 5:
Log("⚠️ 警告:距离强平价格过近!", "#FF0000")
else:
# 空单
distance = (pos['LiquidationPrice'] - current_price) / current_price * 100
Log(f"空单距离强平: {distance:.2f}%")
if distance < 5:
Log("⚠️ 警告:距离强平价格过近!", "#FF0000")
check_liquidation_risk()plaintext
### 计算总持仓价值
```python
def calculate_position_value():
"""计算持仓总价值"""
positions = exchange.GetPosition()
ticker = exchange.GetTicker()
total_value = 0
for pos in positions:
value = pos['Amount'] * ticker['Last']
total_value += value
Log(f"{pos['Type']} 持仓价值: {value:.2f} USDT")
Log(f"总持仓价值: {total_value:.2f} USDT")
return total_value
calculate_position_value()注意事项
- 仅限合约:此方法仅适用于合约交易,现货交易请使用 GetAccount()
- 多持仓:某些交易所支持同时持有多空双向持仓
- 实时更新:持仓信息随价格波动实时变化
相关方法
- SetContractType - 设置合约类型
- SetDirection - 设置开平仓方向
- SetMarginLevel - 设置杠杆倍数
- SetPositionMode - 设置仓位模式(全仓/逐仓)
- GetAccount - 获取账户信息