I have a list of stock transactions that I need to process in order to determine the final position. The data is coming from a CSV file containing information on buys and sells. My goal is to loop through each transaction and calculate the remaining positions at the end.
At the end of the process, I want to generate an array with multiple objects, each describing a specific trade - for example: buying shares of Twitter (1 open trade), selling all purchased shares (closing the previous trade), making another purchase of Shop (1 open trade), selling a portion of those shares (updating the quantity of the previous trade and creating a new closed trade), then buying more shares and eventually selling all of them (creating a new open trade followed by closing all trades).
Here's an example from the 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 data would be transformed 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,
...
}
The process seems simple if I use a recursive function. I can identify all open trades, match quantities to close trades, but then comes the challenge of handling partial quantity sales. How do I know when to stop iterating? At what point do I consider only open trades remaining as the correct result?
I'm facing uncertainty about knowing when to halt the iteration and search for matching positions.