Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Access CoinGecko crypto market data: spot prices, OHLC, trending coins, exchange listings, NFTs, and global stats.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
tools/derivatives.py
1#!/usr/bin/env python32"""3CoinGecko Derivatives Tools45Tools for fetching derivatives market data including tickers and exchanges.6"""78import os9from dotenv import load_dotenv10import json11import argparse12from typing import Dict, Any1314from core.http_client import proxied_get1516# Load environment variables17load_dotenv()181920# MCP Tool Schemas21MCP_DERIVATIVES_SCHEMA = {22"name": "cg_derivatives",23"title": "CoinGecko Derivatives Tickers",24"description": "Get all derivatives tickers (perpetuals, futures).",25"inputSchema": {26"type": "object",27"properties": {28"include_tickers": {29"type": "string",30"description": "Filter: all, unexpired (default)",31"default": "unexpired",32"enum": ["all", "unexpired"]33}34},35"additionalProperties": False36}37}3839MCP_DERIVATIVES_EXCHANGES_SCHEMA = {40"name": "cg_derivatives_exchanges",41"title": "CoinGecko Derivatives Exchanges",42"description": "Get list of derivatives exchanges with ranking.",43"inputSchema": {44"type": "object",45"properties": {46"order": {47"type": "string",48"description": "Sort by: name_asc, name_desc, open_interest_btc_asc, open_interest_btc_desc, trade_volume_24h_btc_asc, trade_volume_24h_btc_desc",49"default": "open_interest_btc_desc"50},51"per_page": {52"type": "integer",53"description": "Results per page (max 100)",54"default": 50,55"minimum": 1,56"maximum": 10057}58},59"additionalProperties": False60}61}6263MCP_CATEGORIES_SCHEMA = {64"name": "cg_categories",65"title": "CoinGecko Coin Categories",66"description": "Get coin categories with market data (DeFi, L1, L2, Memes, etc.).",67"inputSchema": {68"type": "object",69"properties": {70"order": {71"type": "string",72"description": "Sort by: market_cap_desc, market_cap_asc, name_desc, name_asc, market_cap_change_24h_desc, market_cap_change_24h_asc",73"default": "market_cap_desc"74}75},76"additionalProperties": False77}78}798081def get_api_key() -> str:82"""Get CoinGecko API key from environment."""83api_key = os.getenv("COINGECKO_API_KEY")84if not api_key:85raise ValueError("COINGECKO_API_KEY environment variable is required")86return api_key878889def get_derivatives(include_tickers: str = "unexpired") -> Dict[str, Any]:90"""91Get all derivatives tickers.9293Args:94include_tickers: Filter - all or unexpired9596Returns:97Dictionary with derivatives tickers98"""99api_key = get_api_key()100101url = "https://pro-api.coingecko.com/api/v3/derivatives"102headers = {"x-cg-pro-api-key": api_key}103params = {"include_tickers": include_tickers}104105response = proxied_get(url, headers=headers, params=params, timeout=15)106response.raise_for_status()107data = response.json()108109tickers = []110for item in data:111tickers.append({112"market": item.get("market", ""),113"symbol": item.get("symbol", ""),114"index_id": item.get("index_id"),115"price": item.get("price"),116"price_percentage_change_24h": item.get("price_percentage_change_24h"),117"contract_type": item.get("contract_type"),118"index": item.get("index"),119"basis": item.get("basis"),120"spread": item.get("spread"),121"funding_rate": item.get("funding_rate"),122"open_interest": item.get("open_interest"),123"volume_24h": item.get("volume_24h"),124"last_traded_at": item.get("last_traded_at"),125"expired_at": item.get("expired_at")126})127128return {129"tickers": tickers,130"count": len(tickers),131"filter": include_tickers132}133134135def get_derivatives_exchanges(136order: str = "open_interest_btc_desc",137per_page: int = 50138) -> Dict[str, Any]:139"""140Get list of derivatives exchanges with ranking.141142Args:143order: Sort order144per_page: Results per page (max 100)145146Returns:147Dictionary with derivatives exchanges148"""149api_key = get_api_key()150151url = "https://pro-api.coingecko.com/api/v3/derivatives/exchanges"152headers = {"x-cg-pro-api-key": api_key}153params = {154"order": order,155"per_page": min(per_page, 100)156}157158response = proxied_get(url, headers=headers, params=params, timeout=15)159response.raise_for_status()160data = response.json()161162exchanges = []163for item in data:164exchanges.append({165"id": item.get("id", ""),166"name": item.get("name", ""),167"open_interest_btc": item.get("open_interest_btc"),168"trade_volume_24h_btc": item.get("trade_volume_24h_btc"),169"number_of_perpetual_pairs": item.get("number_of_perpetual_pairs"),170"number_of_futures_pairs": item.get("number_of_futures_pairs"),171"image": item.get("image"),172"year_established": item.get("year_established"),173"country": item.get("country"),174"url": item.get("url")175})176177return {178"exchanges": exchanges,179"count": len(exchanges),180"order": order181}182183184def get_categories(order: str = "market_cap_desc") -> Dict[str, Any]:185"""186Get coin categories with market data.187188Args:189order: Sort order (market_cap_desc, market_cap_change_24h_desc, etc.)190191Returns:192Dictionary with coin categories193"""194api_key = get_api_key()195196url = "https://pro-api.coingecko.com/api/v3/coins/categories"197headers = {"x-cg-pro-api-key": api_key}198params = {"order": order}199200response = proxied_get(url, headers=headers, params=params, timeout=15)201response.raise_for_status()202data = response.json()203204categories = []205for item in data:206categories.append({207"id": item.get("id", ""),208"name": item.get("name", ""),209"market_cap": item.get("market_cap"),210"market_cap_change_24h": item.get("market_cap_change_24h"),211"content": item.get("content"),212"top_3_coins": item.get("top_3_coins", []),213"volume_24h": item.get("volume_24h"),214"updated_at": item.get("updated_at")215})216217return {218"categories": categories,219"count": len(categories),220"order": order221}222223224def main():225"""CLI interface for derivatives tools."""226parser = argparse.ArgumentParser(227description="CoinGecko Derivatives Tools",228formatter_class=argparse.RawDescriptionHelpFormatter229)230231subparsers = parser.add_subparsers(dest="command")232233# Derivatives tickers command234deriv_parser = subparsers.add_parser("derivatives", help="Get derivatives tickers")235deriv_parser.add_argument("--filter", default="unexpired", choices=["all", "unexpired"])236237# Exchanges command238exch_parser = subparsers.add_parser("exchanges", help="Get derivatives exchanges")239exch_parser.add_argument("--order", default="open_interest_btc_desc")240exch_parser.add_argument("--limit", type=int, default=50)241242# Categories command243cat_parser = subparsers.add_parser("categories", help="Get coin categories")244cat_parser.add_argument("--order", default="market_cap_desc")245246parser.add_argument("--schema", action="store_true", help="Output MCP schema")247248args = parser.parse_args()249250if args.schema:251schemas = {252"derivatives": MCP_DERIVATIVES_SCHEMA,253"derivatives_exchanges": MCP_DERIVATIVES_EXCHANGES_SCHEMA,254"categories": MCP_CATEGORIES_SCHEMA255}256print(json.dumps(schemas, indent=2))257return 0258259try:260if args.command == "derivatives":261result = get_derivatives(args.filter)262elif args.command == "exchanges":263result = get_derivatives_exchanges(args.order, args.limit)264elif args.command == "categories":265result = get_categories(args.order)266else:267parser.print_help()268return 0269270print(json.dumps(result, indent=2, ensure_ascii=False))271return 0272273except Exception as e:274print(json.dumps({"error": str(e)}, indent=2))275return 1276277278if __name__ == "__main__":279exit(main())280