def append_to_csv(self, trade: TradeFill): csv_filename = "trades_" + trade.config_file_path[:-4] + ".csv" csv_path = os.path.join(data_path(), csv_filename) field_names = tuple(trade.attribute_names_for_file_export()) field_data = tuple(getattr(trade, attr) for attr in field_names) # adding extra field "age" # // indicates order is a paper order so 'n/a'. For real orders, calculate age. age = pd.Timestamp(int((trade.timestamp * 1e-3) - (trade.order.creation_timestamp * 1e-3)), unit='s').strftime('%H:%M:%S') if ( trade.order is not None and "//" not in trade.order_id) else "n/a" field_names += ("age", ) field_data += (age, ) if (os.path.exists(csv_path) and (not self._csv_matches_header(csv_path, field_names))): move( csv_path, csv_path[:-4] + '_old_' + pd.Timestamp.utcnow().strftime("%Y%m%d-%H%M%S") + ".csv") if not os.path.exists(csv_path): df_header = pd.DataFrame([field_names]) df_header.to_csv(csv_path, mode='a', header=False, index=False) df = pd.DataFrame([field_data]) df.to_csv(csv_path, mode='a', header=False, index=False)
def test_attribute_names_for_file_export_are_valid(self): trade_fill = TradeFill(config_file_path=self.config_file_path, strategy=self.strategy_name, market=self.display_name, symbol=self.symbol, base_asset=self.base, quote_asset=self.quote, timestamp=int(time.time()), order_id="OID1", trade_type=TradeType.BUY.name, order_type=OrderType.LIMIT.name, price=Decimal(1000), amount=Decimal(1), leverage=1, trade_fee=AddedToCostTradeFee().to_json(), exchange_trade_id="EOID1", position="NILL") values = [ getattr(trade_fill, attribute) for attribute in TradeFill.attribute_names_for_file_export() ] expected_values = [ trade_fill.exchange_trade_id, trade_fill.config_file_path, trade_fill.strategy, trade_fill.market, trade_fill.symbol, trade_fill.base_asset, trade_fill.quote_asset, trade_fill.timestamp, trade_fill.order_id, trade_fill.trade_type, trade_fill.order_type, trade_fill.price, trade_fill.amount, trade_fill.leverage, trade_fill.trade_fee, trade_fill.position, ] self.assertEqual(expected_values, values)
def test_attribute_names_for_file_export(self): expected_attributes = [ "exchange_trade_id", "config_file_path", "strategy", "market", "symbol", "base_asset", "quote_asset", "timestamp", "order_id", "trade_type", "order_type", "price", "amount", "leverage", "trade_fee", "position", ] self.assertEqual(expected_attributes, TradeFill.attribute_names_for_file_export())