Overall Statistics
Total Trades
1
Average Win
0%
Average Loss
0%
Compounding Annual Return
-99.157%
Drawdown
23.100%
Expectancy
0
Net Profit
0%
Sharpe Ratio
-4.648
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-2.813
Beta
-0.933
Annual Standard Deviation
0.665
Annual Variance
0.442
Information Ratio
-4.976
Tracking Error
0.681
Treynor Ratio
3.312
Total Fees
$300.30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// In this algortihm we show how you can easily use the universe selection feature to fetch symbols
    /// to be traded using the AddUniverse method. This method accepts a function that will return the
    /// desired current set of symbols. Return Universe.Unchanged if no universe changes should be made
    /// </summary>
    public class DropboxUniverseSelectionAlgorithm : QCAlgorithm
    {
        // the changes from the previous universe selection
        static string _symbol;
        private SecurityChanges _changes = SecurityChanges.None;
        // only used in backtest for caching the file results
        private readonly Dictionary<DateTime, List<string>> _backtestSymbolsPerDay = new Dictionary<DateTime, List<string>>();

        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            // this sets the resolution for data subscriptions added by our universe
            UniverseSettings.Resolution = Resolution.Daily;

            // set our start and end for backtest mode
            SetStartDate(2016, 03, 07);
            SetEndDate(DateTime.Now);

            // define a new custom universe that will trigger each day at midnight
            AddUniverse("my-dropbox-universe", Resolution.Daily, dateTime =>
            {
                const string liveUrl = @"https://www.dropbox.com/s/qxa5yq73dvj78dv/gainers.csv?dl=1";
                const string backtestUrl = @"https://www.dropbox.com/s/qxa5yq73dvj78dv/gainers.csv?dl=1";
                var url = LiveMode ? liveUrl : backtestUrl;
                using (var client = new WebClient())
                {
                    // handle live mode file format
                    if (!LiveMode)
                    {
                        // fetch the file from dropbox
                        var file = client.DownloadString(url);
                        var csv = file.Split(',');
                    	List<string> results = new List<string>();
                    	results.Add(csv[1]);
                        // if we have a file for today, break apart by commas and return symbols
                        if (file.Length > 0) return results;
                        // no symbol today, leave universe unchanged
                        return Universe.Unchanged;
                    }

                    // backtest - first cache the entire file
                    if (_backtestSymbolsPerDay.Count == 0)
                    {
                        // fetch the file from dropbox only if we haven't cached the result already
                        var file = client.DownloadString(url);

                        // split the file into lines and add to our cache
                        foreach (var line in file.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            var csv = line.Split(',');
                            //var date = DateTime.Parse(csv[4]);
                            //var date = DateTime.ParseExact(csv[4], "yyyyMMdd", null);
                            var symbols = csv[0];
                            Log("" + symbols);
                            //List<string> primes = new List<string>();
                            //primes.Add(symbols);
                            //_backtestSymbolsPerDay[date] = primes;
                            //Log("" + primes);
                        }
                    }

                    // if we have symbols for this date return them, else specify Universe.Unchanged
                    List<string> result;
                    if (_backtestSymbolsPerDay.TryGetValue(dateTime.Date, out result))
                    {
                        return result;
                    }
                    return Universe.Unchanged;
                }
            });
        }

        /// <summary>
        /// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
        /// </summary>
        /// <code>
        /// TradeBars bars = slice.Bars;
        /// Ticks ticks = slice.Ticks;
        /// TradeBar spy = slice["SPY"];
        /// List{Tick} aaplTicks = slice["AAPL"]
        /// Quandl oil = slice["OIL"]
        /// dynamic anySymbol = slice[symbol];
        /// DataDictionary{Quandl} allQuandlData = slice.Get{Quand}
        /// Quandl oil = slice.Get{Quandl}("OIL")
        /// </code>
        /// <param name="slice">The current slice of data keyed by symbol string</param>
        public override void OnData(Slice slice)
        {
            if (slice.Bars.Count == 0) return;
            if (_changes == SecurityChanges.None) return;

            // start fresh
            Liquidate();

            var percentage = 1m/slice.Bars.Count;
            foreach (var tradeBar in slice.Bars.Values)
            {
                SetHoldings(tradeBar.Symbol, percentage);
            }

            // reset changes
            _changes = SecurityChanges.None;
        }

        /// <summary>
        /// Event fired each time the we add/remove securities from the data feed
        /// </summary>
        /// <param name="changes"></param>
        public override void OnSecuritiesChanged(SecurityChanges changes)
        {
            // each time our securities change we'll be notified here
            _changes = changes;
        }
    }
}                        
/*using System;
using QuantConnect.Securities;
using QuantConnect.Orders.Fees;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Data.Market;
using QuantConnect.Packets;
using QuantConnect.Util;
using System.Reflection;
using QuantConnect.Scheduling;


namespace QuantConnect 
{   
    public class BasicTemplateAlgorithm : QCAlgorithm
    {
        string symbol = "GSI"; //pull data from SymbolSelection.cs
        int _holdings;
        decimal _pct;
        decimal _stopPct;
        bool trigger = false;
        bool first = true;
        bool second = true;
        bool notif = true;
        static string globalString;
        static decimal _globalSkim;
        static decimal timeFrame;
 		static decimal _symPrice;
 		static decimal _readableProfits;
 		static decimal _newStop;
        static readonly decimal EqualWeightPercentage = 1m/3;
        OrderTicket _ordertick;
        DateTime lastTradeTime;
        
        public override void Initialize()
        {
 	
            SetBrokerageModel(BrokerageName.TradierBrokerage, AccountType.Cash);
           	
           	//set date for backtesting
            SetStartDate(2016, 03, 20);         
            SetEndDate(DateTime.Now.Date.AddDays(-1));

            SetCash(2750);
            
            //returns five percent of investible cash
            _stopPct = Portfolio.Cash/3 * -.025m;
            _pct = Portfolio.Cash/3 * .03m;

            AddSecurity(SecurityType.Equity, 
            symbol, 
            Resolution.Second,
            fillDataForward: true, 
            extendedMarketHours: false, 
            leverage: 1);
            
            //Plot(symbol, 30);

            //resolution time frame consolidation AKA: turns our second resolution into minutes
            TradeBarConsolidator consolidator = new TradeBarConsolidator(TimeSpan.FromSeconds(1));
			consolidator.DataConsolidated += MinHandler;
			SubscriptionManager.AddConsolidator(symbol, consolidator);
			
        }
        public void MinHandler(object sender, TradeBar data) {
    	// handle each minute here
    	if (_symPrice > timeFrame)
    		{
    			timeFrame = data.High;
    			var calc = _readableProfits * .10m;
        		_newStop = _readableProfits - calc;
    		}
        }
        
        public void OnData(TradeBars data) 
        {   
        	/*TimeSpan now = DateTime.Now.TimeOfDay;
      		TimeSpan start = new TimeSpan(15, 0, 0);
      		var timen = DateTime.Now.Hour;
			//var CurrHour = timen.Hour;
			
      		if (DateTime.Now > )
        	{
        		Log("" + timen);
      			Log("" + CurrHour);
        		//first = true;
        	}
    		_symPrice = data[symbol].Price;

            var highPrice = _holdings * timeFrame;    
        	var newStopLoss = highPrice * .03m;

        	var currentPriceStop = _globalSkim *.03m;
        	
            _readableProfits = Portfolio.TotalUnrealizedProfit;
            var time = DateTime.Now;
            string messageString = String.Format("{0} \nTime: {1} \nPrice: {2} \nProfit: {3} \nHigh {4}", 
            symbol, 
            time.ToShortTimeString(), 
            _symPrice.ToString(),
            _readableProfits,
            timeFrame.ToString());
            globalString = messageString;
            
                //var equalWeightedPorfolioSize = Portfolio.TotalPortfolioValue/3;
                var shareCount = CalculateOrderQuantity(symbol, EqualWeightPercentage);
                
                if (!Portfolio.HoldStock && first)
					{
					first = false;
					Order(symbol,  shareCount);
                    Notify.Sms("+1#######", "Buy " + messageString);
					}

                _holdings = Portfolio[symbol].Quantity;
                _globalSkim = _holdings * _symPrice;
			
			if (Portfolio.HoldStock && second)
			{
            // set trigger equal to true if profits are greater than 3 percent of invested portfolio cash
            if (_readableProfits > _pct)
            {
            trigger = true;
            if(notif)
            	{
            	notif = false;
            	Notify.Sms("+1#######", "The trigger price has been reached!" + globalString);
            	}
        	}
        	//sell if profits go below high profit stop	
        	if (trigger == true && _readableProfits <= _newStop)
        	{
        		Notify.Sms("+1#######", "Gain Sell " + globalString);
        		Order(symbol, -_holdings);
        		second = false;
        	}
        	//sell if profits go below skim stop
        	if (trigger == true && _readableProfits < _pct)
        	{
        		Notify.Sms("+1#######", "Skim Sell " + globalString);
        		Order(symbol, -_holdings);
        		second = false;
        	}
        	
        	// sell if profits go below 2.5% invested portfolio cash
            if (_readableProfits < _stopPct)
            {
            	Notify.Sms("+1#######", "Loss Sell " + globalString);
            	Order(symbol, -_holdings);
            	second = false;
            }
            
            // sell on close
            Schedule.Event()
    		.EveryDay(symbol)
    		.BeforeMarketClose(symbol, 1)
    		.Run(() =>
    		{
    			Notify.Sms("+1#######", "End Of Day Sell " + globalString);
    			Order(symbol, -_holdings);
    			second = false;
    		});
            }
        }
    }
}
			
			//Log("_stopPct" + _stopPct);
			//Log("_globalSkim" + _globalSkim);
			//Log("timeFrame" + timeFrame);
        	/*TimeSpan elapsedTime = new TimeSpan(0,5,5);

        	Schedule.Event()
    		.EveryDay(symbol)
    		.Every(elapsedTime)
    		.Run(() =>
    		{
    		Notify.Sms("+1#######", "Update " + globalString);
    		});*/