Edit: I'm trying to create an order matching engine for options trading.
I'd like to ask my question by creating a situation:
Amy has a short position in a single (1) call option on AAPL. Let's assume she shorted the call at a price of \$20.
The price of the option is now \$30.
Amy now wants to cover this short. She does so by placing a limit buy order at a price of \$27. The limit order system sees she has an existing short and removes this position that she can further trade (basically locks it down so only a market order or cancel order can mutate it).
Now Amy(who's getting paranoid about her losses) puts in another limit buy order at \$28. But the limit order system does not see any more free options in her account and assumes this is an outright purchase and freezes \$28 from her account.
Along comes a market order that sells Amy a call option at the price of \$28. But Amy doesn't lose the frozen \$28. She instead covers her short. She now has a net 0 position in the aforementioned call. And \$28 are (still)frozen from her cash account.
Along comes another market order which triggers the limit buy at \$27. This time the exchange realizes that the order is an outright buy and transfers a call option in her positions and removes \$27 from her \$28 of frozen cash.
Now Amy is net long 1 call option but still \$1 frozen.
Amy should actually have 0 dollars frozen but my analogy isn't seeing how. I know exchanges currently handle this easily (I think). But how? I'm trying to implement correct accounting but can't seem to be able to it figure out.
Any help would be great! Thanks a lot. Please let me know if you have questions in the comments. I can edit this post to be more clear.