Exemples de code

Documentation complète et exemples pratiques

📚 Exemples de code

JavaScript / Node.js

Client API complet

class BetTrackerClient {
  constructor(apiKey, baseURL = 'https://bettracker.io/api') {
    this.apiKey = apiKey;
    this.baseURL = baseURL;
  }

  async executeTool(tool, args = {}) {
    const response = await fetch(`${this.baseURL}/tools/execute`, {
      method: 'POST',
      headers: {
        'X-API-Key': this.apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ tool, arguments: args })
    });

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

    return response.json();
  }

  // 📊 Statistiques & Paris
  async getUserStats(period = 'month') {
    return this.executeTool('get_user_stats', { period });
  }

  async getRecentBets(limit = 10, status = null, mode = null) {
    const args = { limit };
    if (status) args.status = status;
    if (mode) args.mode = mode;
    return this.executeTool('get_recent_bets', args);
  }

  async getBankrollHistory(days = 30) {
    return this.executeTool('get_bankroll_history', { days });
  }

  async getBudgetStatus() {
    return this.executeTool('get_budget_status');
  }

  // 🏇 Courses & Pronostics
  async getTodayRaces() {
    return this.executeTool('get_today_races');
  }

  async getAIPronostics(status = 'validated') {
    return this.executeTool('get_ai_pronostics', { status });
  }

  async searchRaces(hippodromeCode, date, reunionNumber = null) {
    const args = {};
    if (hippodromeCode) args.hippodrome_code = hippodromeCode;
    if (date) args.date = date;
    if (reunionNumber) args.reunion_number = reunionNumber;
    return this.executeTool('search_races', args);
  }

  async analyzeRace(hippodromeCode, raceNumber, date) {
    return this.executeTool('get_pmu_race_analysis', {
      hippodrome_code: hippodromeCode,
      race_number: raceNumber,
      date: date
    });
  }

  // 👤 Compte & Notifications
  async getSubscriptionInfo() {
    return this.executeTool('get_subscription_info');
  }

  async getNotifications(unreadOnly = false) {
    return this.executeTool('get_notifications', { unread_only: unreadOnly });
  }

  async askAIChat(message) {
    return this.executeTool('ask_ai_chat', { message });
  }
}

Exemples d'utilisation

// Initialiser le client
const client = new BetTrackerClient('btk_votre_clé');

// Statistiques du mois
const stats = await client.getUserStats('month');
console.log(`ROI: ${stats.data.roi}, Win Rate: ${stats.data.win_rate}`);

// 10 derniers paris gagnés
const bets = await client.getRecentBets(10, 'won', 'real');
console.log('Paris gagnés:', bets.data.bets);

// Courses du jour
const races = await client.getTodayRaces();
console.log(`${races.data.count} courses aujourd'hui`);

// Pronostics IA validés
const pronostics = await client.getAIPronostics('validated');
console.log('Pronostics IA:', pronostics.data);

// Analyser une course spécifique
const analysis = await client.analyzeRace('M3', 5, '2025-01-15');
console.log('Analyse de la course:', analysis.data);

Python

Client API complet

import requests
from typing import Dict, Any, Optional

class BetTrackerClient:
    def __init__(self, api_key: str, base_url: str = 'https://bettracker.io/api'):
        self.api_key = api_key
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'X-API-Key': api_key,
            'Content-Type': 'application/json'
        })

    def execute_tool(self, tool: str, arguments: Optional[Dict[str, Any]] = None) -> Dict:
        response = self.session.post(
            f'{self.base_url}/tools/execute',
            json={'tool': tool, 'arguments': arguments or {}}
        )
        response.raise_for_status()
        return response.json()

    # 📊 Statistiques & Paris
    def get_user_stats(self, period: str = 'month') -> Dict:
        return self.execute_tool('get_user_stats', {'period': period})

    def get_recent_bets(self, limit: int = 10, status: str = None, mode: str = None) -> Dict:
        args = {'limit': limit}
        if status:
            args['status'] = status
        if mode:
            args['mode'] = mode
        return self.execute_tool('get_recent_bets', args)

    def get_bankroll_history(self, days: int = 30) -> Dict:
        return self.execute_tool('get_bankroll_history', {'days': days})

    def get_budget_status(self) -> Dict:
        return self.execute_tool('get_budget_status')

    # 🏇 Courses & Pronostics
    def get_today_races(self) -> Dict:
        return self.execute_tool('get_today_races')

    def get_ai_pronostics(self, status: str = 'validated') -> Dict:
        return self.execute_tool('get_ai_pronostics', {'status': status})

    def search_races(self, hippodrome_code: str = None, date: str = None, reunion_number: int = None) -> Dict:
        args = {}
        if hippodrome_code:
            args['hippodrome_code'] = hippodrome_code
        if date:
            args['date'] = date
        if reunion_number:
            args['reunion_number'] = reunion_number
        return self.execute_tool('search_races', args)

    def analyze_race(self, hippodrome_code: str, race_number: int, date: str) -> Dict:
        return self.execute_tool('get_pmu_race_analysis', {
            'hippodrome_code': hippodrome_code,
            'race_number': race_number,
            'date': date
        })

    # 👤 Compte & Notifications
    def get_subscription_info(self) -> Dict:
        return self.execute_tool('get_subscription_info')

    def get_notifications(self, unread_only: bool = False) -> Dict:
        return self.execute_tool('get_notifications', {'unread_only': unread_only})

    def ask_ai_chat(self, message: str) -> Dict:
        return self.execute_tool('ask_ai_chat', {'message': message})

Exemples d'utilisation

# Initialiser le client
client = BetTrackerClient('btk_votre_clé')

# Statistiques du mois
stats = client.get_user_stats('month')
print(f"ROI: {stats['data']['roi']}, Win Rate: {stats['data']['win_rate']}")

# Derniers paris
bets = client.get_recent_bets(limit=10, status='won')
print('Paris gagnés:', bets['data']['bets'])

# Courses du jour
races = client.get_today_races()
print(f"{races['data']['count']} courses aujourd'hui")

# Évolution bankroll sur 30 jours
history = client.get_bankroll_history(30)
print('Historique bankroll:', history['data'])

# Analyse d'une course
analysis = client.analyze_race('M3', 5, '2025-01-15')
print('Analyse:', analysis['data'])

React / Next.js

Hook personnalisé TypeScript

import { useState, useEffect } from 'react';

const API_KEY = process.env.NEXT_PUBLIC_BETTRACKER_API_KEY;
const API_URL = process.env.NEXT_PUBLIC_BETTRACKER_API_URL || 'https://bettracker.io/api';

interface ToolResult<T> {
  success: boolean;
  data: T;
}

export function useBetTrackerTool<T>(tool: string, args?: any) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    async function fetchData() {
      try {
        setLoading(true);
        const response = await fetch(`${API_URL}/tools/execute`, {
          method: 'POST',
          headers: {
            'X-API-Key': API_KEY!,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ tool, arguments: args || {} })
        });

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

        const result: ToolResult<T> = await response.json();
        setData(result.data);
      } catch (err) {
        setError(err as Error);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [tool, JSON.stringify(args)]);

  return { data, loading, error };
}

// Composant exemple - Dashboard
function DashboardStats() {
  const { data: stats, loading, error } = useBetTrackerTool('get_user_stats', { period: 'month' });

  if (loading) return <div>Chargement...</div>;
  if (error) return <div>Erreur: {error.message}</div>;
  if (!stats) return null;

  return (
    <div className="grid grid-cols-4 gap-4">
      <div className="p-4 bg-white rounded-lg shadow">
        <h3 className="text-sm text-gray-500">Paris total</h3>
        <p className="text-2xl font-bold">{stats.total_bets}</p>
      </div>
      <div className="p-4 bg-white rounded-lg shadow">
        <h3 className="text-sm text-gray-500">Win Rate</h3>
        <p className="text-2xl font-bold text-green-600">{stats.win_rate}</p>
      </div>
      <div className="p-4 bg-white rounded-lg shadow">
        <h3 className="text-sm text-gray-500">ROI</h3>
        <p className="text-2xl font-bold text-blue-600">{stats.roi}</p>
      </div>
      <div className="p-4 bg-white rounded-lg shadow">
        <h3 className="text-sm text-gray-500">Profit</h3>
        <p className="text-2xl font-bold">{stats.total_profit}€</p>
      </div>
    </div>
  );
}

// Composant exemple - Courses du jour
function TodayRaces() {
  const { data, loading, error } = useBetTrackerTool('get_today_races');

  if (loading) return <p>Chargement des courses...</p>;
  if (error) return <p>Erreur: {error.message}</p>;

  return (
    <div>
      <h2 className="text-xl font-bold mb-4">
        Courses du jour ({data.count})
      </h2>
      <div className="space-y-2">
        {data.races.map((race, index) => (
          <div key={index} className="p-3 bg-gray-50 rounded">
            <span className="font-semibold">{race.hippodrome_code}</span> -
            Course {race.race_number} - {race.start_time}
          </div>
        ))}
      </div>
    </div>
  );
}

Dashboard complet

Récupérer toutes les données en parallèle

async function getDashboardData(apiKey) {
  const client = new BetTrackerClient(apiKey);

  // Exécuter plusieurs requêtes en parallèle
  const [stats, recentBets, todayRaces, budget, pronostics] = await Promise.all([
    client.getUserStats('month'),
    client.getRecentBets(10),
    client.getTodayRaces(),
    client.getBudgetStatus(),
    client.getAIPronostics('validated')
  ]);

  return {
    stats: stats.data,
    recentBets: recentBets.data.bets,
    todayRaces: todayRaces.data.races,
    budget: budget.data,
    pronostics: pronostics.data
  };
}

// Utilisation
const dashboard = await getDashboardData('btk_votre_clé');
console.log('Dashboard complet:', dashboard);

📚 Ressources

💡 Besoin d'aide ?

Consultez notre chatbot IA pour une assistance personnalisée

Ouvrir le chatbot →

🔑 Clé API

Générez votre clé API pour utiliser ces intégrations

Gérer mes clés →

📊 Statistiques

Explorez vos données PMU et paris hippiques

Voir mes stats →