WebsocketClient + Mongodb
The WebsocketClient now supports data gathering via MongoDB. Given a MongoDB collection, the WebsocketClient will stream results directly into the database collection.
# import PyMongo and connect to a local, running Mongo instance
from pymongo import MongoClient
import cbpro
mongo_client = MongoClient('mongodb://localhost:27017/')
# specify the database and collection
db = mongo_client.cryptocurrency_database
BTC_collection = db.BTC_collection
# instantiate a WebsocketClient instance, with a Mongo collection as a parameter
wsClient = cbpro.WebsocketClient(url="wss://ws-feed.pro.coinbase.com", products="BTC-USD",
mongo_collection=BTC_collection, should_print=False)
wsClient.start()
WebsocketClient Methods
The WebsocketClient subscribes in a separate thread upon initialization. There are three methods which you could overwrite (before initialization) so it can react to the data streaming in. The current client is a template used for illustration purposes only.
onOpen - called once, immediately before the socket connection is made, this is where you want to add initial parameters.
onMessage - called once for every message that arrives and accepts one argument that contains the message of dict type.
on_close - called once after the websocket has been closed.
close - call this method to close the websocket connection (do not overwrite).
import cbpro, time
class myWebsocketClient(cbpro.WebsocketClient):
def on_open(self):
self.url = "wss://ws-feed.pro.coinbase.com/"
self.products = ["LTC-USD"]
self.message_count = 0
print("Lets count the messages!")
def on_message(self, msg):
self.message_count += 1
if 'price' in msg and 'type' in msg:
print ("Message type:", msg["type"],
"\t@ {:.3f}".format(float(msg["price"])))
def on_close(self):
print("-- Goodbye! --")
wsClient = myWebsocketClient()
wsClient.start()
print(wsClient.url, wsClient.products)
while (wsClient.message_count < 500):
print ("\nmessage_count =", "{} \n".format(wsClient.message_count))
time.sleep(1)
wsClient.close()
WebsocketClient + Mongodb The WebsocketClient now supports data gathering via MongoDB. Given a MongoDB collection, the WebsocketClient will stream results directly into the database collection.
WebsocketClient Methods The WebsocketClient subscribes in a separate thread upon initialization. There are three methods which you could overwrite (before initialization) so it can react to the data streaming in. The current client is a template used for illustration purposes only.
Reference: https://github.com/danpaquin/coinbasepro-python