Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

python - Issues Appending Websocket response

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...