期魔方风控模型之委托失败补单程序

图片[1]|期魔方风控模型之委托失败补单程序|魔方商学院

你知道吗?只需简单设置,期魔方风控模型就能自动处理风控委托失败的订单,进行补单操作。

那么,这种功能适用于哪些场景呢?让我们一起来探讨一下!

在实际交易中,我们有时会遇到在任意交易终端(如文华博弈、随身行等)下单后,委托被挂起未成交,或者由于流动性不足导致部分订单未能完全成交。此时,期魔方的自动补单功能就能发挥关键作用。系统会自动撤销未成交的订单,并重新提交补单,确保不会错失交易机会,避免漏单风险。

这一自动补单功能不仅可以应用于全局账户风控,也可以针对特定合约进行精确控制。用户还可以自定义补单方式,选择市价、现价或对价等不同类型的报单方式,以适应不同的市场需求和风险管理策略。

这是这款风控模型的Python源码,适用于期魔方软件

#——————————————#

#文件类型:量化策略

#帮助文档:https://qmfquant.com/static/doc/code/strategyEdit.html

#期魔方,为您提供专业的量化服务

#——————————————#

from pydantic import BaseModel, Field

import time

import datetime

class Params(BaseModel, validate_assignment=True):

    “””参数映射模型”””

    set_symbol_mode:dict   = Field(default={“options”:[“全局”,”指定”],\

                                           “value”:”全局”},title =”跟踪对象”)

    symbols:str            = Field(default=”ag2510,rb2510″,title =”指定的合约”)

    over_time_second:int   = Field(default=10,title = “超时N秒撤单”)

    #run_dis:int            = Field(default=10,title  = “触发间隔”)

    #run_times:int          = Field(default=3,title  = “执行次数”)

    set_price_mode:dict   = Field(default={“options”:[“市价”,”现价”,”对价”],\

                                           “value”:”市价”},title =”报单方式”)

position                   = {}

def on_init(context):

    print(“[on_init] => 初始化…”)    

    context.orders =  {}

    context.wait_open_orders  = []

    print(“[on_init] => 初始化完成.”)

def on_tick(context):

    try:

        #判断订单是否超时 超时发起撤单  并重新开单

        for order_sys_id,order in context.orders.items():

            if order.get(“OrderStatus”) == “3”:

                #未成交

                insert_date = order.get(“InsertDate”)

                insert_time = order.get(“InsertTime”)

                order_time = datetime.datetime.strptime(

                    f”{insert_date} {insert_time}”,”%Y%m%d %H:%M:%S”).timestamp()

                current_time = datetime.datetime.now().timestamp()

                #print(f”订单时间戳=>{order_time}  当前时间戳=>{current_time}”)

                if current_time – order_time > int(context.over_time_second):

                    #撤单

                    print(f”订单时间:{insert_date} {insert_time}  当前的时间 {datetime.datetime.now()}”)

                    print(f”执行超时撤单 [{order_sys_id}]”)

                    action_order(order)

    except Exception as e:

        print(f”撤单判断过程有错误  {e}”)

    try:

        #把需要重开的订单依次执行开启

        while len(context.wait_open_orders) >0:

            order = context.wait_open_orders.pop(0)

            #执行开仓

            result = open_order(context,order)

            if result <=0:

                print(“重开失败”)

                context.wait_open_orders.append(order)

                break

            else:

                print(“报单成功”)        

        …

    except Exception as e:

        print(f”重开过程报错=>{e}”)

    …

def cook_order_key(order):

    return f”{

        order.get(‘InstrumentID’)}_{order.get(‘Direction’)}_{order.get(‘CombOffsetFlag’)}_{order.get(‘VolumeTotalOriginal’)}”

def open_order(context,order):

    try:

        symbol = order.get(“InstrumentID”)

        exchangid = order.get(“ExchangeID”)

        direction = order.get(“Direction”)

        volume    = order.get(“VolumeTotalOriginal”)

        comboffsetflag = order.get(“CombOffsetFlag”)

        tick = get_tick(symbol)

        if not tick.get(“ActionDay”):

            #tick获取失败 返回等待下一次运行

            return -1

        upper_price = float(tick.get(“UpperLimitPrice”))

        lower_price = float(tick.get(“LowerLimitPrice”))

        if context.set_price_mode.get(“value”) == “对价”:

            upper_price = float(tick.get(“BidPrice1”))

            lower_price = float(tick.get(“AskPrice1”))

        if context.set_price_mode.get(“value”) == “现价”:

            upper_price = float(tick.get(“LastPrice”))

            lower_price = float(tick.get(“LastPrice”))

        price  =upper_price if direction==”0″ else lower_price

        order  = {

            “symbol”:symbol,

            “exchangeid”:exchangid,

            “limitprice”:price,

            “direction”:direction,

            “orderpricetype”:”2″,

            “comboffsetflag”:comboffsetflag,

            “volumn”:volume

            }

        print(f”报单信息 => {order}”)

        send_order(order)

    except Exception as e:

        print(f”开单出现错误=>请查看GridTrade.close_order[{e}]”)

        print(e)

        return 0

    return 1

def on_allorder(context,data):

    “””按要求记录全局报单”””

    order_sys_id  = data.get(“OrderSysID”)

    instrument_id = data.get(“InstrumentID”)

    if context.set_symbol_mode.get(“value”) == “指定”:

        if instrument_id not in context.symbols: return

    order_status  = data.get(“OrderStatus”)

    offset         = data.get(“CombOffsetFlag”)

    if  order_status in “3”:

        context.orders[order_sys_id] = data

        print(“收到未成交报单信息”)

    elif order_status == “0”:

        if order_sys_id in context.orders:

            context.orders.pop(order_sys_id)

    elif order_status == “5”:

        if order_sys_id in context.orders:

            context.orders.pop(order_sys_id)

            #首单撤单信息 则按信息重新开启订单

            context.wait_open_orders.append(data)

            #执行开仓

            …

def on_order(context,data):

    “””报单回调函数”””

    #print(f”用来收集本地成交的记录  {data = }”)

    order_sys_id  = data.get(“OrderSysID”)

    instrument_id = data.get(“InstrumentID”)

    if context.set_symbol_mode.get(“value”) == “指定”:

        if instrument_id not in context.symbols: return

    order_status  = data.get(“OrderStatus”)

如何导入和启动风控策略,详见期魔方帮助文档:https://qmfquant.com/static/doc/code/strategyEdit.html

图片[2]|期魔方风控模型之委托失败补单程序|魔方商学院
© 版权声明
THE END
喜欢就支持一下吧
点赞718 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容