Trading Endpoints

Complete reference for all trading-related API endpoints, including order management, position tracking, and trade execution.

Overview

The Trading API provides programmatic access to all trading functionality, allowing you to create, modify, and monitor orders, manage positions, and execute trades automatically.

Base URL

https://api.vibetrading.tech/api/v1

Order Management

Create Order

Create a new trading order.

Endpoint: POST /orders

Request Body:

{
  "symbol": "BTC/USD",
  "side": "buy",
  "type": "market",
  "quantity": 0.1,
  "price": 50000,
  "timeInForce": "GTC",
  "clientOrderId": "unique_order_id"
}

Parameters:

  • symbol (string, required): Trading pair symbol
  • side (string, required): "buy" or "sell"
  • type (string, required): "market", "limit", "stop", "stop_limit"
  • quantity (number, required): Order quantity
  • price (number, optional): Order price (required for limit orders)
  • stopPrice (number, optional): Stop price (required for stop orders)
  • timeInForce (string, optional): "GTC", "IOC", "FOK" (default: "GTC")
  • clientOrderId (string, optional): Unique client identifier

Response:

{
  "orderId": "12345678-1234-1234-1234-123456789012",
  "clientOrderId": "unique_order_id",
  "symbol": "BTC/USD",
  "side": "buy",
  "type": "market",
  "quantity": 0.1,
  "price": 0,
  "stopPrice": 0,
  "timeInForce": "GTC",
  "status": "filled",
  "filledQuantity": 0.1,
  "averagePrice": 49850.25,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:01Z"
}

Get Order

Retrieve details of a specific order.

Endpoint: GET /orders/{orderId}

Response:

{
  "orderId": "12345678-1234-1234-1234-123456789012",
  "clientOrderId": "unique_order_id",
  "symbol": "BTC/USD",
  "side": "buy",
  "type": "market",
  "quantity": 0.1,
  "price": 0,
  "status": "filled",
  "filledQuantity": 0.1,
  "averagePrice": 49850.25,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:01Z",
  "fills": [
    {
      "fillId": "fill_123",
      "quantity": 0.1,
      "price": 49850.25,
      "timestamp": "2024-01-15T10:30:01Z"
    }
  ]
}

List Orders

Retrieve a list of orders with optional filtering.

Endpoint: GET /orders

Query Parameters:

  • symbol (string, optional): Filter by trading pair
  • status (string, optional): Filter by order status
  • side (string, optional): Filter by order side
  • type (string, optional): Filter by order type
  • limit (number, optional): Number of results (max 100, default 50)
  • offset (number, optional): Number of results to skip
  • startTime (string, optional): Start time (ISO 8601)
  • endTime (string, optional): End time (ISO 8601)

Response:

{
  "orders": [
    {
      "orderId": "12345678-1234-1234-1234-123456789012",
      "symbol": "BTC/USD",
      "side": "buy",
      "type": "market",
      "quantity": 0.1,
      "status": "filled",
      "filledQuantity": 0.1,
      "averagePrice": 49850.25,
      "createdAt": "2024-01-15T10:30:00Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "offset": 0,
    "total": 1,
    "hasMore": false
  }
}

Cancel Order

Cancel an existing order.

Endpoint: DELETE /orders/{orderId}

Response:

{
  "orderId": "12345678-1234-1234-1234-123456789012",
  "status": "cancelled",
  "cancelledAt": "2024-01-15T10:35:00Z"
}

Cancel All Orders

Cancel all open orders for a specific symbol.

Endpoint: DELETE /orders

Query Parameters:

  • symbol (string, optional): Cancel orders for specific symbol only

Response:

{
  "cancelledOrders": [
    {
      "orderId": "12345678-1234-1234-1234-123456789012",
      "status": "cancelled"
    }
  ],
  "totalCancelled": 1
}

Position Management

Get Positions

Retrieve current positions.

Endpoint: GET /positions

Query Parameters:

  • symbol (string, optional): Filter by trading pair

Response:

{
  "positions": [
    {
      "symbol": "BTC/USD",
      "side": "long",
      "quantity": 0.1,
      "averagePrice": 49850.25,
      "unrealizedPnl": 150.75,
      "unrealizedPnlPercent": 0.3,
      "markPrice": 50000.0,
      "liquidationPrice": 45000.0,
      "marginUsed": 4985.03,
      "marginRatio": 0.1,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T11:00:00Z"
    }
  ]
}

Close Position

Close an existing position.

Endpoint: POST /positions/{symbol}/close

Request Body:

{
  "quantity": 0.1,
  "type": "market",
  "clientOrderId": "close_position_123"
}

Response:

{
  "orderId": "87654321-4321-4321-4321-210987654321",
  "symbol": "BTC/USD",
  "side": "sell",
  "type": "market",
  "quantity": 0.1,
  "status": "filled",
  "filledQuantity": 0.1,
  "averagePrice": 50000.0,
  "realizedPnl": 149.75,
  "createdAt": "2024-01-15T11:30:00Z"
}

Account Information

Get Account

Retrieve account information and balances.

Endpoint: GET /account

Response:

{
  "accountId": "acc_123456789",
  "accountType": "professional",
  "status": "active",
  "balances": {
    "USD": {
      "available": 10000.0,
      "locked": 500.0,
      "total": 10500.0
    },
    "BTC": {
      "available": 0.1,
      "locked": 0.0,
      "total": 0.1
    }
  },
  "permissions": ["read:account", "write:orders", "read:positions"],
  "tradingEnabled": true,
  "createdAt": "2024-01-01T00:00:00Z"
}

Get Trading Fees

Retrieve current trading fees.

Endpoint: GET /account/fees

Response:

{
  "makerFee": 0.001,
  "takerFee": 0.002,
  "volumeTier": "tier_1",
  "monthlyVolume": 100000.0,
  "nextTierVolume": 500000.0,
  "nextTierMakerFee": 0.0008,
  "nextTierTakerFee": 0.0015
}

Trade History

Get Trades

Retrieve trade history.

Endpoint: GET /trades

Query Parameters:

  • symbol (string, optional): Filter by trading pair
  • orderId (string, optional): Filter by order ID
  • limit (number, optional): Number of results (max 100, default 50)
  • offset (number, optional): Number of results to skip
  • startTime (string, optional): Start time (ISO 8601)
  • endTime (string, optional): End time (ISO 8601)

Response:

{
  "trades": [
    {
      "tradeId": "trade_123456",
      "orderId": "12345678-1234-1234-1234-123456789012",
      "symbol": "BTC/USD",
      "side": "buy",
      "quantity": 0.1,
      "price": 49850.25,
      "fee": 9.97,
      "feeAsset": "USD",
      "timestamp": "2024-01-15T10:30:01Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "offset": 0,
    "total": 1,
    "hasMore": false
  }
}

Order Types

Market Orders

Execute immediately at current market price.

{
  "symbol": "BTC/USD",
  "side": "buy",
  "type": "market",
  "quantity": 0.1
}

Limit Orders

Execute at specified price or better.

{
  "symbol": "BTC/USD",
  "side": "buy",
  "type": "limit",
  "quantity": 0.1,
  "price": 49000
}

Stop Orders

Trigger when price reaches stop level.

{
  "symbol": "BTC/USD",
  "side": "sell",
  "type": "stop",
  "quantity": 0.1,
  "stopPrice": 45000
}

Stop Limit Orders

Trigger as limit order when price reaches stop level.

{
  "symbol": "BTC/USD",
  "side": "sell",
  "type": "stop_limit",
  "quantity": 0.1,
  "price": 44800,
  "stopPrice": 45000
}

Time in Force Options

  • GTC (Good Till Cancelled): Order remains active until filled or cancelled
  • IOC (Immediate or Cancel): Fill immediately or cancel remaining quantity
  • FOK (Fill or Kill): Fill entire quantity immediately or cancel

Order Status Values

  • pending: Order received but not yet processed
  • open: Order is active in the market
  • partially_filled: Order partially executed
  • filled: Order completely executed
  • cancelled: Order cancelled by user
  • rejected: Order rejected by system
  • expired: Order expired due to time in force

Error Handling

Common Errors

Invalid Symbol (400)

{
  "error": "invalid_symbol",
  "message": "The trading pair 'INVALID/USD' is not supported",
  "code": 400
}

Insufficient Balance (400)

{
  "error": "insufficient_balance",
  "message": "Insufficient balance to place order",
  "code": 400,
  "details": {
    "required": 5000.0,
    "available": 4500.0
  }
}

Order Not Found (404)

{
  "error": "order_not_found",
  "message": "Order with ID '12345678-1234-1234-1234-123456789012' not found",
  "code": 404
}

Trading Disabled (403)

{
  "error": "trading_disabled",
  "message": "Trading is currently disabled for your account",
  "code": 403
}

Rate Limits

  • Order Creation: 10 requests per second
  • Order Queries: 100 requests per second
  • Position Queries: 50 requests per second
  • Account Queries: 20 requests per second

Webhooks

Order Updates

Receive real-time order status updates.

Webhook Payload:

{
  "event": "order.updated",
  "timestamp": "2024-01-15T10:30:01Z",
  "data": {
    "orderId": "12345678-1234-1234-1234-123456789012",
    "status": "filled",
    "filledQuantity": 0.1,
    "averagePrice": 49850.25
  }
}

Position Updates

Receive real-time position updates.

Webhook Payload:

{
  "event": "position.updated",
  "timestamp": "2024-01-15T11:00:00Z",
  "data": {
    "symbol": "BTC/USD",
    "quantity": 0.1,
    "unrealizedPnl": 150.75,
    "markPrice": 50000.0
  }
}

Code Examples

Python Trading Bot

import time
from vibe_trading_api import VibeTradingAPI

class TradingBot:
    def __init__(self, api_key, secret_key):
        self.api = VibeTradingAPI(api_key, secret_key)
        self.running = False

    def start(self):
        self.running = True
        while self.running:
            try:
                # Get AI signal
                signal = self.api.get_ai_signal("BTC/USD")

                if signal['recommendation'] == 'buy' and signal['confidence'] > 80:
                    self.place_buy_order("BTC/USD", 0.1)
                elif signal['recommendation'] == 'sell' and signal['confidence'] > 80:
                    self.close_position("BTC/USD")

                time.sleep(60)  # Check every minute
            except Exception as e:
                print(f"Error: {e}")
                time.sleep(30)

    def place_buy_order(self, symbol, quantity):
        order = {
            "symbol": symbol,
            "side": "buy",
            "type": "market",
            "quantity": quantity
        }
        result = self.api.create_order(order)
        print(f"Order placed: {result['orderId']}")

    def close_position(self, symbol):
        positions = self.api.get_positions(symbol=symbol)
        for position in positions:
            if position['quantity'] > 0:
                self.api.close_position(symbol, position['quantity'])
                print(f"Position closed: {symbol}")

# Usage
bot = TradingBot("your_api_key", "your_secret_key")
bot.start()

JavaScript Trading Bot

const VibeTradingAPI = require("vibe-trading-api");

class TradingBot {
  constructor(apiKey, secretKey) {
    this.api = new VibeTradingAPI(apiKey, secretKey);
    this.running = false;
  }

  async start() {
    this.running = true;
    while (this.running) {
      try {
        // Get AI signal
        const signal = await this.api.getAISignal("BTC/USD");

        if (signal.recommendation === "buy" && signal.confidence > 80) {
          await this.placeBuyOrder("BTC/USD", 0.1);
        } else if (signal.recommendation === "sell" && signal.confidence > 80) {
          await this.closePosition("BTC/USD");
        }

        await this.sleep(60000); // Check every minute
      } catch (error) {
        console.error("Error:", error);
        await this.sleep(30000);
      }
    }
  }

  async placeBuyOrder(symbol, quantity) {
    const order = {
      symbol,
      side: "buy",
      type: "market",
      quantity,
    };
    const result = await this.api.createOrder(order);
    console.log(`Order placed: ${result.orderId}`);
  }

  async closePosition(symbol) {
    const positions = await this.api.getPositions({ symbol });
    for (const position of positions) {
      if (position.quantity > 0) {
        await this.api.closePosition(symbol, position.quantity);
        console.log(`Position closed: ${symbol}`);
      }
    }
  }

  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}

// Usage
const bot = new TradingBot("your_api_key", "your_secret_key");
bot.start();

Ready to start trading programmatically? Check out our Market Data API or WebSocket Feeds for real-time data.