【问题标题】:Compare lines from streaming API - Python比较来自流 API 的行 - Python
【发布时间】:2015-11-25 15:42:30
【问题描述】:

我在这里迷路了,我有一个流式传输价格的 API,我正在尝试将倒数第二个价格与最后一个价格进行比较,例如,如果 x > y 则执行某些操作。我不知道如何在价格流动时将最后一个价格与第二个价格进行比较。有人可以阐明这可能是如何工作的吗?提前致谢!

我的直播:

def stream_to_queue(self):
        response = self.connect_to_stream()
        if response.status_code != 200:
            return

        for line in response.iter_lines(1):
            if line:
                try:
                    msg = json.loads(line)
                except Exception as e:
                    print "Caught exception when converting message into json\n" + str(e)
                    return
                if msg.has_key("instrument") or msg.has_key("tick"):
                    price = msg["tick"]["ask"]
                    print price

这会打印 1.23004 这样的价格,然后继续循环并打印更多价格。我试图将当前价格保存在循环外的变量中,然后在出现新价格时引用它,但它不起作用..

我的尝试:

def stream_to_queue(self):
        response = self.connect_to_stream()
        if response.status_code != 200:
            return
        oldLine = ''    
        for line in response.iter_lines(1):
            if line:
                try:
                    msg = json.loads(line)
                except Exception as e:
                    print "Caught exception when converting message into json\n" + str(e)
                    return
                if msg.has_key("instrument") or msg.has_key("tick"):
                    price = msg["tick"]["ask"]

        oldLine = price
        newLine = oldLine 
        if newLine > oldLine:
            print newLine

【问题讨论】:

    标签: python python-2.7 stream compare store


    【解决方案1】:

    几件事:

    1- 您的缩进有点偏离,因为比较应该在“for”循环内完成。在您的情况下,仅在流式传输完成时进行比较。

    2- 您将 oldLine 与 newLine 进行比较,它们是相等的,所以什么都不会发生。相反,您应该将 newLine 与价格进行比较。 考虑以下代码:

    for line in response.iter_lines(1):
            if line:
                try:
                    msg = json.loads(line)
                except Exception as e:
                    print "Caught exception when converting message into json\n" + str(e)
                    return
                if msg.has_key("instrument") or msg.has_key("tick"):
                    price = msg["tick"]["ask"]
    
            oldLine = price
            newLine = oldLine 
            if newLine > price:
                print newLine
    

    【讨论】:

    • 感谢您的帮助,但是,当我在循环中运行它时,它似乎并没有比较价格,事实上,当我们这样做时,它并没有让流媒体价格通过,因为我假设'oldLine' 和 'newLine' 被视为相同的价格?
    • 我是否应该尝试将价格添加到列表中并以这种方式进行比较?
    • 哦,你在比较 newLine 和 oldLine 是相等的,所以什么都不会发生!相反,您应该将 newLine 与 price 进行比较,您将获得所需的响应。
    • 由于某种原因我仍然没有得到任何东西,但我明白你在说什么..
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    相关资源
    最近更新 更多