Getting Historical Bars from ByBit API with Python

ByBit is of the most popular crypto exchanges on the market, and many people trade on it. It’s important to use historical data to backtest trading strategies. So I decided to create an article showing you how you can download historical bars from ByBit with Python.

Libraries used:

import requests 
import json 
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import qgrid
import time

Function to get bars from Bybit:

def get_bybit_bars(symbol, interval, startTime, endTime):

    url = ""

    startTime = str(int(startTime.timestamp()))
    endTime   = str(int(endTime.timestamp()))

    req_params = {"symbol" : symbol, 'interval' : interval, 'from' : startTime, 'to' : endTime}

    df = pd.DataFrame(json.loads(requests.get(url, params = req_params).text)['result'])

    if (len(df.index) == 0):
        return None
    df.index = [dt.datetime.fromtimestamp(x) for x in df.open_time]

    return df

Example of how you can call this function:

get_bybit_bars('ETHUSD', 1, dt.datetime(2020, 1, 1), dt.datetime(2020, 2, 1))

The issue with ByBit API is that you can get a maximum of 200 bars from it. So if you need to get data for a large portion of the time you have to call it multiple times.

Here is the code you can use to get data for the entire history of 1-minute bars for BTCUSD:

df_list = []
last_datetime = dt.datetime(2018, 1, 1)
while True:
    new_df = get_bybit_bars("BTCUSD", 1, last_datetime,
    if new_df is None:
    last_datetime = max(new_df.index) + dt.timedelta(0, 1)

df = pd.concat(df_list)

This will get you around a 1.07 M record for more than a few years. Downloading data this way might cause a block from the API. So to be nice and avoiding blocking use a time.sleep() function in a look with a small number of seconds.

Leave a Reply

Your email address will not be published. Required fields are marked *