python - BadStatusLine 错误后重新启动 Python 脚本

标签 python api python-2.7 streaming

我这里有一个程序,可以传输市场价格并根据价格执行订单,但是,每隔一段时间(大约几个小时)它就会抛出此错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/Users/mattduhon/trading4.py", line 30, in trade
    execution.execute_order(event)
  File "/Users/mattduhon/execution.py", line 34, in execute_order
    response = self.conn.getresponse().read()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1073, in getresponse
    response.begin()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 415, in begin
    version, status, reason = self._read_status()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 379, in _read_status
    raise BadStatusLine(line)
BadStatusLine: ''

一旦发生此错误,程序将继续运行而不执行订单,它只是传输速率。我的问题是如何确保该程序能够继续交易?要么重新启动程序,要么忽略错误或其他什么?提前致谢。

附加代码:

执行.py

import httplib
import urllib


class Execution(object):
    def __init__(self, domain, access_token, account_id):
        self.domain = domain
        self.access_token = access_token
        self.account_id = account_id
        self.conn = self.obtain_connection()

    def obtain_connection(self):
        return httplib.HTTPSConnection(self.domain)

    def execute_order(self, event):
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Bearer " + self.access_token
        }
        params = urllib.urlencode({
            "instrument" : event.instrument,
            "units" : event.units,
            "type" : event.order_type,
            "side" : event.side,
            "stopLoss" : event.stopLoss,
            "takeProfit" : event.takeProfit

        })
        self.conn.request(
            "POST",
            "/v1/accounts/%s/orders" % str(self.account_id),
            params, headers
        )
        response = self.conn.getresponse().read()  #Line34////////////
        print response

还有 Trading4.py

import Queue
import threading
import time
import json


from execution import Execution
from settings4 import STREAM_DOMAIN, API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID
from strategy4 import TestRandomStrategy
from streaming import StreamingForexPrices



#Checks for events and executes order                
def trade(events, strategy, execution):

    while True:

        try:
            event = events.get(False)
        except Queue.Empty:
            pass

        else:
            if event is not None:
                if event.type == 'TICK':
                    strategy.calculate_signals(event)
                elif event.type == 'ORDER':
                    print 
                    execution.execute_order(event)  #Line30//////////////


if __name__ == "__main__":
    heartbeat = 0  # Half a second between polling
    events = Queue.Queue()

# Trade 1 unit of EUR/USD
    instrument = "EUR_USD"
    units = 10

    prices = StreamingForexPrices(
        STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
        instrument, events
    )
    execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)

    strategy = TestRandomStrategy(instrument, units, events)


#Threads
    trade_thread = threading.Thread(target=trade, args=(events, strategy, execution))
    price_thread = threading.Thread(target=prices.stream_to_queue, args=[])
    # stop_thread = threading.Thread(target=rates, args=(events,))      

# Start both threads
    trade_thread.start()
    price_thread.start()
    # stop_thread.start()

最佳答案

捕获异常:

        from httplib import BadStatusLine

       ............

        try:
            response = self.conn.getresponse().read()  #Line34////////////
        except BadStatusLine as e:
            print(e)
        else:          
            print response

关于python - BadStatusLine 错误后重新启动 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30261489/

相关文章:

python - 计算余弦相似度矩阵,无需 scipy、sklearn.metrics.pairwise

python - Matplotlib:在 hexbin 图中使用最频繁值的 bin 组添加边框

python - 随机生成9×9列表,其中条目是1到9之间的整数,在任何行或任何列中都没有重复条目

php - 带有多个api调用的慢PHP页面:我的用户将在等待

python-2.7 - Seaborn 水平条形图

python - 在 Python 中使用 Opencv 降低图像的不透明度

ruby-on-rails - 使用 Ruby 的 Tumblr API

android - 在 Instagram 上获取直接照片

python - 调用 bash 脚本作为 Python 子进程 - Bash 陷入无限循环,输入错误

python - 在我的 Raspberry PI 上使用 Python 和 OpenCV 没有保存视频文件