Search code examples
pythonarraysstreamlimit

Limit the number of elements appended to array - Python


I have a stream from an API that constantly updates the price. the goal is to compare the last two prices and if x > Y then do something. I can get the prices into an array, however, the array grows very large very quick.. How can I limit the number of elements to 2, then compare them?

My code:

def stream_to_queue(self):
        response = self.connect_to_stream()
        if response.status_code != 200:
            return   
        prices = []    
        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"]
                    prices.append(price)

        print prices

Thanks in advance for help!


Solution

  • if msg.has_key("instrument") or msg.has_key("tick"):
        price = msg["tick"]["ask"]
        last_price = None
        if prices:
            last_price = prices[-1]
            prices = [last_price]
            if last_price > price:
                #do stuff
        prices.append(price)