0

Ok so I have two questions about the same code:

Question 1)

Say that I make a request. When that request goes past .5 second, I want it to end the current iteration and retry the connection. Basically, if it fails to get a request, I want it to either try again or exit the iteration so that it can try again. How do I do this? So with the code below, after a while, it gives me a "read time out" error. How do I fix this?

import requests
import json
import time
import sys

def calcProfits():  
    url = 'https://api.gdax.com/products/BTC-USD/trades'
    t0 = time.time()  #timer i made to see if the "timeout" works
    res = requests.get(url, timeout = .5) #i want it to retry after 1 second of failing to get a response, is this correct?
    t1 = time.time()
    total_time = round((t1-t0),3)
    json_res = json.loads(res.text)                 
    currDollarBit = float(json_res[0]['price'])  
    sys.stdout.write(str(currDollarBit) + "   ")
    sys.stdout.write(str(total_time) + "\n")
    time.sleep(1)   

while True:
    calcProfits()

Question 2)

So I came across this question and tried to use except. but I still see that the request is passing the 0.5 seconds i set up in the timeout and nothing is happening. eventually, it does a timeout and it says "UnboundLocalError: local variable 'res' referenced before assignment". i guessing that if it timeout, the res variable is completely ignored? Heres the code:

import requests
import json
import time
import sys

def calcProfits():

    url = 'https://api.gdax.com/products/BTC-USD/trades'
    try: 
        t0 = time.time()  #timer i made to see if the "timeout" works
        res = requests.get(url, timeout = .5)
        t1 = time.time()
        total_time = round((t1-t0),3)
    except Exception as e:
        print("\nTIMEOUT\n")
    json_res = json.loads(res.text)                 
    currDollarBit = float(json_res[0]['price'])  
    sys.stdout.write(str(currDollarBit) + "   ")


    sys.stdout.write(str(total_time) + "\n")
    time.sleep(1)   

while True:
    calcProfits()

Anyways how do i fix it so that it just retires after that 0.5 seconds?

Fried
  • 1
  • 3
  • Why not use the [WebSocket API](https://docs.gdax.com/#websocket-feed) and get realtime updates? Continuously polling like this is bound to get you IP banned. – Blender Feb 01 '18 at 00:59
  • WOA i can get Ip banned from GDAX for this? why? I honestly wanted to practice my scraping skills since im new. Wanted to use API once i get te hand of things – Fried Feb 01 '18 at 01:34

0 Answers0