>
API

Stockfish API

v1.0

ChessStake integrates with a powerful Stockfish 17 NNUE engine to provide real-time chess analysis and AI opponent capabilities. This documentation covers the API endpoints, parameters, and response formats.

Engine Specifications

Our Stockfish integration runs on enterprise-grade infrastructure for maximum performance and reliability.

Stockfish 17
Engine Version
NNUE
Neural Network
32 vCores
Processing Power
128GB DDR5
Memory
Powered by chess-api.com

ChessStake uses chess-api.com as the underlying engine provider. The API offers both REST and WebSocket interfaces for real-time analysis.

REST API Endpoint

The primary endpoint for move analysis and best move calculation.

POST https://chess-api.com/v1

Analyzes a chess position and returns the best move with evaluation.

Request Parameters

Parameter Type Status Description
fen string Required FEN string representing the current board position
depth integer Optional Search depth (1-18). Higher values = stronger play. Default: 12
maxThinkingTime integer Optional Maximum thinking time in milliseconds (max: 100ms)
variants integer Optional Number of alternative moves to return (MultiPV)
searchmoves string Optional Space-separated list of moves to consider (UCI format)
taskId string Optional Custom identifier returned in response for request tracking

Request Example

JavaScript
const response = await fetch('https://chess-api.com/v1', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        fen: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1',
        depth: 12,
        maxThinkingTime: 50
    })
});

const data = await response.json();
console.log(data.san);  // e.g., "e5"
console.log(data.move); // e.g., "e7e5"

Response Format

The API returns a JSON object with the following fields:

JSON Response
{
    "type": "move",
    "eval": 0.35,
    "depth": 12,
    "text": "Slightly better is e5",
    "winChance": 52.3,
    "san": "e5",
    "move": "e7e5",
    "from": "e7",
    "to": "e5",
    "isCapture": false,
    "isCastling": false,
    "isPromotion": false,
    "continuationArr": ["Nf3", "Nc6", "Bb5"]
}

Response Fields

type "move" for normal moves, "bestmove" for final results, "info" for intermediate analysis
eval Position evaluation in pawns (positive = white advantage)
depth Search depth reached during analysis
text Human-readable evaluation description
winChance Estimated win probability percentage (0-100)
mate Number of moves to mate (if mate is found), negative if opponent has mate
san Best move in Standard Algebraic Notation (e.g., "Nf3", "O-O")
move Best move in UCI format (e.g., "g1f3", "e1g1")
from / to Source and destination squares of the move
captured Piece captured (if any): "p", "n", "b", "r", "q"
isCapture Boolean indicating if the move captures a piece
isCastling Boolean indicating if the move is castling
isPromotion Boolean indicating if the move is a pawn promotion
continuationArr Array of expected continuation moves (principal variation)

WebSocket API

For real-time streaming analysis, use the WebSocket endpoint. This is ideal for live game analysis where you need continuous position updates.

WebSocket wss://chess-api.com/v1

Maintains a persistent connection for streaming analysis results.

WebSocket Example

JavaScript
const ws = new WebSocket('wss://chess-api.com/v1');

ws.onopen = () => {
    // Send position for analysis
    ws.send(JSON.stringify({
        fen: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1',
        depth: 15
    }));
};

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

    if (data.type === 'info') {
        // Intermediate analysis update
        console.log(`Depth ${data.depth}: ${data.san} (${data.eval})`);
    } else if (data.type === 'bestmove') {
        // Final result
        console.log(`Best move: ${data.san}`);
    }
};

ws.onerror = (error) => {
    console.error('WebSocket error:', error);
};

Skill Levels & Depth Mapping

The depth parameter directly affects the engine's playing strength. ChessStake maps UI skill levels to specific depth values:

Depth Approximate ELO Skill Level Description
1-3 800 - 1200 Beginner Plays simple moves, often misses tactics
4-6 1200 - 1600 Club Player Basic tactical awareness, some positional play
7-9 1600 - 2000 Intermediate Strong tactics, decent positional understanding
10-12 2000 - 2350 Advanced Expert-level play, deep calculation
13-15 2350 - 2550 Master International Master strength
16-18 2550 - 2750+ Grandmaster World-class play, near-perfect moves
Depth Limitations

Maximum depth is capped at 18 for API requests. Higher depths significantly increase response time. For real-time games, depth 12-15 provides an excellent balance of strength and speed.

ChessStake Implementation

ChessStake uses a server-side proxy to communicate with the Stockfish API, providing additional features and rate limiting.

POST /api/stockfish.php

ChessStake's proxy endpoint for Stockfish analysis. Requires authentication.

Proxy Request Format

JavaScript
// ChessStake game.js implementation
async function getStockfishMove(fen, level) {
    const token = localStorage.getItem('token');

    const response = await fetch('/api/stockfish.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            fen: fen,
            depth: level,
            maxThinkingTime: 50
        })
    });

    return await response.json();
}

Rate Limits

To ensure fair usage and platform stability, the following rate limits apply:

100
Requests per minute (authenticated)
100ms
Max thinking time
18
Maximum depth

Error Handling

The API returns standard HTTP status codes and JSON error responses:

Status Code Description Action
200 Success - Move calculated Process the response normally
400 Invalid FEN or parameters Check request format
401 Unauthorized (ChessStake proxy) Verify authentication token
429 Rate limit exceeded Wait before retrying
500 Server error Retry with exponential backoff
Error Response Example
{
    "success": false,
    "error": "Invalid FEN string",
    "code": "INVALID_FEN"
}

Best Practices

Use Appropriate Depth

Match depth to your use case. For real-time games, depth 10-12 provides strong play with fast responses. Reserve higher depths for analysis features.

Handle Timeouts Gracefully

Always implement timeout handling. If the API doesn't respond within a reasonable time, have a fallback strategy or retry logic.

Validate FEN Strings

Always validate FEN strings client-side before sending to the API. Invalid FEN will result in errors and wasted requests.

Use WebSocket for Streaming

For analysis boards or continuous evaluation, prefer WebSocket connections over repeated REST calls for better performance.