Skip to content

Okx

OKXKlines

A class that helps downloading klines from OKX.

Usage
from tradingtoolbox.exchanges import OKXKlines


klines = OKXKlines()
df = klines.load_klines(
    "PEPE-USDT-SWAP", "1m", days_ago=30
)

load_klines

load_klines(instrument: str, tf: str, days_ago: int = 1, end=datetime.now()) -> DataFrame

Load klines from the past X days. OKX's api is limited in to a max of 100 items. This method, will loop until it finds the amount needed

Parameters:

Name Type Description Default
instrument str

The instrument to fetch

required
tf str

The timeframe to fetch

required
days_ago int

The number of days ago to look at

1
end

The end date

now()
Source code in src/tradingtoolbox/exchanges/okx.py
def load_klines(
    self, instrument: str, tf: str, days_ago: int = 1, end=datetime.now()
) -> pd.DataFrame:
    """
    Load klines from the past X days.
    OKX's api is limited in to a max of 100 items. This method, will loop until it finds the amount needed

    Parameters:
        instrument: The instrument to fetch
        tf: The timeframe to fetch
        days_ago: The number of days ago to look at
        end: The end date
    """
    df = self._find_kline_file(instrument, tf)

    if df is None:
        df = self._fetch_lines(instrument, tf, None)

    start_date = end - pd.Timedelta(days=days_ago)
    while start_date.timestamp() < df["date"].min():  # type: ignore
        new_df = self._fetch_lines(instrument, tf, df["date"].min())
        df = pd.concat([df, new_df])
        df["d"] = pd.to_datetime(df["date"], unit="ms")
        name = self._get_kline_file_name(instrument, tf)
        print(name)
        df.to_parquet(self._get_kline_file_name(instrument, tf))
        time.sleep(0.1)
        print(df)

    df = df.sort_values(by=["date"], ascending=True)
    df["date"] = pd.to_datetime(df["date"], unit="ms")
    return df