I have an array of stock trades that I want to iterate through and I want the output to be a final position. I am parsing a CSV which provides a list of buys and sells. I want to process each of these and understand what is remaining at the end.
By the end I want to have an array that contains multiple objects, each object describes the final position - I bought some twitter (1 trade - open), I sold the whole position (same trade now marked closed), I then bought some shop (1 trade - open), sold SOME of it (previous trade quantity updated and still open, new trade created with sold quantity and closed), then later I bought some more and then sold all (1 new trade, then close all trades)
Example from CSV
{
Action: 'Buy',
Symbol: 'SHOP',
Quantity: '200',
...
},
{
Action: 'Sell',
Symbol: 'SHOP',
Quantity: '200',
...
},
{
Action: 'Buy',
Symbol: 'SHOP',
Quantity: '50',
...
},
{
Action: 'Sell',
Symbol: 'SHOP',
Quantity: '25',
...
},
{
Action: 'Sell',
Symbol: 'SHOP',
Quantity: '25',
...
},
{
Action: 'Buy',
Symbol: 'SHOP',
Quantity: '1',
...
},
This would convert into:
{
stockTicker: 'SHOP',
positionStatus: 'CLOSED',
quantity: 200,
...
},
{
stockTicker: 'SHOP',
positionStatus: 'CLOSED',
quantity: 25,
...
},
{
stockTicker: 'SHOP',
positionStatus: 'CLOSED',
quantity: 25,
...
},
{
stockTicker: 'SHOP',
positionStatus: 'OPEN',
quantity: 1,
...
}
This is pretty straight forward if I create a recursive function. I can iterate through and find all the open positions, I can then iterate again and find all the quantities that match completely and close those trades, but then I need to keep iterating through and looking for partial quantity sales, and then how do I know when to stop? Because eventually there may be no more sells and there may only be open trades remaining - which is correct.
I'm not sure how or when I should decide to stop iterating and looking for matching positions.