Hi, so I'm trying to compare a current SMA value with an SMA value from a number of bars ago- I've looked at the documentation and rolling window example and tried to mirror mine off this template but no luck- is there something in the crypto piece of it causing issue? I appreciate any help!
# 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")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Brokerages import *
from QuantConnect.Indicators import *
#from QuantConnect.Orders import *
from QuantConnect.Data.Market import TradeBar
import decimal as d
### <summary>
### The demonstration algorithm shows some of the most common order methods when working with Crypto assets.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="using quantconnect" />
### <meta name="tag" content="trading and orders" />
class BasicTemplateCryptoAlgorithm(QCAlgorithm):
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.SetStartDate(2021, 1, 4) #Set Start Date
self.SetEndDate(2021, 1, 7) #Set End Date
self.SetCash(10000)
self.SetCash("EUR", 10000)
self.SetCash("BTC", 0)
self.SetCash("ETH", 0)
self.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash)
# Find more symbols here: http://quantconnect.com/data
self.AddCrypto("BTCUSD", Resolution.Hour)
self.AddCrypto("ETHUSD", Resolution.Hour)
self.AddCrypto("BTCEUR", Resolution.Hour)
self.AddCrypto("LTCUSD", Resolution.Hour)
self.window = RollingWindow[TradeBar](2)
self.sma = self.SMA("LTCUSD", 50, Resolution.Hour)
self.sma.Updated += self.SmaUpdated
self.smaWindow = RollingWindow[IndicatorDataPoint](21)
self.SetWarmup(60)
self.first = True
def SmaUpdated(self, sender, updated):
self.smaWindow.Add(updated)
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
'''
#limitPriceBuy = round(self.Securities["LTCUSD"].Price * d.Decimal(1.01), 2)
#limitPriceSell = round(self.Securities["LTCUSD"].Price * d.Decimal(.99), 2)
# Note: all limit orders in this algorithm will be paying taker fees,
# they shouldn't, but they do (for now) because of this issue:
# https://github.com/QuantConnect/Lean/issues/1852
self.window.Add(self.CurrentSlice["LTCUSD"])
if not (self.smaWindow.IsReady and self.window.IsReady): return
if self.first and not self.IsWarmingUp:
self.first = False
self.Log("SMA: {0}".format(self.sma.Samples))
currBar = self.window[0] # Current bar had index zero.
pastBar = self.window[1] # Past bar has index one.
self.Log("Price: {0} -> {1} ... {2} -> {3}".format(pastBar.Time, pastBar.Close, currBar.Time, currBar.Close))
currSma = self.smaWindow[0] # Current SMA had index zero.
pastSma = self.smaWindow[self.smaWindow.Count-1] # Oldest SMA has index of window count minus 1.
self.Log("SMA: {0} -> {1} ... {2} -> {3}".format(pastSma.Time, pastSma.Value, currSma.Time, currSma.Value))
#self.Plot("Chart", "LTCUSD", self.Close)
#prices.ContainsKey("EURUSD")) Plot("Plotter", "EURUSD", prices["EURUSD"].Price)
#self.Plot("Chart", "LTCUSD", self.Securities["LTCUSD"].Price)
#self.Plot("Chart", "SMA", self.sma.Current.Value)
# Price = self.window
# if self.smaWindow[1] < Price:
# if self.Portfolio.CashBook["LTC"].Amount == 0:
# self.Buy("LTCUSD", 2)
#if currSMA.Value > pastSMA.Value[1]:
#if price > self.smaWindow[1]:
# if self.Portfolio.CashBook["LTC"].Amount == 0:
# self.Buy("LTCUSD", 2)
def OnOrderEvent(self, orderEvent):
self.Debug("{} {}".format(self.Time, orderEvent.ToString()))
def OnEndOfAlgorithm(self):
self.Log("{} - TotalPortfolioValue: {}".format(self.Time, self.Portfolio.TotalPortfolioValue))
self.Log("{} - CashBook: {}".format(self.Time, self.Portfolio.CashBook))
Derek Melchin
Hi Conor,
To resolve the issue, we need to replace
self.window.Add(self.CurrentSlice["LTCUSD"])
with
self.window.Add(self.CurrentSlice.Bars["LTCUSD"])
See the attached backtest for reference.
Best,
Derek Melchin
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.
Conor O'Brien
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.
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!