| Overall Statistics |
|
Total Trades 0 Average Win 0% Average Loss 0% Compounding Annual Return 0% Drawdown 0% Expectancy 0 Net Profit 0% Sharpe Ratio 0 Probabilistic Sharpe Ratio 0% Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha 0 Beta 0 Annual Standard Deviation 0 Annual Variance 0 Information Ratio 0 Tracking Error 0 Treynor Ratio 0 Total Fees $0.00 |
from clr import AddReference
AddReference("QuantConnect.Algorithm.Framework")
from QuantConnect.Algorithm.Framework.Execution import ExecutionModel
# Execution Model scaffolding structure example
class StopLossAndProfitTargetExecutionModel(ExecutionModel):
# Fill the supplied portfolio targets efficiently
def Execute(self, algorithm, targets):
pass
# Optional: Securities changes event for handling new securities.
def OnSecuritiesChanged(self, algorithm, changes):
passfrom Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel
from Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel
from G10CurrencySelectionModel import G10CurrencySelectionModel
from MultiTimeFrameEmaAlphaModel import MultiTimeFrameEmaAlphaModel
from StopLossAndProfitTargetExecutionModel import StopLossAndProfitTargetExecutionModel
from ForexPortfolioConstructionModel import ForexPortfolioConstructionModel
class MultiTimeFrameForexScalping(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2019, 9, 10) # Set Start Date
self.SetEndDate(2019, 10 ,10)
self.SetCash(100000) # Set Strategy Cash
self.AddUniverseSelection(G10CurrencySelectionModel())
self.AddAlpha(MultiTimeFrameEmaAlphaModel())
self.SetPortfolioConstruction(ForexPortfolioConstructionModel())
self.SetExecution(StopLossAndProfitTargetExecutionModel())
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 self.Portfolio.Invested:
# self.SetHoldings("SPY", 1)from QuantConnect import *
from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
class G10CurrencySelectionModel(ManualUniverseSelectionModel):
def __init__(self):
super().__init__([Symbol.Create(x, SecurityType.Forex, Market.Oanda) for x in [ "EURUSD", "GBPUSD", "USDJPY", "AUDUSD", "NZDUSD","USDCAD", "USDCHF", "USDNOK", "USDSEK"]])# Your New Python File
# 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("QuantConnect.Common")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Algorithm.Framework")
AddReference("QuantConnect.Indicators")
from QuantConnect import *
from QuantConnect.Indicators import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Alphas import *
class MultiTimeFrameEmaAlphaModel(AlphaModel):
'''Alpha model that uses an EMA cross to create insights'''
def __init__(self,
barHistoryWindow = 5,
longLookBackPeriod = 21,
mediumLookBackPeriod = 13,
shortLookBackPeriod = 8):
self.barHistoryWindow = barHistoryWindow
self.longLookBackPeriod = longLookBackPeriod
self.mediumLookBackPeriod = mediumLookBackPeriod
self.shortLookBackPeriod = shortLookBackPeriod
self.symbolDataBySymbol = {}
def Update(self, algorithm, data):
insights = []
for symbol, symbolData in self.symbolDataBySymbol.items():
if symbolData.IsReady and symbolData.longEntrySetup and symbolData.longEntryTrigger:
insights += [Insight.Price(symbol, timedelta(hours = 4), InsightDirection.Up)]
return insights
def OnSecuritiesChanged(self, algorithm, changes):
for security in changes.AddedSecurities:
symbol = security.Symbol
if symbol not in self.symbolDataBySymbol:
self.symbolDataBySymbol[symbol] = SymbolData(algorithm, symbol, self.barHistoryWindow, self.longLookBackPeriod, self.mediumLookBackPeriod, self.shortLookBackPeriod)
for security in changes.RemovedSecurities:
symbol = security.Symbol
if symbol not in self.symbolDataBySymbol:
symbolData = self.symbolDataBySymbol.pop(symbol, None)
if symbolData != None:
algorithm.SubscriptionManager.RemoveConsolidator(symbol, symbolData.fiveMinutesConsolidate)
algorithm.SubscriptionManager.RemoveConsolidator(symbol, symbolData.sixtyMinutesConsolidate)
class SymbolData:
'''Contains data specific to a symbol required by this model'''
def __init__(self, algorithm, symbol, barHistoryWindow, longLookBackPeriod, mediumLookBackPeriod, shortLookBackPeriod):
self.algorithm = algorithm
self.symbol = symbol
self.barHistoryWindow = barHistoryWindow
self.longLookBackPeriod = longLookBackPeriod
self.mediumLookBackPeriod = mediumLookBackPeriod
self.shortLookBackPeriod = shortLookBackPeriod
self.fiveMinutesConsolidator = QuoteBarConsolidator(timedelta(minutes=5))
self.sixtyMinutesConsolidator = QuoteBarConsolidator(timedelta(minutes=5))
self.fiveMinutesConsolidator.DataConsolidated += self.fiveMinutesBarHandler
self.sixtyMinutesConsolidator.DataConsolidated += self.sixtyMinutesBarHandler
self.algorithm.SubscriptionManager.AddConsolidator(self.symbol, self.fiveMinutesConsolidator)
self.algorithm.SubscriptionManager.AddConsolidator(self.symbol, self.sixtyMinutesConsolidator)
self.emaFiveMinsLong = ExponentialMovingAverage(self.longLookBackPeriod)
self.emaFiveMinsMedium = ExponentialMovingAverage(self.mediumLookBackPeriod)
self.emaFiveMinsShort = ExponentialMovingAverage(self.shortLookBackPeriod)
self.algorithm.RegisterIndicator(self.symbol, self.emaFiveMinsLong, self.fiveMinutesConsolidator)
self.algorithm.RegisterIndicator(self.symbol, self.emaFiveMinsMedium, self.fiveMinutesConsolidator)
self.algorithm.RegisterIndicator(self.symbol, self.emaFiveMinsShort, self.fiveMinutesConsolidator)
self.emaSixtyMinsLong = ExponentialMovingAverage(self.longLookBackPeriod)
self.emaSixtyMinsShort = ExponentialMovingAverage(self.shortLookBackPeriod)
self.algorithm.RegisterIndicator(self.symbol, self.emaSixtyMinsLong, self.sixtyMinutesConsolidator)
self.algorithm.RegisterIndicator(self.symbol, self.emaSixtyMinsShort, self.sixtyMinutesConsolidator)
self.historyFiveMinuteBars = RollingWindow[QuoteBar](self.barHistoryWindow)
self.historySixtyMinuteBars = RollingWindow[QuoteBar](self.barHistoryWindow)
self.historyEmaSixtyMinsLong = RollingWindow[float](self.barHistoryWindow)
self.historyEmaSixtyMinsShort = RollingWindow[float](self.barHistoryWindow)
self.historyEmaFiveMinsLong = RollingWindow[float](self.barHistoryWindow)
self.historyEmaFiveMinsMedium = RollingWindow[float](self.barHistoryWindow)
self.historyEmaFiveMinsShort = RollingWindow[float](self.barHistoryWindow)
self.emaFiveMinsLong.Updated += self.onEmaFiveMinsLong
self.emaFiveMinsMedium.Updated += self.onEmaFiveMinsMedium
self.emaFiveMinsShort.Updated += self.onEmaFiveMinsShort
self.emaSixtyMinsLong.Updated += self.onEmaSixtyMinsLong
self.emaSixtyMinsShort.Updated += self.onEmaSixtyMinsShort
@property
def longEntrySetup(self):
fiveMinFannedOut = all([x > y > z for x,y,z in zip(list(self.historyEmaFiveMinsShort),list(self.historyEmaFiveMinsMedium),list(self.historyEmaFiveMinsLong))])
sixtyMinFannedOut = all([x > y for x,y in zip(list(self.historyEmaSixtyMinsShort),list(self.historyEmaSixtyMinsLong))])
prevBarsAboveShortEMA = all([x > y for x,y in zip([bar.Low for bar in list(self.historyFiveMinuteBars)[0:4]],list(self.historyEmaFiveMinsShort)[:4])])
return fiveMinFannedOut and sixtyMinFannedOut and prevBarsAboveShortEMA
@property
def longEntryTrigger(self):
return self.historyFiveMinuteBars[4].Low <= self.historyEmaFiveMinsShort[4]
@property
def IsReady(self):
return self.historyFiveMinuteBars.IsReady and \
self.historySixtyMinuteBars.IsReady and \
self.historyEmaSixtyMinsLong.IsReady and \
self.historyEmaSixtyMinsShort.IsReady and \
self.historyEmaFiveMinsLong.IsReady and \
self.historyEmaFiveMinsMedium.IsReady and \
self.historyEmaFiveMinsShort.IsReady
def sixtyMinutesBarHandler(self, sender, consolidated):
self.historySixtyMinuteBars.Add(consolidated)
self.algorithm.Plot("60m","EURUSD", consolidated.Close)
def fiveMinutesBarHandler(self, sender, consolidated):
self.historyFiveMinuteBars.Add(consolidated)
self.algorithm.Plot("5m","EURUSD", consolidated.Close)
def onEmaFiveMinsLong(self, sender, updated):
if self.emaFiveMinsLong.IsReady:
self.historyEmaFiveMinsLong.Add(updated.Value)
self.algorithm.Plot("5m","5mEMA21",self.emaFiveMinsLong.Current.Value)
def onEmaFiveMinsMedium(self, sender, updated):
if self.emaFiveMinsMedium.IsReady:
self.historyEmaFiveMinsMedium.Add(updated.Value)
self.algorithm.Plot("5m","5mEMA13", self.emaFiveMinsMedium.Current.Value)
def onEmaFiveMinsShort(self, sender, updated):
if self.emaFiveMinsShort.IsReady:
self.historyEmaFiveMinsShort.Add(updated.Value)
self.algorithm.Plot("5m","5mEMA8", self.emaFiveMinsShort.Current.Value)
def onEmaSixtyMinsLong(self, sender, updated):
if self.emaSixtyMinsLong.IsReady:
self.historyEmaSixtyMinsLong.Add(updated.Value)
self.algorithm.Plot("60m","EMA21",self.emaSixtyMinsLong.Current.Value)
def onEmaSixtyMinsShort(self, sender, updated):
if self.emaSixtyMinsShort.IsReady:
self.historyEmaSixtyMinsShort.Add(updated.Value)
self.algorithm.Plot("60m","EMA8", self.emaSixtyMinsShort.Current.Value)# Portfolio construction scaffolding class; basic method args.
class ForexPortfolioConstructionModel(PortfolioConstructionModel):
# Create list of PortfolioTarget objects from Insights
def CreateTargets(self, algorithm, insights):
targets = []
return targets
# OPTIONAL: Security change details
def OnSecuritiesChanged(self, algorithm, changes):
# Security additions and removals are pushed here.
# This can be used for setting up algorithm state.
# changes.AddedSecurities:
# changes.RemovedSecurities:
pass