I am writing a paper trading system, and what I have works, but I can't help but feel that there's a better way to partially close a stock position; what I currently have seems a little overboard.
Partially Close Scenario: Customer A buys 100 shares of stock X at $1 then, later the customer sells 80 shares at $2; leaving 20 shares on the table.
Close plus Open Scenario: Customer A buys 100 shares of stock X at $1 then later the customer sells 120 shares at $2; opening a new short position with 20 shares.
Pseudo Code
I think posting the actual code is irrelevant for answering this question.
if (customer has active trade) {
if (quantity to close >= quantity open) {
close open trade
if (quantity to close > quantity open)
create new open trade with remaining quantity (close - open)
} else {
// This is where I think it could be better.
close old position at entry price
open new position at old entry price (close quantity)
close new position at specified exit price
open new position at old entry price (old quantity - close quantity)
}
} else {
create new open trade with specified quantity
}
Is there a more efficient way to write the logic above? Both scenarios can be executed as a single trade on most platforms.
NOTE: The community may feel this question has a better home over at Code Review; if this happens to be the case, can it be migrated? I thought it was a better fit here since there's no actual code involved.