Back to Community
How do I calculate profit in code

How can I calculate the profit on an individual stock when I close?

I would like to know if it made money, and store that with some metadata so I can validate a theory. I have the metadata, but I can't easily tell when a position closes or how much it made.

I call order_optimal_portfolio, but I don't know when the sale actually occurs. Is there an event I can subscribe to?
At the end of the day, I check portfolio.positions but it's empty. Probably because everything is sold.
Is a profit number stored somewhere as part of the portfolio.position? Do I have to manually calculate it using the cost_basis?