Login Page - Create Account

Support Board


Date/Time: Sun, 24 Nov 2024 13:50:38 +0000



Python code of number of trade bar (Binance)

View Count: 406

[2024-05-24 12:48:51]
User395175 - Posts: 87
Hi, I wonder is it possible for sc to provide the Python code or more detailed explanation of number of trade bar used on Binance, since we cant use sc for crypto live trading, i hope i can use Binance api directly receive tick data and make the same bar chart as sc.
Date Time Of Last Edit: 2024-05-24 13:45:57
[2024-05-24 15:10:44]
John - SC Support - Posts: 36238
We are really not sure what you are asking for. We do not do any coding in Python.

If you want to get data directly from Binance, then you would need to ask Binance about this.
For the most reliable, advanced, and zero cost futures order routing, use the Teton service:
Sierra Chart Teton Futures Order Routing
[2024-05-24 16:08:49]
User395175 - Posts: 87
When using number of trade bar in sc with binance data feed, the details of how sc combines binance tick data into number of trade bar. i want to do the same with python, and make the same bar chart as sc in python with binance data feed.
[2024-05-24 21:58:34]
d9e5c763 - Posts: 108
I think it's impossible to implement trading and process tick-by-tick data of binance on sierrachart
I have tried before but gave up because the design of binance's derivatives trading is no different from spot trading, where both are traded based on product quantity, this leads to handling situations where the minimum order unit is not 1, causing a lot of noise and a vast amount of raw data, I think this is why sierrachart does not provide tick-by-tick data, and many exchanges, including binance, have this situation with their derivatives design. the quantity in sierrachart's market depth data files is defined as "uint32", so it cannot support decimal points, and I'm not sure if other types of data can support decimal points.
so therefore, I chose to implement okx exchange's real-time tick-by-tick and market depth data on sierrachart through the dtc protocol, as well as order trading, okx's derivatives minimum trading unit was always 1 and now has introduced decimals like 0.1 and 0.01... this can be easily standardized to 1, and for products with particularly small quotes, it can also be easily standardized to quotes between 1 and 0.1, the only downside is that currently, only 5000+5000 levels of market depth are provided, not as much as binance, however, binance's complete depth data is not publicly accessible and requires a certain vip level.
[2024-05-24 22:38:10]
User395175 - Posts: 87
So u are able to do live trading on okx using sc this way?
[2024-05-24 22:55:07]
User395175 - Posts: 87
What i mean is, i want to use python to make the exact same tick bar chart as sc does, and idk how to achieve it. i can use binance api to receive real-time tick data, and make tick bar chart based on the number of trades, but im not sure if i can make the same tick bar chart as the one in sc (same timestamp, same high, low, open, close value at each bar)
Date Time Of Last Edit: 2024-05-24 23:00:56
[2024-05-24 23:14:45]
d9e5c763 - Posts: 108
yes, I can trade okx products on sierrachart using the dtc protocol and display various account information; you don't need to worry about these details, you only need to feed tick-by-tick data into sierrachart through the dtc protocol; my program is written in python and is only about 5K lines long; I am simply stating that you should not attempt to implement binance's live trading functionality and other on sierrachart, as this is likely to be infeasible.
[2024-05-24 23:22:49]
User395175 - Posts: 87
Well, i didn't plan to do trading on sc, but maybe i can use dtc to feed binance tick data into sc and display real-time tick bar chart in sc too? i mean, sc can do it already, but if i feed binance real-time tick data by myself using ur method, it can reduce latency if i use aws server in Tokyo?
Date Time Of Last Edit: 2024-05-24 23:25:39
[2024-05-24 23:27:35]
User395175 - Posts: 87
To do living trading, i only need to read price data from sc and use library like ccxt to send orders to binance directly in python.
[2024-05-24 23:58:56]
d9e5c763 - Posts: 108
sure, this can be implemented, most likely theoretically.
here is the python code for the dtc protocol implementation that I wrote: https://github.com/jseparovic/python-ws-dtc-client
additionally, the biggest problem may be that you need to manage historical data, okx can directly download daily complete tick-by-tick data, and the compressed package size is only a few hundred MiB per day, binance must be much larger, and there seems to be no direct download method.
this is just my personal opinions, and it does not mean that it is really infeasible.
[2024-05-25 12:12:45]
User395175 - Posts: 87
What if i dont want to feed historical data, only real-time tick bar chart?
[2024-05-25 12:15:03]
User395175 - Posts: 87
im curious how sc connect to binance data feed, maybe also used dtc? if sc can provide a way to connect binnace data feed using our own binance websocket api, then it would be nice.
[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

To post a message in this thread, you need to log in with your Sierra Chart account:

Login

Login Page - Create Account