onexit()
onexit()函数由用户实现,用于处理程序退出前的扫尾工作,最长执行时间为 5 分钟。
示例
-
测试
onexit()函数:javascriptfunction main(){ Log("开始运行, 5秒后停止,并执行扫尾函数!") Sleep(1000 * 5) } // 扫尾函数实现 function onexit(){ // 不使用接口获取数据的测试,就无需使用exchange.IO("status")函数判断连接状态,也不用设置合约代码,因为这里仅仅是测试 var beginTime = new Date().getTime() while(true){ var nowTime = new Date().getTime() Log("程序停止倒计时..扫尾开始,已经过去:", (nowTime - beginTime) / 1000, "秒!") Sleep(1000) } }pythonimport time def main(): Log("开始运行, 5秒后停止,并执行扫尾函数!") Sleep(1000 * 5) def onexit(): beginTime = time.time() * 1000 while True: ts = time.time() * 1000 Log("程序停止倒计时..扫尾开始,已经过去:", (ts - beginTime) / 1000, "秒!") Sleep(1000)rustfn main() { Log!("开始运行, 5秒后停止,并执行扫尾函数!"); Sleep(1000 * 5); } // 扫尾函数实现 fn onexit() { // 不使用接口获取数据的测试,就无需使用exchange.IO("status")函数判断连接状态,也不用设置合约代码,因为这里仅仅是测试 let beginTime = Unix() * 1000; loop { let nowTime = Unix() * 1000; Log!("程序停止倒计时..扫尾开始,已经过去:", (nowTime - beginTime) / 1000, "秒!"); Sleep(1000); } }c++void main() { Log("开始运行, 5秒后停止,并执行扫尾函数!"); Sleep(1000 * 5); } void onexit() { auto beginTime = Unix() * 1000; while(true) { auto ts = Unix() * 1000; Log("程序停止倒计时..扫尾开始,已经过去:", (ts - beginTime) / 1000, "秒!"); Sleep(1000); } } -
在回测系统中,策略通常被设计为一个死循环持续轮询执行,这会导致策略中实现的
onexit()函数无法被触发。此时可以通过检测回测系统的结束标记(EOF 异常)来触发onexit()函数的执行。javascriptfunction main() { exchange.SetContractType("rb888") if (IsVirtual()) { try { onTick() } catch (e) { Log("error:", e) } } else { onTick() } } function onTick() { while (true) { var ticker = exchange.GetTicker() LogStatus(_D(), ticker ? ticker.Last : "--") Sleep(500) } } function onexit() { Log("执行扫尾函数") }pythondef main(): exchange.SetContractType("rb888") if IsVirtual(): try: onTick() except Exception as e: Log(e) else: onTick() def onTick(): while True: ticker = exchange.GetTicker() LogStatus(_D(), ticker["Last"] if ticker else "--") Sleep(500) def onexit(): Log("执行扫尾函数")rustfn onTick() { loop { match exchange.GetTicker(None) { Ok(ticker) => LogStatus!(_D(None), ticker.Last), Err(e) => { // 回测结束时接口调用返回 Err,无需像 JavaScript 那样用 try/catch 捕获回测结束异常 Log!("error:", e); return; } } Sleep(500); } } fn main() { let _ = exchange.SetContractType("rb888"); onTick(); } fn onexit() { Log!("执行扫尾函数"); }c++#include <iostream> #include <exception> #include <string> void onTick() { while (true) { auto ticker = exchange.GetTicker(); LogStatus(_D(), ticker); Sleep(500); } } void main() { exchange.SetContractType("rb888"); if (IsVirtual()) { try { onTick(); } catch (...) { std::cerr << "Caught unknown exception" << std::endl; } } else { onTick(); } } void onexit() { Log("执行扫尾函数"); }