I wrote this code that connects to the Coinbase WebSocket API. its supposed to return all orders for every second its running. Coinbase's docs say you can get a request every 4 seconds. When I run the code below I run it for 2 minutes and then key interrupt to stop it. My last test was at 8:00 and I ran it to 8:02. the csv should have rows for 2 minutes but it has only for the first 4 seconds so Im assuming my code is only writing the first response. Also running it with a indefinite loopis not ideal but Im not sure of a better way currently, plus Im just trying to get the correct data.
from websocket import create_connection
import json
import time
import pandas as pd
import os
URL = "wss://ws-feed.pro.coinbase.com"
ws = create_connection(URL)
df = pd.DataFrame()
csv_file = "cbase-test-10.csv"
params = {
"type": "subscribe",
"channels": [{"name": "ticker", "product_ids": ["BTC-USD"]}]
}
while True:
ws.send(json.dumps(params))
result = ws.recv()
#print(result)
time.sleep(4)
converted = json.loads(result)
df = df.append(pd.DataFrame.from_dict(pd.json_normalize(converted), orient='columns'))
#print(df)
#that means file already exists need to append
if(csv_file in os.listdir()):
csv_string = df.to_csv(index=False, encoding='utf-8', header=False)
with open(csv_file, 'a') as f:
f.write(csv_string)
#that means writing file for the first time
else:
csv_string = df.to_csv(index=False, encoding='utf-8')
with open(csv_file, 'w') as f:
f.write(csv_string)
#df.to_csv(csv_file, index=False, encoding='utf-8')
question from:
https://stackoverflow.com/questions/65947900/issues-appending-websocket-response 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…