Overall Statistics
//Copyright Warren Harding 2016.
//Use entirely at your own risk.
//Custom algorithm development: warrencharding@yahoo.com.
//Do not remove this copyright notice.

using System;
using System.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
using QuantConnect.Securities;
namespace QuantConnect
{
    public class Algo4 : QCAlgorithm
    {
    	//You can adjust this first set to optimize.
    	int maPeriod = 60;
    	int rsiPeriod = 3;
    	decimal rsiBuyCutoff=50;
    	decimal rsiSellCutoff=50;
    	decimal lowerBandRatio=0.9m;
    	decimal upperBandRatio = 1.1m;
    	decimal maximumTrade=25000;
    	decimal minimumTrade = 500m;
    	
    	//Your broker is going to hate you if you set these too low as it will result in large amounts of unfilled
    	//order cancellations. It bogs down LEAN as well.
    	int barsToHoldBuyOrdersFor=0;
    	int barsToHoldSellOrdersFor=0;
    	
    	Resolution resolution = Resolution.Daily;
    	
    	decimal ratioOfDollarVolumeForMaxTrade;

		Dictionary<string,RelativeStrengthIndex> rsisBuy=new Dictionary<string,RelativeStrengthIndex>();
		Dictionary<string,RelativeStrengthIndex> rsisSell=new Dictionary<string,RelativeStrengthIndex>();
        Dictionary<string,ExponentialMovingAverage> movingAverages=new Dictionary<string,ExponentialMovingAverage>();
        Dictionary<string,OrderTicket> buyOrders=new Dictionary<string,OrderTicket>();
        Dictionary<string,int> buyOrderCounts = new Dictionary<string,int>();
        Dictionary<string,decimal> buyOrderPrices = new Dictionary<string,decimal>();
        Dictionary<string,OrderTicket> sellOrders=new Dictionary<string,OrderTicket>();
        Dictionary<string,int> sellOrderCounts = new Dictionary<string,int>();
        public override void Initialize()
        {
            SetStartDate(2011, 9, 30);
			SetEndDate(2016, 9, 30);
			
            SetCash(100000);
            
            SetSecurityInitializer(
                new CustomSecurityInitializer(
                // Default if not set by SetBrokerageModel
                BrokerageModel,
                // Your custom fee model   
                new CustomFeeModel()
                ));
            
            //s&p 500, by sorted by volatility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string[1] { "," }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string ticker in tickers)
			{
				AddSecurity(SecurityType.Equity,ticker,resolution);
			}
            foreach (Security s in Securities.Values)
            {
            	movingAverages.Add(s.Symbol,EMA(s.Symbol,maPeriod,resolution));
            	rsisBuy.Add(s.Symbol,RSI(s.Symbol,rsiPeriod,MovingAverageType.Exponential,resolution));
            	rsisSell.Add(s.Symbol,RSI(s.Symbol,rsiPeriod,MovingAverageType.Exponential,resolution));
            }
        
           	//Be careful adjusting this next one, too high of a setting will result in unrealistically large
    		//purchases being made with no regards for slippage.    
        	if (resolution == Resolution.Daily)
	    	{
	    		ratioOfDollarVolumeForMaxTrade = .25m / 6.5m / 60m;
	    	}
	    	else
	    	{
	    		ratioOfDollarVolumeForMaxTrade = .25m;
	    	}
        }
		
        public void OnData(TradeBars data)
        {
			Buy(data);
			Sell(data);
        }
        
        public void Buy(TradeBars data)
        {
        	CancelBuyOrders();
        	int quantity = 0;
        	decimal maxTrade;
            OrderTicket orderTicket;
            decimal buyPrice;
    	    foreach (TradeBar bar in data.Values)
            {
            	if (Portfolio.Cash - SumBuyOrders(buyOrders,buyOrderPrices) < minimumTrade)
                {
                    break;
                }
                if (!Portfolio[bar.Symbol].HoldStock  & movingAverages[bar.Symbol].IsReady)
                {
                    maxTrade=bar.Close*bar.Volume*ratioOfDollarVolumeForMaxTrade;
                    if (maxTrade>maximumTrade)
                    {
                    	maxTrade=maximumTrade;
                    }
                    quantity =(int)Math.Floor(Math.Min(Portfolio.Cash-SumBuyOrders(buyOrders,buyOrderPrices), maxTrade) / bar.Close);
                    quantity=RoundLot(quantity);
                    if (quantity * bar.Close > minimumTrade & quantity > 0)
                    {
                        if (buyOrders.ContainsKey(bar.Symbol) == false)
                        {
                        	buyPrice=movingAverages[bar.Symbol]*lowerBandRatio;
                        	if (bar.Close<buyPrice & rsisBuy[bar.Symbol]>rsiBuyCutoff)
                        	{
                        		buyPrice=bar.Close;
                                orderTicket = LimitOrder(bar.Symbol, quantity,buyPrice);
                                buyOrders.Add(bar.Symbol,orderTicket);
                                buyOrderCounts.Add(bar.Symbol,0);
       							buyOrderPrices.Add(bar.Symbol,buyPrice);
                        	}
                        }
                    }
                }
            }
            foreach (string key in buyOrderCounts.Keys.ToList())
            {
                buyOrderCounts[key] = buyOrderCounts[key] + 1;
            }
        }
        
        public void Sell(TradeBars data)
        {
        	CancelSellOrders();
        	decimal sellPrice;
    	    TradeBar bar;
    	    OrderTicket orderTicket;
            
            foreach (SecurityHolding stock in Portfolio.Values)
            {
                if (Portfolio[stock.Symbol].Quantity > 0 & data.ContainsKey(stock.Symbol))
                {
                    bar = data[stock.Symbol];
                    if (sellOrders.ContainsKey(stock.Symbol)==false)
                    {
                    	sellPrice = movingAverages[stock.Symbol] * upperBandRatio;
                    	if (bar.Close>sellPrice & rsisSell[stock.Symbol]<rsiSellCutoff)
                    	{
                        	sellPrice=bar.Close;
	                        orderTicket = LimitOrder(stock.Symbol, -Portfolio[stock.Symbol].Quantity, sellPrice);
	                        sellOrders.Add(stock.Symbol,orderTicket);
	                        sellOrderCounts.Add(stock.Symbol,0);
                    	}
                    }
                }
            }
            foreach (string key in sellOrderCounts.Keys.ToList())
            {
                sellOrderCounts[key] = sellOrderCounts[key] + 1;
            }
        }
        
        public void CancelBuyOrders()
        {
        	string[] symbols=buyOrders.Keys.ToArray();
        	foreach (string symbol in symbols)
        	{
			    if (buyOrderCounts[symbol]>barsToHoldBuyOrdersFor)
	        	{
	        		buyOrders[symbol].Cancel();
	        		buyOrders.Remove(symbol);
	        		buyOrderCounts.Remove(symbol);
	        		buyOrderPrices.Remove(symbol);
	        	}
        	}
        	symbols=buyOrders.Keys.ToArray();
        	foreach (string symbol in symbols)
        	{
    		    if (buyOrders[symbol].Status == OrderStatus.Filled)
	            {
            		buyOrders.Remove(symbol);
            		buyOrderCounts.Remove(symbol);
            		buyOrderPrices.Remove(symbol);
	            }
        	}
        }
        
        public void CancelSellOrders()
        {
        	string[] symbols=sellOrders.Keys.ToArray();
        	foreach (string symbol in symbols)
        	{
			    if (sellOrderCounts[symbol]>barsToHoldSellOrdersFor)
	        	{
	        		sellOrders[symbol].Cancel();
	        		sellOrders.Remove(symbol);
	        		sellOrderCounts.Remove(symbol);
	        	}
        	}
        	symbols=sellOrders.Keys.ToArray();
        	foreach (string symbol in symbols)
        	{
    		    if (sellOrders[symbol].Status == OrderStatus.Filled)
	            {
            		sellOrders.Remove(symbol);
            		sellOrderCounts.Remove(symbol);
	            }
        	}
        }
        
        public static decimal SumBuyOrders(Dictionary<string,OrderTicket> buyOrders, Dictionary<string,decimal> buyOrderPrices)
        {
        	decimal sum=0;
            foreach (string key in buyOrders.Keys.ToList())
            {
                sum += buyOrders[key].Quantity * buyOrderPrices[key];
            }
            return sum;
        }
        
        public static int RoundLot(int inOddLotQuantity)
        {
            decimal inQuantity = (decimal)inOddLotQuantity;
            if (inQuantity > 2000000)
            {
                decimal small = inQuantity / 1000000;
                small = Math.Floor(small);
                return (int)(small * 1000000);
            }
            if (inQuantity > 200000)
            {
                decimal small = inQuantity / 100000;
                small = Math.Floor(small);
                return (int)(small * 100000);
            }
            if (inQuantity > 20000)
            {
                decimal small = inQuantity / 10000;
                small = Math.Floor(small);
                return (int)(small * 10000);
            }
            if (inQuantity > 2000)
            {
                decimal small = inQuantity / 1000;
                small = Math.Floor(small);
                return (int)(small * 1000);
            }
            if (inQuantity > 200)
            {
                decimal small = inQuantity / 100;
                small = Math.Floor(small);
                return (int)(small * 100);
            }
            if (inQuantity > 20)
            {
                decimal small = inQuantity / 10;
                small = Math.Floor(small);
                return (int)(small * 10);
            }
            return inOddLotQuantity;
        }
       
        
    }
    
    public class CustomFeeModel : IFeeModel
    {
        public decimal GetOrderFee(Security security, Order order)
        {
            decimal fee = order.AbsoluteQuantity*0.01m;
            if (fee<5)
            {
            	fee=5;
            }
            if (fee>10)
            {
            	fee=10;
            }
            return fee;
        }
    }
    
    class CustomSecurityInitializer : BrokerageModelSecurityInitializer
    {
        private readonly IFeeModel _customFeeModel;

        public CustomSecurityInitializer(IBrokerageModel brokerageModel, IFeeModel customFeeModel)
            : base(brokerageModel)
        {
            _customFeeModel = customFeeModel;
        }

        public override void Initialize(Security security)
        {
            // first call the default implementation
            base.Initialize(security);

            // now apply our fee model
            security.FeeModel = _customFeeModel;
        }
    }
}