"""Convert a Hummingbot `export trades` session CSV to a supplied FIFO book locally.""" import argparse import csv from collections import defaultdict from datetime import date, datetime, timezone from decimal import Decimal, InvalidOperation import hashlib import json import os from pathlib import Path import re import tempfile from zoneinfo import ZoneInfo, ZoneInfoNotFoundError HEADER = 'Id,Timestamp,Exchange,Market,Order_type,Side,Price,Amount,Leverage,Position,Age'.split(',') LABEL = re.compile(r'[A-Za-z0-9][A-Za-z0-9._-]{0,47}') SYMBOL = re.compile(r'[A-Za-z0-9][A-Za-z0-9_]{0,47}') NUMBER = re.compile(r'(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,18})?') MAX_BYTES = 32 * 1024 * 1024 def check(condition, message): if not condition: raise ValueError(message) def unique(pairs): result = {} for key, value in pairs: check(key not in result, 'Repeated JSON key in the context file') result[key] = value return result def amount(value, *, positive=False): check(isinstance(value, str) and len(value) <= 80 and re.fullmatch(r'[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]{1,3})?', value), 'Expected an exact decimal string') number = Decimal(value) check(not positive or number > 0, 'A fill quantity and price must be positive') if number == 0: return '0' check(-18 <= number.adjusted() <= 17, 'Amount exceeds workpaper precision') out = format(number, 'f') if '.' in out: out = out.rstrip('0').rstrip('.') check(NUMBER.fullmatch(out), 'Amount exceeds workpaper precision') return out def utc_time(value, zone): local = datetime.strptime(value, '%Y-%m-%d %H:%M:%S') instants = set() for fold in (0, 1): candidate = local.replace(tzinfo=zone, fold=fold).astimezone(timezone.utc) if candidate.astimezone(zone).replace(tzinfo=None) == local: instants.add(candidate) check(len(instants) == 1, 'Ambiguous or nonexistent local time. Use an export from an unambiguous time zone or supply normalized trades.') return instants.pop() def convert(rows, context): required = {'authorized','spotOnly','feeCurrency','exchange','timeZone','inventoryRef','taxYear', 'brokerReporting','openingAsOf','openings','feesUSD'} check(isinstance(context, dict) and required <= context.keys() <= required | {'sameTimeOrder'}, 'Supply the fields shown in the example context') check(context['authorized'] is True and context['spotOnly'] is True and context['feeCurrency'] == 'USD' and context['brokerReporting'] == 'no-broker-form', 'Confirm authorized spot fills, actual USD fees and the reporting category') exchange = context['exchange'] check(isinstance(exchange,str) and re.fullmatch(r'[a-z0-9][a-z0-9_]{0,31}',exchange) and not any(word in exchange for word in ('perpetual','futures','option','paper_trade')), 'Expected a live spot exchange') zone = ZoneInfo(context['timeZone']) year = context['taxYear'] check(type(year) is int and 2025 <= year <= 2099 and LABEL.fullmatch(context['inventoryRef']), 'Invalid tax year or inventory reference') start = context['openingAsOf'] check(re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z',start), 'Opening time must be UTC with a Z suffix') opening_time = datetime.strptime(start,'%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc) check(datetime(1970,1,1,tzinfo=timezone.utc) < opening_time < datetime(year+1,1,1,tzinfo=timezone.utc), 'Opening time must precede the end of the selected year') positions = context['openings'] check(isinstance(positions,dict) and 1 <= len(positions) <= 256, 'Supply one evidenced opening per traded asset') openings = [] for symbol, op in positions.items(): check(SYMBOL.fullmatch(symbol) and isinstance(op,dict) and set(op)=={'quantity','basisUSD','acquired'}, 'Invalid opening record') when = date.fromisoformat(op['acquired']) check(when.isoformat() == op['acquired'] and when <= opening_time.date(), 'Invalid original acquisition date') quantity, basis = amount(op['quantity']), amount(op['basisUSD']) check(quantity != '0' or basis == '0', 'An empty opening cannot carry cost') openings.append(dict(asset=symbol,assetID='venue:'+exchange.replace('_','-')+':'+symbol, acquired=op['acquired'],quantity=quantity,basisUSD=basis)) check(rows.fieldnames == HEADER, 'Expected the CSV created by Hummingbot export trades') fees = context['feesUSD'] check(isinstance(fees,dict), 'Supply actual USD fees keyed by Market/Id') trades, ids, tie_groups, assets = [], {}, defaultdict(list), set() for index, row in enumerate(rows, 2): try: check(index <= 200001 and None not in row and None not in row.values(), 'Unexpected row width or more than 200,000 fills') market, ident = row['Market'], row['Id'] check(row['Exchange'] == exchange and market.endswith('-USD') and market[:-4] in positions, 'Expected the selected exchange and a declared USD-quoted pair') check(row['Order_type'] in ('market','limit','limit_maker') and row['Leverage']=='1' and row['Position']=='NIL' and row['Side'] in ('buy','sell'), 'Expected an unleveraged spot fill') check(ident.strip() == ident and 0 < len(ident) <= 256, 'Missing or oversized exchange trade ID') reference = market + '/' + ident check(reference in fees and reference not in ids, 'Missing explicit USD fee or repeated exchange fill') key = 'hb-' + hashlib.sha256(reference.encode()).hexdigest()[:40] stamp = utc_time(row['Timestamp'], zone) check(stamp.year == year and stamp > opening_time, 'Fill falls outside the selected book cut or tax year') asset = market[:-4] ids[reference] = key assets.add(asset) tie_groups[asset,stamp].append(reference) trades.append(dict(id=key,side=row['Side'],asset=asset,time=stamp.strftime('%Y-%m-%dT%H:%M:%SZ'), quantity=amount(row['Amount'],positive=True),priceUSD=amount(row['Price'],positive=True), feeUSD=amount(fees[reference]))) except (ValueError, TypeError, InvalidOperation) as error: raise ValueError('CSV row '+str(index)+': '+str(error)) from None check(set(ids)==set(fees) and len(set(ids.values()))==len(ids), 'Fee evidence must match every fill exactly once') check(assets==set(positions) and any(t['side']=='sell' for t in trades), 'Supply the traded assets and at least one sale') expected = {frozenset(g) for g in tie_groups.values() if len(g)>1} order = context.get('sameTimeOrder',[]) check(isinstance(order,list) and len(order)==len(expected) and all(isinstance(g,list) and all(isinstance(x,str) for x in g) and len(g)==len(set(g)) for g in order) and {frozenset(g) for g in order}==expected, 'Supply the actual order of same-asset fills sharing a local second using Market/Id references') result = dict(schema='chainiq.spot-trades.v2',authorized=True,method='FIFO',inventoryRef=context['inventoryRef'], taxYear=year,brokerReporting=context['brokerReporting'],openingAsOf=start,openings=openings,trades=trades) if order: result['sameTimeOrder'] = [[ids[ref] for ref in group] for group in order] return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('export',type=Path) parser.add_argument('context',type=Path) parser.add_argument('output',type=Path) args = parser.parse_args() try: for path in (args.export,args.context): check(path.stat().st_size <= 64*1024*1024, 'Input exceeds 64 MiB') ctx = json.loads(args.context.read_text(encoding='utf-8'),object_pairs_hook=unique) with args.export.open(encoding='utf-8-sig',newline='') as source: book = convert(csv.DictReader(source,strict=True),ctx) body = json.dumps(book,ensure_ascii=False,separators=(',',':')).encode()+b'\n' check(len(body)<=MAX_BYTES,'Converted book exceeds the 32 MiB upload limit') with tempfile.NamedTemporaryFile(dir=args.output.parent) as staging: staging.write(body) staging.flush() os.link(staging.name,args.output) print(str(len(book['trades']))+' fills converted to '+str(args.output)) except (OSError, ValueError, KeyError, TypeError, csv.Error, InvalidOperation, ZoneInfoNotFoundError) as exc: parser.exit(2,str(exc)+'\n') if __name__ == '__main__': main()