hello, i need to write a converton from .csv trades (Biannce format) to like real-time candels (like 250 ms websocket) pls make a convertor for this. Input it's trades, exit in candels.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is an example Python script that reads a Binance trades CSV file and aggregates the individual trades into candlestick ("candle") bars at a fixed 250‑millisecond interval. In this example the CSV is assumed to have at least the following columns:
time — the timestamp of the trade in Unix milliseconds (ms)
price — the trade price
qty — the trade quantity
The script uses Pandas to convert the Unix timestamp into a datetime, sets it as the index, and then “resamples” the data to create OHLCV (open, high, low, close, volume) candles. You can adjust the aggregation if your CSV contains different columns or if you’d like to include additional metrics.
Below is the complete code:
python
import pandas as pd
import argparse
def convert_trades_to_candles(input_csv, output_csv, candle_interval='250ms'):
"""
Reads a CSV of trades (Binance format) and converts them into candlesticks
of the desired time interval, then writes the result to a new CSV.
Parameters:
input_csv (str): The path to the input CSV file containing trades.
output_csv (str): The path to the output CSV file for the candles.
candle_interval (str): The resampling interval. Default is '250ms'.
Assumes the CSV has the following columns:
- time: Unix timestamp in ms
- price: Trade price
- qty: Trade quantity (volume)
"""
# Read the CSV file
df = pd.read_csv(input_csv)
# Convert the Unix timestamp (in ms) to datetime.
df['time'] = pd.to_datetime(df['time'], unit='ms')
# Set the datetime as index so we can resample based on it.
df.set_index('time', inplace=True)
# Using Pandas resample we build OHLC candles.
# 'first' gives the open price; 'max' gives the high; 'min' the low; 'last' the close; and we sum quantities for volume.
ohlc_dict = {
'price': ['first', 'max', 'min', 'last'],
'qty': 'sum'
}
candles = df.resample(candle_interval).agg(ohlc_dict)
# Flatten the MultiIndex columns
candles.columns = ['open', 'high', 'low', 'close', 'volume']
# Optionally, you can drop candles that have no data (NaN) from resampling.
candles.dropna(inplace=True)
# Reset the index so that the timestamp becomes a normal column.
candles.reset_index(inplace=True)
# Save the resulting candles to a new CSV file.
candles.to_csv(output_csv, index=False)
return candles
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Convert Binance trades CSV into OHLCV candlesticks (default 250ms interval)."
)
parser.add_argument('input_csv', help='Path to the input CSV file containing trades')
parser.add_argument('output_csv', help='Path to the output CSV file for the candles')
parser.add_argument('--interval', default='250ms', help='Candle interval (e.g., "250ms", "1s", etc.)')
args = parser.parse_args()
candles_df = convert_trades_to_candles(args.input_csv, args.output_csv, args.interval)
print("Candle conversion complete! Here are the first few candles:")
print(candles_df.head())
How It Works
Reading and Converting Time:
The CSV is read into a DataFrame.
The time column is converted from Unix milliseconds into a proper datetime format using pd.to_datetime(…, unit='ms').
Resampling to Candles:
We set the datetime column as the DataFrame index and use the Pandas resample() function for time-based grouping.
For each candle:
Open: the first price in the interval.
High: the maximum price.
Low: the minimum price.
Close: the last price.
Volume: the sum of the quantities traded.
Output:
The aggregated candlestick data is exported into a new CSV.
The script also prints the first few computed candles.
Running the Script
Save the script (for example as trade_to_candles.py) and run it from the command line as follows:
This command will read trades.csv and output candlestick data to candles.csv.
Feel free to adjust the column names or add more fields (for example, quote quantities or trade IDs) if your CSV format differs. This script provides a basic framework for converting trade data into real-time candle data.