我一直在外汇提供商(OANDA)的练习帐户中构建我自己的python(版本3.2.1)交易应用程序,但我在使用基于Linux debian的操作系统接收流媒体价格方面存在一些问题。
特别是,我遵循了他们的“Python流媒体费率”指南:http://developer.oanda.com/rest-live/sample-code/。
我有一个调用函数'connect_to_stream'的线程,它打印出从服务器收到的所有滴答:
streaming_thread = threading.Thread(target=streaming.connect_to_stream, args=[])
streaming_thread.start()
streaming.connect_to_stream函数定义如下:
def connect_to_stream():
[..]#provider-related info are passed here
try:
s = requests.Session()
url = "https://" + domain + "/v1/prices"
headers = {'Authorization' : 'Bearer ' + access_token,
'Connection' : 'keep-alive'
}
params = {'instruments' : instruments, 'accountId' : account_id}
req = requests.Request('GET', url, headers = headers, params = params)
pre = req.prepare()
resp = s.send(pre, stream = True, verify = False)
return resp
except Exception as e:
s.close()
print ("Caught exception when connecting to stream\n%s" % str(e))
if response.status_code != 200:
print (response.text)
return
for line in response.iter_lines(1):
if line:
try:
msg = json.loads(line)
print(msg)
except Exception as e:
print ("Caught exception when connecting to stream\n%s" % str(e))
return
msg变量包含为流媒体收到的标记。
问题是我平均收到三个小时的滴答声,之后连接被删除,脚本挂起而没有收到任何滴答声或抛出异常,理由是“连接重置为对等”。
请您分享一下我在哪里出错的想法吗?是否与请求库有关(iter_lines可能)?
除非引发键盘异常,否则我希望无限期地收到刻度。
由于
答案 0 :(得分:0)
对我来说这似乎并不太奇怪,一项服务会关闭生活超过3小时的连接。
这可能是他们的安全,以确保从鬼客户端释放他们的服务器套接字。
因此,您可能只是在断开连接时重新连接。
try:
s = requests.Session()
url = "https://" + domain + "/v1/prices"
headers = {'Authorization' : 'Bearer ' + access_token,
'Connection' : 'keep-alive'
}
params = {'instruments' : instruments, 'accountId' : account_id}
req = requests.Request('GET', url, headers = headers, params = params)
pre = req.prepare()
resp = s.send(pre, stream = True, verify = False)
return resp
except SocketError as e:
if e.errno == errno.ECONNRESET:
pass # connection has been reset, reconnect.
except Exception as e:
pass # other exceptions but you'll probably need to reconnect too.