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
Estimated Strategy Capacity
$0
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.Orders import *


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._macd = {}
        self._stoch = {}
        
        self.SetStartDate(2020, 1, 1)  #Set Start Date
        self.SetEndDate(2021, 4, 1)    #Set End Date
        self.SetCash(1000)
        
        # Set Strategy Cash (EUR)
        # EUR/USD conversion rate will be updated dynamically
        # self.SetCash("EUR", 10000)

        # self.SetCash("BTC", 1)
        # self.SetCash("ETH", 5)

        self.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash)
        
        symbol = self.AddCrypto("BTCUSD", Resolution.Minute).Symbol
        # self.AddCrypto("ETHUSD", Resolution.Minute)
        # self.AddCrypto("BTCEUR", Resolution.Minute)
        
        #self.AddSecurity(SecurityType.Equity, symbol, Resolution.Minute)
        
        self.macd = self.MACD(symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Minute)
        
        window_length = 5
        self.macdHistogram = RollingWindow[float](window_length)
        self.macdMACD = RollingWindow[float](window_length)
        self.macdSIGNAL = RollingWindow[float](window_length)
        
        self.stocha = self.STO(symbol, 14, Resolution.Minute)
        self.stochStochK = RollingWindow[float](window_length)
        self.stochStochD = RollingWindow[float](window_length)
        
        self.control = False
        
        # Warm up indicators and rolling windows
        period = max(self.macd.WarmUpPeriod, self.stocha.WarmUpPeriod) + window_length
        history = self.History(symbol, period, Resolution.Minute)
        if history.empty:
            return
        history = history.loc[symbol]
        for time, row in history.iterrows():
            tradebar = TradeBar(time, symbol, row.open, row.high, row.low, row.close, row.volume)       
            if self.macd.Update(IndicatorDataPoint(tradebar)):
                self.macdHistogram.Add(self.macd.Histogram.Current.Value)
                self.macdMACD.Add(self.macd.Current.Value)
                self.macdSIGNAL.Add(self.macd.Signal.Current.Value)
                
            if self.stocha.Update(tradebar):
                self.stochStochK.Add(self.stocha.StochK.Current.Value)
                self.stochStochD.Add(self.stocha.StochD.Current.Value)
        
    
    def OnData(self, data):
        self.Quit(f"{self.macd.IsReady and self.stocha.IsReady and self.macdHistogram.IsReady and self.macdMACD.IsReady and self.macdSIGNAL and self.stochStochK.IsReady and self.stochStochD.IsReady}")
        
        # if not (self._macd["Histogram"].IsReady and self._macd["MACD"].IsReady and self._macd["SIGNAL"].IsReady and self._stoch['StochK'].IsReady and self._stoch['StochD'].IsReady): return
        
        
        if self.macdHistogram[0] < self.macdHistogram[1] and ((self.stochStochK[0] > self.stochStochD[0] and self.stochStochK[1] < self.stochStochD[1]) or self.stochStochK[0] > self.stochStochD[0]) and self.macdHistogram[0] < 0 and self.stochStochD[0] < 40 and self.control == False:
            self.control = True
            usdTotal = self.Portfolio.CashBook["USD"].Amount
            limitPrice = round(self.Securities["BTCUSD"].Price * 0.95, 2)
            # use only half of our total USD
            quantity = usdTotal * 0.5 / limitPrice
            self.MarketOrder("BTCUSD", quantity)
            
        elif (self.macdSIGNAL[0] > self.macdMACD[0] and sself.macdSIGNAL[1] < self.macdMACD[1])and self.control == True:
            self.control = False
            limitPrice = round(self.Securities["BTCUSD"].Price * 1.00, 2)
            quantity = self.Portfolio.CashBook["BTC"].Amount
            self.MarketOrder("BTCUSD", -quantity)

        


    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))