# Implementing Hansons LMSR with Limit Orderbooks

I am trying to integrate Hanson's LMSR (see (see logarithmic market scoring rule)into an order-book with traditional bid/ask-limit orders (in KDB+/Q).

The following functions define the basic LMSR functionality and work as expected:

  / hanson's lmsr cost func
.lmsr.p.cost:{[b;q1;q2]
b * log((exp(q1 % b)) + (exp(q2 % b)))
};

/ hanson lmsr price func
/ amt = the amount of shares the trader wants to buy
/ modified to return between 0 to 2, with 1 being equilibrium
.lmsr.mod:{[q1;q2;amt]
b: q1+q2; / arbitrary value, liquidity factor for MM
delta: .lmsr.p.cost[b;q1+amt;q2] - .lmsr.p.cost[b;q1;q2];
m: (delta % amt) * 2; / make m 1-based, instead of 0.5 based
$[null m;:1;:m] }; / amt = the amount of shares the trader wants to buy / price = the current marketprice (which then gets multiplied with the price modifier m) / returns price * calculated multiplier, eg.$1250 * 1.03 = $1287.5 .lmsr.price:{[q1;q2;amt;price] res: price * .lmsr.mod[q1;q2;amt];$[null res;:price;:res]
};


Now when I enter the following values into the equations

price:1250; / current share price, in USD
q1:100;     / shares of outcome 1
q2:110;     / shares of outcome 2
amt: 10;    / no. of shares user wants to buy


I get the following (supposedly correct) results

.lmsr.mod[q1;q2;amt]
>> 0.9659238

.lmsr.price[q1;q2;amt;price]
>> 1207.4046957


I now need a function which tells me how many shares can a user buy until the current price reaches price-level trg

trg: 1400; / target price in USD, aka. how many shares can the user buy until price $1250 reaches$1400
.lmsr.amtUntilPrice[q1;q2;price;trg] << ???? help me


I've build an incremental solution which +1s the amt in the price function until target price is reached, but as you'd guess this is really slow and not feasible.

Would anyone be so kind as to help me with that .lmsr.amtUntilPrice function?

Plugging the amt result that function returns back into the .lmsr.price function with the same q1 and q2 should give a price equal or pretty close to the trg value.