🚀 AI 一键生成 ptrade 策略代码
立即体验

PTrade 期货交易实战:buy_open 与 sell_close 函数及平今/平昨逻辑详解

ptrade | 发布时间: 2026/7/29
以下内容由 EasyQuant 生成。

问题描述

请根据以下 SEO 主题生成完整页面内容:

Title: PTrade 期货交易实战:buy_open 与 sell_close 函数及平今/平昨逻辑详解

Question: 请问在 ptrade 中如何进行期货的多头开仓与平仓操作?上期所平今仓怎么设置?

解决方案

PTrade 期货交易实战:buy_open 与 sell_close 函数及平今/平昨逻辑详解

在 PTrade 量化交易平台中,期货交易接口与股票交易接口(如 order)存在明显区别。针对期货的多头交易,PTrade 提供了专门的 buy_open(多开)与 sell_close(多平)API。同时,针对上海期货交易所(XSGE)等交易所的特殊规则,平仓时还需要特别注意平今仓平昨仓的逻辑设置。


一、期货多头开仓:buy_open 函数

buy_open 用于买入开仓(建立多头头寸)。

1. 函数签名

buy_open(contract, amount, limit_price=None)

2. 参数说明

  • contract (str): 期货合约代码,需加交易所尾缀。如 'IF2309.CCFX'(中金所)、'CU2112.XSGE'(上期所)。
  • amount (int): 交易手数,必须为正整数。
  • limit_price (float, 可选): 买入限价。若不传该参数,实盘场景下默认使用行情快照最新价报单,回测场景下以当前分钟 K 线最新价报单。

3. 返回值

  • 返回 Order 对象的 idstr);若创建订单失败,则返回 None

二、期货多头平仓:sell_close 函数与平今/平昨逻辑

sell_close 用于卖出平仓(平掉现有的多头头寸)。

1. 函数签名

sell_close(contract, amount, limit_price=None, close_today=False)

2. 参数说明

  • contract (str): 期货合约代码。
  • amount (int): 拟平仓的手数,必须为正整数。
  • limit_price (float, 可选): 卖出平仓限价。
  • close_today (bool, 默认 False): 平仓方式标识
    • False(默认):优先平昨仓,不足部分再平今仓。
    • True:仅平今仓。若委托数量大于当前今仓可用数量,系统会自动调整为实际今仓数量。

3. 上期所 (XSGE) 特别注意规则

核心提示close_today=True 选项仅对上海期货交易所 (XSGE) 生效。其他交易所(如中金所 CCFX、大商所 DCE、郑商所 CZCE 等)默认区分或无需强行指定平今仓,若在非上期所合约中设置 close_today=True,系统会弹出警告并自动强行转换为 close_today=False


三、期货基础信息与保证金设置

在编写期货策略时,建议结合合约信息查询及手续费/保证金设置接口:

  1. 获取合约信息 (get_instruments)
    inst = get_instruments('CU2112.XSGE')
    # 可获取 inst.trade_unit(交易单位)、inst.contract_multiplier(合约乘数)、inst.margin_rate(保证金比例)等
    
  2. 设置回测保证金与手续费(仅回测模块生效)
    set_margin_rate("CU", 0.08)           # 设置沪铜保证金比例为 8%
    set_future_commission("CU", 0.00004)   # 按比例设置手续费,或按固定元/手设置
    

四、完整代码示例:双均线期货平今/平昨策略

以下是一个完整可运行的 PTrade 期货多头交易策略示例:

def initialize(context):
    # 订阅上期所沪铜合约
    g.security = 'CU2112.XSGE'
    set_universe(g.security)
    # 设置沪铜品种保证金比例为 8%
    set_margin_rate("CU", 0.08)

def handle_data(context, data):
    security = g.security
    
    # 获取历史收盘价计算均线
    df = get_history(10, '1d', 'close', security_list=security)
    if df is None or len(df) < 10:
        return
        
    ma5 = df['close'][-5:].mean()
    ma10 = df['close'][-10:].mean()
    current_price = data[security]['close']
    
    # 获取多头持仓
    position = get_position(security)
    long_amount = position.long_amount          # 多头总持仓
    today_long_amount = position.today_long_amount  # 多头今仓数量
    
    # 金叉:5日均线上穿10日均线,且无多头持仓,买入开仓 1 手
    if ma5 > ma10 and long_amount == 0:
        buy_open(security, 1, limit_price=current_price)
        log.info(f"金叉买入开仓: {security}, 价格: {current_price}")
        
    # 死叉:5日均线下穿10日均线,且存在多头持仓,进行平仓
    elif ma5 < ma10 and long_amount > 0:
        # 上期所平仓逻辑处理
        if "XSGE" in security:
            if today_long_amount > 0:
                # 优先平今仓
                sell_close(security, today_long_amount, limit_price=current_price, close_today=True)
                log.info(f"死叉平今仓: {security}, 数量: {today_long_amount}")
            
            # 若平完今仓后仍有昨仓,平昨仓
            yesterday_long = long_amount - today_long_amount
            if yesterday_long > 0:
                sell_close(security, yesterday_long, limit_price=current_price, close_today=False)
                log.info(f"死叉平昨仓: {security}, 数量: {yesterday_long}")
        else:
            # 非上期所合约直接调用优先平昨
            sell_close(security, long_amount, limit_price=current_price, close_today=False)
            log.info(f"死叉平仓: {security}, 数量: {long_amount}")