Overall Statistics
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 = "IMI";
        int _quantity;
        decimal _pct;
        decimal _stopPct;
        bool trigger = false;
        bool first = true;
        bool notif = true;
        static string globalString;
        static decimal _globalSkim;
        static decimal timeFrame;
 		static decimal _symPrice;
        static readonly decimal EqualWeightPercentage = 1m/3;

        //DateTime lastTradeTime;
        //DateTime dayTime;
        //bool boolstate = false;
        
        public override void Initialize()
        {
            SetBrokerageModel(BrokerageName.TradierBrokerage, AccountType.Cash);
           	
           	//set date for backtesting
            SetStartDate(2016, 03, 7);         
            SetEndDate(DateTime.Now.Date.AddDays(-1));

            SetCash(2750);
            
            //returns five percent of investible cash
            var fivePct = Portfolio.Cash/3 * .025m;
            var threePct = Portfolio.Cash/3 * .03m;
			
			//set global variable from local variable
            _pct = threePct;
            //set stop percentage equal to one third of cash minus previous value
            _stopPct = Portfolio.Cash/3 - fivePct;

            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.FromMinutes(1));
			consolidator.DataConsolidated += MinHandler;
			SubscriptionManager.AddConsolidator(symbol, consolidator);
			
			/*TradeBarConsolidator dayconsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1));
			dayconsolidator.DataConsolidated += DayHandler;
			SubscriptionManager.AddConsolidator(symbol, dayconsolidator);*/
			
        }
        public void MinHandler(object sender, TradeBar data) {
    	// handle each minute here
    	if (_symPrice > timeFrame)
    		{
    			timeFrame = data.High;
    			//Log("" + timeFrame);
    		}
        }
        
        /*public Maximum MAX(Symbol symbol)
        {
        var maxi = symbol.Price;
      	return;
        }*/
        	
        /*}
        public void DayHandler(object sender, TradeBar data) {
    	// handle day data
    	//lastTradeTime = data.Time;
    	}*/
        
        public void OnData(TradeBars data) 
        {   

        	/*if (Time - lastTradeTime.Date < TimeSpan.FromDays(1));
            {
                //only trade once a day at market open
                return;
                
            }

            Log("" + Time);*/
            var hi = data[symbol].High;
            Log("" + hi);

        	TimeSpan elapsedTime = new TimeSpan(0,3,0);

        	Schedule.Event()
    		.EveryDay(symbol)
    		.Every(elapsedTime)
    		.Run(() =>
    		{
    		Notify.Sms("+15126454560", "Update " + globalString);
    		});
    		
     		// update high price every minute
            var highPrice = _quantity * timeFrame;
        	var newStopLoss = highPrice * .03m;
        	var newStopLosss = newStopLoss * .10m;
        	
        	var highPriceStop = newStopLoss - newStopLosss;
        	var currentPriceStop = _globalSkim *.03m;
            
            var symPrice = data[symbol].Price;
            _symPrice = symPrice;
            
            var 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());
            //Decimal.ToInt32(readableProfits));
            
            globalString = messageString;
            
                //int quantity = (int)Math.Floor(Portfolio.Cash / data[symbol].Close / 3);
                var equalWeightedPorfolioSize = Portfolio.TotalPortfolioValue/3;
                var shareCount = CalculateOrderQuantity(symbol, EqualWeightPercentage);
                if (first)
					{
						first = false;
					Order(symbol,  shareCount, tag: "Order Target Value: $" + Math.Round(equalWeightedPorfolioSize, 2));
                    Notify.Sms("+15126454560", "Buy " + messageString);
					}
                
                var holdings = Portfolio[symbol].Quantity;
                _quantity = holdings;
                var skimProfits = holdings * symPrice;
                _globalSkim = skimProfits;
            
			if (Portfolio.HoldStock)
			{
            // set trigger equal to true if profits are greater than 3 percent of invested portfolio cash
            if (readableProfits > _pct)
            {
            trigger = true;
            //Order(symbol, -_quantity);
            if(notif)
            	{
            	notif = false;
            	Notify.Sms("+15126454560", "The trigger price has been reached!" + globalString);
            	}
        	}
        	//sell if profits go below high profit stop	
        	if (trigger == true && currentPriceStop < highPriceStop)
        	{
        		Notify.Sms("+15126454560", "Gain Sell " + globalString);
        		//Log("h" + highPriceStop);
                //Log("c" + currentPriceStop);
        		Order(symbol, -_quantity);
        	}
        	
        	// sell if profits go below 5% invested portfolio cash
            if (_globalSkim < _stopPct)
            {
            	Notify.Sms("+15126454560", "Loss Sell " + globalString);
            	Order(symbol, -_quantity);
            }
            
            // sell on close
            Schedule.Event()
    		.EveryDay(symbol)
    		.BeforeMarketClose(symbol, 1)
    		.Run(() =>
    		{
    			Notify.Sms("+15126454560", "End Of Day Sell " + globalString);

    			Order(symbol, -_quantity);
    			
    		});
			}
        }
    }
}