CCXT
Python Examples

Build Ohlcv Bars

Build Ohlcv Bars — CCXT Python code example.

import os
import sys

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
import asyncio
import ccxt.pro as ccxt  # noqa: E402


# AUTO-TRANSPILE #
# Bulding OHLCV array from trades (executions) data is a bit tricky. For example, if you want to build 100 ohlcv bars of 1-minute timeframe, then you have to fetch the 100 minutes of trading data. So, higher timeframe bars require more trading data (i.e. building 100 bars of 1-day timeframe OHLCV would require massive amount of trading data, which might not be desirable for user, because of data-usage rate limits)
async def example_with_fetch_trades():
    exch = ccxt.binance({})
    timeframe = '1m'
    symbol = 'OGN/USDT'
    since = exch.milliseconds() - 1000 * 60 * 30  # last 30 mins
    limit = 1000
    trades = await exch.fetch_trades(symbol, since, limit)
    generated_bars = exch.build_ohlcvc(trades, timeframe, since, limit)
    # you can ignore 6th index ("count" field) from ohlcv entries, which is not part of OHLCV standard structure and is just added internally by `buildOHLCVC` method
    print('[REST] Constructed', len(generated_bars), 'bars from trades: ', generated_bars)

    await exch.close()

async def example_with_watch_trades():
    exch = ccxt.binance({})
    timeframe = '1m'
    symbol = 'DOGE/USDT'
    limit = 1000
    since = exch.milliseconds() - 10 * 60 * 1000 * 1000  # last 10 hrs
    collected_trades = []
    collected_bars = []
    while True:
        ws_trades = await exch.watch_trades(symbol, since, limit, {})
        collected_trades = collected_trades + ws_trades
        generated_bars = exch.build_ohlcvc(collected_trades, timeframe, since, limit)
        # Note: first bar would be partially constructed bar and its 'open' & 'high' & 'low' prices (except 'close' price) would probably have different values compared to real bar on chart, because the first obtained trade timestamp might be somewhere in the middle of timeframe period, so the pre-period would be missing because we would not have trades data. To fix that, you can get older data with `fetchTrades` to fill up bars till start bar.
        for i in range(0, len(generated_bars)):
            bar = generated_bars[i]
            bar_timestamp = bar[0]
            collected_bars_length = len(collected_bars)
            last_collected_bar_timestamp = collected_bars[collected_bars_length - 1][0] if collected_bars_length > 0 else 0
            if bar_timestamp == last_collected_bar_timestamp:
                # if timestamps are same, just updarte the last bar
                collected_bars[collected_bars_length - 1] = bar
            elif bar_timestamp > last_collected_bar_timestamp:
                collected_bars.append(bar)
                # remove the trades from saved array, which were till last collected bar's open timestamp
                collected_trades = exch.filter_by_since_limit(collected_trades, bar_timestamp)
        # Note: first bar would carry incomplete values, please read comment in "buildOHLCVCFromWatchTrades" method definition for further explanation
        print('[WS] Constructed', len(collected_bars), 'bars from', symbol, 'trades: ', collected_bars)


    await exch.close()

asyncio.run(example_with_fetch_trades())


asyncio.run(example_with_watch_trades())