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
import decimal as d
from datetime import datetime, timedelta
from System.Drawing import Color

### Crypto Currency
class gdaxCurrencyAlgorithm(QCAlgorithm):

    def Initialize(self):
        
        # gdax brokerage defaults
        self.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash)
        self.DefaultOrderProperties = GDAXOrderProperties()
        self.DefaultOrderProperties.PostOnly = False
        
        # backtest parameters
        self.cash = 1000
        self.SetStartDate(2018, 2, 5)
        self.SetEndDate(2018, 2, 9)
        
        # crypto settings
        self.crypto = "BTCUSD"
        resolution = Resolution.Minute
        self.AddCrypto(self.crypto, resolution)
        self.SetBenchmark(SecurityType.Crypto, self.crypto)
        
        # set cash
        self.cash = d.Decimal(self.cash)
        self.SetCash(self.cash)
        
        # EMA
        self.ema = self.EMA(self.crypto, 12, resolution)
        
        # WARMUP
        self.SetWarmUp(12)
        
        # charting parameters
        sPlot = Chart('Strategy Equity')
        sPlot.AddSeries(Series('Price', SeriesType.Line, 2))
        sPlot.AddSeries(Series('EMA', SeriesType.Line, 2))

        self.AddChart(sPlot)

    def OnData(self, data):
        
        # setup parameters
        security = self.Securities[self.crypto]
        price, quantity = security.Price, security.Holdings.Quantity
        
        # warmup process
        if self.IsWarmingUp: return 
    
        # charting call
        self.chartMyindicators()
        
        # flip from 0% to 100% repeatedly
        self.SetHoldings(self.crypto, 1 if not quantity else 0)
        
        portfolio = self.Portfolio
        
    # Override SetHoldings to use limit orders (ratio is of totalPortfolioValue)
    def SetHoldings(self, symbol, ratio):

        security = self.Securities[self.crypto]
        if not security.IsTradable:
            self.Debug("{} is not tradable.".format(self.crypto))
            return    # passive fail
        ratio = d.Decimal(ratio)
        price, quantity = security.Price, security.Holdings.Quantity
        
        # Keep 2% Cash    (for the limit order, rounding errors, and safety)
        totalPortfolioValue = self.Portfolio.TotalPortfolioValue * d.Decimal(0.001)
        
        # +0.1% Limit Order example (limit=1.001)
        # (to make sure it executes quickly and without much loss)
        # (if you set the limit large it will act like a market order)
        limit = 1.00002
        
        # Set purchasing ratio for crytpo
        desiredQuantity = totalPortfolioValue * ratio / price
        rawQuantity = desiredQuantity - quantity
        orderQuantity = round(rawQuantity, 9)
       
        # limit needs to be inverse when selling
        rawPrice = price * d.Decimal(limit if orderQuantity >= 0 else 1/limit)
        limitPrice = round(rawPrice, 2)
        
        # define a small tolerance on our checks to avoid bouncing
        tolerance = 0.0008
        
        # cancel open orders
        self.Transactions.CancelOpenOrders(self.crypto)
        
        '''-- BUY --'''    
        if quantity <= 0:
            if (self.ema.Current.Value + 30) > price:
                self.Log("Limit Order: {} coins @ ${} per coin".format(orderQuantity, limitPrice))
                self.LimitOrder(symbol, orderQuantity, limitPrice)
        '''------------------------------------------------------------------'''
        
        '''-- SELL --'''
        if quantity > 0:
            if (self.ema.Current.Value - 30) < price:
                    self.Log("Limit Order: {} coins @ ${} per coin".format(orderQuantity, limitPrice))
                    self.LimitOrder(symbol, orderQuantity, limitPrice)
        '''------------------------------------------------------------------'''
        self.previous = self.Time
        
    def chartMyindicators(self):
        
        # setup parameters
        security = self.Securities[self.crypto]
        price = security.Price
        
        # chart properties
        self.Plot('Strategy Equity', "PRICE", price)
        self.Plot('Strategy Equity', "EMA", round(self.ema.Current.Value,3))