如何使用定时器进行定时撤单

The code below demonstrates how to use strategy timer to cancel a limit order if the order is not filled within 20 seconds.

以下代码演示了如何使用策略定时器对限价单发出20秒后没有完全成交的报单进行撤单

Note how Clock.Now is used to obtain current strategy time. This technique works in both simulation and live trading modes.

留意Clock.Now是如何获取策略时间。这项技术在模拟和实盘模式下都能正常工作。

  1. using OpenQuant.API;
  2.  
  3. public class MyStrategy : Strategy
  4. {
  5. private Order order;
  6. private bool entry = true;
  7.  
  8. public override void OnBar(Bar bar)
  9. {
  10. if (HasPosition)
  11. ClosePosition();
  12.  
  13. if (entry)
  14. {
  15. order = LimitOrder(OrderSide.Buy, 100, bar.Close - 0.03);
  16. order.Send();
  17.  
  18. AddTimer(Clock.Now.AddSeconds(20));
  19.  
  20. entry = false;
  21. }
  22. }
  23.  
  24. public override void OnTimer(DateTime signalTime)
  25. {
  26. if (!order.IsDone)
  27. order.Cancel();
  28.  
  29. entry = true;
  30. }
  31. }