In [ ]:
import numpy as np
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from datetime import datetime, timedelta
from QuantConnect.Data.Market import TradeBar
from clr import AddReference
from QuantConnect.Python import PythonQuandl
from QuantConnect.Securities.Equity import EquityExchange
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")
### <summary>
### Pre market trend algorithm - My first algo 
### </summary>

class preMarketTrend(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2013,1, 2)  #Set Start Date
        self.SetEndDate(2013,1,4)     #Set End Date
        self.SetCash(25000)           #Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Minute
        self.UniverseSettings.Leverage = 4
        self.UniverseSettings.ExtendedMarketHours = True
        self.AddUniverse(self.CoarseSelectionFunction)

        # Find more symbols here: http://quantconnect.com/data
        self.SetBrokerageModel (BrokerageName.InteractiveBrokersBrokerage) # Defaults to margin account
         # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
        self.SetWarmUp(timedelta(1))
        # Create a Rolling Window to keep the 4 decimal
        self.closeWindow = RollingWindow[TradeBar](2)
        
    def CoarseSelectionFunction(self, coarse):
        sortedByVolume = []
        for tickers in coarse:
            if (tickers.Volume > 50000) and (tickers.Price > 7):
                sortedByVolume.append (tickers.Symbol)
        return sortedByVolume

        
    def OnData(self, data):
        #slices = self.History(timedelta(7))
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        # Wait for windows to be ready.
        #if not (self.closeWindow.IsReady): 
        #    return
    
        if self.IsWarmingUp: 
            return             
        
        for stocks in data.Bars:
            #self.closeWindow.Add(data[stocks.Key])            
            stock =  (stocks.Key)
            bars = self.History([stock], timedelta(1), Resolution.Daily)
            closes = []
           
            for index,tradeBar in bars.loc[stock].iterrows():
                closes.append(tradeBar["close"])
            #close = bars["close"] 
            close =  (closes[-1])
            
            if self.Time.hour == 9 and self.Time.minute == 20 :
                price =  (self.Securities[stocks.Key].Price)
                currentVolume = self.Securities[stocks.Key].Volume
                limitOrderTicket = self.LimitOrder(stocks.Key, 400, price)
                if ( (abs (close-price) / close) * 100.0 ) >= 2 :
                    self.Log ("{0}: {1} : {2}".format (stocks.Key, currentVolume, price))
                    limitOrderTicket = self.LimitOrder(stocks.Key, 400, price)