import csv import dataclasses from pathlib import Path import fin_depo @dataclasses.dataclass(frozen=True) class CsvFileLogger: """Outputs the given `TradeOrderDetails` to the CSV file at the specified path. """ path: Path def __call__(self, trade_order: fin_depo.data.TradeOrderDetails): fieldnames: list[str] = [ 'executed_time', 'input_asset', 'input_amount', 'output_asset', 'output_amount', 'fee_asset', 'fee_amount', 'order_id', 'raw_order_details', ] # Ensure that directory exists self.path.parent.mkdir(parents=True, exist_ok=True) # Write row in CSV file with open(self.path, 'a') as f: writer = csv.DictWriter(f, fieldnames=fieldnames) d = trade_order.__dict__ d['input_asset'] = d['input'].asset d['input_amount'] = d['input'].amount d['output_asset'] = d['output'].asset d['output_amount'] = d['output'].amount d['fee_asset'] = d['fee'].asset d['fee_amount'] = d['fee'].amount del d['fee'], d['input'], d['output'] writer.writerow(d)