Skip to content

cointoss.sources.coingecko

coingecko

CoinGecko API client.

MARKET_CHART_MAX_DAYS = 365 module-attribute

How far back /coins/{id}/market_chart reaches without a paid key.

Measured: days=max answers HTTP 401 Unauthorized on the free tier. The ceiling is enforced before the request rather than discovered as a 401, and never quietly clipped to 365, because a window silently shortened to a year looks like a coin that simply has no older history.

MARKETS_MAX_PER_PAGE = 250 module-attribute

The most coins one /coins/markets page returns; a wider listing is paged.

MarketChartRangeUnavailable

Bases: ValueError

More market chart history was asked for than the free tier serves.

Source code in src/cointoss/sources/coingecko.py
class MarketChartRangeUnavailable(ValueError):
    """More market chart history was asked for than the free tier serves."""

OhlcCandle

Bases: BaseModel

OHLC candle. timestamp is milliseconds since epoch (CoinGecko convention).

Source code in src/cointoss/sources/coingecko.py
class OhlcCandle(BaseModel):
    """OHLC candle. `timestamp` is milliseconds since epoch (CoinGecko convention)."""

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore")
    timestamp: int
    open: float
    high: float
    low: float
    close: float

    @property
    def dt(self) -> datetime:
        """Timestamp as a UTC datetime."""
        return datetime.fromtimestamp(self.timestamp / 1000, tz=UTC)

    @model_validator(mode="before")
    @classmethod
    def from_list(cls, data: Any) -> Any:
        # CoinGecko returns OHLC as [ts, o, h, l, c] arrays
        if isinstance(data, list) and len(data) == 5:  # pyright: ignore[reportUnknownArgumentType]
            return {  # pyright: ignore[reportUnknownVariableType]
                "timestamp": data[0],
                "open": data[1],
                "high": data[2],
                "low": data[3],
                "close": data[4],
            }
        return data  # pyright: ignore[reportUnknownVariableType]

dt property

Timestamp as a UTC datetime.

MarketChartPoint

Bases: BaseModel

One [ts, value] pair. timestamp is milliseconds since epoch (CoinGecko convention).

Source code in src/cointoss/sources/coingecko.py
class MarketChartPoint(BaseModel):
    """One `[ts, value]` pair. `timestamp` is milliseconds since epoch (CoinGecko convention)."""

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore")
    timestamp: int
    value: float

    @property
    def dt(self) -> datetime:
        """Timestamp as a UTC datetime."""
        return datetime.fromtimestamp(self.timestamp / 1000, tz=UTC)

    @model_validator(mode="before")
    @classmethod
    def from_list(cls, data: Any) -> Any:
        # CoinGecko returns each market chart series as [ts, value] arrays
        if isinstance(data, list) and len(data) == 2:  # pyright: ignore[reportUnknownArgumentType]
            return {"timestamp": data[0], "value": data[1]}  # pyright: ignore[reportUnknownVariableType]
        return data  # pyright: ignore[reportUnknownVariableType]

dt property

Timestamp as a UTC datetime.

MarketChart

Bases: BaseModel

Three parallel series over one time range: price, market cap and traded volume.

Measured against the live API, the three carry identical timestamps, but nothing in the payload guarantees that, so they are kept as three series rather than zipped into one row type here. cointoss.prices.bars_from_market_chart aligns them by UTC day.

Source code in src/cointoss/sources/coingecko.py
class MarketChart(BaseModel):
    """Three parallel series over one time range: price, market cap and traded volume.

    Measured against the live API, the three carry identical timestamps, but nothing in the
    payload guarantees that, so they are kept as three series rather than zipped into one row
    type here. `cointoss.prices.bars_from_market_chart` aligns them by UTC day.
    """

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore")
    prices: list[MarketChartPoint] = []
    market_caps: list[MarketChartPoint] = []
    total_volumes: list[MarketChartPoint] = []

CoinGeckoClient

Bases: NamespaceFragment

Async HTTP client for the CoinGecko public API.

Parameters:

Name Type Description Default
rpm float | None

Max requests per minute. None means no local rate limiting. CoinGecko demo API allows ~30 rpm.

None
Source code in src/cointoss/sources/coingecko.py
class CoinGeckoClient(NamespaceFragment):
    """Async HTTP client for the CoinGecko public API.

    Args:
        rpm: Max requests per minute. None means no local rate limiting.
            CoinGecko demo API allows ~30 rpm.
    """

    def __init__(self, rpm: float | None = None) -> None:
        self._min_interval: float | None = 60.0 / rpm if rpm else None
        self._last_request: float = 0.0

    async def _get(self, path: str, params: dict[str, str] | None = None) -> Any:
        """Make a GET request and return parsed JSON.

        Enforces the rpm interval between requests.
        On HTTP 429, reads the Retry-After header and sleeps before retrying.
        """
        url = f"{BASE_URL}{path}"
        if params:
            url = f"{url}?{urlencode(params)}"
        client = AsyncHTTPClient()
        while True:
            # Enforce local rate limit
            if self._min_interval is not None:
                elapsed = time.monotonic() - self._last_request
                if elapsed < self._min_interval:
                    await asyncio.sleep(self._min_interval - elapsed)
            try:
                self._last_request = time.monotonic()
                response = await client.fetch(url)
                return json.loads(response.body)
            except HTTPClientError as exc:
                if exc.code != 429:
                    raise
                retry_after = 60.0
                if exc.response and exc.response.headers.get("Retry-After"):
                    try:
                        retry_after = float(exc.response.headers["Retry-After"])
                    except ValueError:
                        pass
                log.warning("Rate limited on %s, retrying after %.0fs", path, retry_after)
                await asyncio.sleep(retry_after)

    @require_cache
    @nsnode(tags=["api"])
    async def fetch_coin_list(
        self,
        *,
        include_platform: bool | None = None,
    ) -> list[CoinListItem]:
        """Fetch the full list of coins from /coins/list.

        Args:
            include_platform: Include platform contract addresses.
                API default: false.
        """
        params = _build_params(include_platform=include_platform)
        data = await self._get("/coins/list", params or None)
        return [CoinListItem.model_validate(item) for item in data]

    @require_cache
    @nsnode(tags=["api"])
    async def fetch_coins_markets(
        self,
        vs_currency: str = "usd",
        *,
        ids: str | None = None,
        names: str | None = None,
        symbols: str | None = None,
        include_tokens: str | None = None,
        category: str | None = None,
        order: str | None = None,
        per_page: int | None = None,
        page: int | None = None,
        sparkline: bool | None = None,
        price_change_percentage: str | None = None,
        locale: str | None = None,
        precision: str | None = None,
        include_rehypothecated: bool | None = None,
    ) -> list[CoinsMarketItem]:
        """Fetch coin market data from /coins/markets.

        Args:
            vs_currency: Target currency of market data. API default: usd.
            ids: Coin IDs, comma-separated.
            names: Coin names, comma-separated.
            symbols: Coin symbols, comma-separated.
            include_tokens: For symbol lookups: "top" or "all".
            category: Filter by category slug.
            order: Sort order. API default: market_cap_desc.
            per_page: Results per page (1-250). API default: 100.
            page: Page number. API default: 1.
            sparkline: Include 7-day sparkline. API default: false.
            price_change_percentage: Price change timeframes, comma-separated
                (1h, 24h, 7d, 14d, 30d, 200d, 1y).
            locale: Localization language. API default: en.
            precision: Decimal places for price ("full" or "0"-"18").
            include_rehypothecated: Include rehypothecated tokens. API default: false.
        """
        params = _build_params(
            vs_currency=vs_currency,
            ids=ids,
            names=names,
            symbols=symbols,
            include_tokens=include_tokens,
            category=category,
            order=order,
            per_page=per_page,
            page=page,
            sparkline=sparkline,
            price_change_percentage=price_change_percentage,
            locale=locale,
            precision=precision,
            include_rehypothecated=include_rehypothecated,
        )
        data = await self._get("/coins/markets", params or None)
        return [CoinsMarketItem.model_validate(item) for item in data]

    @require_cache
    @nsnode(tags=["api"])
    async def fetch_coin(
        self,
        coin_id: str,
        *,
        localization: bool | None = None,
        tickers: bool | None = None,
        market_data: bool | None = None,
        community_data: bool | None = None,
        developer_data: bool | None = None,
        sparkline: bool | None = None,
        include_categories_details: bool | None = None,
        dex_pair_format: str | None = None,
    ) -> CoinDetail:
        """Fetch coin detail from /coins/{id}.

        Args:
            coin_id: CoinGecko coin ID.
            localization: Include localized languages. API default: true.
            tickers: Include tickers data. API default: true.
            market_data: Include market data. API default: true.
            community_data: Include community data. API default: true.
            developer_data: Include developer data. API default: true.
            sparkline: Include 7-day sparkline. API default: false.
            include_categories_details: Include category details. API default: false.
            dex_pair_format: DEX pair format: "contract_address" or "symbol".
                API default: contract_address.
        """
        params = _build_params(
            localization=localization,
            tickers=tickers,
            market_data=market_data,
            community_data=community_data,
            developer_data=developer_data,
            sparkline=sparkline,
            include_categories_details=include_categories_details,
            dex_pair_format=dex_pair_format,
        )
        data = await self._get(f"/coins/{coin_id}", params or None)
        return CoinDetail.model_validate(data)

    @require_cache
    @nsnode(tags=["api"])
    async def fetch_coin_ohlc(
        self,
        coin_id: str,
        vs_currency: str = "usd",
        days: str = "30",
        *,
        precision: str | None = None,
    ) -> list[OhlcCandle]:
        """Fetch OHLC candle data from /coins/{id}/ohlc.

        Args:
            coin_id: CoinGecko coin ID.
            vs_currency: Target currency. API default: usd.
            days: Data up to N days ago (1, 7, 14, 30, 90, 180, 365).
            precision: Decimal places for price ("full" or "0"-"18").
        """
        params = _build_params(
            vs_currency=vs_currency,
            days=days,
            precision=precision,
        )
        data = await self._get(f"/coins/{coin_id}/ohlc", params or None)
        return [OhlcCandle.model_validate(item) for item in data]

    @require_cache
    @nsnode(tags=["api"])
    async def fetch_market_chart(
        self,
        coin_id: str,
        vs_currency: str = "usd",
        days: str | int = MARKET_CHART_MAX_DAYS,
        *,
        interval: str | None = None,
        precision: str | None = None,
    ) -> MarketChart:
        """Fetch price, market cap and volume series from /coins/{id}/market_chart.

        The only CoinGecko endpoint that yields daily points with volume; `/coins/{id}/ohlc` is
        4-hourly below 90 days and 4-daily above it and carries no volume at all. Measured,
        `days=365` returns 366 points spaced 24 hours apart on 00:00 UTC plus a trailing point
        at the current time. Granularity is chosen by the API from `days`: hourly below 90 days,
        daily at 90 and above.

        Rate-limited hard enough to throttle on a second immediate call, so construct the client
        with `rpm` when fetching more than one coin.

        Args:
            coin_id: CoinGecko coin ID.
            vs_currency: Target currency. API default: usd.
            days: Data up to N days ago, 1 to 365. Larger windows and `max` need a paid key and
                raise `MarketChartRangeUnavailable` rather than being clipped or 401ing.
            interval: Force a data interval ("5m", "hourly", "daily"). Paid tiers only; omit it
                to take the automatic granularity.
            precision: Decimal places for price ("full" or "0"-"18").
        """
        params = _build_params(
            vs_currency=vs_currency,
            days=_checked_days(days),
            interval=interval,
            precision=precision,
        )
        data = await self._get(f"/coins/{coin_id}/market_chart", params or None)
        return MarketChart.model_validate(data)

fetch_coin_list(*, include_platform=None) async

Fetch the full list of coins from /coins/list.

Parameters:

Name Type Description Default
include_platform bool | None

Include platform contract addresses. API default: false.

None
Source code in src/cointoss/sources/coingecko.py
@require_cache
@nsnode(tags=["api"])
async def fetch_coin_list(
    self,
    *,
    include_platform: bool | None = None,
) -> list[CoinListItem]:
    """Fetch the full list of coins from /coins/list.

    Args:
        include_platform: Include platform contract addresses.
            API default: false.
    """
    params = _build_params(include_platform=include_platform)
    data = await self._get("/coins/list", params or None)
    return [CoinListItem.model_validate(item) for item in data]

fetch_coins_markets(vs_currency='usd', *, ids=None, names=None, symbols=None, include_tokens=None, category=None, order=None, per_page=None, page=None, sparkline=None, price_change_percentage=None, locale=None, precision=None, include_rehypothecated=None) async

Fetch coin market data from /coins/markets.

Parameters:

Name Type Description Default
vs_currency str

Target currency of market data. API default: usd.

'usd'
ids str | None

Coin IDs, comma-separated.

None
names str | None

Coin names, comma-separated.

None
symbols str | None

Coin symbols, comma-separated.

None
include_tokens str | None

For symbol lookups: "top" or "all".

None
category str | None

Filter by category slug.

None
order str | None

Sort order. API default: market_cap_desc.

None
per_page int | None

Results per page (1-250). API default: 100.

None
page int | None

Page number. API default: 1.

None
sparkline bool | None

Include 7-day sparkline. API default: false.

None
price_change_percentage str | None

Price change timeframes, comma-separated (1h, 24h, 7d, 14d, 30d, 200d, 1y).

None
locale str | None

Localization language. API default: en.

None
precision str | None

Decimal places for price ("full" or "0"-"18").

None
include_rehypothecated bool | None

Include rehypothecated tokens. API default: false.

None
Source code in src/cointoss/sources/coingecko.py
@require_cache
@nsnode(tags=["api"])
async def fetch_coins_markets(
    self,
    vs_currency: str = "usd",
    *,
    ids: str | None = None,
    names: str | None = None,
    symbols: str | None = None,
    include_tokens: str | None = None,
    category: str | None = None,
    order: str | None = None,
    per_page: int | None = None,
    page: int | None = None,
    sparkline: bool | None = None,
    price_change_percentage: str | None = None,
    locale: str | None = None,
    precision: str | None = None,
    include_rehypothecated: bool | None = None,
) -> list[CoinsMarketItem]:
    """Fetch coin market data from /coins/markets.

    Args:
        vs_currency: Target currency of market data. API default: usd.
        ids: Coin IDs, comma-separated.
        names: Coin names, comma-separated.
        symbols: Coin symbols, comma-separated.
        include_tokens: For symbol lookups: "top" or "all".
        category: Filter by category slug.
        order: Sort order. API default: market_cap_desc.
        per_page: Results per page (1-250). API default: 100.
        page: Page number. API default: 1.
        sparkline: Include 7-day sparkline. API default: false.
        price_change_percentage: Price change timeframes, comma-separated
            (1h, 24h, 7d, 14d, 30d, 200d, 1y).
        locale: Localization language. API default: en.
        precision: Decimal places for price ("full" or "0"-"18").
        include_rehypothecated: Include rehypothecated tokens. API default: false.
    """
    params = _build_params(
        vs_currency=vs_currency,
        ids=ids,
        names=names,
        symbols=symbols,
        include_tokens=include_tokens,
        category=category,
        order=order,
        per_page=per_page,
        page=page,
        sparkline=sparkline,
        price_change_percentage=price_change_percentage,
        locale=locale,
        precision=precision,
        include_rehypothecated=include_rehypothecated,
    )
    data = await self._get("/coins/markets", params or None)
    return [CoinsMarketItem.model_validate(item) for item in data]

fetch_coin(coin_id, *, localization=None, tickers=None, market_data=None, community_data=None, developer_data=None, sparkline=None, include_categories_details=None, dex_pair_format=None) async

Fetch coin detail from /coins/{id}.

Parameters:

Name Type Description Default
coin_id str

CoinGecko coin ID.

required
localization bool | None

Include localized languages. API default: true.

None
tickers bool | None

Include tickers data. API default: true.

None
market_data bool | None

Include market data. API default: true.

None
community_data bool | None

Include community data. API default: true.

None
developer_data bool | None

Include developer data. API default: true.

None
sparkline bool | None

Include 7-day sparkline. API default: false.

None
include_categories_details bool | None

Include category details. API default: false.

None
dex_pair_format str | None

DEX pair format: "contract_address" or "symbol". API default: contract_address.

None
Source code in src/cointoss/sources/coingecko.py
@require_cache
@nsnode(tags=["api"])
async def fetch_coin(
    self,
    coin_id: str,
    *,
    localization: bool | None = None,
    tickers: bool | None = None,
    market_data: bool | None = None,
    community_data: bool | None = None,
    developer_data: bool | None = None,
    sparkline: bool | None = None,
    include_categories_details: bool | None = None,
    dex_pair_format: str | None = None,
) -> CoinDetail:
    """Fetch coin detail from /coins/{id}.

    Args:
        coin_id: CoinGecko coin ID.
        localization: Include localized languages. API default: true.
        tickers: Include tickers data. API default: true.
        market_data: Include market data. API default: true.
        community_data: Include community data. API default: true.
        developer_data: Include developer data. API default: true.
        sparkline: Include 7-day sparkline. API default: false.
        include_categories_details: Include category details. API default: false.
        dex_pair_format: DEX pair format: "contract_address" or "symbol".
            API default: contract_address.
    """
    params = _build_params(
        localization=localization,
        tickers=tickers,
        market_data=market_data,
        community_data=community_data,
        developer_data=developer_data,
        sparkline=sparkline,
        include_categories_details=include_categories_details,
        dex_pair_format=dex_pair_format,
    )
    data = await self._get(f"/coins/{coin_id}", params or None)
    return CoinDetail.model_validate(data)

fetch_coin_ohlc(coin_id, vs_currency='usd', days='30', *, precision=None) async

Fetch OHLC candle data from /coins/{id}/ohlc.

Parameters:

Name Type Description Default
coin_id str

CoinGecko coin ID.

required
vs_currency str

Target currency. API default: usd.

'usd'
days str

Data up to N days ago (1, 7, 14, 30, 90, 180, 365).

'30'
precision str | None

Decimal places for price ("full" or "0"-"18").

None
Source code in src/cointoss/sources/coingecko.py
@require_cache
@nsnode(tags=["api"])
async def fetch_coin_ohlc(
    self,
    coin_id: str,
    vs_currency: str = "usd",
    days: str = "30",
    *,
    precision: str | None = None,
) -> list[OhlcCandle]:
    """Fetch OHLC candle data from /coins/{id}/ohlc.

    Args:
        coin_id: CoinGecko coin ID.
        vs_currency: Target currency. API default: usd.
        days: Data up to N days ago (1, 7, 14, 30, 90, 180, 365).
        precision: Decimal places for price ("full" or "0"-"18").
    """
    params = _build_params(
        vs_currency=vs_currency,
        days=days,
        precision=precision,
    )
    data = await self._get(f"/coins/{coin_id}/ohlc", params or None)
    return [OhlcCandle.model_validate(item) for item in data]

fetch_market_chart(coin_id, vs_currency='usd', days=MARKET_CHART_MAX_DAYS, *, interval=None, precision=None) async

Fetch price, market cap and volume series from /coins/{id}/market_chart.

The only CoinGecko endpoint that yields daily points with volume; /coins/{id}/ohlc is 4-hourly below 90 days and 4-daily above it and carries no volume at all. Measured, days=365 returns 366 points spaced 24 hours apart on 00:00 UTC plus a trailing point at the current time. Granularity is chosen by the API from days: hourly below 90 days, daily at 90 and above.

Rate-limited hard enough to throttle on a second immediate call, so construct the client with rpm when fetching more than one coin.

Parameters:

Name Type Description Default
coin_id str

CoinGecko coin ID.

required
vs_currency str

Target currency. API default: usd.

'usd'
days str | int

Data up to N days ago, 1 to 365. Larger windows and max need a paid key and raise MarketChartRangeUnavailable rather than being clipped or 401ing.

MARKET_CHART_MAX_DAYS
interval str | None

Force a data interval ("5m", "hourly", "daily"). Paid tiers only; omit it to take the automatic granularity.

None
precision str | None

Decimal places for price ("full" or "0"-"18").

None
Source code in src/cointoss/sources/coingecko.py
@require_cache
@nsnode(tags=["api"])
async def fetch_market_chart(
    self,
    coin_id: str,
    vs_currency: str = "usd",
    days: str | int = MARKET_CHART_MAX_DAYS,
    *,
    interval: str | None = None,
    precision: str | None = None,
) -> MarketChart:
    """Fetch price, market cap and volume series from /coins/{id}/market_chart.

    The only CoinGecko endpoint that yields daily points with volume; `/coins/{id}/ohlc` is
    4-hourly below 90 days and 4-daily above it and carries no volume at all. Measured,
    `days=365` returns 366 points spaced 24 hours apart on 00:00 UTC plus a trailing point
    at the current time. Granularity is chosen by the API from `days`: hourly below 90 days,
    daily at 90 and above.

    Rate-limited hard enough to throttle on a second immediate call, so construct the client
    with `rpm` when fetching more than one coin.

    Args:
        coin_id: CoinGecko coin ID.
        vs_currency: Target currency. API default: usd.
        days: Data up to N days ago, 1 to 365. Larger windows and `max` need a paid key and
            raise `MarketChartRangeUnavailable` rather than being clipped or 401ing.
        interval: Force a data interval ("5m", "hourly", "daily"). Paid tiers only; omit it
            to take the automatic granularity.
        precision: Decimal places for price ("full" or "0"-"18").
    """
    params = _build_params(
        vs_currency=vs_currency,
        days=_checked_days(days),
        interval=interval,
        precision=precision,
    )
    data = await self._get(f"/coins/{coin_id}/market_chart", params or None)
    return MarketChart.model_validate(data)