cancel
Showing results for 
Search instead for 
Did you mean: 

Finding avg order price/liquidity needed

iamqmortal
New Contributor
Dear Q Gods,

Given a list of sizes, prices and a target order qty:
q)sz:5 5 5 5;
q)px:1 1.1 1.2 1.3;
q)qty:6;

I'm trying to find the weighted avg price for the whole steps of liquidity needed to fill a given order size (I cannot take partial liquidity).

Example: 

For an order qty of 6, I require two levels of liquidity (6<= 5+5)

((5 * 1) + (5 * 1.1)) / 10 
= 1.05

Essentially I would like to do:

5 5 0 0 wavg 1 1.1 1.2 1.3

Is there an elegant Q solution to this?

Many thanks, 
A Q Mortal
5 REPLIES 5

clarker8
New Contributor
Hi, 

I think
?[0<deltas qty&sums sz;sz;0]wavg px
Should do what you're looking for. 

Thanks, 
Roger.

sohagan
New Contributor
this what you want?

q)sz:5 5 5 5; px:1 1.1 1.2 1.3; qty:6; @[sz;1_where qty<sums sz;:;0] wavg px
1.05

//try with changed targets
q)qty:12 ; @[sz;1_where qty<sums sz;:;0] wavg px
1.1
q)qty:20 ; @[sz;1_where qty<sums sz;:;0] wavg px
1.15

TerryLynch
New Contributor II
Another approach:

q)wavg[sz*0<sz+qty-\sz;px]
1.05

Nice Terry,

Just noticed the y in my solution - should be sz obv

very nice, short and neat approaches

we could also use the fact that available liquidity is monotonically increasing

Terry's
q)\ts:100000 wavg[sz*0<sz+qty-\sz;px]
390 1040

a couple of simple transformations on Jason's
q)\ts:100000 (sz*(sums sz)<sz+"f"$qty)wavg px
256 1024

this is actually slower and much longer
q)\ts:100000 (`s#(1+0,-1_sums sz)!(sums px*sz)%sums sz)qty
482 1808

however it is a vectorized solution in qty
so if multiple quantities are calculated it is better
q)qty:10000?0

q)\ts:100 {wavg[sz*0<sz+x-\sz;px]}each qty
3382 356928

q)\ts:100 {(sz*(sums sz)<sz+"f"$x)wavg px}each qty
2912 356944

q)\ts:100 (`s#(1+0,-1_sums sz)!(sums px*sz)%sums sz)qty
61 262864

cheers,
   Attila