Indicator Examples (BB, MACD, SMA, EMA, RSI, ATR)

Back

By popular request I've developed an example project with the common indicators, including: Bollinger Bands, Simple Moving Average, Exponential Moving Average, Relative Strength Index, Average True Range and MACD. Down the bottom of the algorithm we plot them together with price. I've also set it up to use Daily consolidators - this way the plots look like characteristic ones you'll see on other stock charting websites.

The engine updates the indicators automatically and feeds the value through to the algorithms output for charting! Its a pretty cool system under the hood. I'd recommend looking at the Github project.
Update Backtest






The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.



 
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Standard deviation?
0

Thanks @Tadas -- I've updated the QCU algorithm to include standard deviation, aroon and momentum as well.

You can see all the indicators here: https://github.com/QuantConnect/Lean/blob/master/Algorithm/QCAlgorithm.Indicators.cs
1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Thanks, @Jared, though I saw somewhere what values go to different indicators :D

Also, searched, but didn't found how to use, let's say OnData(ImportedData id) along with usual OnData(TradeBars data)?
0

I'll try push new documentation this weekend @TT - for now you can look at the classes themselves to know the properties of each indicator. E.g. Aroon Up - https://github.com/QuantConnect/Lean/blob/master/Indicators/AroonOscillator.cs#L31

I've updated the algorithm again to include an example of a RSI indicator on custom data. It takes 3 lines instead of one because you need to tell us how to consolidate it together, and then manually register/subscribe the indicator class for data updates.
1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Ah, ok, thank you, now starting to pick it up. QC platform is too much flexible :) Missing piece for me was:

var bitcoinIdentityConsolidator = new IdentityDataConsolidator();
0

I have some questions regarding this example. How do I modify the code the indicators are being calculated on 30 minute bars instead of daily or minute bar. I'm not sure how to setup and access the indicators to work on multiple securities.

ex.

public void OnData(TradeBars data)
{

foreach(var symbol in Securities.Keys)
{
if (data["symbol"].High > _bb.UpperBand["symbol"] ) { //do something };
}

}
0

Hey @Johnny! I like to use a pattern I refer to as SymbolData. Here's a link to a thread showing an example of it.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hi Michael,

Thank you for your wonderful suggestion. I modified the basic template to handle multiple securities. However, I'm still not sure what to do regarding the resolution.

Is it possible for QuantConnect to use multiple resolutions with each indicators? Ex. use 5 minute bars for RSI, 10 minutes bars for EMA, and 30 minute bars for SMA?
2

Sounds like you need to use the consolidator system! Consolidators can take high resolution data (tick,second,minute, ect...) and aggregate it into lower resolution data (5min, 45 min, anything...).

Have a peak at this thread which shows how to make a consolidator and indicators that depend on the consolidator. For multiple time frames, you'll need multiple consolidators.

An important note, one consolidator can only be used with one symbol! So if you're doing multiple symbols you'll need one consolidator per symbol per time frame (5min, 10min, ect...).
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Would something like this work if I wanted to create Bollinger Bands from 15 minutes bars? Also, is there a way for me to pass in the bar's open, high, low, and close into the SymbolData class? Thanks again for your help.

public SymbolData(string symbol, QCAlgorithm algorithm)
{

Symbol = symbol;
_bb = new BollingerBands(50, 3, MovingAverageType.Simple);
algorithm.RegisterIndicator(Symbol, _bb, TimeSpan.FromMinutes(15));
}
1

The bollingerbands look to be created correctly. Try plotting it to verify. As for passing in the OHLC data, there are various ways to do this. Do you want a method to be called with the data?

You could define a SymbolData.OnData(TradeBar bar) which could be called from your algorithm's OnData method.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Jared, did you mean you plotted the indicators as well as price or on top of price, because when i run it i get separate charts. Have you guys figured out a solution to plotting ex. 2 different EMAs on top of price?
0

The following code will plot two EMAs on top of the SPY closing price on the registered resolution:var price = Identity("SPY");
var fast = EMA("SPY", 7);
var slow = EMA("SPY", 14);
PlotIndicator("SPY", price, fast, slow);


Take a peek at the attached code below which creates a new plot called 'SPY' for the price and EMAs.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Is there a way to put this on the "Stockplot" that shows when the algorithm makes moves in the market?
0

oh nice, great thank you Michael! Good question Stephen that would also be very helpful
0

I think it would be easier (and more general) to place the execution plots on the custom indicator chart. For example, if you're working with a MACD and RSI on separate charts, it may be helpful to plot a scatter plot on each of those charts with buy/sell points. Have a look at the QCU How Do I Create Custom Charts? available in the university tab. This details how to define some custom charts, including buy/sell points.

If you want price data overlayed on your custom chart, you can use:PlotIndicator("MyCustomChartName", Identity("SPY", Resolution.Daily));
This will add the closing daily spy price as a series to the 'MyCustomChartName' chart.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


You're completely right. I got that up and running. Thank you! One more question now that I have that:

I'm using this plot to help debug my algorithm. Is there any way to adjust the vertical scale? I know you can adjust the horizontal easily, but sometimes it's still tough to see.

Thank you again!
0

Sadly we can't currently adjust the vertical scale
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Ah, that's ok. Thank you again for the help!!!
0

Is there a way to have these calculate on the close of the set resolution?

fast = EMA(Symbol, 25, Resolution.Minute);

something like this (obviously doesn't work but sort of shows what I mean):

fast = EMA(Symbol, 25, Resolution.Minute.Close);
0

By default any single dimension indicator (SMA, EMA, ect..) uses the closing of the bar. If you'd like to use something else, you can specify a function that selects what value to use:fast = EMA(Symbol, 25, Resolution.Minute, baseData => ((TradeBar)baseData).High);
There are some helpers to make this easier, so the above could be written as:fast = EMA(Symbol, 25, Resolution.Minute, Field.High);
Here's a link to the Field class.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


I'm getting this following error when I tried to use the consolidator in the backtest. What is the proper way to register the indicator?

"Backtest Error: Error initializing algorithm: Type mismatch found between consolidator and indicator for symbol: DIA.Consolidator outputs type TradeBar but indicator expects input type IndicatorDataPoint"

public SymbolData(string symbol, QCAlgorithm algorithm)
{
Symbol = symbol;
_bb = new BollingerBands(100, 3, MovingAverageType.Simple);
_atr = new AverageTrueRange(100, MovingAverageType.Simple);
algorithm.RegisterIndicator(Symbol, _bb, TimeSpan.FromMinutes(15));
algorithm.RegisterIndicator(Symbol, _atr, TimeSpan.FromMinutes(30));
}
0

Hey Johnny, you'll need to include some of your Initialize code. From the error message the symbol with issue is 'DIA'. Is this custom data? The error message is saying you're trying to register an indicator that accepts a single value (such as close, or high) but passing a full TradeBar. You can try appending 'Field.Close' to the RegisterIndicator call for '_bb'. If you still have issues please share the full algorithm and we can be of further assistance!
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hey Michael,

Thanks for taking a look at my code. DIA is an ETF that tracks the Dow 30. It is a standard symbol in the quantconnect database. If I try to append the Field.Close then I must use the quantconnection resolution class instead of time span. There is currently a method that converts resolution to timespan. Do you think it would be possible to implement a feature that convert timespan to resolution allowing us to create our own custom resolutions.

Ex. TimeSpan.FromMinutes(15).ToResolution();

Also, the feature using strings for symbol is now deprecated. Where do I find a symbol's sid? That information is not displayed in the data manager.

using System;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using QuantConnect.Indicators;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.CSharp.MyTradingStrategies;

namespace QuantConnect.Algorithm
{
public class BollingerBandsAlgorithm : QCAlgorithm
{
class SymbolData
{
public readonly string Symbol;
public readonly BollingerBands _bb;
public readonly AverageTrueRange _atr;
public bool isReady { get { return _bb.IsReady && _atr.IsReady; } }

public SymbolData(string symbol, QCAlgorithm algorithm)
{
Symbol = symbol;
_bb = new BollingerBands(100, 3, MovingAverageType.Simple);
_atr = new AverageTrueRange(100, MovingAverageType.Simple);
algorithm.RegisterIndicator(Symbol, _bb, TimeSpan.FromMinutes(15));
algorithm.RegisterIndicator(Symbol, _atr, TimeSpan.FromMinutes(15));
}
}
private List symbols = new List()
{ "DIA", "DXJ", "EEM", "EFA", "EWZ",
"FXI", "GDX","IWM", "IYR", "QQQ",
"SPY", "XLB", "XLE","XLF", "XLI",
"XLK", "XLP", "XLU", "XLV", "XLY" };

private Dictionary Symbols = new Dictionary();

//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
//Initialize
SetStartDate(2007, 1, 1);
SetEndDate(DateTime.Now.AddDays(-1));
SetCash(100000);

foreach (var symbol in symbols)
{
AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
Symbols.Add(symbol, new SymbolData(symbol, this));
}
}

public void OnData(TradeBars data)
{
foreach (var symbolData in Symbols.Values)
{
if (!symbolData.isReady || data.ContainsKey(symbolData.Symbol))
return;

if (!Portfolio.HoldStock)
{
var _buyPrice = symbolData._bb.LowerBand;
var _buySignal = data[symbolData.Symbol].Close > _buyPrice;
if (_buySignal) { SetHoldings(symbolData.Symbol, 1); }
}
else
{
var _sellPrice = symbolData._bb.UpperBand;
var _sellSignal = data[symbolData.Symbol].Close > _sellPrice;
if (_sellSignal) { Liquidate(symbolData.Symbol); }
}
}
}
}
}
0

Hey Johnny, I've added the requested overload. It will be available in the next deploy. Just a head up, it won't work with the ATR since the field selector required for ATR requires a TradeBar.

The ToResolution method is a great idea, but may require a little thought on our end since it is a widely used enumeration.

An alternate solution is to have your SymbolData class accept a TradeBarConsolidator which you could create from your Initialize method:var consolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(15));
Then there are overloads available that accept the Field parameter.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


thank you for this good/hard work, it's helping me so much but i see code 
i want to know where code sell there ! 
when sell ? [where is mehod sell at code ]? 
 

0

Do we have a Python implementation of these indicators ?

1

If you click Indicators in the documentation you'll see them depending on

your language preferences.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Jared Broad

I followed your instruction.
It bring me to
https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/IndicatorSuiteAlgorithm.py
I copy and paste the code.

# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Indicators")


from System import *
from QuantConnect import *
from QuantConnect.Indicators import *
from QuantConnect.Data import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.Custom import *
from QuantConnect.Algorithm import *
from QuantConnect.Python import *

### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="using quantconnect" />
### <meta name="tag" content="trading and orders" />
class IndicatorSuiteAlgorithm(QCAlgorithm):
'''Demonstration algorithm of popular indicators and plotting them.'''

def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

self.symbol = "SPY"
self.customSymbol = "WIKI/FB"
self.price = None

self.SetStartDate(2013, 1, 1) #Set Start Date
self.SetEndDate(2014, 12, 31) #Set End Date
self.SetCash(25000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data

self.AddEquity(self.symbol, Resolution.Daily)
self.AddData(Quandl, self.customSymbol, Resolution.Daily)

# Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
self.indicators = {
'BB' : self.BB(self.symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily),
'RSI' : self.RSI(self.symbol, 14, MovingAverageType.Simple, Resolution.Daily),
'EMA' : self.EMA(self.symbol, 14, Resolution.Daily),
'SMA' : self.SMA(self.symbol, 14, Resolution.Daily),
'MACD' : self.MACD(self.symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily),
'MOM' : self.MOM(self.symbol, 20, Resolution.Daily),
'MOMP' : self.MOMP(self.symbol, 20, Resolution.Daily),
'STD' : self.STD(self.symbol, 20, Resolution.Daily),
# by default if the symbol is a tradebar type then it will be the min of the low property
'MIN' : self.MIN(self.symbol, 14, Resolution.Daily),
# by default if the symbol is a tradebar type then it will be the max of the high property
'MAX' : self.MAX(self.symbol, 14, Resolution.Daily),
'ATR' : self.ATR(self.symbol, 14, MovingAverageType.Simple, Resolution.Daily),
'AROON' : self.AROON(self.symbol, 20, Resolution.Daily)
}

# Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator
# These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value
# We'll define these 'selector' functions to select the Low value
#
# For more information on 'anonymous functions' see: http:#en.wikipedia.org/wiki/Anonymous_function
# https:#msdn.microsoft.com/en-us/library/bb397687.aspx
#
self.selectorIndicators = {
'BB' : self.BB(self.symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low),
'RSI' :self.RSI(self.symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low),
'EMA' :self.EMA(self.symbol, 14, Resolution.Daily, Field.Low),
'SMA' :self.SMA(self.symbol, 14, Resolution.Daily, Field.Low),
'MACD' : self.MACD(self.symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low),
'MOM' : self.MOM(self.symbol, 20, Resolution.Daily, Field.Low),
'MOMP' : self.MOMP(self.symbol, 20, Resolution.Daily, Field.Low),
'STD' : self.STD(self.symbol, 20, Resolution.Daily, Field.Low),
'MIN' : self.MIN(self.symbol, 14, Resolution.Daily, Field.High),
'MAX' : self.MAX(self.symbol, 14, Resolution.Daily, Field.Low),
# ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar
# before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two
'ATR' : self.ATR(self.symbol, 14, MovingAverageType.Simple, Resolution.Daily, Func[IBaseData, IBaseDataBar](self.selector_double_TradeBar)),
'AROON' : self.AROON(self.symbol, 20, Resolution.Daily, Func[IBaseData, IBaseDataBar](self.selector_double_TradeBar))
}
# Custom Data Indicator:
self.rsiCustom = self.RSI(self.customSymbol, 14, MovingAverageType.Simple, Resolution.Daily)
self.minCustom = self.MIN(self.customSymbol, 14, Resolution.Daily)
self.maxCustom = self.MAX(self.customSymbol, 14, Resolution.Daily)

# in addition to defining indicators on a single security, you can all define 'composite' indicators.
# these are indicators that require multiple inputs. the most common of which is a ratio.
# suppose we seek the ratio of BTC to SPY, we could write the following:
spyClose = Identity(self.symbol)
fbClose = Identity(self.customSymbol)

# this will create a new indicator whose value is FB/SPY
self.ratio = IndicatorExtensions.Over(fbClose, spyClose)

# we can also easily plot our indicators each time they update using th PlotIndicator function
self.PlotIndicator("Ratio", self.ratio)

# The following methods will add multiple charts to the algorithm output.
# Those chatrs names will be used later to plot different series in a particular chart.
# For more information on Lean Charting see: https://www.quantconnect.com/docs#Charting
Chart('BB')
Chart('STD')
Chart('ATR')
Chart('AROON')
Chart('MACD')
Chart('Averages')
# Here we make use of the Schelude method to update the plots once per day at market close.
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.BeforeMarketClose(self.symbol), self.update_plots)

def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''

if (#not data.Bars.ContainsKey(self.symbol) or
not self.indicators['BB'].IsReady or
not self.indicators['RSI'].IsReady):
return

self.price = data[self.symbol].Close

if not self.Portfolio.HoldStock:
quantity = int(self.Portfolio.Cash / self.price)
self.Order(self.symbol, quantity)
self.Debug('Purchased SPY on ' + self.Time.strftime('%Y-%m-%d'))

def update_plots(self):
if not self.indicators['BB'].IsReady or not self.indicators['STD'].IsReady:
return

# Plots can also be created just with this one line command.
self.Plot('RSI', self.indicators['RSI'])
# Custom data indicator
self.Plot('RSI-FB', self.rsiCustom)

# Here we make use of the chats decalred in the Initialize method, plotting multiple series
# in each chart.
self.Plot('STD', 'STD', self.indicators['STD'].Current.Value)

self.Plot('BB', 'Price', self.price)
self.Plot('BB', 'BollingerUpperBand', self.indicators['BB'].UpperBand.Current.Value)
self.Plot('BB', 'BollingerMiddleBand', self.indicators['BB'].MiddleBand.Current.Value)
self.Plot('BB', 'BollingerLowerBand', self.indicators['BB'].LowerBand.Current.Value)


self.Plot('AROON', 'Aroon', self.indicators['AROON'].Current.Value)
self.Plot('AROON', 'AroonUp', self.indicators['AROON'].AroonUp.Current.Value)
self.Plot('AROON', 'AroonDown', self.indicators['AROON'].AroonDown.Current.Value)

# The following Plot method calls are commented out because of the 10 series limit for backtests
#self.Plot('ATR', 'ATR', self.indicators['ATR'].Current.Value)
#self.Plot('ATR', 'ATRDoubleBar', self.selectorIndicators['ATR'].Current.Value)
#self.Plot('Averages', 'SMA', self.indicators['SMA'].Current.Value)
#self.Plot('Averages', 'EMA', self.indicators['EMA'].Current.Value)
#self.Plot('MOM', self.indicators['MOM'].Current.Value)
#self.Plot('MOMP', self.indicators['MOMP'].Current.Value)
#self.Plot('MACD', 'MACD', self.indicators['MACD'].Current.Value)
#self.Plot('MACD', 'MACDSignal', self.indicators['MACD'].Signal.Current.Value)

def selector_double_TradeBar(self, bar):
trade_bar = TradeBar()
trade_bar.Close = 2 * bar.Close
trade_bar.DataType = bar.DataType
trade_bar.High = 2 * bar.High
trade_bar.Low = 2 * bar.Low
trade_bar.Open = 2 * bar.Open
trade_bar.Symbol = bar.Symbol
trade_bar.Time = bar.Time
trade_bar.Value = 2 * bar.Value
trade_bar.Period = bar.Period
return trade_bar


It shows errors:

270 | 01:48:04: Building Project ID: 6115297 Content Signature: 86a623f1d158e4d2baf9af7ccbbbe7ef271 | 01:48:04: Build Error: File: Main.cs Line:1 Column:1308 - Preprocessor directives must appear as the first non-whitespace character on a line272 | 01:48:04: Build Error: File: Main.cs Line:2 Column:0 - Preprocessor directives must appear as the first non-whitespace character on a line273 | 01:48:04: Build Error: File: Main.cs Line:3 Column:0 - Preprocessor directives must appear as the first non-whitespace character on a line274 | 01:48:04: Build Error: File: Main.cs Line:4 Column:0 - Preprocessor directives must appear as the first non-whitespace character on a line275 | 01:48:04: Build Error: File: Main.cs Line:5 Column:0 - Preprocessor directives must appear as the first non-whitespace character on a line

 

What I am doing wrong?

0

Hi Vladimir,

The code above is Python but the error shows the filename is Main.cs. To resolve this, set your account language to Python, create a new project, then paste the code in the new project.

Best,
Derek Melchin

0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Derek Melchin

This helped along with fixing 186 unexpected indents.
So I decided to post it here in case others need it.

0


Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!