PeakBot Docs
Bots EndpointBot Data

Bot Logs

Create log entries for bot operations and debugging

Create log entries to track bot operations, errors, and debugging information. Logs can be associated with specific user broker accounts for better traceability.

Endpoint

POST /api/bots/:slug/logs

Authentication

All requests require bot API key authentication via the x-api-key header.

headers: {
  'x-api-key': 'your-bot-api-key'
}

Path Parameters

ParameterTypeRequiredDescription
slugstringYesBot identifier (alphanumeric, hyphens, underscores only)

Slug Validation

The slug must match the regex pattern: /^[a-zA-Z0-9_-]+$/

Request Body

{
  level: "info" | "warn" | "error" | "debug";
  message: string;
  userBrokerAccountId?: string;  // UUID format
  metadata?: Record<string, unknown>;
}

Request Body Schema

FieldTypeRequiredDescription
levelstringYesLog level. Must be one of: "info", "warn", "error", "debug"
messagestringYesLog message content
userBrokerAccountIdstring (UUID)NoOptional UUID of the user broker account associated with this log entry
metadataRecord<string, unknown>NoOptional additional metadata as key-value pairs

Validation Rules

  • level must be exactly one of: "info", "warn", "error", "debug"
  • message must be a non-empty string
  • userBrokerAccountId must be a valid UUID format if provided: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
  • If userBrokerAccountId is provided, the account must exist in the system

Response

Success Response (200 OK)

{
  "success": true,
  "log": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "botId": "123e4567-e89b-12d3-a456-426614174000",
    "level": "info",
    "message": "Trade executed successfully",
    "createdAt": "2024-01-15T10:30:00.000Z"
  }
}

Response Schema

FieldTypeDescription
successbooleanAlways true for successful requests
logobjectCreated log entry
log.idstringUUID of the created log entry
log.botIdstringUUID of the bot
log.levelstringLog level
log.messagestringLog message
log.createdAtstringISO 8601 timestamp of log creation

Error Responses

400 Bad Request

Invalid JSON:

{
  "error": "Invalid JSON in request body",
  "code": "BAD_REQUEST"
}

Missing required field:

{
  "error": "level is required and must be a string",
  "code": "BAD_REQUEST"
}

Invalid log level:

{
  "error": "level must be one of: info, warn, error, debug",
  "code": "BAD_REQUEST"
}

Invalid UUID format:

{
  "error": "userBrokerAccountId must be a valid UUID",
  "code": "BAD_REQUEST"
}

Invalid slug format:

{
  "error": "Invalid slug format. Only alphanumeric characters, hyphens, and underscores are allowed.",
  "code": "BAD_REQUEST"
}

401 Unauthorized

Missing API key:

{
  "message": "API key required. Include x-api-key header."
}

403 Forbidden

Invalid API key:

{
  "message": "Invalid API key for this bot"
}

404 Not Found

Bot not found:

{
  "error": "Bot with slug 'my-bot' not found",
  "code": "NOT_FOUND"
}

Account not found:

{
  "error": "User broker account with id '550e8400-e29b-41d4-a716-446655440000' not found",
  "code": "NOT_FOUND"
}

500 Internal Server Error

{
  "error": "Internal server error",
  "code": "INTERNAL_SERVER_ERROR"
}

Code Examples

TypeScript

async function createBotLog(
  botSlug: string,
  apiKey: string,
  level: "info" | "warn" | "error" | "debug",
  message: string,
  userBrokerAccountId?: string,
  metadata?: Record<string, unknown>
) {
  const response = await fetch(`https://api.example.com/api/bots/${botSlug}/logs`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": apiKey,
    },
    body: JSON.stringify({
      level,
      message,
      ...(userBrokerAccountId && { userBrokerAccountId }),
      ...(metadata && { metadata }),
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Failed to create log: ${error.error}`);
  }

  return await response.json();
}

// Example usage
const log = await createBotLog(
  "my-trading-bot",
  "your-api-key",
  "info",
  "Trade executed successfully",
  "550e8400-e29b-41d4-a716-446655440000",
  { tradeId: "123", symbol: "AAPL" }
);
console.log("Log created:", log.log.id);

Python

import requests
from typing import Optional, Dict, Any, Literal

def create_bot_log(
    bot_slug: str,
    api_key: str,
    level: Literal["info", "warn", "error", "debug"],
    message: str,
    user_broker_account_id: Optional[str] = None,
    metadata: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """
    Create a bot log entry.
    
    Args:
        bot_slug: Bot identifier
        api_key: Bot API key
        level: Log level (info, warn, error, debug)
        message: Log message
        user_broker_account_id: Optional UUID of user broker account
        metadata: Optional metadata dictionary
        
    Returns:
        Response dictionary with created log entry
        
    Raises:
        requests.HTTPError: If the request fails
    """
    url = f"https://api.example.com/api/bots/{bot_slug}/logs"
    
    payload = {
        "level": level,
        "message": message
    }
    
    if user_broker_account_id:
        payload["userBrokerAccountId"] = user_broker_account_id
    
    if metadata:
        payload["metadata"] = metadata
    
    headers = {
        "Content-Type": "application/json",
        "x-api-key": api_key
    }
    
    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()
    
    return response.json()

# Example usage
log = create_bot_log(
    bot_slug="my-trading-bot",
    api_key="your-api-key",
    level="info",
    message="Trade executed successfully",
    user_broker_account_id="550e8400-e29b-41d4-a716-446655440000",
    metadata={"tradeId": "123", "symbol": "AAPL"}
)
print(f"Log created: {log['log']['id']}")

Use Cases

Logging Trade Execution

// Log successful trade execution
await createBotLog(
  "my-bot",
  apiKey,
  "info",
  `Trade executed: ${symbol} ${side} ${quantity} @ ${price}`,
  userBrokerAccountId,
  {
    tradeId: trade.id,
    symbol,
    side,
    quantity,
    price,
    timestamp: new Date().toISOString()
  }
);

Logging Errors

# Log error with context
create_bot_log(
    bot_slug="my-bot",
    api_key=api_key,
    level="error",
    message="Failed to execute order",
    user_broker_account_id=account_id,
    metadata={
        "error": str(e),
        "orderId": order_id,
        "symbol": symbol,
        "retryCount": 3
    }
)

Debug Logging

// Debug log for troubleshooting
await createBotLog(
  "my-bot",
  apiKey,
  "debug",
  "Checking market conditions",
  undefined,
  {
    marketData: {
      price: 150.25,
      volume: 1000000,
      timestamp: Date.now()
    }
  }
);