"""Replay Binance's two spot trade archives for 2026-08-21 (Python 3.9+). python replay.py.txt # read the four public archive URLs python replay.py.txt --from-dir ./files # two ZIPs and their .CHECKSUM files """ import argparse import csv from datetime import datetime, timedelta, timezone from decimal import Decimal import hashlib import io import json from pathlib import Path from urllib.request import Request, urlopen from zipfile import ZipFile DAY = '2026-08-21' MIDNIGHT = datetime(2026, 8, 21, tzinfo=timezone.utc) DAY_US = 86400 * 1_000_000 START = int(MIDNIGHT.timestamp()) * 1_000_000 CUTOFF = START + 3 * 3600 * 1_000_000 BIN_US = 1800 * 1_000_000 WINDOW = START BASE = 'https://data.binance.vision/data/spot/daily/trades' def fetch(url, path): if path is not None: return (path / url.rsplit('/',1)[1]).read_bytes() with urlopen(Request(url, headers={'User-Agent':'Litecoin.watch historical market study'}), timeout=40) as response: return response.read() def iso(us): return (MIDNIGHT + timedelta(microseconds=us-START)).isoformat(timespec='microseconds').replace('+00:00','Z') def summarize(symbol, directory=None): name = f'{symbol}-trades-{DAY}.zip' url = f'{BASE}/{symbol}/{name}' raw = fetch(url, directory) stamp, named = fetch(url+'.CHECKSUM', directory).decode().strip().split() computed = hashlib.sha256(raw).hexdigest() if named.lstrip('*') != name or computed != stamp.lower(): raise ValueError(f'Archive checksum mismatch for {symbol}.') before = after = 0 first_after = last_before = None bins = [0]*12 ids = set() with ZipFile(io.BytesIO(raw)) as archive: with archive.open(name[:-3]+'csv') as stream: for row in csv.reader(io.TextIOWrapper(stream, encoding='utf-8-sig', newline='')): if row and row[0].lower() in ('id','trade id','trade_id'): continue ident, price, size, quote_size, ts, _, _ = row ts, ident = int(ts), int(ident) if not START <= ts < START + DAY_US or ident in ids or min(Decimal(price), Decimal(size)) <= 0: raise ValueError(f'Unexpected row at {symbol} trade {ident}.') ids.add(ident) index = (ts-WINDOW)//BIN_US if 0 <= index < len(bins): bins[index] += 1 trade = (ts, ident, price, size, quote_size) if ts < CUTOFF: before += 1 if last_before is None or trade[:2] > last_before[:2]: last_before = trade else: after += 1 if first_after is None or trade[:2] < first_after[:2]: first_after = trade def record(trade): if trade is None: return None ts, ident, price, size, quote = trade return dict(trade_id=ident, time_utc=iso(ts), offset_from_cutoff_us=ts-CUTOFF, price_in_quote_per_ltc=price, quantity_ltc=size, quote_quantity=quote) return dict(symbol=symbol, archive=url, checksum_file=url+'.CHECKSUM', sha256=computed, trades_before_cutoff=before, trades_at_or_after_cutoff=after, day_count=before+after, last_before=record(last_before), first_at_or_after=record(first_after), half_hour_counts=bins) def report(directory=None): return dict(exchange='Binance', market='Spot', utc_day=DAY, cutoff_utc=iso(CUTOFF), bin_start_times_utc=[iso(WINDOW+i*BIN_US) for i in range(12)], bin_width_seconds=1800, bin_definition='Left endpoint included, right endpoint excluded. Counts are individual trade rows.', markets=[summarize(symbol,directory) for symbol in ('LTCBNB','LTCUSDT')]) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--from-dir', type=Path, help='Read the ZIPs and checksums from this directory.') args = parser.parse_args() print(json.dumps(report(args.from_dir), indent=2))