ARTICLE · 1386288
频繁报撤单监控工具,送源码
频繁报撤单监控工具,送源码有了ctpcmd工具,写些交易小工具太轻松了,把需求告诉AI,分分钟就给你写出来了,不需要折腾CTPAPI那些个回调逻辑,脏活累活ctpcmd全都干完了,咱直接用就行。 前两天一个群友还说因为不了解频繁报撤单规则,以为只要没成交就不产生任何交易费用,就这样白白送了几万块给交易所,注意,频繁报撤单的信息费是交易所收的,不是期货公司要,所以这个钱基本就别想退了。还记得前两年有个家伙就因为这个坑一天血亏400万信息费吗,一笔没成交,报撤了几十万笔订单,后来没音信了,不知道怎么处理的。 这个监控工具只是粗略进行了统计,没有按交易所规则说的按品种统计,如果需要的话,我后面改进一下,有AI,做这些东西简单得很。高净值朋友欢迎加入我们百万实盘群啊,后面像这种小工具可能就只送我们实盘群友们了,加入方式见openctp官网:http://www.openctp.cn/Friends.html 工具用法: python order_monitor.py --channel SimNow-7x24 --user xxx --password xxx 效果:(有报警声音) 
监控脚本源码:

import argparsefrom pathlib import Pathimport subprocessimport jsonimport timefrom typing import Dict, List, Tupleimport winsound# ===================== 配置区 =====================WINDOW_SEC = 60# 阈值:全局报单、全局撤单、窗口报单、窗口撤单THRESHOLD_TOTAL_ORDER = 1000THRESHOLD_TOTAL_CANCEL = 100THRESHOLD_WIN_ORDER = 10THRESHOLD_WIN_CANCEL = 5# 推送webhook,钉钉/企业微信,为空则只控制台打印告警WEBHOOK_URL = ""# ==================================================# 订单存储: key = f"{ExchangeID}|{OrderSysID}"# value: {"status": str, "canceled": bool}order_map: Dict[str, Dict] = {}# 滑动窗口事件列表: (timestamp, key, event_type)# event_type: "order" / "cancel"win_events: List[Tuple[float, str, str]] = []total_order = 0total_cancel = 0def send_alert(msg: str):t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())alert_text = f"[{t}] ⚠️ ALERT: {msg}"print(alert_text, flush=True)winsound.Beep(880, 200)if WEBHOOK_URL:import requeststry:payload = {"msgtype": "text","text": {"content": alert_text}}requests.post(WEBHOOK_URL, json=payload, timeout=3)except Exception as e:print(f"webhook send fail: {e}")def prune_window(now: float) -> Tuple[int, int]:"""清理过期事件,返回当前窗口内 order 数量、cancel 数量"""global win_eventsnew_list = []win_o = 0win_c = 0for ts, key, typ in win_events:if now - ts <= WINDOW_SEC:new_list.append((ts, key, typ))if typ == "order":win_o += 1elif typ == "cancel":win_c += 1win_events = new_listreturn win_o, win_cdef check_threshold(now: float):win_order, win_cancel = prune_window(now)if total_order > THRESHOLD_TOTAL_ORDER:send_alert(f"【全局报单超限】总报单笔={total_order},阈值={THRESHOLD_TOTAL_ORDER}")if total_cancel > THRESHOLD_TOTAL_CANCEL:send_alert(f"【全局撤单超限】总撤单笔={total_cancel},阈值={THRESHOLD_TOTAL_CANCEL}")if win_order > THRESHOLD_WIN_ORDER:send_alert(f"【窗口报单超限】{WINDOW_SEC}s内报单={win_order},阈值={THRESHOLD_WIN_ORDER}")if win_cancel > THRESHOLD_WIN_CANCEL:send_alert(f"【窗口撤单超限】{WINDOW_SEC}s内撤单={win_cancel},阈值={THRESHOLD_WIN_CANCEL}")def process_one_line(line: str):global total_order, total_cancelline = line.strip()if not line or (not line.startswith("{") or not line.endswith("}")):returntry:msg = json.loads(line)except json.JSONDecodeError:print(f"json parse failed:{line}")return# 只处理event=Order的委托回报if msg.get("event") != "Order":returndata = msg["data"]exchange_id = data.get("ExchangeID")order_sys_id = data.get("OrderSysID")order_status = data.get("OrderStatus")if not exchange_id or not order_sys_id:returnkey = f"{exchange_id}|{order_sys_id}"now = time.time()if key not in order_map:# 第一次收到这个订单:计一笔报单order_map[key] = {"status": order_status,"canceled": False}total_order += 1win_events.append((now, key, "order"))else:rec = order_map[key]if order_status == "5" and not rec["canceled"]:# 首次变为撤单,计数一次撤单rec["status"] = order_statusrec["canceled"] = Truetotal_cancel += 1win_events.append((now, key, "cancel"))else:# 只是状态更新(已成、部分成交等),不新增计数rec["status"] = order_statusprint(f"总报单笔={total_order},总撤单笔={total_cancel}")check_threshold(now)if __name__ == "__main__":ap = argparse.ArgumentParser(description="频繁报撤单监控")ap.add_argument("--config", default="brokers.xml", help="配置文件,默认brokers.xml")ap.add_argument("--channel", required=True, help="通道")ap.add_argument("--user", required=True, help="账号")ap.add_argument("--password", required=True, help="密码")ns = ap.parse_args()# 清除CTPAPI状态文件以便以RESUME模式进行断点续传for f in Path(".").glob("*.con"):try:f.unlink()print(f"deleted {f}")except Exception as e:print(f"cannot delete {f}, maybe in use: {e}")exit(-1)cmd = ["ctporder","--no-pretty","--channel", ns.channel,"--user", ns.user,"--password", ns.password,"subscribe", "resume"]proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,encoding="utf-8",bufsize=1)print("running ...", flush=True)while True:line = proc.stdout.readline()if not line:# ctporder程序挂起print("ctporder killed", flush=True)breakprocess_one_line(line)















































































