I am writing a stock market trading game base on yahoo using php/mysql & it’s almost done. Last part I’m struggling is calculating the profit & loss
Lets say have these as transaction
Starting balance = $5000
> order_id stock_id transaction qty_shares cost user_id
> 1 1234 B 100 1000 1
> 2 1234 B 50 450 1
> 3 1234 S 80 640 1
> 4 1234 S 30 300 1
I’m lost trying to come up with an algorithm or a mysql query to calculate the profit & loss
Added after reading the 2 replies posted below
Additional Note :
Please take note that in this scenerio 150 shares was purchased & only 110 shares was sold & all was purchased & sold at different prices
Then:
PHP:
It could all be done on a single query, but if speed is more important then this could be faster than subqueries.
EDIT:
For average profit/loss per share:
This should return the average price per share for each transaction type, per stock type per user. so the transaction S row is average price sold for, and transaction B row is average price bought for. The difference between them is average profit or loss.
That query should return the number of shares sold per row multiplied by the current average price per share, giving you the average margin per transaction with the sold margin being negative. You may find the query slow though. I’d recommend using this information as a starting point and finding the best way for your application.