'Append websocket data to a list in python

I'm trying to record some websocket data to a list and perform operations on it. The list are created but with the wrong data. should I use redis to store the data and perform the operation ? I want to perform operation 'on the fly' and take actions if a condition is met. so it should be as fast as possible.

here is the code :

import json                                                              
import websocket 
import asyncio



this = json.dumps({'op': 'subscribe', 'channel': 'ticker', 'market': 'BTC/USD'})                      
this2 = json.dumps({'op': 'subscribe', 'channel': 'ticker', 'market': 'ETH/USD'}) 

vx = list()
def sav(ps):
  vx.append(ps)
  list2 = [x for x in vx if x != []]
  last_element = list2[-1]
  #print(last_element)
  return last_element
  
def on_open(wsapp):   
  tickers = "BTC/USD"
  wsapp.send(json.dumps({'op': 'subscribe', 'channel': 'ticker', 'market': tickers}))
  wsapp.send(this2)

def on_message(wsapp, message):                                                   
  #print(message)                                                          
  btc = list()
  eth = list()
  response = json.loads(str(message))

  if response['market'] == "BTC/USD":                    
    resp1 = response['data']['bid']
    
    btc.append(resp1)
    
    print(f'ask price btc :', resp1)
    
  else:
    resp2 = response['data']['ask']
    eth.append(resp2)
    print(f'bid price ETH/USD :', resp2)

  print(f'r btc', btc)
  print(f'r eth', eth)
  sav(btc)
  sav(eth)
  
  # I'm trying to divide btc by eth like that :
  print(sav(btc)/sav(eth))
  
  
  # print(vx)
wsapp = websocket.WebSocketApp('wss://ftx.com/ws/', on_message=on_message, on_open=on_open)
wsapp.run_forever()

the script return two list but the data is wrong. and nothing is printed when I try to divide btc / eth. I want the list for btc/usd and eth to be populated with the last data received in order to perform calculations but it looks like the function "On_message" reset the lists each time it's called.

ask price btc : 38125.0
r btc [38125.0]
r eth []
[38125.0]
[38125.0]
bid price ETH/USD : 2659.1
r btc []
r eth [2659.1]
[2659.1]
[2659.1]
ask price btc : 38125.0
r btc [38125.0]
r eth []
[2659.1]
[38125.0]
bid price ETH/USD : 2659.0
r btc []
r eth [2659.0]
[2659.0]
[2659.0]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source