3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在融资融券(两融)量化交易中,实时监控信用账户的合约发生额流水对于风险控制和资金管理至关重要。ptrade 平台提供了专门的信用交易查询接口 get_margin_contractreal,允许投资者在交易时间内实时获取账户的合约流水明细。
get_margin_contractreal() 函数用于查询信用账户的实时合约流水。该接口仅在两融交易模块可用,且仅支持在 PTrade 客户端运行。
正常情况下,该接口返回一个 pandas.DataFrame 对象,包含以下核心字段:
init_date: 交易日期 (int)compact_id: 合约编号 (str)client_id: 客户编号 (str)money_type: 币种类别 (str)market_type: 证券市场 (str)entrust_no: 委托编号 (int)compact_type: 合约类别 (str,0-融资,1-融券,2-其他负债)stock_code: 证券代码 (str)business_flag: 业务标志 (int)occur_balance: 发生金额 (float)post_balance: 后资金额 (float)occur_amount: 发生数量 (float)post_amount: 后证券额 (float)occur_fare: 发生费用 (float)post_fare: 后余费用 (float)occur_interest: 发生利息 (float)post_interest: 后余利息 (float)remark: 备注 (str)以下是一个完整的 ptrade 策略示例。该策略在盘中通过 handle_data 周期性调用 get_margin_contractreal 接口,实时监控流水变化,并在盘后(after_trading_end)将当日的流水明细导出为 CSV 文件保存到研究根目录下。
import pandas as pd
import os
def initialize(context):
# 初始化策略,设置监控的股票池
g.security = '600570.SS' # 恒生电子
set_universe(g.security)
# 获取研究根目录路径
g.research_path = get_research_path()
g.has_logged = False
def handle_data(context, data):
# 仅在交易场景下执行监控
if is_trade():
# 获取实时合约流水
df_contract_real = get_margin_contractreal()
if df_contract_real is not None and not df_contract_real.empty:
if not g.has_logged:
log.info("发现实时合约流水记录:")
log.info(df_contract_real.head())
g.has_logged = True
else:
if not g.has_logged:
log.info("当前暂无实时合约流水记录。")
g.has_logged = True
def after_trading_end(context, data):
log.info("盘后处理:开始导出当日信用合约发生额流水...")
# 获取当日最终的合约流水
df_contract_real = get_margin_contractreal()
if df_contract_real is not None and not df_contract_real.empty:
# 拼接保存路径
file_name = "margin_contract_real_flow.csv"
save_path = os.path.join(g.research_path, file_name)
# 导出为 CSV 文件
df_contract_real.to_csv(save_path, index=False, encoding='utf-8-sig')
log.info(f"当日合约流水已成功导出至研究目录:{save_path}")
else:
log.warning("今日未产生任何信用合约流水,无需导出。")
get_margin_contractreal 接口仅在实盘/仿真两融交易中有效,回测环境不支持此接口(回测时会返回 None)。utf-8-sig 编码,确保在 Excel 中直接打开时中文备注(remark 字段)不会出现乱码。