def fetchExpirationDate(self, dateUrl, date):
     # date as epoch time
     today = datetime.datetime.utcnow()
     optionSet = []
     print("Fetching {0}".format(dateUrl))
     with urllib.request.urlopen(dateUrl) as response:
         html = response.read()
     d = json.loads(html)
     calls = d['optionChain']['result'][0]['options'][0]['calls']
     puts = d['optionChain']['result'][0]['options'][0]['puts']
     for put in puts:
         option = Option(self.stock, OptionType.PUT, put['strike'], put['lastPrice'], put['ask'], put['bid'], today)
         option.setExpirationDate(date)
         option.setApr()
         optionSet.append(option)
     for call in calls:
         option = Option(self.stock, OptionType.CALL, call['strike'], call['lastPrice'], call['ask'], call['bid'],
                         today)
         option.setExpirationDate(date)
         option.setApr()
         optionSet.append(option)
     return optionSet
    def fetchdata(self, stock):
        #pprint(self._config)
        self.stock = stock
        urlParams = {
            'apikey': self._config['tda_api_key'],
            'symbol': stock.getSymbol(),
            'contractType': "PUT",
            'range': 'OTM',
            'OptionType': 'S'
        }
        url = self._baseUrl + urllib.parse.urlencode(urlParams)

        args = urllib.parse.urlencode(urlParams).encode("utf-8")
        headers = {}
        useAccessToken = True
        if useAccessToken == True:
            headers = {
                "Authorization":
                "Bearer {0}".format(self._config['access_token'])
            }

        request = urllib.request.Request(url, headers=headers, method='GET')

        #pprint(request.get_full_url())
        #pprint(request.headers)
        #pprint(request.data)
        #pprint(request.get_method())

        try:
            response = urllib.request.urlopen(request)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                print("v" * 20)
                print("Error occurred fetching {0}".format(
                    request.get_full_url()))
                print(e)
                print("off to fetch new tokens")
                print("^" * 20)
                self.refreshToken()
        else:
            html = response.read()
            d = json.loads(html)

            self.stock.setUnderlyingPrice(d['underlyingPrice'])

            putExpDateMap = d['putExpDateMap']
            putExpDates = putExpDateMap.keys()
            today = datetime.datetime.utcnow()

            optionSet = []
            for expiryDays in putExpDates:
                date, days = expiryDays.split(':')
                pattern = '%Y-%m-%d'
                epoch = int(time.mktime(time.strptime(date, pattern)))
                # todo this is in localtime. Probably is supposed to be 4pm est
                # todo this is just a hack...
                tmp = epoch // 86400
                epoch = tmp * 86400

                thisDateMap = putExpDateMap[expiryDays]
                for strike in thisDateMap.keys():
                    bid = thisDateMap[strike][0]['bid']
                    ask = thisDateMap[strike][0]['ask']
                    last = thisDateMap[strike][0]['last']
                    option = Option(self.stock, OptionType.PUT, float(strike),
                                    last, ask, bid, today)
                    option.setExpirationDate(epoch)
                    option.setApr()
                    optionSet.append(option)

            return optionSet