Pharos
Contract

exchange.SetPositionMode()

设置仓位模式:全仓(Cross)或逐仓(Isolated)。

语法

python
exchange.SetPositionMode(mode)

参数

参数类型必填说明
modestr仓位模式:"cross"(全仓)或 "isolated"(逐仓)

返回值

无返回值。如果设置失败会抛出异常。

说明

仓位模式介绍

  • 全仓模式(Cross)

    • 使用账户全部可用余额作为保证金
    • 所有仓位共享保证金
    • 盈利的仓位可以为亏损的仓位提供支持
    • 风险较高但资金利用率高
  • 逐仓模式(Isolated)

    • 为每个仓位分配独立的保证金
    • 仓位之间互不影响
    • 最大亏损限于该仓位的保证金
    • 风险可控但资金利用率低

注意事项

  1. 当前持仓限制:切换仓位模式前必须平掉所有持仓
  2. 交易所支持
    • ✅ Gate.io 永续合约:完全支持
    • ⚠️ Binance 永续合约:暂未实现
    • ❌ 现货交易:不支持(会返回错误)
  3. 杠杆设置
    • 全仓模式:杠杆倍数在账户层面统一设置
    • 逐仓模式:可以为每个仓位设置不同的杠杆倍数

示例

基础用法

python
# 设置为全仓模式
exchange.SetPositionMode("cross")
Log("已切换到全仓模式")

# 设置为逐仓模式
exchange.SetPositionMode("isolated")
Log("已切换到逐仓模式")

安全切换仓位模式

python
def switch_position_mode(target_mode):
    """安全地切换仓位模式"""
    # 检查当前持仓
    position = exchange.GetPosition()
    if position:
        Log("⚠️ 检测到当前持仓,无法切换仓位模式")
        Log("请先平仓后再切换")
        return False
    
    try:
        exchange.SetPositionMode(target_mode)
        mode_name = "全仓" if target_mode == "cross" else "逐仓"
        Log(f"✓ 成功切换到{mode_name}模式")
        return True
    except Exception as e:
        Log(f"✗ 切换失败: {e}")
        return False

# 切换到全仓模式
switch_position_mode("cross")

初始化策略配置

python
def init_strategy():
    """策略初始化:设置交易环境"""
    # 1. 设置合约类型
    exchange.SetContractType("swap")
    Log("✓ 设置为永续合约")
    
    # 2. 设置仓位模式
    exchange.SetPositionMode("cross")
    Log("✓ 设置为全仓模式")
    
    # 3. 设置杠杆倍数
    exchange.SetMarginLevel(10)
    Log("✓ 设置10倍杠杆")
    
    # 4. 验证配置
    current_leverage = exchange.GetMarginLevel()
    Log(f"当前杠杆: {current_leverage}倍")
    
    Log("策略初始化完成")

# 在策略开始时调用
def main():
    init_strategy()
    # 继续执行策略逻辑...

根据账户余额选择模式

python
def auto_select_position_mode():
    """根据账户余额自动选择仓位模式"""
    account = exchange.GetAccount()
    balance = account['Balance']
    
    # 余额较大使用全仓,充分利用资金
    # 余额较小使用逐仓,控制风险
    if balance >= 10000:
        mode = "cross"
        mode_name = "全仓"
        reason = "余额充足,使用全仓提高资金利用率"
    else:
        mode = "isolated"
        mode_name = "逐仓"
        reason = "余额较少,使用逐仓控制风险"
    
    Log(f"账户余额: {balance:.2f} USDT")
    Log(f"选择{mode_name}模式 - {reason}")
    
    # 确保无持仓后切换
    position = exchange.GetPosition()
    if not position:
        exchange.SetPositionMode(mode)
        Log(f"✓ 已切换到{mode_name}模式")
    else:
        Log("⚠️ 有持仓存在,稍后切换")

auto_select_position_mode()

全仓与逐仓风险对比

python
def compare_position_modes():
    """对比全仓和逐仓的风险"""
    account = exchange.GetAccount()
    balance = account['Balance']
    ticker = exchange.GetTicker()
    price = ticker['Last']
    
    # 假设开仓参数
    position_size = 0.1  # BTC
    leverage = 10
    
    Log("=== 仓位模式风险对比 ===")
    Log(f"账户余额: {balance:.2f} USDT")
    Log(f"开仓数量: {position_size} BTC @ {price:.2f} USDT")
    Log(f"杠杆倍数: {leverage}x")
    
    # 计算保证金
    position_value = price * position_size
    required_margin = position_value / leverage
    
    Log(f"\n仓位价值: {position_value:.2f} USDT")
    Log(f"所需保证金: {required_margin:.2f} USDT")
    
    # 全仓模式分析
    Log("\n【全仓模式】")
    Log(f"- 可用保证金: {balance:.2f} USDT(全部余额)")
    Log(f"- 强平价格: 取决于账户总权益")
    Log(f"- 优点: 资金利用率高,可以开更多仓位")
    Log(f"- 缺点: 一个仓位爆仓可能导致全部资金损失")
    
    # 逐仓模式分析
    Log("\n【逐仓模式】")
    Log(f"- 仓位保证金: {required_margin:.2f} USDT")
    Log(f"- 强平价格: 仅影响该仓位")
    Log(f"- 优点: 风险隔离,最大亏损 = 该仓位保证金")
    Log(f"- 缺点: 资金利用率低,需要为每个仓位分配保证金")
    
    # 建议
    risk_ratio = (required_margin / balance) * 100
    Log(f"\n单笔仓位占比: {risk_ratio:.1f}%")
    if risk_ratio > 50:
        Log("建议: 使用逐仓模式,避免单笔交易风险过大")
    else:
        Log("建议: 可以使用全仓模式,提高资金效率")

compare_position_modes()

策略模板:全仓模式下的多仓位管理

python
def cross_mode_multi_position_strategy():
    """全仓模式下管理多个仓位"""
    exchange.SetPositionMode("cross")
    exchange.SetMarginLevel(5)  # 全仓5倍杠杆
    
    account = exchange.GetAccount()
    total_balance = account['Balance']
    
    # 将资金分配到3个币种
    symbols = ['BTC_USDT', 'ETH_USDT', 'SOL_USDT']
    allocation_per_symbol = total_balance * 0.3  # 每个币种30%
    
    Log(f"总余额: {total_balance:.2f} USDT")
    Log(f"每个币种分配: {allocation_per_symbol:.2f} USDT")
    Log("策略: 全仓模式下同时持有3个币种的仓位")
    
    for symbol in symbols:
        # 这里可以实现具体的开仓逻辑
        Log(f"准备开仓: {symbol}")
        # exchange.SetCurrency(symbol)
        # ... 开仓逻辑
    
    Log("✓ 全仓模式优势: 盈利仓位可以支持亏损仓位,避免提前止损")

cross_mode_multi_position_strategy()

策略模板:逐仓模式下的风险控制

python
def isolated_mode_risk_control():
    """逐仓模式下的严格风险控制"""
    exchange.SetPositionMode("isolated")
    
    account = exchange.GetAccount()
    total_balance = account['Balance']
    
    # 单笔最大风险:总资金的2%
    max_risk_per_trade = total_balance * 0.02
    
    # 设置止损比例10%
    stop_loss_ratio = 0.10
    
    # 计算仓位大小
    leverage = 10
    max_position_margin = max_risk_per_trade / stop_loss_ratio
    
    Log("=== 逐仓模式风险控制策略 ===")
    Log(f"总资金: {total_balance:.2f} USDT")
    Log(f"单笔最大风险: {max_risk_per_trade:.2f} USDT (2%)")
    Log(f"止损比例: {stop_loss_ratio * 100}%")
    Log(f"单笔最大保证金: {max_position_margin:.2f} USDT")
    Log(f"杠杆: {leverage}x")
    
    ticker = exchange.GetTicker()
    price = ticker['Last']
    max_position_value = max_position_margin * leverage
    max_position_size = max_position_value / price
    
    Log(f"\n开仓参数:")
    Log(f"- 当前价格: {price:.2f} USDT")
    Log(f"- 最大开仓量: {max_position_size:.4f} BTC")
    Log(f"- 仓位价值: {max_position_value:.2f} USDT")
    Log(f"- 占用保证金: {max_position_margin:.2f} USDT")
    
    Log("\n✓ 逐仓优势: 即使该仓位爆仓,最大亏损也仅为 {:.2f} USDT".format(max_position_margin))

isolated_mode_risk_control()

错误处理

python
def set_position_mode_with_error_handling(mode):
    """带错误处理的仓位模式设置"""
    if mode not in ["cross", "isolated"]:
        Log(f"✗ 错误: 无效的仓位模式 '{mode}'")
        Log("有效值: 'cross' 或 'isolated'")
        return False
    
    try:
        exchange.SetPositionMode(mode)
        mode_name = "全仓" if mode == "cross" else "逐仓"
        Log(f"✓ 成功设置为{mode_name}模式")
        return True
        
    except Exception as e:
        error_msg = str(e)
        
        # 常见错误处理
        if "not supported" in error_msg.lower():
            Log("✗ 当前交易所或交易类型不支持设置仓位模式")
            Log("提示: 仓位模式仅适用于合约交易")
            
        elif "position" in error_msg.lower():
            Log("✗ 存在持仓,无法切换仓位模式")
            Log("解决方案: 先平掉所有持仓后再切换")
            
        elif "not implemented" in error_msg.lower():
            Log("✗ 当前交易所暂未实现仓位模式设置")
            Log("支持的交易所: Gate.io 永续合约")
            
        else:
            Log(f"✗ 设置失败: {error_msg}")
        
        return False

# 使用示例
set_position_mode_with_error_handling("cross")

最佳实践

1. 策略启动时设置

python
def main():
    # 在策略最开始设置仓位模式
    exchange.SetPositionMode("cross")
    exchange.SetMarginLevel(10)
    
    # 确认设置成功后开始交易
    Log("环境配置完成,开始交易...")

2. 新手建议

python
# 新手建议使用逐仓模式 + 低杠杆
exchange.SetPositionMode("isolated")
exchange.SetMarginLevel(3)
Log("新手配置: 逐仓 + 3倍杠杆,控制风险")

3. 专业交易者

python
# 专业交易者可以使用全仓模式 + 适中杠杆
exchange.SetPositionMode("cross")
exchange.SetMarginLevel(10)
Log("专业配置: 全仓 + 10倍杠杆,提高资金效率")

相关文档

常见问题

Q1: 全仓和逐仓哪个更好?

A: 取决于你的风险偏好:

  • 风险承受能力强、资金量大 → 全仓模式,提高资金利用率
  • 风险厌恶、新手、小资金 → 逐仓模式,控制单笔风险

Q2: 可以随时切换仓位模式吗?

A: 不可以。切换前必须平掉所有持仓。建议在策略启动时设置好,运行中不要切换。

Q3: 全仓模式下爆仓会怎样?

A: 全仓模式下,如果账户总权益低于维持保证金要求,所有仓位都会被强平,可能损失全部资金。

Q4: 逐仓模式可以设置不同杠杆吗?

A: 理论上可以,但当前实现中 SetMarginLevel() 是全局设置。建议在逐仓模式下保持统一杠杆倍数。

Q5: 现货交易可以设置仓位模式吗?

A: 不可以。仓位模式是合约交易的特性,现货交易不涉及保证金和杠杆。