Overall Statistics
Total Trades
36
Average Win
0.05%
Average Loss
-0.19%
Compounding Annual Return
-99.999%
Drawdown
3.100%
Expectancy
-0.809
Net Profit
-3.097%
Sharpe Ratio
-11.225
Loss Rate
85%
Win Rate
15%
Profit-Loss Ratio
0.27
Alpha
-7.805
Beta
24.643
Annual Standard Deviation
0.348
Annual Variance
0.121
Information Ratio
-12.175
Tracking Error
0.334
Treynor Ratio
-0.158
Total Fees
$159.61
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using QuantConnect.Data;
using System.Net;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// Basic template algorithm simply initializes the date range and cash. This is a skeleton
    /// framework you can use for designing an algorithm.
    /// </summary>
    public class BasicTemplateAlgorithm : QCAlgorithm
    {
    	//Variables to hold data and statuses
        Dictionary<string, double> _PLB_List = new Dictionary<string, double>();
        Dictionary<string, double> _PHB_List = new Dictionary<string, double>();
        Dictionary<string, double> _15M_List = new Dictionary<string, double>();
        Dictionary<string, double> _PDLH_List = new Dictionary<string, double>();
        Dictionary<string, double> _Days_Low_List = new Dictionary<string, double>();
        Dictionary<string, double> _Days_High_List = new Dictionary<string, double>();
        Dictionary<string, double> _MOC_List = new Dictionary<string, double>();
        Dictionary<string, double> _Entry_List = new Dictionary<string, double>();
        Dictionary<string, OrderTicket> _OrderTicket_List = new Dictionary<string, OrderTicket>();
        Dictionary<string, Symbol> _SymLst = new Dictionary<string, Symbol>();
        
        string tickersString;
        // List<SymbolData> _listData=new List<SymbolData>();
        Dictionary<string, SymbolData> _listData = new Dictionary<string, SymbolData>();
        
        //Hold list of symbols from CSV
        Dictionary<string, int> _SymbolList = new Dictionary<string, int>();
        List<string> _SymbolTypeList = new List<string>();
        
        //double _PerSYmbolCash = 0;
        int _SymbolCount = 0;
        int _SymbolQty=0;
        //Flag indicating whether MarketOnOpen order placed
        bool isMOOPlaced=false;
        
        //  //Flag indicating whether Initial Stop Loss order placed
        // bool isInitStopLossPlaced=false;
        
        //  //Flag indicating whether Adjusted Stop Loss order placed
        // bool isASLPlaced=false;
        
        //Flag indicating whether Market On Close order placed
        bool isMOCPlaced=false;
        
        string[] _sym = { "BSMX" };//"YRCW","HIMX","VMC","VSTO"
        string[] _symTim = { "10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30", "11:45", "12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30", "13:45", "14:00", "14:15", "14:30", "14:45", "15:00" };

        // bool marketStart = true;
        // bool openOrderPlaced = false;
        
        decimal BuyingPower=0;
        decimal LeverageFactor=0;
        int OrderSize=0;
        //decimal AdjBP=0;
        
        //Portfolio.Cash.ToString()
        // The first event where we need to Initialize the things
        public override void Initialize()
        {
        	//Set date range for getting data 																																	
           //  SetStartDate(DateTime.Now);
           //SetEndDate(DateTime.Now);
            SetStartDate(2017,10,13);
            SetEndDate(2017,10,13);
            SetBrokerageModel(BrokerageName.Default, AccountType.Margin);
            
            //Set cash for trading
            SetCash(100000);
           
          
           
           	//Initiate symbol listing from a CSV
            ReadSymbolsFromCSV();
            
            //Buying variables 
            LeverageFactor=3M;
            BuyingPower=Portfolio.Cash*LeverageFactor;
           if(_SymbolCount<20)
           {
           	BuyingPower=(_SymbolCount*BuyingPower)/20;
           }
           
            OrderSize =Convert.ToInt32(BuyingPower / _SymbolCount);
            Debug("Portfolio.Cash => "+Portfolio.Cash+",BuyingPower=> "+BuyingPower+" ,Order SIze=> "+OrderSize);
            
            //SetCash(BuyingPower);
            //Initialize all variables with data
            InitializeIndicators();
            
            //Schedule an event to run at 9:14 everyday to submit MOO Orders
            Schedule.Event().EveryDay().At(9, 15).Run(() =>
            {
                Debug("Send MOO 15 mins earlier before market opens 9:15 =>"+ DateTime.Now.ToString());
                PlaceMOOOrders();
                isMOOPlaced=false;
            });

			//Schedule an event to run at 3:44 everyday to submit MOC Orders
            Schedule.Event().EveryDay().At(15, 44).Run(() =>
            {
                Debug("Send MOC 15 mins earlier before market close =>"+ DateTime.Now.ToString());
                PlaceMOCOrders();
                isMOCPlaced=false;
            });
        }
       
       //Read symbol listing from a CSV file uploaded over an FTP
       public void ReadSymbolsFromCSV(){
            //string url = @"http://vishal-test.softwaregenius.net/QuantData_Org.csv";
            string url = @"ftp://ifinancialtech.com/ift_Trading.csv";

            using (var client = new WebClient{Credentials = new NetworkCredential("softgen@ifinancialtech.com", "Softgen#123"),})
            {
                tickersString = client.DownloadString(url);
                string[] data = tickersString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                int i = 1;
                while (i< data.Count())
                {
                	string[] item=data[i].Split(',');
                	//Debug("Symbol read =" + item);
                    _SymbolList.Add(item[0].Trim(), i);
                    _SymbolTypeList.Add(item[1].Trim());
                   
                    _OrderTicket_List[item[0].Trim()]=null;
                    SymbolData _data = new SymbolData();
                    _data._Symbol=item[0].Trim();
                    _data._Type=item[1].Trim();
                    _listData[item[0].Trim()]=_data;
                     i = i + 1;
                    _SymbolCount++;
                    //Debug("Order Ticket For "+item+"=>"+_OrderTicket_List[item]);
                }
            }
            //_SymbolList.Add("HIMX", 0);
           //_SymbolList.Add("YRCW", 0);
           //_SymbolList.Add("HIMX", 1);
           //_SymbolList.Add("WFT", 2);
           //_SymbolList.Add("VMC", 3);
           //_SymbolList.Add("VSTO", 4);
          //_SymbolList.Add("SBRA", 5);
          //_SymbolList.Add("OMI", 6);
          //_SymbolList.Add("NUVA", 7);
   //        SymbolData _data = new SymbolData();
   //          _data._Symbol="HIMX";
   //          _data._Type="L";
   //          _listData["HIMX"]=_data;
			// _SymbolCount=1;
            UniverseSettings.Resolution = Resolution.Second;
           // UniverseSettings.Leverage=4M;
       }
       
       //Initialize all variables with data
       public void InitializeIndicators() {
       	#region "Get the Data for PLB,PHB,PDLH"
            foreach (var item in _SymbolList)
            {
            	Debug("Int=>"+item.Key);
                //AddEquity(item.Key, Resolution.Minute);
                 AddSecurity(SecurityType.Equity, item.Key, Resolution.Minute);
                 Securities[item.Key].SetLeverage(4M);
                Securities[item.Key].FeeModel = new InteractiveBrokersFeeModel();
                // //Get the Data for PLB,PHB,PDLH
                 FillStartData(item.Key);
                
                // //Calculate Rng Low, Rng High, Entry point
                // _listData[item.Key] = (CalculateData(item.Key));
                
            }
            
            #endregion
       }
       
       //Place MOO orders
       public void PlaceMOOOrders(){
       	//Check for MOO, if not, place MOO
        	if (!isMOOPlaced)
        	{
        		string _sym="";
        		foreach(var symb in _SymbolList){
        			// 
        			_sym=symb.Key;
        			_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(_Entry_List[_sym]));
        			//_SymbolQty=CalculateOrderQuantity(_sym, 3m);
        			// Debug("Symbol Buying power=>"+Portfolio.GetBuyingPower(_sym));
        			// Debug("Margin For Symbol=>"+Portfolio.GetMarginRemaining(_sym,OrderDirection.Buy));
        			//Debug("_Entry_List[_sym]=>"+_Entry_List[_sym]);
        			if(_listData[_sym]._Type=="S")
        			{
        				_SymbolQty=-Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundUp(_Entry_List[_sym])));
        			}
        			else
        			{
        				_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundDown(_Entry_List[_sym])));
        			}
        			//	_OrderTicket_List[symb.Key] =
        			_SymbolQty=1000;
        		MarketOnOpenOrder(symb.Key, _SymbolQty, tag: "MOO " +_sym);
                   Debug("Market On Open Order place for " + symb.Key+" at "+_Entry_List[_sym]+" and Qty=>"+_SymbolQty);
        		}
        		//System.Threading.Thread.Sleep(300000);
        		isMOOPlaced=true;
        	}
        	//Debug("Place MOO Orders called");
        	//MarketOnOpenOrder("SPY",1,tag:"SPY");
       }
       
       //Place MOC Orders
       public void PlaceMOCOrders(){
       	if (!isMOCPlaced)
        	{
        			string _sym="";
        		foreach(var item1 in _SymbolList){
        			 #region "Market-On-Close (MOC) Logic"
                        
                        if (_OrderTicket_List[item1.Key].Status != OrderStatus.Filled)
                        {
                        //	Debug("Sending MOC order for "+item1.Key);
                            //_OrderTicket_List[item1.Key] =
                            	_sym=item1.Key;
                            //_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(_Entry_List[_sym]));
                            //_SymbolQty=CalculateOrderQuantity(_sym, 3m);
                            if(_listData[_sym]._Type=="L")
			        			{
			        				_SymbolQty=-Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundUp(_Entry_List[_sym])));
			        			}
			        			else
			        			{
			        				_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundDown(_Entry_List[_sym])));
			        			}
                            MarketOnCloseOrder(item1.Key,_SymbolQty, tag: "Market-On-Close order");
                             Debug("Market On close Order place for " + _sym +" at 3:44");
                        }
                        
                    #endregion
        		}
        	}
       }
       //decimal _Every15MinuteLow=0;
        //Event fired when data arrieves
        public void OnData(TradeBars bars)
        {
        	//Debug("Start");
        	//Debug("OnData called-Count = " + bars.Count);
        	if (bars.Count>0 ) {
        	
	        	foreach(KeyValuePair<Symbol, TradeBar> bar in bars){
	        	//Debug("End at "+bar.Value.Time.ToString("H:mm"));
	        	if(bars.ContainsKey(bar.Key))
	        	{
	        			
	        		
	        		//Debug(" ==> Bar Time :"+bar.Value.Time+" Symbol="+bar.Key);
	        		//Print 15 minute Low value for comparision
	        		// if (bar.Value.Time.ToString("H:mm") == "9:30")
	        		// {
	        		// 	_Every15MinuteLow=bars[bar.Key].Low;
	        		// }
	        		// if(bars[bar.Key].Low<_Every15MinuteLow)
	        		// {
	        		// 	_Every15MinuteLow=bars[bar.Key].Low;
	        		// }
	        		
	        		// if (bar.Value.Time.ToString("H:mm") == "9:45" || bar.Value.Time.ToString("H:mm") == "9:45" || Array.Exists(_symTim, element => element == bar.Value.Time.ToString("H:mm")))
	          //      {
	          //      	//Debug("Low in 15 Minute range "+_Every15MinuteLow);
	          //      	//Debug("15 Minute Low at "+bar.Value.Time.ToString("H:mm")+" is "+bars[bar.Key].Low.ToString());
	          //      }
	        		#region "Initial stop loss order Logic"
			
					//Debug("Inside initial stop loss");
					//Debug(bar.Value.Time.ToString("H:mm"));
					if (bar.Value.Time.ToString("H:mm") == "9:30" ||bar.Value.Time.ToString("H:mm") == "9:31"||bar.Value.Time.ToString("H:mm") == "9:32"){
					
						//Debug("Inside initial stop loss condition");
						//Debug("_listData[bar.Key]._Entry"+_listData[bar.Key]._Entry.ToString());
						//Debug("Convert.ToDouble(bar.Value.Open)"+Convert.ToDouble(bar.Value.Open).ToString());
						//SymbolData sysData = new SymbolData();
						//_listData[bar.Key]._Entry = Convert.ToDouble(bar.Value.Open);
						if(_listData[bar.Key]._Type=="S")
		        		{
		        			_listData[bar.Key]._Entry =RoundUp(Convert.ToDouble(bar.Value.Open));
		        		}
		        		else
		        		{
		        			_listData[bar.Key]._Entry = RoundDown(Convert.ToDouble(bar.Value.Open));
		        		}
						
						//sysData._Symbol = bar.Key;
						
						
                	
		                //Calculate Rng Low, Rng High, Entry point
		                _listData[bar.Key] = (CalculateData(_listData[bar.Key]));
		                
                		if(_OrderTicket_List[bar.Key]==null)
                		{
                		if( _listData[bar.Key]._Entry> _listData[bar.Key]._Rng_Low &&  _listData[bar.Key]._Entry< _listData[bar.Key]._Rng_High)
						{
							//Debug("Setting initial stop loss");
							#region "Calculate Exit on market start,Initial stop loss order"
							
							_listData[bar.Key]._Exit = CalcExitStart(_listData[bar.Key]);
							//_SymbolQty=Convert.ToInt32((OrderSize/Convert.ToDecimal(_listData[bar.Key]._Exit)));
							//_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(_Entry_List[bar.Key]));
								//_SymbolQty=CalculateOrderQuantity(bar.Key, 3m);
								if(_listData[bar.Key]._Type=="L")
			        			{
			        				_SymbolQty=-Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundUp(_Entry_List[bar.Key])));
			        			}
			        			else
			        			{
			        				_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundDown(_Entry_List[bar.Key])));
			        			}
									// Debug("Symbol Buying power=>"+Portfolio.GetBuyingPower(bar.Key));
        						// Debug("Margin For Symbol=>"+Portfolio.GetMarginRemaining(bar.Key,OrderDirection.Sell));
        						Debug("Entry=>"+_listData[bar.Key]._Entry+" ,1% Loss=>"+_listData[bar.Key]._P1_Loss+" ,2% Loss=>"+_listData[bar.Key]._P2_Loss+" ,3% Loss=>"+_listData[bar.Key]._P3_Loss+" ,1/2 Percent Range=>"+_listData[bar.Key]._P1_By_4+" ,PDL=>"+_listData[bar.Key]._PDL_H);
							Debug("Sending (initial) StopMarketOrder for "+ bar.Key + " with Entry value="+_listData[bar.Key]._Entry+" and Exit value="+_listData[bar.Key]._Exit+",Qty=>"+_SymbolQty+" at time=>"+bar.Value.Time.ToString("H:mm"));
							_OrderTicket_List[bar.Key] = StopMarketOrder(bar.Key,_SymbolQty, Convert.ToDecimal(_listData[bar.Key]._Exit), tag: "initial stop loss order placed at "+bar.Value.Time.ToString());
							#endregion
						}
						else
						{
							// Debug("Placing market orders for out of range positions.");
							// Debug("Symbol Buying power=>"+Portfolio.GetBuyingPower(bar.Key));
        						Debug("Margin For Symbol=>"+Portfolio.GetMarginRemaining(bar.Key,OrderDirection.Sell));
								if(_listData[bar.Key]._Type=="L")
			        			{
			        				_SymbolQty=-Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundUp(_Entry_List[bar.Key])));
			        			}
			        			else
			        			{
			        				_SymbolQty=Convert.ToInt32(OrderSize/Convert.ToDecimal(RoundDown(_Entry_List[bar.Key])));
			        			}
							_OrderTicket_List[bar.Key] = MarketOrder(bar.Key,_SymbolQty);
						}
						}
					}
				#endregion
				
					#region "Adjusted Stop-Loss"
	                if (bar.Value.Time.ToString("H:mm") == "9:45" && _OrderTicket_List[bar.Key].Status != OrderStatus.Filled && _listData[bar.Key]._Exit>=0 && _OrderTicket_List[bar.Key].OrderId>0)//&& _OrderTicket_List[bar.Key]!=null
	                {
						//Debug("Order Status at 9:45=>"+_OrderTicket_List[bar.Key].Status);
	                    //Debug("Updating Adj STop Loss for"+_OrderTicket_List[bar.Key].OrderId);
	                        #region "Calculate exit at 15 Minute and 1 second"
	                        
	                        if(_listData[bar.Key]._Type=="S")
			        		{
			        			_listData[bar.Key]._T15_Min = RoundUp(Convert.ToDouble(bars[bar.Key].Low));
			        		}
			        		else
			        		{
			        			_listData[bar.Key]._T15_Min = RoundDown(Convert.ToDouble(bars[bar.Key].Low));
			        		}
							//_listData[bar.Key]._T15_Min=Convert.ToDouble(_Every15MinuteLow);
	                        _listData[bar.Key]._Exit = CalcExit_15Minute(_listData[bar.Key]);
	                        #endregion
	                        Debug("Adjusted Stop Loss and order submission=>"+bar.Key + " with exit price="+ _listData[bar.Key]._Exit);
	                        //Debug(_OrderTicket_List[bar.Key].OrderId+"<=>"+_listData[bar.Key]._Exit);
	                        //Debug("Symbol Buying power=>"+Portfolio.GetBuyingPower(bar.Key));
        					//Debug("Margin For Symbol=>"+Portfolio.GetMarginRemaining(bar.Key,OrderDirection.Sell));
	                        Debug("Sending (Adjusted) StopMarketOrder for "+ bar.Key + " with Entry value="+_listData[bar.Key]._Entry+" and Exit value="+_listData[bar.Key]._Exit+" at time=>"+bar.Value.Time.ToString("H:mm"));
	                        _OrderTicket_List[bar.Key].Update(new UpdateOrderFields { StopPrice = Convert.ToDecimal(_listData[bar.Key]._Exit)});		
	  				}
		        	#endregion
		        	
		        	#region "Multi-Adjusted Stop-Loss order Logic"
	                if (Array.Exists(_symTim, element => element == bar.Value.Time.ToString("H:mm")) && _OrderTicket_List[bar.Key].Status != OrderStatus.Filled)
	                {
	                	// Debug("Time in Multi-Adjusted Time range : " + bar.Value.Time.ToString("H:mm") + " for position="+bar.Key+"("+ _OrderTicket_List[bar.Key].OrderId+ ") and status="+_OrderTicket_List[bar.Key].Status);
	                	
	                    	#region "Calculate exit at 15 Minute and 1 second"
	                        if(_listData[bar.Key]._Type=="S")
			        		{
			        			_listData[bar.Key]._T15_Min = RoundUp(Convert.ToDouble(bars[bar.Key].Low));
			        		}
			        		else
			        		{
			        			_listData[bar.Key]._T15_Min = RoundDown(Convert.ToDouble(bars[bar.Key].Low));
			        		}
			        		//_listData[bar.Key]._T15_Min=Convert.ToDouble(_Every15MinuteLow);
	                        #endregion
	                        #region "Stop Loss  Order"
	                        
	                        if (_listData[bar.Key]._T15_Min < _listData[bar.Key]._P2_Loss && _listData[bar.Key]._Exit>=0 && _OrderTicket_List[bar.Key].OrderId>0)//&& _listData[bar.Key]._Exit > _listData[bar.Key]._P2_Loss
	                        {
	                        // Debug("Multi-Adjusted for "+bar.Key+" at "+bar.Value.Time.ToString("H:mm")+"=>15 Minute Low=>"+_listData[bar.Key]._T15_Min+" and 2% loss=>"+_listData[bar.Key]._P2_Loss);
	                        //Debug("Updating Multi-Adjusted for"+_OrderTicket_List[bar.Key].OrderId);
	                        _listData[bar.Key]._Exit=_listData[bar.Key]._T15_Min-0.01;
	                        // Debug("Symbol Buying power=>"+Portfolio.GetBuyingPower(bar.Key));
        					// Debug("Margin For Symbol=>"+Portfolio.GetMarginRemaining(bar.Key,OrderDirection.Sell));
	                        Debug("Multi-Adjusted for "+bar.Key+" at "+bar.Value.Time.ToString("H:mm")+"=>15 Minute Low=>"+_listData[bar.Key]._T15_Min+" and 2% loss=>"+_listData[bar.Key]._P2_Loss);
	                        Debug("Sending (Multi-Adjusted) StopMarketOrder for "+ bar.Key + " with Entry value="+_listData[bar.Key]._Entry+" and 15 minute Low value="+Convert.ToDecimal(_listData[bar.Key]._T15_Min - 0.01)+" and 2% loss=>"+_listData[bar.Key]._P2_Loss+" at time=>"+bar.Value.Time.ToString("H:mm"));
	                        _OrderTicket_List[bar.Key].Update(new UpdateOrderFields { StopPrice = Convert.ToDecimal(_listData[bar.Key]._T15_Min - 0.01),Tag="Multi-Adjusted Stop Loss order Updated at"+bar.Value.Time.ToString() });		
	                        }
	                   
	                    #endregion
	                }
		            #endregion
	        	}
	        	}
        	}
       
        }
        
        public override void OnOrderEvent(OrderEvent fill)
        {
        	
            var order = Transactions.GetOrderById(fill.OrderId);
            //if(order.Type!=OrderType.MarketOnOpen)
            {
            	 //Debug("Got order Status for OrderId="+fill.OrderId + "- Time="+ Time + " - Order Type=" + order.Type + " - Order Status=>" + fill.Status+"-Tag=>"+order.Tag+"-Price=>"+order.Price+"-Duration=>"+order.Duration+"-Fill Price=>"+fill.FillPrice);
            string sym=fill.Symbol;
			Debug("Symbol=>"+fill.Symbol+",Stop Price=>"+_listData[sym]._Exit+"-Fill Price=>"+fill.FillPrice+ " - Order Status=>" + fill.Status+ " - Order Type=" + order.Type);
			List<Order> openOrders = Transactions.GetOpenOrders();
			//List<Order> openOrders = Transactions.GetOrders(x => x.Status.IsOpen()).ToList();
			foreach(var opnOrd in openOrders){
			//Debug("Open order=>"+opnOrd.Id);
            }
           //GetOrderFee(Security security, Order order)
           if(fill.Status==OrderStatus.Filled)
           {
           	var feesPerShare=Securities[fill.Symbol].FeeModel.GetOrderFee(Securities[fill.Symbol], order)/order.Quantity;
           	Debug("Order Fee for Symbol "+fill.Symbol+" for fill price "+fill.FillPrice+" Fess/share=>"+feesPerShare+" For Total Shares=>"+order.Quantity);
           	Debug(_listData[fill.Symbol]._Symbol+","+_listData[fill.Symbol]._PLB+","+_listData[fill.Symbol]._PHB+","+_listData[fill.Symbol]._Rng_Low+","+_listData[fill.Symbol]._Rng_High+","+_listData[fill.Symbol]._Entry+","+_listData[fill.Symbol]._T15_Min+","+_listData[fill.Symbol]._P1_Loss+","+_listData[fill.Symbol]._PDL_H+","+_listData[fill.Symbol]._P1_By_4+","+_listData[fill.Symbol]._P2_Loss+","+_listData[fill.Symbol]._Exit+","+fill.FillPrice);
           	Debug("Completed Orders for "+fill.Symbol+" AbsoluteQuantity=>"+fill.FillQuantity+"Quantity=>"+order.Quantity+",Portfolio[]=>"+Portfolio[fill.Symbol].Quantity);
           }
           if(fill.Status==OrderStatus.PartiallyFilled)
           {
           	Debug("PartiallyFilled Order for "+fill.Symbol+" AbsoluteQuantity=>"+order.AbsoluteQuantity+"Quantity=>"+order.Quantity+",Portfolio[]=>"+Portfolio[fill.Symbol].Quantity);
           }
           
			}
    
            // foreach (var item in _SymbolList)
            // {
            //     if (_OrderTicket_List[item.Key] != null)
            //     {
            //         //Plot("Order Ticket",item.Key,Portfolio[item.Key].Price);
            //         if (_OrderTicket_List[item.Key].Status != OrderStatus.Filled)
            //         {
            //             Plot("Order tickersString", "stop loss order", _OrderTicket_List[item.Key].Get(OrderField.StopPrice));
            //         }
            //     }
            // }

        }
        public override void OnEndOfDay(Symbol symbol)
		{
			// string sym="";
			// 	foreach(var item1 in _SymbolList){
			// 		sym=item1.Key;
			// 		Debug("End day order status for Symbol=>"+sym+",Order status=>"+_OrderTicket_List[sym].Status);
			// 	}
		  Liquidate(symbol);
		}

        //Get the Data for PLB,PHB,PDLH
        public void FillStartData(string _symbol)
        {
        	//_listData[_symbol] = new SymbolData();
        	_listData[_symbol]._Exit=0;
        	//Get History data for 3 days
            IEnumerable<TradeBar> bars = History(_symbol, TimeSpan.FromDays(4), Resolution.Daily);
            //Debug("Bar counts in FillStartData="+ bars.Count());
            int i = 1;
            foreach (TradeBar item in bars)
            {
            	//Debug("FillStartData Bar="+item.Time);
                switch (i)
                {
                    case 1:
                    	if(_listData[_symbol]._Type=="S")
	        			{
	        				_PDLH_List[_symbol] = Convert.ToDouble(item.High);
	        			}
	        			else
	        			{
	        				_PDLH_List[_symbol] = Convert.ToDouble(item.Low);	
	        			}
                        
                        break;
                    case 2:
                        if (Convert.ToDouble(item.Open) < Convert.ToDouble(item.Close))
                        {
                            _PLB_List[_symbol] = Convert.ToDouble(item.Open);
                            _PHB_List[_symbol] = Convert.ToDouble(item.Close);

                        }
                        else
                        {
                            _PLB_List[_symbol] = Convert.ToDouble(item.Close);
                            _PHB_List[_symbol] = Convert.ToDouble(item.Open);
                        }
						if(_listData[_symbol]._Type=="S")
	        			{
	        				if (_PDLH_List[_symbol] < Convert.ToDouble(item.High))
	                        {
	                            _PDLH_List[_symbol] = Convert.ToDouble(item.High);
	                        }
	        			}
	        			else
	        			{
	        				if (_PDLH_List[_symbol] > Convert.ToDouble(item.Low))
	                        {
	                            _PDLH_List[_symbol] = Convert.ToDouble(item.Low);
	                        }
	        			}
                        
                         _Entry_List[_symbol]=Convert.ToDouble(item.Close);
                        break;
                    // case 3://Get the values for DayLow,DayHigh,MOC for current day
                    //     _Days_Low_List[_symbol] = Convert.ToDouble(item.Low);
                    //     _Days_High_List[_symbol] = Convert.ToDouble(item.High);
                    //     _MOC_List[_symbol] = Convert.ToDouble(item.Close);
                    //     //_Entry_List[_symbol] = Convert.ToDouble(item.Open);
                    //     break;
                }
                i = i + 1;
            }
        }
        
        //Get the data for 15 Minute
        public void FillData_15M(string _symbol)
        {
            IEnumerable<TradeBar> barsM = History(_symbol, 390, Resolution.Minute);
            int i = 1;
            foreach (TradeBar item in barsM)
            {
                if (i == 16)
                {
                    _15M_List[_symbol] = Convert.ToDouble(item.Low);
                    /*	Debug("=============15 Minute Initialize================");
                        Debug("Symbol "+item.Symbol.ToString());
                        Debug("Time "+item.Time.ToString());
                        Debug("Open "+item.Open.ToString());
                        Debug("High "+item.High.ToString());
                        Debug("Low "+item.Low.ToString());
                        Debug("Close "+item.Close.ToString());
                        Debug("I "+i.ToString());
                        Debug("-----------------------------");*/
                }
                i = i + 1;
            }
        }
        
        public SymbolData CalculateData(SymbolData _data)
        {
            //SymbolData _data = new SymbolData();
            //_data._Symbol = _symbol.ToString();
            _data._PLB = _PLB_List[_data._Symbol];
            _data._PHB = _PHB_List[_data._Symbol];

            //_data._Entry = _Entry_List[_data._Symbol];
            _data._Days_Low = 0; //_Days_Low_List[_symbol];
            _data._Days_High = 0; // _Days_High_List[_symbol];
            _data._T15_Min = 0;//_15M_List[_symbol];
            _data._PDL_H = _PDLH_List[_data._Symbol];
            _data._MOC = 0; //_MOC_List[_symbol];
            //_data._Type = _data._Type;
            _data._ExitVal = 0;
            
            
            if (_data._Type == "L")
            {
            	_data._Rng_Low = RoundDown(Convert.ToDouble(_data._PLB * 0.98));
            	_data._Rng_High = RoundDown(Convert.ToDouble(_data._PHB * 1.03));//Convert.ToDouble(data.PHB * 1.025);
                if (_data._Entry >= 20)
                {
                    //_data._P1_Loss = Math.Round((_data._Entry * 0.99), 2);/
                    _data._P1_Loss = RoundDown((_data._Entry * 0.99));
                }
                else
                {
                    // _data._P1_Loss = Math.Round((_data._Entry * 0.985), 2);
                     _data._P1_Loss = RoundDown((_data._Entry * 0.985));
                }

                // _data._P2_Loss = Math.Round((_data._Entry * 0.98), 2);
                // _data._P3_Loss = Math.Round((_data._Entry * 0.97), 2);
                _data._P2_Loss = RoundDown((_data._Entry * 0.98));
                _data._P3_Loss =RoundDown((_data._Entry * 0.97));

                if (_data._Entry < 20)
                {
                    _data._P1_By_4 = RoundDown((_data._PDL_H * 1.01));
                }
                else
                {
                    _data._P1_By_4 = RoundDown((_data._PDL_H * 1.005));
                }
                //_data._P1_By_4 = (0.01 + (_data._PDL_H * 1.0025));
            }
            else
            {
				_data._Rng_Low = RoundUp(Convert.ToDouble(_data._PLB * 0.98));
            	_data._Rng_High = RoundUp(Convert.ToDouble(_data._PHB * 1.03));//Convert.ToDouble(data.PHB * 1.025);
                // _data._P1_Loss = Math.Round((_data._Entry * 1.01), 2);
                // _data._P2_Loss = Math.Round((_data._Entry * 1.02), 2);
                // _data._P3_Loss = Math.Round((_data._Entry * 1.03), 2);
                _data._P1_Loss = RoundUp((_data._Entry * 1.01));
                _data._P2_Loss = RoundUp((_data._Entry * 1.02));
                _data._P3_Loss = RoundUp((_data._Entry * 1.03));
                _data._P1_By_4 = RoundUp(((_data._PDL_H * 0.9975)));
            }
            
            //Debug("Inside CalculateData : Entry="+_data._Entry+",PDL="+_data._PDL_H+", 1% Loss="+_data._P1_Loss+",2% Loss="+_data._P2_Loss + ", PDL="+_data._PDL_H+ ", 3% Loss="+_data._P3_Loss);
            
            /*_data._Exit = Math.Round(CalcLongExit(_data), 2);
             if (_data._ExitVal != _data._Exit)
               {
                   _data._Exit = 0;
               }*/
            return _data;
        }
        
        public double CalcExit_15Minute(SymbolData item)
        {
        	if(item._Type=="L")
        	{
        		return CalcLongExit_15Minute(item);	
        	}
        	else
        	{
        		return CalcShortExit_15Minute(item);	
        	}
        }
        
        public double CalcLongExit_Start(SymbolData item)
        {
           	//Debug("Calculating exit value for initial stop loss : 2% Loss="+item._P2_Loss + ", PDL="+item._PDL_H+ ", 3% Loss="+item._P3_Loss);
            if (item._P2_Loss < item._PDL_H)
            {
                item._Exit = item._P2_Loss-0.01;
            }
            else
            {
                if (item._PDL_H > item._P3_Loss)
                {
                    item._Exit = item._PDL_H-0.01;
                }
                else
                {
                    item._Exit = item._P3_Loss+0.01;//_P2_Loss
                }
            }
            
           return RoundDown(item._Exit);
        }
        public double CalcLongExit_15Minute(SymbolData item)
        {
            //Step-2
           
            if (item._T15_Min < item._P1_Loss)
            {

                
                if (item._T15_Min > item._P3_Loss)
                {
                    item._Exit = item._T15_Min;
                }
                else
                {
                    item._Exit = item._P3_Loss;
                }

            }
            else
            {
                item._Exit = item._P1_Loss;
            }
             double maxi = 0;
			if (item._PDL_H < item._P2_Loss)
                {
                    if (item._PDL_H > item._P3_Loss)
                    {
                        maxi = item._PDL_H;
                    }
                    else
                    {
                        maxi = item._P3_Loss;
                    }

                }
                else
                {
                    maxi = item._P2_Loss;
                }

            if (item._Exit >= maxi)
            {
                if (item._Exit != item._P3_Loss)
                {
                    if ((item._Exit > item._PDL_H && item._Exit < item._P1_By_4))
                    {
                        item._Exit = item._PDL_H - 0.01;
                    }
                    else
                    {
                        item._Exit = item._Exit - 0.01;
                    }
                }
                else
                {
                    item._Exit = item._P3_Loss + 0.01;
                }
            }
            else
            {
                item._Exit = maxi - 0.01;
            }


            //End Step-2
           return RoundDown(item._Exit);
        }
        public double CalcExitStart(SymbolData item)
        {
        	if(item._Type=="L")
        	{
        		return CalcLongExit_Start(item);	
        	}
        	else
        	{
        		return CalcShortExit_Start(item);	
        	}
        }
        public double CalcShortExit_Start(SymbolData item)
        {	
        	//Step-1
            if (item._P2_Loss > item._PDL_H)
            {
                item._Exit = item._P2_Loss+0.01;
            }
            else
            {
                if (item._PDL_H < item._P3_Loss)
                {
                    item._Exit = item._P3_Loss-0.01;
                }
                else
                {
                    item._Exit = item._PDL_H+0.01;

                }
            }
             return RoundUp(item._Exit);
        }
         public double CalcShortExit_15Minute(SymbolData item)
        {
        	//Step-2
            if (item._Exit != item._P3_Loss)
            {
                if (item._T15_Min > item._P1_Loss)
                {
                    item._Exit = item._T15_Min;
                }
                else
                {
                    item._Exit = item._P1_Loss;
                }
                Double maxi = 0;
                if (item._PDL_H > item._P2_Loss)
                {
                    maxi = item._PDL_H;
                }
                else
                {
                    maxi = item._P2_Loss;
                }
                if (item._Exit > maxi)
                {
                    if (item._Exit < maxi)//&& (item.Exit > item.PDL_H && item.Exit < item.P1_By_4)
                    {
                        item._Exit = item._PDL_H + 0.01;
                    }
                    else
                    {
                        item._Exit = item._P3_Loss - 0.01;
                    }
                }
                else
                {
                    item._Exit = item._Exit + 0.01;
                }
            }
            else
            {
                item._Exit = item._P3_Loss - 0.01;
            }
            return RoundUp(item._Exit);
        }
        public Double RoundDown(Double value)
        {
        	string s1=value.ToString("0.0000");
             s1 = s1.Substring(0, s1.IndexOf(".") + 3);
            //return Math.Floor(value * 100) / 100;
            return Convert.ToDouble(s1);
            //return value;
        }
        public Double RoundUp(Double value)
        {
        	// string s1=value.ToString("0.0000");
        	// Double frac=Convert.ToDouble(s1.Substring(s1.IndexOf("."),2))+0.01;
         //    s1 = s1.Substring(0, s1.IndexOf("."))+frac.ToString();
         //    return Convert.ToDouble(s1);
            //return Math.Ceiling(value * 100) / 100;
            return Math.Round(value,2);
        }

    }
    
}
namespace QuantConnect {

    //
    //	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 SymbolData : BaseData
    {
        public int _SrNo;
        public string _Symbol;
        public double _PLB;
        public double _PHB;
        public double _Rng_Low;
        public double _Rng_High;
        public double _Entry;
        public double _Days_Low;
        public double _Days_High;
        public double _Exit;
        public double _Net;
        public double _T15_Min;
        public double _P1_Loss;
        public double _PDL_H;
        public double _P1_By_4;
        public double _P2_Loss;
        public double _P3_Loss;
        public double _MOC;
        public string _Type;
        public double _ExitVal;
    }
}