Skip to main content
Use Cursor to build trading bots and applications powered by The Brain. This guide shows you how to integrate the Gigabrain API into your development workflow with Cursor’s AI assistant.

Prerequisites

  • Cursor editor installed
  • Gigabrain API key from your Profile
  • Basic knowledge of Python or JavaScript

Quick Start

1

Get your API key

  1. Sign in to Gigabrain
  2. Go to Profile → API Keys
  3. Generate a new API key (format: gb_sk_...)
2

Set up your project

Create a new directory for your trading bot:
mkdir gigabrain-bot
cd gigabrain-bot
Create a .env file to store your API key:
GIGABRAIN_API_KEY=gb_sk_your_key_here
Never commit your API key to version control. Add .env to your .gitignore.
3

Configure Cursor rules

Create .cursor/rules.md in your project root to teach Cursor about Gigabrain API patterns:
# Gigabrain API Development Rules

## API Configuration
- Base URL: `https://api.gigabrain.gg`
- All endpoints prefixed with `/v1`
- Authentication: `Authorization: Bearer gb_sk_...`
- Set timeout to at least 600 seconds for all requests

## Response Format
- All responses have a `content` field (not `message`)
- For structured data, add "Respond as JSON" to your query
- Parse the `content` field to access JSON data

## Rate Limits
- 60 requests per minute
- Monitor `X-RateLimit-Remaining-Minute` header
- Implement exponential backoff on 429 errors

## Best Practices
- Always use environment variables for API keys
- Handle errors gracefully (401, 429, 500, 504)
- Cache responses when appropriate
- Log session_id for debugging
- Use structured JSON queries for automation

## Example Query Patterns
- Simple: "What is the price of BTC?"
- Structured: "Get funding rates for top 10 perps. Respond as JSON array with: symbol, funding_rate, open_interest"
- Multi-agent: "Analyze ETH on the 4H chart with technical and microstructure analysis"

Example: Funding Rate Monitor Bot

Build a bot that monitors funding rates and alerts when they reach extreme levels.
funding_monitor.py
import os
import requests
import json
from dotenv import load_dotenv
import time

load_dotenv()

API_KEY = os.getenv("GIGABRAIN_API_KEY")
BASE_URL = "https://api.gigabrain.gg"

def get_funding_rates():
    """Fetch funding rates for top perpetual contracts"""
    response = requests.post(
        f"{BASE_URL}/v1/chat",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "message": "Get funding rates for top 20 perpetual contracts. Respond as JSON array with: symbol, funding_rate, open_interest, long_short_ratio"
        },
        timeout=600
    )

    if response.status_code == 200:
        data = response.json()
        return json.loads(data["content"])
    elif response.status_code == 429:
        retry_after = response.headers.get("Retry-After", 60)
        print(f"Rate limited. Retrying after {retry_after}s")
        time.sleep(int(retry_after))
        return get_funding_rates()
    else:
        raise Exception(f"API Error: {response.status_code}")

def check_extreme_funding(funding_data, threshold=0.03):
    """Alert on extreme funding rates"""
    alerts = []

    for token in funding_data:
        rate = token["funding_rate"]
        if abs(rate) > threshold:
            direction = "LONG" if rate > 0 else "SHORT"
            alerts.append({
                "symbol": token["symbol"],
                "funding_rate": rate,
                "direction": direction,
                "open_interest": token["open_interest"],
                "long_short_ratio": token.get("long_short_ratio")
            })

    return alerts

def main():
    print("🧠 Gigabrain Funding Rate Monitor")
    print("=" * 50)

    funding_data = get_funding_rates()
    alerts = check_extreme_funding(funding_data, threshold=0.02)

    if alerts:
        print(f"\n⚠️  {len(alerts)} EXTREME FUNDING ALERTS:")
        for alert in alerts:
            print(f"\n{alert['symbol']}:")
            print(f"  Funding Rate: {alert['funding_rate']:.4%}")
            print(f"  Direction: {alert['direction']} crowded")
            print(f"  Open Interest: ${alert['open_interest']:,.0f}")
            print(f"  Long/Short Ratio: {alert.get('long_short_ratio', 'N/A')}")
    else:
        print("\n✅ No extreme funding rates detected")

if __name__ == "__main__":
    main()

Using Cursor Composer

Cursor’s Composer feature is perfect for building complex trading bots with Gigabrain. Here’s how to use it effectively:

Example Prompt for Composer

Build a trading signal aggregator that:
1. Fetches Fear & Greed Index from Gigabrain API
2. Gets funding rates for BTC, ETH, SOL
3. Retrieves current narratives with momentum scores
4. Combines all signals into a single "market regime" score
5. Logs results to a JSON file with timestamps

Use the Gigabrain API patterns from .cursor/rules.md
Handle rate limits and errors gracefully
Add proper TypeScript types for all API responses
Cursor will use your .cursor/rules.md to generate code that follows Gigabrain API best practices.

Common Integration Patterns

Pattern 1: Structured Data Queries

Always specify exact fields for consistent responses:
query = """
Get BTC fear and greed index. Respond as JSON with:
fear_greed_index, fear_greed_label, btc_dominance,
altcoin_season_index, market_cap_total
"""

Pattern 2: Error Handling

Implement retry logic for transient errors:
def api_call_with_retry(message, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(
                f"{BASE_URL}/v1/chat",
                headers={"Authorization": f"Bearer {API_KEY}"},
                json={"message": message},
                timeout=600
            )

            if response.status_code == 200:
                return response.json()
            elif response.status_code in [500, 503, 504]:
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)  # Exponential backoff
                    continue
            else:
                response.raise_for_status()

        except requests.exceptions.Timeout:
            if attempt < max_retries - 1:
                continue
            raise

    raise Exception("Max retries exceeded")

Pattern 3: Rate Limit Monitoring

Track your API usage:
def check_rate_limits(response):
    """Monitor rate limit headers"""
    remaining = response.headers.get("X-RateLimit-Remaining-Minute")
    reset_time = response.headers.get("X-RateLimit-Reset-Minute")

    if remaining and int(remaining) < 5:
        print(f"⚠️  Only {remaining} requests remaining until {reset_time}")

Next Steps

Gigabrain provides market intelligence tools, not financial advice. Always implement proper risk management in your trading bots. See the Risk Disclosure.