import json
from decimal import Decimal as D


BID, ASK = D("99.90"), D("100.10")
SIZE, INITIAL_CASH, FEE = D(10), D(5000), D("0.0005")


def replay(path, cross_only):
    inventory, cash, buys, sells = D(0), INITIAL_CASH, 0, 0
    for price in path:
        bid_reached = price < BID if cross_only else price <= BID
        ask_reached = price > ASK if cross_only else price >= ASK
        if inventory == 0 and buys == 0 and bid_reached:
            inventory = SIZE
            cash -= SIZE * BID * (1 + FEE)
            buys += 1
        elif inventory > 0 and ask_reached:
            cash += inventory * ASK * (1 - FEE)
            inventory = D(0)
            sells += 1
    result = cash + path[-1] * inventory - INITIAL_CASH
    return [buys, sells, int(inventory), float(result)]


def run():
    down_first = list(map(D, ("100", "99.90", "100.10", "100")))
    up_first = list(map(D, ("100", "100.10", "99.90", "100")))
    through = list(map(D, ("100", "99.89", "100.11", "100")))
    settings = [("A", down_first, False), ("B", up_first, False),
                ("C", down_first, True), ("D", through, True)]
    rows = [[name, *replay(path, cross_only)] for name, path, cross_only in settings]
    assert rows[0][1:] == [1, 1, 0, 1.0]
    assert rows[1][1:] == [1, 0, 10, 0.5005]
    assert rows[2][1:] == [0, 0, 0, 0]
    assert rows[3][1:] == [1, 1, 0, 1.0]
    return rows


if __name__ == "__main__":
    print(json.dumps(run()))
