Hi,
I have included below, a sample python script (FakeMongoData.py
) that generates some random (fake) data and inserts it into a MongoDB Collection named TestCollection
. You have to keep this script running in another command prompt/terminal along with server.py
in the previous post. Also remember to change the text FloatingEquity
in line 62 in the server.py script to TestCollection
. To see the Websocket results while the two scripts are running, open your browser and type localhost:8000
in the address bar , then right click → Inspect → Console. Please find the script FakeMongoData.py
below:
import pymongo
from pymongo import MongoClient,ReturnDocument
from pymongo.errors import ConnectionFailure, AutoReconnect, BulkWriteError, OperationFailure
from datetime import datetime, timedelta
import credentials
import random
import time
## Load MongoDB Credentials and Cluster details
## Fix MongoClient DB connection errors by following this - https://www.youtube.com/watch?v=wvlJGvP18Qk
credentials_mongodb = credentials.mongodb
user_id = credentials_mongodb["username"]
password = credentials_mongodb["password"]
domain = credentials_mongodb["domain"]
database = credentials_mongodb["db"]
CLIENT_URI = "mongodb+srv://{}:{}@{}/admin?retryWrites=true&w=majority".format(user_id, password, domain)
def MongoDB_Connection(client_uri : str = CLIENT_URI) -> dict:
'''
Makes a connection to the MongoDB Cluster and returns success or exception handling (error) messages.
## Reference: https://www.programcreek.com/python/example/94224/pymongo.errors
Parameters
----------
client_url : str, default = CLIENT_URI stored in MongoWorks.py
Client URL to connect to the MongoDB cluster.
Returns
-------
dict : {Success or Failure message}
'''
client = MongoClient(client_uri)
try:
client.admin.command('ismaster') # The ismaster command is cheap and does not require auth.
return client
except (AutoReconnect, ConnectionFailure) as e:
error_message = e + ": Server not available"
print(error_message)
return e
def MongoDB_Collection_Write(collection_name : str, docs_to_insert: dict, db: str = database) -> str:
'''
Writes documents to a MongoDB Collection.
Parameters
----------
collection_name : str, name of the collection in MongoDB
docs_to_insert : a single dict,
Document to insert into a MongoDB collection in list of dicts format
db : str, name of the database in MongoDB
Returns
-------
messages : dict, {doc_iD : Success/Failure message}
Success or Failure message with documents insertion ID
'''
client = MongoDB_Connection()
db = client[db]
collection = db[collection_name]
try:
result = collection.insert_one(docs_to_insert).inserted_id
message = "{} - Document Inserted successfully into `{}` collection".format(result, collection_name)
return {result : message}
except Exception as e:
error_message = "An {} Exception occured when inserting a document into `{}` Collection. ".format(e,collection_name)
print(error_message)
return error_message
initial_equity = 100000.0
while True:
new_row = {}
timestamp = datetime.now().replace(microsecond=0)
pnl = round(random.uniform(-1000,999), 2)
nr_open_positions = random.randint(0,5)
equity = round(initial_equity + pnl, 2)
new_row = {"time": timestamp, "equity": equity, "PnL" : pnl, "OpenPositions" : int(nr_open_positions)}
MongoDB_Collection_Write(collection_name = "TestCollection", docs_to_insert = new_row) ## Insert last equity value at the time of closing the last open position
print(f"Timestamp: {timestamp} || OpenPositions: {nr_open_positions} || Equity: {equity} US$ || Profit: {pnl} US$")
time.sleep(1)
I hope this helps to recreate the problem at your end, very easily. The resulting incoming stream of WebSocket data from MongoDB needs to be plotted in a streaming line plot equity
vs. time
and other fields like OpenPositions
, PnL
needs to be shown on these dash cards . Let me know if you need any further assistance from my end.
Best Regards,
Dilip