量化编程

来源:互联网 发布:淘宝匿名评价id采集 编辑:程序博客网 时间:2024/04/26 10:11
  1. </pre>转载需注明出处:<a target=_blank href="http://blog.csdn.net/minimicall?viewmode=contents">http://blog.csdn.net/minimicall?viewmode=contents</a>,<a target=_blank href="http://cloudtrade.top/">http://cloudtrade.top/</a></p><p></p><p>上一节已经说明了实时事件和处理接口。这一节需要说明回测里面的实时事件处理。主要是开启一个新的线程来处理定时事件。例如每天开市的时候的事件和每天闭市时候触发的事件。还有你可以定义任意一个给定时间的事件。</p><p>下面我们通过代码来说 明问题</p><p><pre name="code" class="csharp">/* 
  2.  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. 
  3.  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. 
  4.  *  
  5.  * Licensed under the Apache License, Version 2.0 (the "License");  
  6.  * you may not use this file except in compliance with the License. 
  7.  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
  8.  *  
  9.  * Unless required by applicable law or agreed to in writing, software 
  10.  * distributed under the License is distributed on an "AS IS" BASIS, 
  11.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  12.  * See the License for the specific language governing permissions and 
  13.  * limitations under the License. 
  14.  * 
  15. */  
  16.   
  17. using System;  
  18. using System.Collections.Generic;  
  19. using System.Threading;  
  20. using QuantConnect.Interfaces;  
  21. using QuantConnect.Packets;  
  22. using QuantConnect.Logging;  
  23.   
  24. namespace QuantConnect.Lean.Engine.RealTime  
  25. {  
  26.     /// <summary>  
  27.     /// Psuedo realtime event processing for backtesting to simulate realtime events in fast forward.  
  28.     /// 伪实时事件处理,为回归测试实时事件(快进)  
  29.     /// </summary>  
  30.     public class BacktestingRealTimeHandler : IRealTimeHandler  
  31.     {  
  32.         /********************************************************  
  33.         * PRIVATE VARIABLES 
  34.         *********************************************************/  
  35.         //Threading  
  36.         private DateTime _time = new DateTime();  
  37.         private bool _exitTriggered;  
  38.         private bool _isActive = true;  
  39.         private AlgorithmNodePacket _job;//相关任务  
  40.   
  41.         //Events:  
  42.         private List<RealTimeEvent> _events;  
  43.   
  44.         //Algorithm and Handlers:  
  45.         private IAlgorithm _algorithm;//相关算法  
  46.         private Dictionary<SecurityType, MarketToday> _today;//今日市场  
  47.   
  48.         /********************************************************  
  49.         * PUBLIC PROPERTIES 
  50.         *********************************************************/  
  51.         /// <summary>  
  52.         /// Realtime Moment.  
  53.         /// </summary>  
  54.         public DateTime Time  
  55.         {  
  56.             get  
  57.             {  
  58.                 return _time;  
  59.             }  
  60.         }  
  61.   
  62.         /// <summary>  
  63.         /// Events array we scan to trigger realtime events.  
  64.         /// </summary>  
  65.         public List<RealTimeEvent> Events  
  66.         {  
  67.             get   
  68.             {  
  69.                 return _events;  
  70.             }  
  71.         }  
  72.   
  73.         /// <summary>  
  74.         /// Flag indicating the hander thread is completely finished and ready to dispose.  
  75.         /// </summary>  
  76.         public bool IsActive  
  77.         {  
  78.             get  
  79.             {  
  80.                 return _isActive;  
  81.             }  
  82.         }  
  83.   
  84.         /// <summary>  
  85.         /// Market hours for today for each security type in the algorithm  
  86.         /// 为算法中每种证券类型的今日交易时间(例如股票和黄金的交易时间就不一样的,如果该算法涉及到这两种证券类型)  
  87.         /// </summary>  
  88.         public Dictionary<SecurityType, MarketToday> MarketToday  
  89.         {  
  90.             get  
  91.             {  
  92.                 throw new NotImplementedException("MarketToday is not currently needed in backtesting mode");//回归测试不需要  
  93.                 return _today;  
  94.             }  
  95.         }  
  96.   
  97.         /********************************************************  
  98.         * PUBLIC CONSTRUCTOR 
  99.         *********************************************************/  
  100.         /// <summary>  
  101.         /// Setup the algorithm data, cash, job start end date etc.  
  102.         /// 设置算法数据、现金、任务开始和结束时间等信息,通过algorithm和job即可  
  103.         /// </summary>  
  104.         public BacktestingRealTimeHandler(IAlgorithm algorithm, AlgorithmNodePacket job)   
  105.         {  
  106.             //Initialize:  
  107.             _algorithm = algorithm;  
  108.             _events = new List<RealTimeEvent>();  
  109.             _job = job;  
  110.             _today = new Dictionary<SecurityType, MarketToday>();  
  111.         }  
  112.   
  113.         /********************************************************  
  114.         * PUBLIC METHODS 
  115.         *********************************************************/  
  116.         /// <summary>  
  117.         /// Setup the events for this date.  
  118.         /// 设置该日的事件  
  119.         /// </summary>  
  120.         /// <param name="date">Date for event</param>  
  121.         public void SetupEvents(DateTime date)  
  122.         {  
  123.             //Clear any existing events:清除已经存在的事件  
  124.             ClearEvents();  
  125.   
  126.             //Set up the events:设置事件  
  127.             //1. Default End of Day Times:  
  128.             foreach (var security in _algorithm.Securities.Values)//遍历算法中涉及的每一个证券  
  129.             {  
  130.                 //Register Events:注册事件  
  131.                 Log.Debug("BacktestingRealTimeHandler.SetupEvents(): Adding End of Day: " + security.Exchange.MarketClose.Add(TimeSpan.FromMinutes(-10)));  
  132.   
  133.                 //1. Setup End of Day Events:  
  134.                 //设置事件结束时间(23:50)  
  135.                 var closingToday = date.Date + security.Exchange.MarketClose.Add(TimeSpan.FromMinutes(-10));  
  136.                 var symbol = security.Symbol;//证券代号  
  137.                 AddEvent(new RealTimeEvent( closingToday, () =>  
  138.                 {//匿名方法  
  139.                     try  
  140.                     {  
  141.                         _algorithm.OnEndOfDay(symbol);//在一天闭市的时候会调用该函数  
  142.                     }  
  143.                     catch (Exception err)  
  144.                     {  
  145.                         Engine.ResultHandler.RuntimeError("Runtime error in OnEndOfDay event: " + err.Message, err.StackTrace);  
  146.                         Log.Error("BacktestingRealTimeHandler.SetupEvents(): EOD: " + err.Message);  
  147.                     }  
  148.                 }));  
  149.             }  
  150.   
  151.             // fire just before the day rolls over, 11:58pm在一天即将结束的时候调用。。。。(尼玛,和上面究竟啥子关系)  
  152.             AddEvent(new RealTimeEvent(date.AddHours(23.967), () =>  
  153.             {//匿名方法  
  154.                 try  
  155.                 {  
  156.                     _algorithm.OnEndOfDay();  
  157.                     Log.Trace(string.Format("BacktestingRealTimeHandler: Fired On End of Day Event() for Day({0})", _time.ToShortDateString()));  
  158.                 }  
  159.                 catch (Exception err)  
  160.                 {  
  161.                     Engine.ResultHandler.RuntimeError("Runtime error in OnEndOfDay event: " + err.Message, err.StackTrace);  
  162.                     Log.Error("BacktestingRealTimeHandler.SetupEvents.Trigger OnEndOfDay(): " + err.Message);  
  163.                 }  
  164.             }, true));  
  165.         }  
  166.           
  167.         /// <summary>  
  168.         /// Normally this would run the realtime event monitoring. Backtesting is in fastforward so the realtime is linked to the backtest clock.  
  169.         /// This thread does nothing. Wait until the job is over.  
  170.         /// </summary>  
  171.         public void Run()  
  172.         {  
  173.             _isActive = false;  
  174.         }  
  175.   
  176.   
  177.         /// <summary>  
  178.         /// Add a new event to our list of events to scan.  
  179.         /// </summary>  
  180.         /// <param name="newEvent">Event object to montitor daily.</param>  
  181.         public void AddEvent(RealTimeEvent newEvent)  
  182.         {  
  183.             _events.Add(newEvent);  
  184.         }  
  185.   
  186.         /// <summary>  
  187.         /// Scan the event list with the current market time and see if we need to trigger the callback.  
  188.         /// </summary>  
  189.         public void ScanEvents()  
  190.         {  
  191.             for (var i = 0; i < _events.Count; i++)  
  192.             {  
  193.                 _events[i].Scan(_time);  
  194.             }  
  195.         }  
  196.   
  197.         /// <summary>  
  198.         /// Clear any outstanding events.  
  199.         /// </summary>  
  200.         public void ClearEvents()  
  201.         {  
  202.             _events.Clear();  
  203.         }  
  204.   
  205.         /// <summary>  
  206.         /// Reset the events for a new day.  
  207.         /// </summary>  
  208.         public void ResetEvents()  
  209.         {  
  210.             for (var i = 0; i < _events.Count; i++)  
  211.             {  
  212.                 _events[i].Reset();  
  213.             }  
  214.         }  
  215.   
  216.   
  217.         /// <summary>  
  218.         /// Set the time for the realtime event handler.  
  219.         /// </summary>  
  220.         /// <param name="time">Current time.</param>  
  221.         public void SetTime(DateTime time)  
  222.         {  
  223.             //Check for day reset:  
  224.             if (_time.Date != time.Date)  
  225.             {  
  226.                 // Backtest Mode Only:   
  227.                 // > Scan & trigger any remaining events which haven't been triggered (e.g. daily bar data with "daily event" at 4pm):  
  228.                 ScanEvents();  
  229.   
  230.                 //Reset all the daily events with today's date:  
  231.                 SetupEvents(time.Date);  
  232.             }  
  233.   
  234.             //Set the time:  
  235.             _time = time;  
  236.   
  237.             // Backtest Mode Only:   
  238.             // > Scan the event every time we set the time. This allows "fast-forwarding" of the realtime events into sync with backtest.  
  239.             ScanEvents();  
  240.         }  
  241.   
  242.         /// <summary>  
  243.         /// Stop the real time thread  
  244.         /// </summary>  
  245.         public void Exit()  
  246.         {  
  247.             _exitTriggered = true;  
  248.         }  
  249.   
  250.     } // End Result Handler Thread:  
  251.   
  252. // End Namespace 
0 0
原创粉丝点击