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
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
# 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.
import datetime
import clr
from clr import AddReference
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")

from System import *
import numpy as np
from QuantConnect import *
from QuantConnect.Data import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d

global stopprice
### <summary>
### In this example we look at the canonical 15/30 day moving average cross. This algorithm
### will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses
### back below the 30.
### </summary>
### <meta name="tag" content="warmup" />
### <meta name="tag" content="crypto" />
### <meta name="tag" content="indicators" />
### <meta name="tag" content="indicator classes" />
### <meta name="tag" content="moving average cross" />
### <meta name="tag" content="strategy example" />
class CryptoWarmupMovingAverageCross(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(2017, 1, 01)  #Set Start Date
        self.SetEndDate(2017, 10, 23)    #Set End Date
        self.SetCash(40000)             #Set Strategy Cash
        self.previous = None
        self.stopprice = 999999999

        # Set brokerage we are using: GDAX for cryptos
        self.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash)
        
        # Set crypto to BTC at Minute Resolution
        self.AddCrypto("BTCUSD", Resolution.Minute)
        
        consolidator =  TradeBarConsolidator(1440)
        
        self.fast_btc = SimpleMovingAverage(10)
        self.slow_btc = SimpleMovingAverage(20)
        
        self.RegisterIndicator("BTCUSD", self.fast_btc, consolidator)
        self.RegisterIndicator("BTCUSD", self.slow_btc, consolidator)
        
        self.SubscriptionManager.AddConsolidator("BTCUSD", consolidator)
       
        # "slow_period + 1" because rolling window waits for one to fall off the back to be considered ready
        # History method returns a dict with a pandas.DataFrame
        dataset = ["BTCUSD"]
        startdate = datetime.datetime(2017, 10, 1, 18, 00)
        enddate = datetime.datetime.now()
        history = self.History(dataset, startdate, enddate, Resolution.Minute)
        
        if history.empty:
            return

        # Populate warmup data
        for index, row in history.loc["BTCUSD"].iterrows():
            self.fast_btc.Update(index, row["close"])
            self.slow_btc.Update(index, row["close"])

        # Log warmup status
        self.Log("FAST {0} READY. Samples: {1}".format("IS" if self.fast_btc.IsReady else "IS NOT", self.fast_btc.Samples))
        self.Log("SLOW {0} READY. Samples: {1}".format("IS" if self.slow_btc.IsReady else "IS NOT", self.slow_btc.Samples))


    def OnData(self, data):
            
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        # a couple things to notice in this method:
        #  1. We never need to 'update' our indicators with the data, the engine takes care of this for us
        #  2. We can use indicators directly in math expressions
        #  3. We can easily plot many indicators at the same time

        # wait for our slow ema to fully initialize
        if not self.fast_btc.IsReady:
            return
        if not self.slow_btc.IsReady:
            return

        # only once every 15 minutes
        now = datetime.datetime.now()
        
        if self.previous is not None and self.previous + datetime.timedelta(minutes=120) <= now:
            return

        # define a small tolerance on our checks to avoid bouncing
        tolerance = 0.00015

        #self.Log("Percentage is {0} ".format(stoppercent))
        #self.Log("Current price is {0}".format(str(self.Securities["BTCUSD"].Price)))
        holdings = self.Portfolio["BTCUSD"].Quantity
        
        
        
        self.previous = datetime.datetime.now()