1+ # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
2+ # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
3+ #
4+ # Licensed under the Apache License, Version 2.0 (the "License");
5+ # you may not use this file except in compliance with the License.
6+ # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
7+ #
8+ # Unless required by applicable law or agreed to in writing, software
9+ # distributed under the License is distributed on an "AS IS" BASIS,
10+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+ # See the License for the specific language governing permissions and
12+ # limitations under the License.
13+
14+ from datetime import datetime , timedelta
15+
16+ from clr import AddReference
17+ AddReference ("System" )
18+ AddReference ("QuantConnect.Algorithm" )
19+ AddReference ("QuantConnect.Indicators" )
20+ AddReference ("QuantConnect.Common" )
21+
22+ from System import *
23+ from QuantConnect import *
24+ from QuantConnect .Algorithm import *
25+ from QuantConnect .Indicators import *
26+ from QuantConnect .Data .Market import *
27+
28+
29+ class CustomChartingAlgorithm (QCAlgorithm ):
30+ '''4.0 DEMONSTRATION OF CUSTOM CHARTING FLEXIBILITY:
31+
32+ The entire charting system of quantconnect is adaptable. You can adjust it to draw whatever you'd like.
33+
34+ Charts can be stacked, or overlayed on each other.
35+ Series can be candles, lines or scatter plots.
36+
37+ Even the default behaviours of QuantConnect can be overridden'''
38+ def __init__ (self ):
39+ self .__fastMA = None
40+ self .__slowMA = None
41+ self .__lastPrice = None
42+ self .__resample = None
43+ self .__resamplePeriod = None
44+
45+
46+ def Initialize (self ):
47+ '''Called at the start of your algorithm to setup your requirements'''
48+
49+ self .SetStartDate (2010 , 3 , 3 ) #Set Start Date
50+ self .SetEndDate (2014 , 3 , 3 ) #Set End Date
51+ self .SetCash (100000 ) #Set Strategy Cash
52+ # Find more symbols here: http://quantconnect.com/data
53+ self .AddSecurity (SecurityType .Equity , "SPY" , Resolution .Minute )
54+
55+ #Chart - Master Container for the Chart:
56+ stockPlot = Chart ("Trade Plot" )
57+ #On the Trade Plotter Chart we want 3 series: trades and price:
58+ buyOrders = Series ("Buy" , SeriesType .Scatter , 0 )
59+ sellOrders = Series ("Sell" , SeriesType .Scatter , 0 )
60+ assetPrice = Series ("Price" , SeriesType .Line , 0 )
61+ stockPlot .AddSeries (buyOrders )
62+ stockPlot .AddSeries (sellOrders )
63+ stockPlot .AddSeries (assetPrice )
64+ self .AddChart (stockPlot )
65+
66+ avgCross = Chart ("Strategy Equity" )
67+ fastMA = Series ("FastMA" , SeriesType .Line , 1 )
68+ slowMA = Series ("SlowMA" , SeriesType .Line , 1 )
69+ avgCross .AddSeries (fastMA )
70+ avgCross .AddSeries (slowMA )
71+ self .AddChart (avgCross )
72+
73+ self .__resample = datetime (self .StartDate )
74+ self .__resamplePeriod = timedelta (minutes = (self .EndDate - self .StartDate ).TotalMinutes / 2000 )
75+
76+
77+ def OnEndOfDay (self ):
78+ '''OnEndOfDay Event Handler - At the end of each trading day we fire this code.
79+ To avoid flooding, we recommend running your plotting at the end of each day.'''
80+ #Log the end of day prices:
81+ self .Plot ("Trade Plot" , "Price" , self .__lastPrice )
82+
83+
84+ def OnData (self , data ):
85+ '''On receiving new tradebar data it will be passed into this function. The general pattern is:
86+ "public void OnData( CustomType name ) {...}"
87+
88+ Arguments:
89+ data: Slice object keyed by symbol containing the stock data
90+ '''
91+ if not data .ContainsKey ("SPY" ) or data ["SPY" ] is None : return
92+
93+ pyTime = datetime (self .Time )
94+ self .__lastPrice = data ["SPY" ].Close
95+
96+ if self .__fastMA == None : self .__fastMA = self .__lastPrice
97+ if self .__slowMA == None : self .__slowMA = self .__lastPrice
98+
99+ self .__fastMA = (0.01 * self .__lastPrice ) + (0.99 * self .__fastMA )
100+ self .__slowMA = (0.001 * self .__lastPrice ) + (0.999 * self .__slowMA )
101+
102+ if pyTime > self .__resample :
103+ self .__resample = pyTime + self .__resamplePeriod
104+ self .Plot ("Strategy Equity" , "FastMA" , self .__fastMA )
105+ self .Plot ("Strategy Equity" , "SlowMA" , self .__slowMA )
106+
107+ #On the 5th days when not invested buy:
108+ if pyTime .day % 13 == 0 and not self .Portfolio .Invested :
109+ self .Order ("SPY" , int (self .Portfolio .Cash / data ["SPY" ].Close ))
110+ self .Plot ("Trade Plot" , "Buy" , self .__lastPrice )
111+
112+ elif pyTime .day % 21 == 0 and self .Portfolio .Invested :
113+ self .Plot ("Trade Plot" , "Sell" , self .__lastPrice )
114+ self .Liquidate ()
0 commit comments