"""Educational, fee-free LMSR arithmetic. Run: python3 lmsr-pricing.py
No real accounts, collateral, orders, fees, market feed or signing code.
Finite-scale floating-point examples, not a production quote implementation.
"""
import math
from itertools import product


def state(q, b):
    qs = tuple(float(x) for x in q)
    b = float(b)
    if len(qs) < 2 or not math.isfinite(b) or b <= 0 or any(not math.isfinite(x) for x in qs):
        raise ValueError('use at least two finite quantities and a finite positive b')
    return qs, b


def cost(q, b):
    qs, b = state(q, b)
    top = max(qs)
    # Center BEFORE exponentiation. Example q=10000,b=10 does not exp(1000).
    result = top + b * math.log(math.fsum(math.exp((x - top) / b) for x in qs))
    if not math.isfinite(result):
        raise ValueError('cost outside the supported floating-point scale')
    return result


def prices(q, b):
    qs, b = state(q, b)
    top = max(qs)
    weights = [math.exp((x - top) / b) for x in qs]
    total = math.fsum(weights)
    return [x / total for x in weights]


def payment(q, delta, b):
    qs, b = state(q, b)
    ds = tuple(float(x) for x in delta)
    if len(qs) != len(ds) or any(not math.isfinite(x) for x in ds):
        raise ValueError('finite trade quantities must match state dimension')
    # The subtraction can lose precision at extreme common inventory offsets.
    return cost([x + d for x, d in zip(qs, ds)], b) - cost(qs, b)


def checks():
    q0 = [0, 0]
    expected = [(5, 7.168904152415136, .8807970779778823),
                (10, 6.2011450695827754, .7310585786300049),
                (20, 5.6185960724032284, .6224593312018546)]
    for b, want_cost, want_price in expected:
        actual = payment(q0, [10, 0], b)
        assert math.isclose(actual, want_cost, abs_tol=1e-11)
        assert math.isclose(prices([10, 0], b)[0], want_price, abs_tol=1e-12)
        assert 5 < actual < 10 * want_price
        split = payment(q0, [4, 0], b) + payment([4, 0], [6, 0], b)
        assert math.isclose(split, actual, abs_tol=1e-11)
        reverse = payment([10, 0], [-10, 0], b)
        assert math.isclose(reverse, -actual, abs_tol=1e-11)
        print('b=', b, 'payment=', actual, 'ending Yes=', want_price, 'maker bound=', b * math.log(2))
    for n in range(2, 6):
        b = 10
        for q in product((0, 10, 100), repeat=n):
            ps = prices(q, b)
            assert math.isclose(math.fsum(ps), 1, abs_tol=1e-12)
            assert all(0 <= p <= 1 for p in ps)
            revenue = cost(q, b) - cost([0] * n, b)
            assert max(q) - revenue <= b * math.log(n) + 1e-10
            shifted = [x + 1000 for x in q]
            assert math.isclose(cost(shifted, b) - cost(q, b), 1000, abs_tol=1e-10)
            assert all(math.isclose(a, z, abs_tol=1e-12) for a, z in zip(ps, prices(shifted, b)))
    assert math.isfinite(cost([10000, 0], 10))
    assert math.isclose(payment([0, 0], [100, 0], 10), 93.06898218339272, abs_tol=1e-11)
    for q, b in [([0], 1), ([0, 0], 0), ([0, 0], -1), ([math.nan, 0], 1), ([0, 0], math.inf)]:
        try:
            cost(q, b)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid state accepted')
    try:
        payment([0, 0], [1], 10)
    except ValueError:
        pass
    else:
        raise AssertionError('mismatched trade dimension accepted')
    print('Examples, finite inventory grid, invariants and invalid-input checks passed')


if __name__ == '__main__':
    checks()
