This is for keeping track of market positions. Raw data is pulled from .csv files provided by brokers. Each row is a record. My issue comes into play when cross trading occurs. Ex. owning 1000, and in one order selling 2,000 shares and opening a short position. I have two records from raw data, a buy of 1,000 shares, and a sell of 2,000 shares. But a new position has been created - short 1,000 shares. So that is 3 position changes, Open of 1,000 shares, close of 1,000 shares, and open -1,000 shares.
I need a query that will recognize that 1,000 shares were bought, and that is a long/buy position, but then recognizes that a sale of anything more than 1,000 shares will close the long position, takes the difference and artificially create a new short position, even though there isn't a record of this.
All of these records fall into the transactions table. This is where the .csv files are imported to.
My query uses four columns from the transactions table to group opening and closing amounts: date, time, symbol, buy/sell. It then sums the quantity field for each group.
I only know how to query the raw data, so I only get one row of information for the scenario above. But a need a second row of information for the new position.
So instead of this:
symbol | qty opened | qty closed
xyz | 1000 | 2000
I need this:
symbol | qty opened | qty closed
xyz | 1000 | 1000
xyz | -1000 | Null
Any guidance would be appreciated.
