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
namespace QuantConnect 
{   
    /*
    *   QuantConnect University: Full Basic Template:
    *
    *   The underlying QCAlgorithm class is full of helper methods which enable you to use QuantConnect.
    *   We have explained some of these here, but the full algorithm can be found at:
    *   https://github.com/QuantConnect/Lean/tree/master/Algorithm
    */
    public class BasicTemplateAlgorithm : QCAlgorithm
    {
    	string Symbol = null;
    	int RollingSize = 2;
    	RollingWindow<TradeBar> history = null;
        //Initialize the data and resolution you require for your strategy:
        public override void Initialize() 
        {
            //Start and End Date range for the backtest:
            SetStartDate(2017, 1, 9);         
            //SetEndDate(DateTime.Now.Date.AddDays(-1));
            SetEndDate(2017,1,23);
            //Cash allocation
            SetCash(25000);
            Symbol="VXX";
            //Add as many securities as you like. All the data will be passed into the event handler:
            //AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);
            AddSecurity(SecurityType.Equity, Symbol, Resolution.Minute);
            
            history = new RollingWindow<TradeBar>(RollingSize);
        }

        //Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol.
        public void OnData(TradeBars data) 
        {   
        	TradeBar b = null;
        	data.TryGetValue(Symbol, out b);
        	//Console.WriteLine("hello world");
        	if (history.IsReady ){
        		//console.Wr("HISTORY " + history[0].Close+" "+history[1].Close);
        		//Console.WriteLine("hello");
        		
        		Console.WriteLine(history[0].Close.ToString()+" "+history[1].Close.ToString());
        	}
            // "TradeBars" object holds many "TradeBar" objects: it is a dictionary indexed by the symbol:
            // 
            //  e.g.  data["MSFT"] data["GOOG"]
            
            /*if (!Portfolio.HoldStock) 
            {
                int quantity = (int)Math.Floor(Portfolio.Cash / data["SPY"].Close);
                
                //Order function places trades: enter the string symbol and the quantity you want:
                Order("SPY",  quantity);
                
                //Debug sends messages to the user console: "Time" is the algorithm time keeper object 
                Debug("Purchased SPY on " + Time.ToShortDateString());
                
                //You can also use log to send longer messages to a file. You are capped to 10kb
                //Log("This is a longer message send to log.");
            }*/
            if (  b!=null && IsLastTradingMin(b) == true)
                {
                        history.Add(b);
                        //lastClose = data[Symbol];
                        //Debug("Add a bar " + b.Time.ToString() +" " + (history.Count >= RollingSize)  );
                }
        }
        bool IsFirstTradingMin(TradeBar b)
        {
            if ( b.Time.Hour==9 && b.Time.Minute == 31)
                return true;
            else
                return false;
        }
        bool IsLastTradingMin(TradeBar b)
        {
            if ( b.Time.Hour==15 && b.Time.Minute == 59)
                return true;
            else
                return false;
        } // IsLastTradingMin
    }
}
namespace QuantConnect.Algorithm.Examples 
{

    //
    //	Make sure to change "BasicTemplateAlgorithm" to your algorithm class name, and that all
    //	files use "public partial class" if you want to split up your algorithm namespace into multiple files.
    //

    //public partial class BasicTemplateAlgorithm : QCAlgorithm, IAlgorithm
    //{
    //  Extension functions can go here...(ones that need access to QCAlgorithm functions e.g. Debug, Log etc.)
    //}

    //public class Indicator 
    //{
    //  ...or you can define whole new classes independent of the QuantConnect Context
    //}
    public class RollingWin<T>  : IReadOnlyWindow<T>
    {
        // the backing list object used to hold the data
        public  List<T> _list;
        // read-write lock used for controlling access to the underlying list data structure
        //private readonly ReaderWriterLockSlim _listLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
        // the most recently removed item from the window (fell off the back)
        private T _mostRecentlyRemoved;
        // the total number of samples taken by this indicator
        private decimal _samples;
        // used to locate the last item in the window as an indexer into the _list
        private int _tail;

        /// <summary>
        ///     Initializes a new instance of the RollwingWindow class with the specified window size.
        /// </summary>
        /// <param name="size">The number of items to hold in the window</param>
        public RollingWin(int size)
        {
            if (size < 1)
            {
                throw new ArgumentException("RollingWindow must have size of at least 1.", "size");
            }
            _list = new List<T>(size);
        }

        /// <summary>
        ///     Gets the size of this window
        /// </summary>
        public int Size
        {
            get
            { 
                return _list.Capacity;
            }
        }

        /// <summary>
        ///     Gets the current number of elements in this window
        /// </summary>
        public int Count
        {
            get
            { 
                return _list.Count;
            }
        }

        /// <summary>
        ///     Gets the number of samples that have been added to this window over its lifetime
        /// </summary>
        public decimal Samples
        {
            get
            { 
                 return _samples;
            }
        }

        /// <summary>
        ///     Gets the most recently removed item from the window. This is the
        ///     piece of data that just 'fell off' as a result of the most recent
        ///     add. If no items have been removed, this will throw an exception.
        /// </summary>
        public T MostRecentlyRemoved
        {
            get
            {
                    if (!IsReady)
                    {
                        throw new InvalidOperationException("No items have been removed yet!");
                    }
                    return _mostRecentlyRemoved;
                

            }
        }

        /// <summary>
        ///     Indexes into this window, where index 0 is the most recently
        ///     entered value
        /// </summary>
        /// <param name="i">the index, i</param>
        /// <returns>the ith most recent entry</returns>
        public T this [int i]
        {
            get
            {
                    //_listLock.EnterReadLock();

                    if (i >= Count)
                    {
                        throw new ArgumentOutOfRangeException("i", i, string.Format("Must be between 0 and Count {0}", Count));
                    }
                    return _list[(Count + _tail - i - 1) % Count];
               
            }
            set
            {
                    if (i >= Count)
                    {
                        throw new ArgumentOutOfRangeException("i", i, string.Format("Must be between 0 and Count {0}", Count));
                    }
                    _list[(Count + _tail - i - 1) % Count] = value;
                
            }
        }

        /// <summary>
        ///     Gets a value indicating whether or not this window is ready, i.e,
        ///     it has been filled to its capacity and one has fallen off the back
        /// </summary>
        public bool IsReady
        {
            get
            { 
               return Samples > Size;
            }
        }

        /// <summary>
        ///     Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        ///     A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public IEnumerator<T> GetEnumerator()
        {
            // we make a copy on purpose so the enumerator isn't tied 
            // to a mutable object, well it is still mutable but out of scope
            var temp = new List<T>(Count);
            

                for (int i = 0; i < Count; i++)
                {
                    temp.Add(this[i]);
                }
                return temp.GetEnumerator();

        }

        /// <summary>
        ///     Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        ///     An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        /// <summary>
        ///     Adds an item to this window and shifts all other elements
        /// </summary>
        /// <param name="item">The item to be added</param>
        public void Add(T item)
        {
                _samples++;
                if (Size == Count)
                {
                    // keep track of what's the last element
                    // so we can reindex on this[ int ]
                    _mostRecentlyRemoved = _list[_tail];
                    _list[_tail] = item;
                    _tail = (_tail + 1) % Size;
                }
                else
                {
                    _list.Add(item);
                }
        }

        /// <summary>
        ///     Clears this window of all data
        /// </summary>
        public void Reset()
        {
            _samples = 0;
            _list.Clear();
        }
    }

}