
I have a list of trades sorted by time

For each there is time, side (buy sell), price, size, open or close trade

How can i group the opening trade with the closing trade?

here is an example:

OPEN MSFT BUY 100 59.99
CLOSE MSFT SELL -100 60.00
OPEN MSFT BUY 200 61.00
CLOSE MSFT SELL -150 61.00
CLOSE MSFT SELL -50 61.00

i basically want the open to be grouped with the subsequent closes up to 
its size. In the second above the open was filled by two separate orders.
There could also be the same scenario where there are mutliple opens to one
close but they still follow sequentially.

=========

myopenclose: ("SSFFT"; enlist ",") 0: `openclose.csv

openclose: ("SSFFT"; enlist ",") 0: `openclose.csv;

show openclose

Note that these are ordered in time, but not by stock.
So, first order them by stock.

You need not restrict yourself
to grouping on stock.
You can group on more stuff.
In particular, you might like to group on stocks and trades
within that stock whose amount sums to 0. 

Let's try  to rewrite the open-close query to get all the purchases and
sales together.
	q opencloseadvanced.q

Exercise 7 (hard)
Call a "bundle" in a stock a consecutive series of trades where the price
either stays the same or increases with each trade.
(Example: if price is 1 2 3 4 2 3 4 5  4 3 2 1 1 1 2 3
then the bundles will be 1 2 3 4, 2 3 4 5 and then 1 1 1 2 3)
Find the weighted average price per bundle per stock.
	q bundle.q

Here is another related challenge 
for more practice with this concept.
We may not be interested in the data about individual stocks,
but rather about categories of stocks.
In our generated data, the amounts are generated as follows:
amount: 100*(1+n?1000)
Thus, we may be interested in statistics about those in the 
low range (0-9999 inclusive), middle (10,000 - 49,000) and larger.

Let's start by observing the following.

x: til 20
0 5 13 bin x

Notice that the first group (the zeroes) are between 0 and 4 inclusive,
the second group between 5 and 12 inclusive.

This doesn't require x to be sorted.
For example,
x: 20 ? 16
0 5 13 bin x

What is interesting is that we can group based on this idea.
Hint: Think about 0 10000 50000 bin amount



Exercise 8. (Middle) We want to find the average price of
stocks in which the amounts fall between 1 and 9999 (low), 
10000 to 49999 (middle), and more (high).
	q rangegroup.q



So far, we have dealt with small tables.
If we have big tables, we may want to put each column in 
a different file. 
https://code.kx.com/trac/wiki/Cookbook/SplayedTables

Exercise 9.  (Middle) Save a 100,000
sized generated random table in problem 4 as a splayed table below
a directory called splaydir.
	q genandsplay.q / to store
	q ./splaydir / to retrieve


To retrieve the table, type 
q ./splaydir
and try the following queries:
\t select avg amount by stock from rantrade
\t select avg amount, max time, avg price by stock from rantrade

