### GetOhlcParams Example Usage Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/api-reference.md Demonstrates how to instantiate and use the GetOhlcParams model. Shows the expected output format for start and end times after validation. ```python from pricehub.models import GetOhlcParams params = GetOhlcParams( broker="binance_spot", symbol="BTCUSDT", interval="1d", start="2024-10-01", end="2024-10-05" ) print(params.start) # 2024-10-01T00:00:00+00:00 print(params.end) # 2024-10-05T00:00:00+00:00 ``` -------------------------------- ### Install Optional Dependencies for Plotting Source: https://github.com/eslazarev/pricehub/blob/main/docs/installation.md Installs libraries needed for generating plots, as shown in later documentation examples. ```bash pip install matplotlib plotly ``` -------------------------------- ### Install Pricehub from Source Source: https://github.com/eslazarev/pricehub/blob/main/docs/installation.md Installs the development version of pricehub. Clone the repository, navigate to the directory, and install using pip. ```bash git clone https://github.com/eslazarev/pricehub.git cd pricehub pip install -e . ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/eslazarev/pricehub/blob/main/docs/contributing.md Clone the repository, create and activate a virtual environment, install the project in editable mode, and install development dependencies. ```bash git clone https://github.com/eslazarev/pricehub.git cd pricehub python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install -e . pip install mypy black pylint pytest pytest-cov pytest-mock ``` -------------------------------- ### Visualization Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Basic example of visualizing OHLC data using matplotlib. Ensure matplotlib is installed (`pip install matplotlib`). ```python import matplotlib.pyplot as plt from pricehub import get_ohlc data = get_ohlc( symbols="BTC/USDT", interval="1h", broker="binance", days=1, ) plt.figure(figsize=(12, 6)) plt.plot(data.index, data['close'], label='Close Price') plt.title('BTC/USDT 1-Hour Close Price (Last 24 Hours)') plt.xlabel('Timestamp') plt.ylabel('Price') plt.legend() plt.grid(True) plt.show() ``` -------------------------------- ### Install Pricehub from PyPI Source: https://github.com/eslazarev/pricehub/blob/main/docs/installation.md Installs the latest stable release of pricehub and its core dependencies. ```bash pip install pricehub ``` -------------------------------- ### Verify Pricehub Installation Source: https://github.com/eslazarev/pricehub/blob/main/docs/installation.md Confirms a successful installation by fetching and printing the head of OHLC data for BTCUSDT from Binance Spot. ```python from pricehub import get_ohlc df = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-03") print(df.head()) ``` -------------------------------- ### Install Optional Dependencies for Parquet Export Source: https://github.com/eslazarev/pricehub/blob/main/docs/installation.md Installs libraries required for exporting data to Parquet format. Choose either pyarrow (recommended) or fastparquet. ```bash pip install pyarrow ``` ```bash pip install fastparquet ``` -------------------------------- ### Backward Pagination Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Demonstrates backward pagination, used by Bybit and OKX, where the API returns the newest data first. Requires reversing the fetched batches. ```python while cursor > start_time: fetch(start_time, cursor) cursor = earliest_candle_time - 1 reverse_batch() ``` -------------------------------- ### Get OHLC Data Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/types.md Demonstrates how to fetch OHLC data for a specific trading pair and interval. The output is a pandas DataFrame with a DatetimeIndex. ```python from pricehub import get_ohlc df = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-05") print(df) # Output: # Open High Low Close Volume # Open time # 2024-10-01 00:00:00 63309.0 63872.0 63000.0 63733.9 39397.714 # 2024-10-02 00:00:00 63700.0 63784.0 61100.0 62134.1 242613.990 # ... print(df.index) # DatetimeIndex(['2024-10-01 00:00:00', '2024-10-02 00:00:00', ...], dtype='datetime64[ns, UTC]', name='Open time', freq=None) print(df['Close'].dtype) # float64 ``` -------------------------------- ### Install and Fetch OHLC Data with PriceHub Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/INDEX.txt Install the library using pip and fetch OHLC data for a specific trading pair and interval. The fetched data is returned as a pandas DataFrame. ```python pip install pricehub ``` ```python from pricehub import get_ohlc df = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-05") print(df.head()) df.to_csv("data.csv") ``` -------------------------------- ### Forward Pagination Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Implements forward pagination, suitable for APIs like Binance, Coinbase, and Bitget Spot/Futures. It naturally orders data by time and uses simple cursor management. ```python while start_time < end_time: fetch(start_time, end_time) start_time = last_candle_time + increment ``` -------------------------------- ### Bidirectional Pagination Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Illustrates bidirectional pagination as used by KuCoin Futures. This pattern detects the data direction and advances forward or backward accordingly to handle changing API behavior. ```python detect_direction(first_timestamp, last_timestamp) if ascending: advance_forward() else: advance_backward() ``` -------------------------------- ### Time-Series Analysis Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Shows basic time-series analysis on retrieved OHLC data, including calculating moving averages. Requires pandas. ```python from pricehub import get_ohlc data = get_ohlc( symbols="BTC/USDT", interval="1h", broker="binance", days=7, # Fetch last 7 days of data ) # Calculate a 20-period simple moving average data['SMA_20'] = data['close'].rolling(window=20).mean() print(data.tail()) ``` -------------------------------- ### Timestamp Formats Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Illustrates various accepted timestamp formats for data retrieval. Ensure your timestamps are in one of these formats. ```python from pricehub import get_ohlc # Example timestamps: # 1. Unix timestamp (seconds) # 2. Unix timestamp (milliseconds) # 3. ISO 8601 format # 4. Date string (YYYY-MM-DD) # 5. Datetime object # 6. Pandas Timestamp object # 7. Pandas DatetimeIndex object data = get_ohlc( symbols="BTC/USDT", interval="1d", broker="binance", start_time=1678886400, # Unix timestamp (seconds) end_time=1678972800000, # Unix timestamp (milliseconds) ) print(data.head()) ``` -------------------------------- ### Handling Different Symbols Across Brokers Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/configuration.md This example shows how to fetch data for the same cryptocurrency (BTC) from different exchanges, using their respective symbol formats. Note the variations like 'BTCUSDT', 'BTC-USDT', and 'XBTUSD'. ```python # With different symbols for different brokers df_binance = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-05") df_kucoin = get_ohlc("kucoin_spot", "BTC-USDT", "1d", "2024-10-01", "2024-10-05") df_kraken = get_ohlc("kraken_spot", "XBTUSD", "1d", "2024-10-01", "2024-10-05") ``` -------------------------------- ### Cursor-Based Pagination Example Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Shows cursor-based pagination, a method managed by the API itself, used by Kraken and KuCoin Spot. It continues fetching data until a null cursor is encountered or an end time is reached. ```python cursor = None while cursor is not None: results, next_cursor = fetch(cursor) cursor = next_cursor break_if(cursor >= end_time) ``` -------------------------------- ### Retrieve 1-day OHLC data from Bybit Spot using timestamps Source: https://github.com/eslazarev/pricehub/blob/main/README.md Fetch daily OHLC data for ETHUSDT from Bybit Spot using Unix timestamps for start and end dates. Note the different units for start (seconds) and end (milliseconds) timestamps. ```python from pricehub import get_ohlc df = get_ohlc( broker="bybit_spot", symbol="ETHUSDT", interval="1d", start=1727740800.0, # Unix timestamp in seconds for "2024-10-01" end=1728086400000, # Unix timestamp in ms for "2024-10-05" ) print(df) ``` ```text Open High Low Close Volume Turnover Open time 2024-10-01 2602.00 2659.31 2413.15 2447.95 376729.77293 9.623060e+08 2024-10-02 2447.95 2499.82 2351.53 2364.01 242498.88477 5.914189e+08 2024-10-03 2364.01 2403.50 2309.75 2349.91 242598.38255 5.716546e+08 2024-10-04 2349.91 2441.82 2339.15 2414.67 178050.43782 4.254225e+08 2024-10-05 2414.67 2428.69 2389.83 2414.54 106665.69595 2.573030e+08 ``` -------------------------------- ### Fetch Bybit Spot OHLC Data with Unix Timestamps (1-Day Interval) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Get OHLC data for ETHUSDT on Bybit Spot using Unix timestamps for start and end dates. PriceHub supports various timestamp formats including seconds and milliseconds. ```python from pricehub import get_ohlc df = get_ohlc( broker="bybit_spot", symbol="ETHUSDT", interval="1d", start=1727740800.0, # Unix seconds end=1728086400000, # Unix milliseconds ) print(df) ``` -------------------------------- ### Get OHLC Data with Minimal Configuration Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/configuration.md Use this snippet for basic OHLC data retrieval with string-formatted dates. Ensure all required parameters are provided. ```python from pricehub import get_ohlc import datetime # Minimal configuration (all required parameters) df = get_ohlc( broker="binance_spot", symbol="BTCUSDT", interval="1d", start="2024-10-01", end="2024-10-05" ) ``` -------------------------------- ### Get Broker Class from Enum Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/api-reference.md Demonstrates how to retrieve the concrete broker implementation class from a Broker enum member and instantiate it. ```python from pricehub.models import Broker broker_enum = Broker.BINANCE_SPOT broker_class = broker_enum.get_broker_class() instance = broker_class() ``` -------------------------------- ### Fetch KuCoin Futures OHLC Data (1-Hour Interval) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Get OHLC data for XBTUSDTM on KuCoin Futures with a 1-hour interval. ```python from pricehub import get_ohlc df = get_ohlc( broker="kucoin_futures", symbol="XBTUSDTM", interval="1h", start="2024-12-01", end="2024-12-02", ) ``` -------------------------------- ### Handle API Rate Limiting Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/errors.md Implement a retry mechanism with a delay when encountering a rate limit error (HTTP 429). This example waits for 60 seconds before continuing. ```python from pricehub import get_ohlc import requests import time symbols = ["BTCUSDT", "ETHUSDT", "BNBUSDT"] for symbol in symbols: try: df = get_ohlc("binance_spot", symbol, "1d", "2024-10-01", "2024-10-02") print(f"Fetched {symbol}") except requests.HTTPError as e: if e.response.status_code == 429: print(f"Rate limited. Waiting 60 seconds...") time.sleep(60) else: raise ``` -------------------------------- ### Fetch Bitget Spot OHLC Data (1-Day Interval) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Get OHLC data for BTCUSDT on Bitget Spot with a 1-day interval. The returned columns include Open, High, Low, Close, Volume, Quote volume, and USDT volume. ```python from pricehub import get_ohlc df = get_ohlc( broker="bitget_spot", symbol="BTCUSDT", interval="1d", start="2024-12-01", end="2024-12-05", ) ``` -------------------------------- ### Retrieve 1-hour OHLC data from KuCoin Spot Source: https://github.com/eslazarev/pricehub/blob/main/README.md Fetch hourly OHLC data for BTC-USDT from KuCoin Spot between specified start and end dates. The data is then printed. ```python from pricehub import get_ohlc df = get_ohlc( broker="kucoin_spot", symbol="BTC-USDT", interval="1h", start="2024-10-01", end="2024-10-02" ) print(df) ``` -------------------------------- ### Plot Daily Close Prices (Binance Futures) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Fetch daily OHLC data for BTCUSDT on Binance Futures for the last year and plot the 'Close' price using Matplotlib. Requires `matplotlib` to be installed. ```python import matplotlib.pyplot as plt from pricehub import get_ohlc df = get_ohlc("binance_futures", "BTCUSDT", "1d", "2023-11-01", "2024-11-01") df["Close"].plot(figsize=(12, 5), title="BTCUSDT Futures — Daily Close") plt.show() ``` -------------------------------- ### Retrieve 1-hour OHLC data from KuCoin Futures Source: https://github.com/eslazarev/pricehub/blob/main/README.md Fetch hourly OHLC data for XBTUSDTM from KuCoin Futures between specified start and end dates. The data is then printed. ```python from pricehub import get_ohlc df = get_ohlc( broker="kucoin_futures", symbol="XBTUSDTM", interval="1h", start="2024-10-01", end="2024-10-02" ) print(df) ``` -------------------------------- ### Plot Weekly Candlestick Chart (Binance Spot) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Fetch weekly OHLC data for BTCUSDT on Binance Spot for the last 5 years and create an interactive candlestick chart using Plotly. Requires `plotly` to be installed. ```python import plotly.graph_objects as go from pricehub import get_ohlc df = get_ohlc("binance_spot", "BTCUSDT", "1w", "2019-11-01", "2024-11-01") fig = go.Figure(go.Candlestick( x=df.index, open=df["Open"], high=df["High"], low=df["Low"], close=df["Close"] )) fig.update_layout(title="BTCUSDT Spot — Weekly OHLC") fig.show() ``` -------------------------------- ### Get OHLC Data with Datetime Objects Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/configuration.md Fetch OHLC data using explicit datetime objects for start and end dates. This provides precise control over the time range. ```python # With explicit datetime objects df = get_ohlc( broker="bybit_linear", symbol="ETHUSDT", interval="1h", start=datetime.datetime(2024, 10, 1), end=datetime.datetime(2024, 10, 2) ) ``` -------------------------------- ### Get OHLC Data Source: https://github.com/eslazarev/pricehub/blob/main/README.md Retrieve Open, High, Low, Close (OHLC) data for a given symbol and interval from a specified broker. Ensure you have pandas installed as the function returns a DataFrame. ```python def get_ohlc(broker: SupportedBroker, symbol: str, interval: Interval, start: Timestamp, end: Timestamp) -> pd.DataFrame: """ Retrieves OHLC data for the specified broker, symbol, interval, and date range. - Parameters: - broker: The broker to fetch data from (e.g., `binance_spot`, `bybit_spot`, `okx_futures`, `kraken_spot`). - symbol: The trading pair symbol (e.g., `BTCUSDT`). - interval: The interval for OHLC data (`1m`, `1h`, `1d`, etc.). - start: Start time of the data (supports various formats). - end: End time of the data (supports various formats). - Returns: - pandas.DataFrame: A DataFrame containing OHLC data. """ ``` -------------------------------- ### Get OHLC Data with Unix Timestamps Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/configuration.md Retrieve OHLC data using Unix timestamps in milliseconds for start and end dates. This is useful when working with systems that provide time in this format. ```python # With Unix timestamps (milliseconds) df = get_ohlc( broker="kraken_spot", symbol="XBTUSD", interval="1w", start=1727740800000, end=1728172800000 ) ``` -------------------------------- ### Get OHLC Data from Binance Spot Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/api-reference.md Use this function to retrieve OHLC candle data for a specified symbol and interval from Binance Spot. Ensure the start timestamp is before the end timestamp. Large date ranges are handled automatically. ```python from pricehub import get_ohlc # Fetch 1-hour OHLC data from Binance Spot df = get_ohlc( broker="binance_spot", symbol="BTCUSDT", interval="1h", start="2024-10-01", end="2024-10-02" ) print(df.head()) # Output: # Open High Low Close Volume # Open time # 2024-10-01 00:00:00 63309.0 63872.0 63000.0 63733.9 39397.714 # 2024-10-01 01:00:00 63733.9 63920.0 63615.0 63800.0 35204.512 ``` -------------------------------- ### Configuration Constants and Rules Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Details runtime configuration, default values, and validation rules for the pricehub library. ```APIDOC ## Configuration ### Description Details runtime configuration, default values, and validation rules for the pricehub library. ### Constants - `TIMEOUT_SEC`: Default request timeout (10 seconds). ### Validation Rules - `GetOhlcParams` validation rules. - Timestamp coercion logic. - Interval validation phases. ### Broker-Specific Configuration - Pagination limits. - Category parameters. ### Environment - Python version requirements (3.8+). - Dependencies table with versions. ``` -------------------------------- ### Catch ValueError for Start Date After End Date Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/errors.md Catch ValueError when the start date is chronologically after the end date. This validation prevents illogical date ranges. ```python from pricehub import get_ohlc # Raises ValueError: The 'start' date must be before the 'end' date. df = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-05", "2024-10-01") ``` ```python try: df = get_ohlc("binance_spot", "BTCUSDT", "1d", end_date, start_date) except ValueError as e: if "start" in str(e) and "before" in str(e): print("Start date must be before end date. Swap your parameters.") ``` -------------------------------- ### KuCoin Spot Broker Implementation Details Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Details for the KuCoin Spot broker, including API endpoint, supported intervals, and DataFrame columns. Uses Unix seconds for requests and backward pagination. ```text Module: pricehub.brokers.broker_kucoin_spot API Endpoint: https://api.kucoin.com/api/v1/market/candles Supported Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 1w Interval Map: String codes with time unit (e.g., "1m" → "1min", "1h" → "1hour") DataFrame Columns: ["Open time", "Open", "High", "Low", "Close", "Volume", "Turnover"] Pagination: Backward pagination using startAt and endAt parameters (Unix seconds). Data is paginated by advancing endAt backward. Deduplication using a dict keyed by timestamp. Implementation Notes: - Uses Unix seconds for API requests - KuCoin returns candles in descending order; stored in dict for deduplication - Column reordering: KuCoin returns [timestamp, open, high, low, close, volume, turnover]; implementation maps open and high correctly but note high/low column order differs - Maximum data points per request is API-dependent (no explicit limit in code) - Status code in response is "200000" for success - Uses raise_for_status() and checks response code - Data is sorted ascending after collection ``` -------------------------------- ### Bitget Spot Broker Implementation Details Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Details for the Bitget Spot broker, including API endpoint, supported intervals, and DataFrame columns. Uses millisecond Unix timestamps and returns 8 columns with a maximum of 1000 data points per request. ```text Module: pricehub.brokers.broker_bitget_spot API Endpoint: https://api.bitget.com/api/v2/spot/market/candles Supported Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 4h, 6h, 12h, 1d, 3d, 1w, 1M Interval Map: Mixed — short codes for some intervals (e.g., "1m" → "1min", "1h" → "1h", "1d" → "1day") DataFrame Columns: ["Open time", "Open", "High", "Low", "Close", "Volume", "Quote volume", "USDT volume"] Pagination: Forward pagination using startTime and endTime parameters (Unix milliseconds). Cursor advances by the last candle's timestamp + 1ms. Implementation Notes: - Uses millisecond Unix timestamps - Returns 8 columns (OHLCV + quote volume + USDT volume) - Maximum 1000 data points per request - Response status code is "00000" for success - Timestamps are filtered within the loop - Data is sorted ascending after collection - Uses raise_for_status() and checks response code ``` -------------------------------- ### Compare Prices Across Exchanges Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/getting-started.md Fetch data for the same symbol and timeframe from different exchanges (e.g., Binance, Bybit, OKX) to compare closing prices. ```python from pricehub import get_ohlc binance = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-05") bybit = get_ohlc("bybit_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-05") okx = get_ohlc("okx_spot", "BTC-USDT", "1d", "2024-10-01", "2024-10-05") print("Binance Close:", binance["Close"].iloc[-1]) print("Bybit Close:", bybit["Close"].iloc[-1]) print("OKX Close:", okx["Close"].iloc[-1]) ``` -------------------------------- ### Import Internal Models and Abstract Base Class Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/README.md Optionally, import internal models and the abstract base class for brokers if needed for advanced usage. ```python from pricehub.models import SupportedBroker, Timestamp, Interval, GetOhlcParams, Broker from pricehub.brokers import BrokerABC # Abstract base; concrete brokers are internal ``` -------------------------------- ### GetOhlcParams Model Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/api-reference.md Defines the structure and validation rules for OHLC fetch parameters. It includes broker, symbol, interval, and time range (start and end). ```APIDOC ## Class GetOhlcParams ### Description Validated request parameters for a single OHLC fetch, used internally by `get_ohlc`. ### Attributes | Attribute | Type | Description | |-----------|------|-------------| | broker | `Broker` | Enum member identifying exchange and market | | symbol | `str` | Native exchange symbol | | interval | `Interval` | Candle interval literal | | start | `arrow.Arrow` | Inclusive window start in UTC | | end | `arrow.Arrow` | Exclusive window end in UTC | ### Validators **`convert_to_arrow(value: Any) -> arrow.Arrow`** (field validator for `start` and `end`) Coerces loose timestamp values to `arrow.Arrow`. Accepts integers/floats (Unix seconds or milliseconds), ISO 8601 strings, `datetime`, `pandas.Timestamp`, or pre-built `arrow.Arrow` instances. - **Raises:** `ValueError` if the value cannot be parsed as a timestamp. **`check_start_before_end(self) -> GetOhlcParams`** (model validator) Ensures `start` precedes `end`. - **Raises:** `ValueError` if `start >= end`. ### Example ```python from pricehub.models import GetOhlcParams params = GetOhlcParams( broker="binance_spot", symbol="BTCUSDT", interval="1d", start="2024-10-01", end="2024-10-05" ) print(params.start) # 2024-10-01T00:00:00+00:00 print(params.end) # 2024-10-05T00:00:00+00:00 ``` ``` -------------------------------- ### Basic Pricehub Usage Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Demonstrates basic retrieval of OHLC candle data for a specified symbol and interval. No API keys are required. ```python from pricehub import get_ohlc # Get 1-hour candles for BTC/USDT on Binance data = get_ohlc( symbols="BTC/USDT", interval="1h", broker="binance", ) print(data.head()) ``` -------------------------------- ### Handling Timeouts Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Demonstrates how to configure and handle request timeouts. If the request exceeds the specified timeout, a timeout error will occur. ```python from pricehub import get_ohlc, PricehubError try: data = get_ohlc( symbols="BTC/USDT", interval="1h", broker="binance", timeout_sec=0.01, # Set a very short timeout to trigger the error ) except PricehubError as e: print(f"Caught expected timeout error: {e}") ``` -------------------------------- ### Compare Across Exchanges Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Illustrates fetching data for the same symbol from different exchanges to compare pricing or liquidity. Ensure to check interval support for each broker. ```python from pricehub import get_ohlc data_binance = get_ohlc( symbols="BTC/USDT", interval="1h", broker="binance", ) data_kraken = get_ohlc( symbols="BTC/USDT", interval="1h", broker="kraken", ) print("Binance Data:") print(data_binance.head()) print("\nKraken Data:") print(data_kraken.head()) ``` -------------------------------- ### Timestamp Formats Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/README.md Examples of accepted timestamp formats, including ISO 8601 strings, Unix timestamps, Python datetime objects, pandas Timestamps, and arrow.Arrow objects. ```python # ISO 8601 string "2024-10-01" # Unix seconds / milliseconds 1727740800 or 1727740800000 # Python datetime/date datetime.datetime(2024, 10, 1) or datetime.date(2024, 10, 1) # pandas.Timestamp pd.Timestamp("2024-10-01") # arrow.Arrow arrow.get("2024-10-01") ``` -------------------------------- ### Bitget Futures Broker Implementation Details Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Details for the Bitget Futures broker, including API endpoint, product type, supported intervals, and DataFrame columns. Uses millisecond Unix timestamps and returns 7 columns with a maximum of 200 data points per request. ```text Module: pricehub.brokers.broker_bitget_futures API Endpoint: https://api.bitget.com/api/v2/mix/market/history-candles Product Type Parameter: "USDT-FUTURES" Supported Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 4h, 6h, 12h, 1d, 1w, 1M Interval Map: Uppercase for some intervals (e.g., "1h" → "1H", "1d" → "1D") DataFrame Columns: ["Open time", "Open", "High", "Low", "Close", "Volume", "Quote volume"] Pagination: Forward pagination (same as spot) Implementation Notes: - Uses millisecond Unix timestamps - Futures endpoint is different from spot: /mix/market/history-candles (vs. /spot/market/candles) - Requires productType parameter set to "USDT-FUTURES" - Returns 7 columns (OHLCV + quote volume, no USDT volume) - Maximum 200 data points per request (vs. 1000 for spot) - Pagination and error handling identical to spot - Data is sorted ascending after collection ``` -------------------------------- ### Load Multiple Symbols Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Demonstrates fetching data for multiple cryptocurrency symbols simultaneously. This is useful for comparative analysis. ```python from pricehub import get_ohlc symbols = [ "BTC/USDT", "ETH/USDT", "SOL/USDT", ] data = get_ohlc( symbols=symbols, interval="4h", broker="binance", ) print(data.head()) ``` -------------------------------- ### Catch ValueError for Invalid Timestamp Format Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/errors.md Handle ValueError exceptions that occur when the start or end date parameters are not in a valid timestamp format. This ensures robust date parsing. ```python from pricehub import get_ohlc # Raises ValueError: Invalid date format for value 'not-a-date': ... df = get_ohlc("binance_spot", "BTCUSDT", "1d", "not-a-date", "2024-10-05") ``` ```python try: df = get_ohlc("binance_spot", "BTCUSDT", "1d", "invalid", "2024-10-05") except ValueError as e: if "Invalid date format" in str(e): print("Could not parse timestamp. Use ISO 8601, Unix timestamp, or datetime object.") ``` -------------------------------- ### Get Bitget Futures Historical Candles Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/api-reference.md Retrieves historical candle data for Bitget Futures. Supports various intervals and a maximum of 200 data points per request. ```APIDOC ## GET /api/v2/mix/market/history-candles ### Description Retrieves historical candle data for Bitget Futures. ### Method GET ### Endpoint https://api.bitget.com/api/v2/mix/market/history-candles ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., BTCUSDT). - **interval** (string) - Required - The interval for the candles (e.g., 1m, 5m, 1h, 1d). Supported intervals: `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `1w`, `1M`. - **startTime** (integer) - Optional - The start time for the data in milliseconds. - **endTime** (integer) - Optional - The end time for the data in milliseconds. - **limit** (integer) - Optional - The maximum number of data points to retrieve (default: 200). ### Response #### Success Response (200) - **openTime** (integer) - Open time of the candle. - **open** (string) - The opening price. - **high** (string) - The highest price. - **low** (string) - The lowest price. - **close** (string) - The closing price. - **volume** (string) - The trading volume. - **quoteVolume** (string) - The quote asset volume. ``` -------------------------------- ### KuCoin Futures Broker Implementation Details Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/broker-implementations.md Details for the KuCoin Futures broker, including API endpoint, supported intervals, and DataFrame columns. Uses Unix milliseconds and bidirectional pagination. ```text Module: pricehub.brokers.broker_kucoin_futures API Endpoint: https://api-futures.kucoin.com/api/v1/kline/query Supported Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d, 1w, 1M Interval Map: Numeric minutes (e.g., "1m" → 1, "1h" → 60, "1d" → 1440, "1M" → 43200) DataFrame Columns: ["Open time", "Open", "High", "Low", "Close", "Volume", "Turnover"] Pagination: Bidirectional pagination. API indicates direction via ascending flag (comparing first and last timestamps). For ascending data, advance forward; for descending, go backward. Implementation Notes: - Uses Unix milliseconds - Interval parameter is "granularity" (numeric minutes) - Step size for pagination is granularity * 60 * 1000 ms - Response format is identical to spot - Data direction is detected by comparing first and last timestamps - Deduplication using dict keyed by timestamp - Uses raise_for_status() and checks response code ``` -------------------------------- ### Broker-Specific Implementations Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Detailed profiles for each of the 14 broker implementations, including their specific API details, pagination strategies, and data handling quirks. ```APIDOC ## Broker Implementations ### Description Provides in-depth technical reference for each of the 14 broker implementations. ### Profiles Detailed profiles for each broker group (e.g., Binance, Bybit, Coinbase Spot, OKX, Kraken, KuCoin, Bitget) including: - Pagination algorithm (forward, backward, bidirectional, cursor-based) - Timestamp handling - Deduplication strategies - Exchange-specific quirks - DataFrame column mapping - API endpoint URLs - Supported intervals ``` -------------------------------- ### Save Fetched Data to Files Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/README.md Save the retrieved OHLC data to various file formats including CSV, Excel, and Parquet. Note that Parquet requires the 'pyarrow' or 'fastparquet' library to be installed. ```python from pricehub import get_ohlc df = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-01-01", "2024-12-31") df.to_csv("btcusdt_daily.csv") df.to_excel("btcusdt_daily.xlsx") df.to_parquet("btcusdt_daily.parquet") # Requires pyarrow or fastparquet ``` -------------------------------- ### Resample to Custom Intervals (e.g., 10 Minutes) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Fetch data at a finer granularity (e.g., 5 minutes) and then resample it to a custom interval (e.g., 10 minutes) using pandas. This is useful when an exchange doesn't natively support the desired interval. ```python from pricehub import get_ohlc df = get_ohlc("bybit_spot", "SOLUSDT", "5m", "2024-10-01", "2024-11-01") df_10m = df.resample("10min").agg({ "Open": "first", "High": "max", "Low": "min", "Close": "last", "Volume": "sum", }) ``` -------------------------------- ### Catching requests.HTTPError Exceptions Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/errors.md This example shows how to use a try-except block to catch `requests.HTTPError` and differentiate between various HTTP status codes like rate limiting (429) or server errors (5xx). ```python import requests from pricehub import get_ohlc try: df = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-02") except requests.HTTPError as e: if e.response.status_code == 429: print("Rate limit exceeded. Wait before retrying.") elif e.response.status_code >= 500: print("Exchange server error. Try again later.") else: print(f"HTTP error: {e}") ``` -------------------------------- ### Retrieve 6-hour OHLC data from Binance Spot Source: https://github.com/eslazarev/pricehub/blob/main/README.md Fetch OHLC data for BTCUSDT from Binance Spot with a 6-hour interval between specified start and end dates. The retrieved data is then printed to the console. ```python from pricehub import get_ohlc df = get_ohlc( broker="binance_spot", symbol="BTCUSDT", interval="6h", start="2024-10-01", end="2024-10-02" ) print(df) ``` ```text Open High Low Close Volume Close time Quote asset volume Number of trades Taker buy base asset volume Taker buy quote asset volume Ignore Open time 2024-10-01 00:00:00 63309.0 63872.0 63000.0 63733.9 39397.714 2024-10-01 05:59:59.999 2.500830e+09 598784.0 19410.785 1.232417e+09 0.0 2024-10-01 06:00:00 63733.9 64092.6 63683.1 63699.9 32857.923 2024-10-01 11:59:59.999 2.100000e+09 446330.0 15865.753 1.014048e+09 0.0 2024-10-01 12:00:00 63700.0 63784.0 61100.0 62134.1 242613.990 2024-10-01 17:59:59.999 1.512287e+10 2583155.0 112641.347 7.022384e+09 0.0 2024-10-01 18:00:00 62134.1 62422.3 60128.2 60776.8 114948.208 2024-10-01 23:59:59.999 7.031801e+09 1461890.0 54123.788 3.312086e+09 0.0 2024-10-02 00:00:00 60776.7 61858.2 60703.3 61466.7 51046.012 2024-10-02 05:59:59.999 3.133969e+09 668558.0 27191.919 1.669187e+09 0.0 ``` -------------------------------- ### Fetch KuCoin Spot OHLC Data (1-Hour Interval) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Retrieve OHLC data for BTC-USDT on KuCoin Spot with a 1-hour interval. Note that KuCoin uses dash-separated symbols. ```python from pricehub import get_ohlc df = get_ohlc( broker="kucoin_spot", symbol="BTC-USDT", interval="1h", start="2024-12-01", end="2024-12-02", ) ``` -------------------------------- ### Get OHLC Data Source: https://github.com/eslazarev/pricehub/blob/main/docs/api.md Retrieves OHLC data for a specified broker, symbol, interval, and date range. Handles pagination automatically. Ensure correct broker, symbol, and interval formats are used. ```python def get_ohlc( broker: SupportedBroker, symbol: str, interval: Interval, start: Timestamp, end: Timestamp, ) -> pandas.DataFrame: ``` -------------------------------- ### Bitget Spot Broker Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/api-reference.md Provides access to Bitget Spot market data. It supports various time intervals and has a limit on data points per request. ```APIDOC ## BrokerBitgetSpot ### Description This class implements the Bitget Spot broker, allowing users to fetch historical kline data. ### API URL `https://api.bitget.com/api/v2/spot/market/candles` ### Supported Intervals `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `3d`, `1w`, `1M` ### Columns `Open time`, `Open`, `High`, `Low`, `Close`, `Volume`, `Quote volume`, `USDT volume` ### Max Data Points 1000 per request ``` -------------------------------- ### Fetch Kraken Futures OHLC Data (1-Hour Interval) Source: https://github.com/eslazarev/pricehub/blob/main/docs/usage.md Retrieve OHLC data for PF_XBTUSD on Kraken Futures with a 1-hour interval. Kraken Futures uses specific symbol notations like `PF_XBTUSD` and supports various intervals. ```python from pricehub import get_ohlc df = get_ohlc( broker="kraken_futures", symbol="PF_XBTUSD", interval="1h", start="2024-12-01", end="2024-12-02", ) ``` -------------------------------- ### Get OHLC with Different Timestamp Formats Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/types.md Demonstrates using get_ohlc with various equivalent timestamp formats: string, Unix epoch integer, and datetime.date object. All these inputs are internally converted to arrow.Arrow objects. ```python from pricehub import get_ohlc import datetime # All equivalent: df1 = get_ohlc("binance_spot", "BTCUSDT", "1d", "2024-10-01", "2024-10-05") df2 = get_ohlc("binance_spot", "BTCUSDT", "1d", 1727740800, 1728172800) df3 = get_ohlc("binance_spot", "BTCUSDT", "1d", datetime.date(2024, 10, 1), datetime.date(2024, 10, 5)) ``` -------------------------------- ### Handling Rate Limiting Source: https://github.com/eslazarev/pricehub/blob/main/_autodocs/MANIFEST.md Illustrates how to handle potential rate limiting errors from exchanges. The library may raise an HTTPError, which can be caught and retried. ```python import time import requests from pricehub import get_ohlc, PricehubError MAX_RETRIES = 5 RETRY_DELAY_SEC = 10 for attempt in range(MAX_RETRIES): try: data = get_ohlc( symbols="BTC/USDT", interval="1m", # Use a frequent interval to increase chance of rate limiting broker="binance", days=1, ) print("Successfully retrieved data.") break except requests.HTTPError as e: if e.response.status_code == 429: # Rate limit error code print(f"Attempt {attempt + 1} failed: Rate limited. Retrying in {RETRY_DELAY_SEC} seconds...") time.sleep(RETRY_DELAY_SEC) else: print(f"Attempt {attempt + 1} failed with HTTP error: {e}") break except PricehubError as e: print(f"Attempt {attempt + 1} failed with Pricehub error: {e}") break except Exception as e: print(f"An unexpected error occurred: {e}") break ```