"""Run with Python 3 beside trades.csv and snapshot.json. No network or packages needed.""" import csv from collections import Counter from decimal import Decimal as D import json from pathlib import Path def replay(folder): snapshot = json.loads((folder / "snapshot.json").read_text(encoding="utf-8")) with (folder / "trades.csv").open(encoding="utf-8", newline="") as source: tape = list(csv.DictReader(source)) window = snapshot["trade_window"] assert len(tape) == window["count"] assert [int(row["trade_id"]) for row in tape] == list(range(window["first_id"], window["last_id"] + 1)) supply = D(snapshot["supply"]["circulating_ltc"]) size = lambda r: D(r["size"]) price = lambda r: D(r["price"]) gross = lambda r: size(r) * price(r) counts = Counter() turnover = Counter() examples = {} for before, after in zip(tape, tape[1:]): difference = price(after) - price(before) direction = "up" if difference > 0 else "down" if difference < 0 else "flat" counts[direction] += 1 turnover[direction] += gross(after) # Chronological overwrite selects the latest pair for each direction. examples[direction] = { "from": before, "to": after, "fill_usd": gross(after), "price_change_usd_per_ltc": difference, "fixed_supply_change_usd": supply * difference, } bids = [(D(p), D(q)) for p, q in snapshot["order_book"]["best_20_bids"]] sale = {} for target in (D("1"), D("100")): left, proceeds, used = target, D(0), 0 for bid, available in bids: take = min(left, available) left -= take proceeds += take * bid used += 1 if left == 0: break filled = target - left sale[str(target)] = {"covered_ltc": filled, "unpriced_ltc": left, "levels_used": used, "gross_usd": proceeds, "average_usd": proceeds / filled, "difference_from_best_on_covered_ltc_usd": bids[0][0] * filled - proceeds} total = sum(map(gross, tape)) assert sum(counts.values()) == len(tape) - 1 assert sum(turnover.values()) + gross(tape[0]) == total return { "first": tape[0], "last": tape[-1], "supply_ltc": supply, "one_cent_usd": supply * D("0.01"), "counts": counts, "examples": examples, "gross_by_step_usd": turnover, "all_100_ltc": sum(map(size, tape)), "all_100_usd": total, "first_to_last_change_usd": supply * (price(tape[-1]) - price(tape[0])), "best_bid": bids[0], "sale_replay": sale, } if __name__ == "__main__": print(json.dumps(replay(Path(__file__).resolve().parent), default=str, indent=2))