API Authentication

Complete guide to authenticating with the Vibe Trading API, including API key management, request signing, and security best practices.

Overview

The Vibe Trading API uses API key-based authentication with HMAC-SHA256 request signing for secure access to trading endpoints and account data.

Authentication Methods

API Key Authentication

  • API Key: Unique identifier for your account
  • Secret Key: Used for request signing (keep this secure)
  • Request Signing: HMAC-SHA256 signature for request validation

OAuth 2.0 (Coming Soon)

  • Authorization Code Flow: For third-party applications
  • Client Credentials: For server-to-server communication
  • Refresh Tokens: For long-term access management

Getting Your API Keys

Step 1: Access API Settings

  1. Log into your Vibe Trading account
  2. Navigate to Account Settings > API Management
  3. Click "Generate New API Key"

Step 2: Configure API Key

  • Name: Descriptive name for your API key
  • Permissions: Select required permissions
  • IP Restrictions: Limit access to specific IP addresses (optional)
  • Expiration: Set expiration date (optional)

Step 3: Save Credentials

  • API Key: Copy and store securely
  • Secret Key: Copy and store securely (shown only once)
  • Permissions: Note the granted permissions

Request Authentication

Headers Required

Every API request must include these headers:

X-API-Key: your_api_key_here
X-Timestamp: 1640995200
X-Signature: calculated_signature_here
Content-Type: application/json

Signature Generation

The signature is calculated using HMAC-SHA256:

// Example signature generation
const crypto = require("crypto");

function generateSignature(secretKey, method, path, body, timestamp) {
  const message = method + path + body + timestamp;
  return crypto.createHmac("sha256", secretKey).update(message).digest("hex");
}

// Usage
const signature = generateSignature(
  secretKey,
  "POST",
  "/api/v1/orders",
  JSON.stringify(orderData),
  timestamp
);

Timestamp Requirements

  • Format: Unix timestamp (seconds since epoch)
  • Tolerance: ±5 minutes from server time
  • Precision: Seconds (not milliseconds)

API Key Permissions

Trading Permissions

  • read:orders: View order history and status
  • write:orders: Create, modify, and cancel orders
  • read:positions: View current positions
  • write:positions: Modify position settings

Account Permissions

  • read:account: View account information and balance
  • read:transactions: View transaction history
  • write:withdrawals: Initiate withdrawals (requires additional verification)

Market Data Permissions

  • read:market: Access market data and price feeds
  • read:signals: View AI trading signals
  • read:analytics: Access trading analytics and reports

Security Best Practices

API Key Management

  • Store Securely: Use environment variables or secure key management
  • Rotate Regularly: Change API keys every 90 days
  • Monitor Usage: Review API activity logs regularly
  • Limit Permissions: Only grant necessary permissions

Request Security

  • Use HTTPS: Always use encrypted connections
  • Validate Timestamps: Ensure accurate system time
  • Rate Limiting: Respect API rate limits
  • Error Handling: Implement proper error handling

Code Examples

Python

import hmac
import hashlib
import time
import requests
import json

class VibeTradingAPI:
    def __init__(self, api_key, secret_key, base_url="https://api.vibetrading.tech"):
        self.api_key = api_key
        self.secret_key = secret_key
        self.base_url = base_url

    def _generate_signature(self, method, path, body, timestamp):
        message = f"{method}{path}{body}{timestamp}"
        return hmac.new(
            self.secret_key.encode(),
            message.encode(),
            hashlib.sha256
        ).hexdigest()

    def _make_request(self, method, path, data=None):
        timestamp = str(int(time.time()))
        body = json.dumps(data) if data else ""
        signature = self._generate_signature(method, path, body, timestamp)

        headers = {
            "X-API-Key": self.api_key,
            "X-Timestamp": timestamp,
            "X-Signature": signature,
            "Content-Type": "application/json"
        }

        url = f"{self.base_url}{path}"
        response = requests.request(method, url, headers=headers, data=body)
        return response.json()

    def get_account(self):
        return self._make_request("GET", "/api/v1/account")

    def create_order(self, order_data):
        return self._make_request("POST", "/api/v1/orders", order_data)

# Usage
api = VibeTradingAPI("your_api_key", "your_secret_key")
account = api.get_account()

JavaScript/Node.js

const crypto = require("crypto");
const axios = require("axios");

class VibeTradingAPI {
  constructor(apiKey, secretKey, baseUrl = "https://api.vibetrading.tech") {
    this.apiKey = apiKey;
    this.secretKey = secretKey;
    this.baseUrl = baseUrl;
  }

  generateSignature(method, path, body, timestamp) {
    const message = `${method}${path}${body}${timestamp}`;
    return crypto
      .createHmac("sha256", this.secretKey)
      .update(message)
      .digest("hex");
  }

  async makeRequest(method, path, data = null) {
    const timestamp = Math.floor(Date.now() / 1000).toString();
    const body = data ? JSON.stringify(data) : "";
    const signature = this.generateSignature(method, path, body, timestamp);

    const headers = {
      "X-API-Key": this.apiKey,
      "X-Timestamp": timestamp,
      "X-Signature": signature,
      "Content-Type": "application/json",
    };

    const url = `${this.baseUrl}${path}`;
    const response = await axios({
      method,
      url,
      headers,
      data: body,
    });

    return response.data;
  }

  async getAccount() {
    return this.makeRequest("GET", "/api/v1/account");
  }

  async createOrder(orderData) {
    return this.makeRequest("POST", "/api/v1/orders", orderData);
  }
}

// Usage
const api = new VibeTradingAPI("your_api_key", "your_secret_key");
const account = await api.getAccount();

Error Handling

Authentication Errors

Invalid API Key (401)

{
  "error": "invalid_api_key",
  "message": "The provided API key is invalid or expired",
  "code": 401
}

Invalid Signature (401)

{
  "error": "invalid_signature",
  "message": "The request signature is invalid",
  "code": 401
}

Timestamp Too Old (401)

{
  "error": "timestamp_too_old",
  "message": "The request timestamp is outside the acceptable time window",
  "code": 401
}

Insufficient Permissions (403)

{
  "error": "insufficient_permissions",
  "message": "Your API key does not have permission to access this resource",
  "code": 403
}

Rate Limiting (429)

{
  "error": "rate_limit_exceeded",
  "message": "Too many requests. Please slow down.",
  "code": 429,
  "retry_after": 60
}

Rate Limits

Default Limits

  • Trading Endpoints: 100 requests per minute
  • Market Data: 1000 requests per minute
  • Account Data: 200 requests per minute

Rate Limit Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995260

Handling Rate Limits

  • Monitor Headers: Check rate limit headers in responses
  • Implement Backoff: Use exponential backoff for retries
  • Cache Data: Cache frequently accessed data
  • Batch Requests: Combine multiple operations when possible

Testing Authentication

Test Endpoint

Use the test endpoint to verify your authentication:

curl -X GET "https://api.vibetrading.tech/api/v1/test" \
  -H "X-API-Key: your_api_key" \
  -H "X-Timestamp: $(date +%s)" \
  -H "X-Signature: calculated_signature"

Expected Response

{
  "status": "success",
  "message": "Authentication successful",
  "timestamp": 1640995200
}

Troubleshooting

Common Issues

Signature Mismatch

  • Check Secret Key: Ensure secret key is correct
  • Verify Message Format: Method + Path + Body + Timestamp
  • Check Encoding: Ensure proper UTF-8 encoding
  • Validate Timestamp: Use Unix timestamp in seconds

Timestamp Errors

  • Sync System Time: Ensure accurate system time
  • Check Timezone: Use UTC time
  • Tolerance Window: Stay within ±5 minutes

Permission Denied

  • Check API Key Permissions: Verify required permissions
  • Review Endpoint Access: Some endpoints require specific permissions
  • Contact Support: For permission issues

Debugging Tips

  • Log Requests: Keep detailed request logs
  • Test with cURL: Use cURL for manual testing
  • Validate Signatures: Use online HMAC calculators for verification
  • Check Network: Ensure stable internet connection

Security Considerations

API Key Security

  • Never Share: Keep API keys private
  • Use Environment Variables: Don't hardcode in source code
  • Implement Key Rotation: Change keys regularly
  • Monitor Usage: Watch for unusual activity

Network Security

  • Use HTTPS: Always use encrypted connections
  • Validate Certificates: Verify SSL certificates
  • Implement Timeouts: Set appropriate request timeouts
  • Handle Errors: Implement proper error handling

Application Security

  • Input Validation: Validate all input data
  • Output Sanitization: Sanitize output data
  • Error Messages: Don't expose sensitive information
  • Logging: Log security events appropriately

Migration Guide

From v1 to v2 API

  • New Endpoints: Some endpoints have changed
  • Enhanced Security: Improved authentication methods
  • Better Error Handling: More detailed error responses
  • Rate Limiting: Updated rate limit policies

Backward Compatibility

  • Deprecated Endpoints: Old endpoints still work but are deprecated
  • Migration Timeline: 6-month notice for breaking changes
  • Support: Migration assistance available

Ready to start using the API? Check out our Trading Endpoints or Market Data API.