Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
12.999%
Drawdown
9.200%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0.919
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0.087
Beta
0.006
Annual Standard Deviation
0.096
Annual Variance
0.009
Information Ratio
-0.064
Tracking Error
0.135
Treynor Ratio
15.199
namespace QuantConnect {

    /// <summary>
    /// Custom Data Type: Bitcoin data from Quandl.
    /// http://www.quandl.com/help/api-for-bitcoin-data
    /// </summary>
    public class Bitcoin : BaseData
    {
        //Set the defaults:
        public decimal Open = 0;
        public decimal High = 0;
        public decimal Low = 0;
        public decimal Close = 0;
        public decimal VolumeBTC = 0;
        public decimal VolumeUSD = 0;
        public decimal WeightedPrice = 0;

        /// <summary>
        /// 1. DEFAULT CONSTRUCTOR: Custom data types need a default constructor.
        /// We search for a default constructor so please provide one here. It won't be used for data, just to generate the "Factory".
        /// </summary>
        public Bitcoin()
        {
            this.Symbol = "BTC";
        }

        /// <summary>
        /// 2. RETURN THE STRING URL SOURCE LOCATION FOR YOUR DATA:
        /// This is a powerful and dynamic select source file method. If you have a large dataset, 10+mb we recommend you break it into smaller files. E.g. One zip per year.
        /// We can accept raw text or ZIP files. We read the file extension to determine if it is a zip file.
        /// </summary>
        /// <param name="config">Subscription data, symbol name, data type</param>
        /// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
        /// <param name="datafeed">Datafeed type: Backtesting or the Live data broker who will provide live data. You can specify a different source for live trading! </param>
        /// <returns>string URL end point.</returns>
        public override string GetSource(SubscriptionDataConfig config, DateTime date, DataFeedEndpoint datafeed)
        {
            switch (datafeed)
            {
                //Backtesting Data Source: Example of a data source which varies by day (commented out)
                default:
                case DataFeedEndpoint.Backtesting:
                    //return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
                    // OR simply return a fixed small data file. Large files will slow down your backtest
                    return "http://www.quandl.com/api/v1/datasets/BITCOIN/BITSTAMPUSD.csv?sort_order=asc";

                case DataFeedEndpoint.LiveTrading:
                    //Alternative live socket data source for live trading
                    return "....";
            }
        }

        /// <summary>
        /// 3. READER METHOD: Read 1 line from data source and convert it into Object.
        /// Each line of the CSV File is presented in here. The backend downloads your file, loads it into memory and then line by line
        /// feeds it into your algorithm
        /// </summary>
        /// <param name="line">string line from the data source file submitted above</param>
        /// <param name="config">Subscription data, symbol name, data type</param>
        /// <param name="date">Current date we're requesting. This allows you to break up the data source into daily files.</param>
        /// <param name="datafeed">Datafeed type - Backtesting or LiveTrading</param>
        /// <returns>New Bitcoin Object which extends BaseData.</returns>
        public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, DataFeedEndpoint datafeed)
        {
            //New Bitcoin object
            Bitcoin coin = new Bitcoin();

            try
            {
                //Example File Format:
                //Date,      Open   High    Low     Close   Volume (BTC)    Volume (Currency)   Weighted Price
                //2011-09-13 5.8    6.0     5.65    5.97    58.37138238,    346.0973893944      5.929230648356
                string[] data = line.Split(',');
                coin.Time = DateTime.Parse(data[0]);
                coin.Open = Convert.ToDecimal(data[1]);
                coin.High = Convert.ToDecimal(data[2]);
                coin.Low = Convert.ToDecimal(data[3]);
                coin.Close = Convert.ToDecimal(data[4]);
                coin.VolumeBTC = Convert.ToDecimal(data[5]);
                coin.VolumeUSD = Convert.ToDecimal(data[6]);
                coin.WeightedPrice = Convert.ToDecimal(data[7]);
                coin.Symbol = "BTC";
                coin.Value = coin.Close;
            }
            catch { /* Do nothing, skip first title row */ }

            return coin;
        }
    }
}
namespace QuantConnect 
{   
    /*
    *   QuantConnect University: Bollinger Bands Example:
    */
    public class IndicatorSuiteAlgorithm : QCAlgorithm
    {
        string _symbol = "SPY";
        string _customSymbol = "BTC";
        
        BollingerBands _bb;
        RelativeStrengthIndex _rsi;
        AverageTrueRange _atr;
        ExponentialMovingAverage _ema;
        SimpleMovingAverage _sma;
        
        //***NEW
        
        DateTime sampledToday = DateTime.Now;
        
        SimpleMovingAverage _smaLo;
        SimpleMovingAverage _smaHi;
        //***NEW
        
        MovingAverageConvergenceDivergence _macd;
        AroonOscillator _aroon;
        Momentum _mom;
        StandardDeviation _std;
        
        //RSI Custom Data:
        RelativeStrengthIndex _rsiCustom;
        
        //SMA custom:
        
        decimal _price;
        
        //***NEW
        decimal _low;
        decimal _high;
        decimal _prevLow;
        decimal _prevHi;
        int quantity;
        //***NEW
        
        
        //Initialize the data and resolution you require for your strategy:
        public override void Initialize()
        {
            //Initialize
            DateTime today = DateTime.Now;
            SetStartDate(2014, 1, 1);         
            SetEndDate(today.AddDays(-1)); 
            SetCash(25000);
            
            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);
            
            //Add the Custom Data:
            AddData<Bitcoin>("BTC");
            
            //Set up Indicators:
            _bb = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily);
            _rsi = RSI(_symbol, 14,  MovingAverageType.Simple, Resolution.Daily);
            _atr = ATR(_symbol, 14,  MovingAverageType.Simple, Resolution.Daily);
            _ema = EMA(_symbol, 14, Resolution.Daily);
            _sma = SMA(_symbol, 14, Resolution.Daily);
            
            //***NEW
            _smaLo = SMA(_symbol, 1, Resolution.Daily);
            _smaHi = SMA(_symbol, 1, Resolution.Daily);
            _prevLow = 1000000.00m;
            _prevHi = 0.00m;
          //***NEW
            
            _macd = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily);
            _aroon = AROON(_symbol, 20, Resolution.Daily);
            _mom = MOM(_symbol, 20, Resolution.Daily);
            _std =  STD(_symbol, 20, Resolution.Daily);
            
            //Custom Data Indicator:
            //1. Manually create instance of indicator class
            _rsiCustom = new RelativeStrengthIndex(_customSymbol, 14); 
            //2. Create a "consolidator". If you don't need one use "IdentityDataConsolidator" which means "pass data through".
            var bitcoinIdentityConsolidator = new IdentityDataConsolidator<Bitcoin>();
            //3. Manually Register Indicator to receive updates (using data.Value to generate indicator).
            RegisterIndicator("BTC", _rsiCustom, bitcoinIdentityConsolidator, x => x.Value);
            //Note: If you want you could manually update the indicator class values with _rsiCustom.Update(): 
            
            
            //***NEW
            RegisterIndicator(_symbol, _smaLo, ResolveConsolidator(_symbol, Resolution.Daily), baseData => ((TradeBar)baseData).Low);
            RegisterIndicator(_symbol, _smaHi, ResolveConsolidator(_symbol, Resolution.Daily), baseData => ((TradeBar)baseData).High);
            //***NEW
        }
        
        //Custom data event handler:
        public void OnData(Bitcoin data)
        { //
        }

        public void OnData(TradeBars data)
        {   
            if (!_smaLo.IsReady) return;
            
            //***NEW
            if (sampledToday == data[_symbol].Time.Date) return;
            //***NEW
            
            _price = data[_symbol].Close;
            
            //***NEW
            int holdings = Portfolio[_symbol].Quantity;
            _low = data[_symbol].Low;
            _high = data[_symbol].High;
            //***NEW
            
            if (!Portfolio.HoldStock) 
            { 
                int quantity = (int)Math.Floor(Portfolio.Cash / data[_symbol].Close);
                
                //Order function places trades: enter the string symbol and the quantity you want:
                Order(_symbol,  quantity);
                
                //Debug sends messages to the user console: "Time" is the algorithm time keeper object 
                Debug("Purchased SPY on " + Time.ToShortDateString());
            }
        

        }
        
        // Fire plotting events once per day:
        public override void OnEndOfDay() 
        {
            if (!_bb.IsReady) return;
            
            Plot("BB", "Price", _price);
            Plot("BB", _bb.UpperBand, _bb.MiddleBand, _bb.LowerBand);
            
            //***NE
            Plot("SMAs", "low", _low);
            Plot("SMAs", "high", _high);
            Plot("SMAs", "sma Lo", _smaLo);
            Plot("SMAs", "sma Hi", _smaHi);
            //***NEW
            
            Plot("RSI", _rsi);
            
            //Custom data indicator
            Plot("RSI-BTC", _rsiCustom);
            
            Plot("ATR", _atr);
            
            //Plot("STD", _std);
            
            Plot("AROON", _aroon.AroonUp, _aroon.AroonDown);
            
            // Plot("MOM", _mom);
            
            // Plot("MACD", "Price", _price);
            // Plot("MACD", _macd.Fast, _macd.Slow);
            
            // Plot("Averages", _ema, _sma);
        }
    }
}