FortiBlox LogoFortiBlox Docs

🔌 API Usage Guide

Complete guide to using the FortiBlox Oracle API for real-time cryptocurrency price data and market intelligence.

API Usage Guide

Military-Grade Oracle API: Access real-time cryptocurrency price data with 99.9% uptime guarantee, multi-source validation, and enterprise-grade security.

The FortiBlox Oracle API provides developers with programmatic access to real-time cryptocurrency price data, historical charts, market analytics, and data source management. Our military-grade oracle aggregates data from multiple premium sources to ensure maximum accuracy and reliability.

Get API Access →

Quick Start

1. Authentication

All API requests require authentication using a Bearer token in the Authorization header:

# Get your API key from https://oracle.fortiblox.com/subscription
export FORTIBLOX_API_KEY="your_api_key_here"

# Make authenticated requests
curl -X GET "https://oracle.fortiblox.com/api/v1/price/BTC" \
  -H "Authorization: Bearer $FORTIBLOX_API_KEY" \
  -H "Content-Type: application/json"

2. Your First API Call

const apiKey = 'your_api_key_here';
const baseUrl = 'https://oracle.fortiblox.com/api/v1';

async function getBitcoinPrice() {
  const response = await fetch(`${baseUrl}/price/BTC`, {
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    }
  });

  const data = await response.json();
  console.log(`Bitcoin Price: $${data.price}`);
  console.log(`Confidence Score: ${data.confidence}%`);
  return data;
}

getBitcoinPrice();

📚 Oracle Resources

Before diving into API endpoints, explore our comprehensive resource center:

📡 Interactive API Documentation

Access the complete API reference with live testing:

# Get comprehensive API documentation
curl -X GET "https://oracle.fortiblox.com/api/v1/resources/api-docs" \
  -H "Authorization: Bearer YOUR_API_KEY"

Returns: Complete API documentation with:

  • 📊 Interactive Examples: Test endpoints directly in browser
  • 🔧 Authentication Guide: Bearer token setup and usage
  • Rate Limiting Info: Tier-specific request limits
  • 🛡️ Security Features: Military-grade encryption details
  • 🎯 Supported Symbols: Complete list of available cryptocurrencies

💰 Pricing & Subscription Information

Get detailed pricing information for all tiers:

# Get subscription tiers and pricing
curl -X GET "https://oracle.fortiblox.com/api/v1/resources/pricing" \
  -H "Authorization: Bearer YOUR_API_KEY"

Available Subscription Tiers:

  • 🆓 Community Access: 1,000 requests/month, basic support
  • 🏗️ X1 Builders: 50,000 requests/month, FREE for verified builders
  • 💼 Professional: 100,000 requests/month, $29/month
  • 🏢 Enterprise: 1M requests/month, $199/month
  • 🏛️ Ultra Access: Unlimited requests, $999/month

🔧 Simplified Tier Information

Get quick tier comparison data:

# Get simplified tier information
curl -X GET "https://oracle.fortiblox.com/api/v1/resources/tiers" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response includes:

  • 📊 Rate limiting details (requests per second/month)
  • 💰 Pricing breakdown for each tier
  • 🎯 Feature comparison matrix
  • 🔄 Token bucket rate limiting methodology

Core API Endpoints

Price Data Endpoints

Get Single Price

GET /api/v1/price/{symbol}

Parameters:

  • symbol (string, required): Cryptocurrency symbol (BTC, ETH, SOL, etc.)

Response:

{
  "success": true,
  "symbol": "BTC",
  "price": 67890.45,
  "confidence": 94,
  "volume24h": 6433479490.25,
  "change24h": -0.49,
  "high24h": 68773.1,
  "low24h": 67370.0,
  "sources": ["CoinGecko", "Binance US", "Coinbase Pro", "Kraken Pro"],
  "timestamp": "2025-09-17T15:02:07.805Z",
  "source": "Military-Grade Airgapped Oracle"
}

Example:

curl -X GET "https://oracle.fortiblox.com/api/v1/price/BTC" \
  -H "Authorization: Bearer YOUR_API_KEY"

Get Multiple Prices

GET /api/v1/prices?symbols=BTC,ETH,SOL

Parameters:

  • symbols (string, required): Comma-separated list of symbols (max 50)

Example:

const symbols = ['BTC', 'ETH', 'SOL', 'ADA'];
const response = await fetch(`${baseUrl}/prices?symbols=${symbols.join(',')}`, {
  headers: { 'Authorization': `Bearer ${apiKey}` }
});

const data = await response.json();
console.log(`Retrieved ${data.count} prices`);
data.prices.forEach(price => {
  console.log(`${price.symbol}: $${price.price}`);
});

Get Price History

GET /api/v1/price/{symbol}/history?hours=24&limit=100

Parameters:

  • symbol (string, required): Cryptocurrency symbol
  • hours (number, optional): Time range in hours (default: 24, max: 168)
  • limit (number, optional): Max records to return (default: 100, max: 1000)

Example:

import requests

def get_price_history(symbol, hours=24):
    url = f"https://oracle.fortiblox.com/api/v1/price/{symbol}/history"
    params = {"hours": hours, "limit": 100}
    headers = {"Authorization": f"Bearer {api_key}"}

    response = requests.get(url, params=params, headers=headers)
    data = response.json()

    print(f"Retrieved {data['count']} historical records for {symbol}")
    return data['history']

btc_history = get_price_history('BTC', hours=168)  # Last week

Data Sources Endpoints

Get Data Sources

GET /api/v1/data-sources

Response:

{
  "success": true,
  "count": 10,
  "sources": [
    {
      "id": "binance",
      "name": "Binance",
      "provider": "binance",
      "category": "cex",
      "type": "api",
      "enabled": true,
      "status": "active",
      "stats": {
        "totalKeys": 3,
        "activeKeys": 2,
        "avgUptime24h": 99.5,
        "avgResponseTime": 231
      }
    }
  ]
}

Get Source Statistics

GET /api/v1/data-sources/stats

Example Response:

{
  "success": true,
  "totalSources": 10,
  "activeSources": 9,
  "operationalSources": 8,
  "totalApiKeys": 15,
  "activeApiKeys": 12,
  "totalRequests24h": 45230,
  "avgSuccessRate": 94,
  "activeFeeds": 6,
  "avgConfidence": 92
}

System Information

Get API Documentation

GET /api/v1/resources/api-docs

Returns: Complete API documentation with interactive examples

Get Subscription Tiers

GET /api/v1/resources/pricing

Returns: Available subscription tiers with features and pricing

Get System Metrics

GET /api/v1/metrics

Example Response:

{
  "uptime": 11548.304,
  "timestamp": "2025-09-17T15:02:54.428Z",
  "system": {
    "activeFeeds": 6,
    "totalSources": 5,
    "systemHealth": 94.52,
    "averageLatency": 170,
    "requestRate": 12,
    "errorRate": 0.2
  }
}

Subscription Tiers & Rate Limits

🆓 Community Access

1,000 requests/month • Basic support • Primary oracle only

🏗️ X1 Builders

50,000 requests/month • FREE for verified builders • Full oracle access

💼 Professional

100,000 requests/month • $29/month • Enhanced validation

🏢 Enterprise

1M requests/month • $199/month • Priority support

🏛️ Ultra Access

Unlimited requests • $999/month • Dedicated infrastructure

Rate Limiting

All tiers include rate limiting based on requests per second:

  • Community: 1 req/sec
  • X1 Builders: 30 req/sec
  • Professional: 10 req/sec
  • Enterprise: 100 req/sec
  • Ultra: 1,000 req/sec

Code Examples

JavaScript/Node.js

class FortiBloxOracle {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://oracle.fortiblox.com/api/v1';
  }

  async request(endpoint) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`API Error: ${response.status} ${response.statusText}`);
    }

    return response.json();
  }

  async getPrice(symbol) {
    return this.request(`/price/${symbol.toUpperCase()}`);
  }

  async getPrices(symbols) {
    const symbolsStr = symbols.join(',').toUpperCase();
    return this.request(`/prices?symbols=${symbolsStr}`);
  }

  async getPriceHistory(symbol, hours = 24) {
    return this.request(`/price/${symbol.toUpperCase()}/history?hours=${hours}`);
  }

  async getSources() {
    return this.request('/data-sources');
  }
}

// Usage
const oracle = new FortiBloxOracle('your_api_key_here');

// Get single price
const btcPrice = await oracle.getPrice('BTC');
console.log(`Bitcoin: $${btcPrice.price}`);

// Get multiple prices
const prices = await oracle.getPrices(['BTC', 'ETH', 'SOL']);
console.log('Crypto prices:', prices.prices);

// Get price history
const history = await oracle.getPriceHistory('BTC', 168); // Last week
console.log(`Historical data points: ${history.count}`);

Python

import requests
import json
from typing import List, Dict, Optional

class FortiBloxOracle:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://oracle.fortiblox.com/api/v1'
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })

    def _request(self, endpoint: str) -> Dict:
        response = self.session.get(f'{self.base_url}{endpoint}')
        response.raise_for_status()
        return response.json()

    def get_price(self, symbol: str) -> Dict:
        """Get current price for a cryptocurrency symbol."""
        return self._request(f'/price/{symbol.upper()}')

    def get_prices(self, symbols: List[str]) -> Dict:
        """Get current prices for multiple cryptocurrency symbols."""
        symbols_str = ','.join([s.upper() for s in symbols])
        return self._request(f'/prices?symbols={symbols_str}')

    def get_price_history(self, symbol: str, hours: int = 24, limit: int = 100) -> Dict:
        """Get historical price data for a symbol."""
        return self._request(f'/price/{symbol.upper()}/history?hours={hours}&limit={limit}')

    def get_sources(self) -> Dict:
        """Get information about all data sources."""
        return self._request('/data-sources')

    def get_metrics(self) -> Dict:
        """Get system health metrics."""
        return self._request('/metrics')

# Usage example
if __name__ == "__main__":
    oracle = FortiBloxOracle('your_api_key_here')

    # Get Bitcoin price
    btc_data = oracle.get_price('BTC')
    print(f"Bitcoin Price: ${btc_data['price']:,.2f}")
    print(f"Confidence: {btc_data['confidence']}%")

    # Get multiple prices
    portfolio = ['BTC', 'ETH', 'SOL', 'ADA']
    prices_data = oracle.get_prices(portfolio)

    print("\nPortfolio Prices:")
    for price_info in prices_data['prices']:
        print(f"{price_info['symbol']}: ${price_info['price']:,.2f}")

    # Get price history
    history = oracle.get_price_history('BTC', hours=24)
    print(f"\nRetrieved {history['count']} historical data points")

Go

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "strings"
    "time"
)

type FortiBloxOracle struct {
    APIKey  string
    BaseURL string
    Client  *http.Client
}

type PriceData struct {
    Success    bool     `json:"success"`
    Symbol     string   `json:"symbol"`
    Price      float64  `json:"price"`
    Confidence float64  `json:"confidence"`
    Volume24h  float64  `json:"volume24h"`
    Change24h  float64  `json:"change24h"`
    Sources    []string `json:"sources"`
    Timestamp  string   `json:"timestamp"`
}

func NewFortiBloxOracle(apiKey string) *FortiBloxOracle {
    return &FortiBloxOracle{
        APIKey:  apiKey,
        BaseURL: "https://oracle.fortiblox.com/api/v1",
        Client: &http.Client{
            Timeout: 30 * time.Second,
        },
    }
}

func (f *FortiBloxOracle) request(endpoint string) ([]byte, error) {
    req, err := http.NewRequest("GET", f.BaseURL+endpoint, nil)
    if err != nil {
        return nil, err
    }

    req.Header.Set("Authorization", "Bearer "+f.APIKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := f.Client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("API error: %d %s", resp.StatusCode, resp.Status)
    }

    return io.ReadAll(resp.Body)
}

func (f *FortiBloxOracle) GetPrice(symbol string) (*PriceData, error) {
    data, err := f.request("/price/" + strings.ToUpper(symbol))
    if err != nil {
        return nil, err
    }

    var priceData PriceData
    err = json.Unmarshal(data, &priceData)
    if err != nil {
        return nil, err
    }

    return &priceData, nil
}

func main() {
    oracle := NewFortiBloxOracle("your_api_key_here")

    // Get Bitcoin price
    btcPrice, err := oracle.GetPrice("BTC")
    if err != nil {
        fmt.Printf("Error getting BTC price: %v\n", err)
        return
    }

    fmt.Printf("Bitcoin Price: $%.2f\n", btcPrice.Price)
    fmt.Printf("Confidence: %.1f%%\n", btcPrice.Confidence)
    fmt.Printf("24h Change: %.2f%%\n", btcPrice.Change24h)
    fmt.Printf("Sources: %v\n", btcPrice.Sources)
}

Error Handling

HTTP Status Codes

  • 200 OK: Successful request
  • 400 Bad Request: Invalid parameters or request format
  • 401 Unauthorized: Invalid or missing API key
  • 403 Forbidden: API key lacks required permissions
  • 404 Not Found: Resource not found (e.g., unsupported symbol)
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Oracle system error
  • 503 Service Unavailable: Oracle temporarily unavailable

Error Response Format

{
  "success": false,
  "error": "INVALID_SYMBOL",
  "message": "Symbol 'INVALID' is not supported",
  "details": {
    "symbol": "INVALID",
    "supported_symbols": ["BTC", "ETH", "SOL", "ADA", "DOT"]
  },
  "timestamp": "2025-09-17T15:02:07.805Z"
}

Rate Limit Headers

Monitor rate limit status using response headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1663123200
Retry-After: 60

📚 Oracle Resource Endpoints

🎓 Developer Guides

Access comprehensive developer documentation:

# Get developer guides and tutorials
curl -X GET "https://oracle.fortiblox.com/resources/guides" \
  -H "Authorization: Bearer YOUR_API_KEY"

Guide Categories:

  • 🚀 Quick Start: Get up and running in 5 minutes
  • 🔐 Authentication: Secure API key management
  • 📊 Data Integration: Building real-time price feeds
  • 🛡️ Security Best Practices: Enterprise-grade implementation
  • Performance Optimization: Caching and rate limiting
  • 🐛 Troubleshooting: Common issues and solutions

🏗️ Oracle Architecture Models

Understand different oracle implementation patterns:

# Get oracle models and architecture patterns
curl -X GET "https://oracle.fortiblox.com/resources/oracle-models" \
  -H "Authorization: Bearer YOUR_API_KEY"

Oracle Models Available:

  • 🔄 Pull-Based Oracle: Traditional request-response model

    • 💡 Use Cases: Price lookups, batch processing, periodic updates
    • Pros: Simple integration, lower cost, predictable usage
    • Cons: Higher latency, not real-time, manual refresh needed
    • 🎯 Best For: Dashboard applications, daily reports, historical analysis
  • ⚡ Real-Time Streaming: Live WebSocket data streams

    • 💡 Use Cases: Trading applications, live dashboards, arbitrage bots
    • Pros: Instant updates, low latency, event-driven
    • Cons: Higher complexity, more bandwidth, requires WebSocket support
    • 🎯 Best For: Trading platforms, real-time monitoring, automated trading

💻 SDKs & Code Examples

Get client libraries and code samples:

# Get SDKs and code examples
curl -X GET "https://oracle.fortiblox.com/resources/sdks" \
  -H "Authorization: Bearer YOUR_API_KEY"

Available Resources:

  • 📦 Official SDKs: TypeScript, Python, Go, Rust client libraries
  • 💻 Code Examples: Copy-paste examples for all major languages
  • 🔧 Integration Templates: Boilerplate code for common use cases
  • 📱 Mobile Examples: React Native and Flutter implementations
  • 🌐 Web Components: JavaScript widgets and charts
  • 🐳 Docker Examples: Containerized oracle integration

📊 Specific Tier Information

Get detailed information about a specific subscription tier:

# Get details for a specific tier
curl -X GET "https://oracle.fortiblox.com/api/v1/resources/tiers/professional" \
  -H "Authorization: Bearer YOUR_API_KEY"

Tier-Specific Details:

Professional Tier Features:
- Monthly Price: $29 USD
- Requests Per Month: 100,000
- Requests Per Second: 10
- Rate Limit: Token bucket methodology
- Support Level: Email support
- Data Sources: Primary + Secondary + 3 Premium APIs
- Update Frequency: 15 seconds
- Historical Data: 6 months retention
- WebSocket Access: Included
- Priority Support: Standard

Best Practices

1. Implement Proper Error Handling

async function safeApiCall(endpoint) {
  try {
    const response = await fetch(`${baseUrl}${endpoint}`, {
      headers: { 'Authorization': `Bearer ${apiKey}` }
    });

    // Check rate limits
    const remaining = response.headers.get('X-RateLimit-Remaining');
    if (remaining && parseInt(remaining) < 10) {
      console.warn('Rate limit approaching, consider backing off');
    }

    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After');
      throw new Error(`Rate limited. Retry after ${retryAfter} seconds`);
    }

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API Error: ${errorData.message || response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('API call failed:', error);
    throw error;
  }
}

2. Use Caching for Efficiency

class CachedOracle {
  constructor(apiKey, cacheTTL = 60000) { // 1 minute cache
    this.oracle = new FortiBloxOracle(apiKey);
    this.cache = new Map();
    this.cacheTTL = cacheTTL;
  }

  async getPrice(symbol) {
    const key = `price_${symbol}`;
    const cached = this.cache.get(key);

    if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
      return cached.data;
    }

    const data = await this.oracle.getPrice(symbol);
    this.cache.set(key, { data, timestamp: Date.now() });
    return data;
  }
}

3. Batch Requests When Possible

// Instead of multiple single requests
const btc = await oracle.getPrice('BTC');
const eth = await oracle.getPrice('ETH');
const sol = await oracle.getPrice('SOL');

// Use batch request
const prices = await oracle.getPrices(['BTC', 'ETH', 'SOL']);

4. Monitor API Health

async function monitorOracleHealth() {
  try {
    const metrics = await oracle.request('/metrics');

    if (metrics.system.systemHealth < 90) {
      console.warn('Oracle system health degraded:', metrics.system.systemHealth);
    }

    if (metrics.system.errorRate > 5) {
      console.error('High error rate detected:', metrics.system.errorRate);
    }

    return metrics;
  } catch (error) {
    console.error('Health check failed:', error);
  }
}

// Check health every 5 minutes
setInterval(monitorOracleHealth, 5 * 60 * 1000);

Supported Cryptocurrencies

Major Cryptocurrencies

  • BTC - Bitcoin
  • ETH - Ethereum
  • SOL - Solana
  • ADA - Cardano
  • DOT - Polkadot
  • USDC - USD Coin
  • USDT - Tether

DeFi Tokens

  • UNI - Uniswap
  • LINK - Chainlink
  • AAVE - Aave
  • COMP - Compound

Exchange Tokens

  • BNB - Binance Coin
  • CRO - Cronos
  • FTT - FTX Token

Symbol Support: New cryptocurrencies are added regularly. Use the /data-sources endpoint to see the latest supported symbols from each source.

Webhooks & Real-Time Data

WebSocket Connections (Enterprise+)

const ws = new WebSocket('wss://oracle.fortiblox.com/api/v1/ws');

ws.onopen = () => {
  // Authenticate
  ws.send(JSON.stringify({
    type: 'auth',
    api_key: 'your_api_key'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);

  if (data.type === 'price_update') {
    console.log(`${data.symbol} updated: $${data.price}`);
  }
};

// Subscribe to price updates
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'prices',
  symbols: ['BTC', 'ETH', 'SOL']
}));

Security Features

  • 🔒 Military-Grade Encryption: AES-256-GCM encryption for all data
  • 🛡️ Multi-Source Validation: Cross-reference multiple data sources
  • 🔍 Real-Time Anomaly Detection: Automatic detection of price manipulation
  • ⚡ DDoS Protection: Enterprise-grade infrastructure protection
  • 📊 Audit Logging: Complete audit trail of all API requests
  • 🎯 Rate Limiting: Per-API-key rate limiting and abuse prevention

Support & Resources

  • 📧 Technical Support: [email protected]
  • 📚 Documentation: Complete API reference and guides
  • 💬 Discord Community: Join our developer community
  • 🐛 Issue Reporting: GitHub issues for bug reports
  • 🔔 Status Page: Real-time system status updates

API Key Security: Never expose your API key in client-side code or public repositories. Use environment variables and secure storage for production applications.

🚀 Getting Started Checklist

Quick Start for New Developers:

  1. 📖 Explore Resources - Visit https://oracle.fortiblox.com/resources/api-docs
  2. 💰 Choose Your Tier - Review pricing at https://oracle.fortiblox.com/resources/pricing
  3. 🔑 Get API Key - Sign up at https://oracle.fortiblox.com/subscription
  4. 🎓 Follow Guides - Step-by-step tutorials at https://oracle.fortiblox.com/resources/guides
  5. 💻 Download SDKs - Client libraries at https://oracle.fortiblox.com/resources/sdks
  6. 🏗️ Choose Architecture - Oracle models at https://oracle.fortiblox.com/resources/oracle-models
  7. 🚀 Start Building - Implement your first oracle integration
  8. 📊 Monitor Usage - Track consumption and optimize performance

Next Steps