Calculating profits and losses from a mathematical perspective is trivial, just subtract all things sold to all things bought. The remainder is your profit. That’s pretty much how retail works.
This article was originally published at https://wasteofserver.com. You may want to check it there for new updates and comments.
In future markets tough, people may get confused as you’ll have open positions, which in retail would translate to inventory, that may not have been bought yet (if you’re short selling).
Say you’re trading in Mini S&P Futures
from CME.
The contract lot size
is 50 units
and it's currently trading at around 5140
. Let's see how that works out in a simple BUY/SELL trade:
// final value is num_contracts * lot_size * price
BUY 2 ESH4 @ 5140.00 > 514_000 USD
SELL 2 ESH4 @ 5141.00 > 514_100 USD
+100 USD (PNL)
Let’s add a third order to the mix to see how it works:
BUY 2 ESH4 @ 5140.00 > 514_000 USD
SELL 2 ESH4 @ 5141.00 > 514_100 USD
SELL 2 ESH4 @ 5142.00 > 514_200 USD
If you think it through, you have an open position of -2 ES
contracts that you'll eventually have to close. To calculate the instant P&L you must assume current market price.
BUY 2 ESH4 @ 5140.00 > 514_000 USD
SELL 2 ESH4 @ 5141.00 > 514_100 USD
SELL 2 ESH4 @ 5142.00 > 514_200 USD
// current market price is 5145.00
// you have -2 ES contracts to close
BUY 2 ESH4 @ 5145.00 > 514_500 USD
-200 USD (PNL)
Simple arithmetic. Buy orders are treated as negative values, sell orders are treated as positive values. That’s really all you need to think about.
If you’re not flat, you’ll have a position that you must pretend to close (at current market value) to calculate your current P&L.
BUY 3 ESH4 @ 5100 = -3 * 50 * 5100
BUY 2 ESH4 @ 5150 = -2 * 50 * 5150
BUY 1 ESH4 @ 5200 = -1 * 50 * 5200
SELL 4 ESH4 @ 5300 = +4 * 50 * 5300
// contracts open (-3) - 2 - 1 + 4
= -2 = -2 * 50 * current_market_price
Given a large amount of orders, multiplied by a non-trivial number of users, it may become troublesome fast. But as you’ve probably guessed by now, the system only needs to do that calculation on fills
.
As soon as an order gets filled, you calculate the P&L for all filled positions and cache it. You also cache the number of contracts open. Then you just need to do a single calculation:
pnl_realized + contracts_open * lot_size * current_market_price
If your system is not doing any sort of risk control, you can push that calculation to the user GUI.
I’ve recently been gifted this Amazon Basics phone holder, and I’m converted. It found a place in the kitchen and, from reading newspapers in the morning to serving as a recipe holder, it’s proven its worth daily. Highly recommended!
This article was originally published at https://wasteofserver.com. You may want to check it there for new updates and comments.