Support Board
Date/Time: Sun, 24 Nov 2024 16:05:42 +0000
Post From: Python code of number of trade bar (Binance)
[2024-05-25 13:08:07] |
User395175 - Posts: 87 |
If i use below python code to make number of trade bar, can i get the exact same tick bar chart as sc does? i want to creating tick bars in python match exactly with Sierra Chart's tick bars, including the same timestamp, open, high, low, close, and volume data for each bar import websocket import json import pandas as pd from datetime import datetime # Initialize global variables tick_data = [] tick_bar_data = [] current_day = None TICK_BAR_SIZE = 4000 VOLUME_SCALE_FACTOR = 10000 # Define WebSocket callback functions def on_message(ws, message): global tick_data global tick_bar_data global current_day # Parse the incoming message msg = json.loads(message) # Extract relevant trade data trade_time = datetime.fromtimestamp(msg['E'] / 1000) trade = { 'timestamp': trade_time, 'price': float(msg['p']), 'quantity': float(msg['q']) * VOLUME_SCALE_FACTOR } # Check if it's a new day if current_day is None or trade_time.date() != current_day: current_day = trade_time.date() tick_data = [] # Reset tick data for the new day print(f"New day started: {current_day}") # Append trade to tick data tick_data.append(trade) # Check if we have enough trades to form a tick bar if len(tick_data) >= TICK_BAR_SIZE: # Aggregate the trades into a tick bar tick_df = pd.DataFrame(tick_data[:TICK_BAR_SIZE]) # Only take the first TICK_BAR_SIZE trades tick_bar = { 'timestamp': tick_df['timestamp'].iloc[0], 'open': tick_df['price'].iloc[0], 'high': tick_df['price'].max(), 'low': tick_df['price'].min(), 'close': tick_df['price'].iloc[-1], 'volume': tick_df['quantity'].sum() } # Append the tick bar to the tick bar data tick_bar_data.append(tick_bar) # Remove the used trades and reset for the next bar tick_data = tick_data[TICK_BAR_SIZE:] # Print the tick bar data (or you can store it) print(tick_bar) def on_error(ws, error): print(error) def on_close(ws): print("### WebSocket closed ###") def on_open(ws): # Subscribe to the trade stream for BTCUSDT params = { "method": "SUBSCRIBE", "params": ["btcusdt@trade"], "id": 1 } ws.send(json.dumps(params)) # Create WebSocket connection ws = websocket.WebSocketApp("wss://stream.binance.com:9443/ws", on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) # Run WebSocket ws.run_forever() Date Time Of Last Edit: 2024-05-25 13:37:09
|