Skip to content

Instantly share code, notes, and snippets.

@robie2011
Created June 11, 2019 11:13
Show Gist options
  • Save robie2011/1cd3fc30fa2afc0c4b698cddf378e83d to your computer and use it in GitHub Desktop.
Save robie2011/1cd3fc30fa2afc0c4b698cddf378e83d to your computer and use it in GitHub Desktop.
Python Websocket Example
import websocket
import json
class WebsocketHandlers:
def on_error(ws, error):
print("error")
print(error)
def on_message(ws, message):
obj = json.loads(message)
if not ("time" in obj):
print("ignoring message: ")
print(obj)
return
print(f"{obj['time']} {obj['product_id']} {obj['price']}")
#write_db(obj) // todo: custom logic
def on_open(ws):
print("opened")
with open("subscription.json") as json_file:
subscribeMessage = json.load(json_file)
print(json.dumps(subscribeMessage))
ws.send(json.dumps(subscribeMessage))
# websocket.enableTrace(True)
ws = websocket.WebSocketApp(
"wss://ws-feed.pro.coinbase.com",
on_message = WebsocketHandlers.on_message,
on_error = WebsocketHandlers.on_error)
ws.on_open = WebsocketHandlers.on_open
ws.run_forever()
# note: websocket connection to coinbase is (currently) interrupted spontaneously
# It seems to be an issue on their side.
# Same connection problem can be observed when programing with kotlin & javascript
{
"type": "subscribe",
"channels": [
{
"name": "ticker",
"product_ids": [
"LTC-EUR",
"BTC-EUR",
"ZRX-EUR",
"BCH-EUR",
"ETC-EUR"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment