I'm trying to create a stock trading simulator with react, node, and socketIO, and I need to save the stocks that a user has in an object like this:
var user = {
name: "patrick",
portfolio: [
{
ticker: "AAPL",
sharesOwned: 5,
currentPrice: {
ticker: "MSFT",
sharesOwned: 10,
currentPrice: "120.12"
}
}
]
}
The problem is, I'd like to display a list of the stocks the user owns along with the CURRENT
market price in realtime.
I sort of accomplished this by just looping through each stock the user owns in the backend and calling the IEX API to give me a new price and just update the currentPrice like this in ever loop:
user.portfolio.currentPrice = await getStockPrice();
assuming I've created a function called getStockPrice()
. Of course, the loop would be wrapped in an async function to use await.
Doing it this way does update the list in realtime, but the program has to loop through every stock the user owns first, then returns a new portfolio with the updated prices and is then sent to the client via socketIO. This process happens every ~3
seconds and the realtime streaming is being handled by a setInterval
in the backend which is timed every 4 seconds.
Looking at it correctly, using MongoDB, I could change the data structure to store items the following way:
var user = {
name: "patrick",
portfolio: {
aapl: { shares: 5, currentPrice: 2121 }
msft: { shares: 10, currentPrice: 24242 }
}
}
Indexing here with MongoDB would give me O(logn)
if I'm not mistaken. But I'd still have to loop to get know which stock's price I want to get, which is still O(n)
.
So all together, I think this ends up being O(logn + n)
which is super bad for a realtime streaming app.
How can I get around this using react and socket without having to loop and keep this atleast O(logn)
assuming we're not accounting for the time it takes for an api to respond?
And please correct me if my analysis is wrong.