API Integration

Integrate Moondraft's powerful trading and data APIs into your applications. Our comprehensive API suite provides access to real-time market data, trading functionality, portfolio management, and blockchain interactions.

API Capabilities:

  • Real-time and historical market data
  • Programmatic trading and order management
  • Portfolio tracking and analytics
  • Token creation and management
  • WebSocket streaming for live updates

Getting Started

API Authentication

Creating API Keys

  1. Navigate to Settings: Go to Account Settings → API Management
  2. Generate New Key: Click "Create API Key" and provide a description
  3. Set Permissions: Choose appropriate access levels for your use case
  4. IP Restrictions: Add IP whitelist for enhanced security (recommended)
  5. Save Credentials: Securely store your API key and secret

Security Best Practices:

  • Never share your API secret key
  • Use IP restrictions when possible
  • Implement proper secret management
  • Regularly rotate API keys
  • Use minimum required permissions

Authentication Methods

API Key Authentication

Example API key authentication:

const headers = {
  'X-API-Key': 'your-api-key',
  'X-API-Secret': 'your-api-secret',
  'Content-Type': 'application/json'
};

const response = await fetch('https://api.moondraft.com/v1/account', {
  method: 'GET',
  headers: headers
});
JWT Token Authentication

JWT token authentication for enhanced security:

const token = await getJWTToken(apiKey, apiSecret);
const headers = {
  'Authorization': `Bearer ${token}`,
  'Content-Type': 'application/json'
};

Market Data API

Real-Time Price Data

Current Prices

GET /v1/market/prices

const getPrices = async (symbols) => {
  const response = await fetch(`https://api.moondraft.com/v1/market/prices?symbols=${symbols.join(',')}`);
  return response.json();
};

Example Response:

{
  "data": {
    "SOL/USDC": {
      "price": 23.45,
      "change_24h": 0.0234,
      "volume_24h": 1234567.89,
      "last_updated": "2025-09-29T16:30:00Z"
    }
  }
}

Order Book Data

GET /v1/market/orderbook

const getOrderBook = async (symbol, depth = 50) => {
  const response = await fetch(`https://api.moondraft.com/v1/market/orderbook?symbol=${symbol}&depth=${depth}`);
  return response.json();
};

Example Response:

{
  "symbol": "SOL/USDC",
  "bids": [
    [23.45, 100.0],  // [price, quantity]
    [23.44, 250.5]
  ],
  "asks": [
    [23.46, 150.0],
    [23.47, 200.0]
  ],
  "timestamp": "2025-09-29T16:30:00Z"
}

Historical Data

OHLCV Candlestick Data

GET /v1/market/candles

const getCandles = async (symbol, interval, start, end) => {
  const params = new URLSearchParams({
    symbol: symbol,
    interval: interval,  // 1m, 5m, 1h, 1d, etc.
    start: start,
    end: end
  });
  
  const response = await fetch(`https://api.moondraft.com/v1/market/candles?${params}`);
  return response.json();
};

Example Response:

{
  "data": [
    {
      "timestamp": "2025-09-29T16:00:00Z",
      "open": 23.40,
      "high": 23.55,
      "low": 23.35,
      "close": 23.45,
      "volume": 12345.67
    }
  ]
}

Trading API

Order Management

Placing Orders

POST /v1/trading/orders

const placeOrder = async (orderData) => {
  const response = await fetch('https://api.moondraft.com/v1/trading/orders', {
    method: 'POST',
    headers: {
      'X-API-Key': 'your-api-key',
      'X-API-Secret': 'your-api-secret',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(orderData)
  });
  return response.json();
};

Market Order Example:

const marketOrder = {
  symbol: 'SOL/USDC',
  side: 'buy',
  type: 'market',
  quantity: 10.0
};

Limit Order Example:

const limitOrder = {
  symbol: 'SOL/USDC',
  side: 'sell',
  type: 'limit',
  quantity: 10.0,
  price: 25.00,
  time_in_force: 'GTC'  // Good Till Canceled
};

Order Status and Management

Get Order Status:

const getOrder = async (orderId) => {
  const response = await fetch(`https://api.moondraft.com/v1/trading/orders/${orderId}`, {
    headers: authHeaders
  });
  return response.json();
};

Cancel Order:

const cancelOrder = async (orderId) => {
  const response = await fetch(`https://api.moondraft.com/v1/trading/orders/${orderId}`, {
    method: 'DELETE',
    headers: authHeaders
  });
  return response.json();
};

Get Active Orders:

const getActiveOrders = async () => {
  const response = await fetch('https://api.moondraft.com/v1/trading/orders/active', {
    headers: authHeaders
  });
  return response.json();
};

Advanced Order Types

Stop Loss Orders

const stopLossOrder = {
  symbol: 'SOL/USDC',
  side: 'sell',
  type: 'stop_loss',
  quantity: 10.0,
  stop_price: 20.00,
  trigger_type: 'last_price'
};

Take Profit Orders

const takeProfitOrder = {
  symbol: 'SOL/USDC',
  side: 'sell',
  type: 'take_profit',
  quantity: 10.0,
  limit_price: 30.00
};

Bracket Orders

const bracketOrder = {
  symbol: 'SOL/USDC',
  side: 'buy',
  type: 'bracket',
  quantity: 10.0,
  entry_price: 23.50,
  stop_loss: 21.00,
  take_profit: 27.00
};

Account and Portfolio API

Account Information

GET /v1/account/info

const getAccountInfo = async () => {
  const response = await fetch('https://api.moondraft.com/v1/account/info', {
    headers: authHeaders
  });
  return response.json();
};

Example Response:

{
  "account_id": "acc_123456789",
  "email": "user@example.com",
  "trading_enabled": true,
  "withdrawal_enabled": false,
  "created_at": "2025-01-15T10:30:00Z"
}

Portfolio Balances

GET /v1/account/balances

const getBalances = async () => {
  const response = await fetch('https://api.moondraft.com/v1/account/balances', {
    headers: authHeaders
  });
  return response.json();
};

Example Response:

{
  "balances": [
    {
      "asset": "SOL",
      "available": 150.0,
      "locked": 10.0,
      "total": 160.0
    },
    {
      "asset": "USDC", 
      "available": 5000.0,
      "locked": 500.0,
      "total": 5500.0
    }
  ]
}

Transaction History

GET /v1/account/transactions

const getTransactions = async (asset = null, limit = 50) => {
  const params = new URLSearchParams({
    limit: limit.toString()
  });
  if (asset) params.append('asset', asset);
  
  const response = await fetch(`https://api.moondraft.com/v1/account/transactions?${params}`, {
    headers: authHeaders
  });
  return response.json();
};

Token Management API

Token Creation

POST /v1/tokens/create

const createToken = async (tokenData) => {
  const response = await fetch('https://api.moondraft.com/v1/tokens/create', {
    method: 'POST',
    headers: authHeaders,
    body: JSON.stringify(tokenData)
  });
  return response.json();
};

Token Data Example:

const tokenData = {
  name: "My Awesome Token",
  symbol: "MAT",
  decimals: 9,
  total_supply: 1000000,
  description: "An awesome utility token",
  image_url: "https://example.com/logo.png",
  social_links: {
    website: "https://mytoken.com",
    twitter: "https://twitter.com/mytoken",
    discord: "https://discord.gg/mytoken"
  }
};

Token Management Operations

Mint Tokens

const mintTokens = async (tokenId, amount, recipient) => {
  const response = await fetch(`https://api.moondraft.com/v1/tokens/${tokenId}/mint`, {
    method: 'POST',
    headers: authHeaders,
    body: JSON.stringify({
      amount: amount,
      recipient: recipient
    })
  });
  return response.json();
};

Burn Tokens

const burnTokens = async (tokenId, amount) => {
  const response = await fetch(`https://api.moondraft.com/v1/tokens/${tokenId}/burn`, {
    method: 'POST',
    headers: authHeaders,
    body: JSON.stringify({ amount: amount })
  });
  return response.json();
};

WebSocket API

Real-Time Data Streaming

WebSocket URL: wss://ws.moondraft.com/v1/stream

const ws = new WebSocket('wss://ws.moondraft.com/v1/stream');

ws.onopen = () => {
  // Subscribe to price updates
  ws.send(JSON.stringify({
    method: 'subscribe',
    channels: ['prices', 'trades', 'orderbook'],
    symbols: ['SOL/USDC', 'ETH/USDC']
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch(data.channel) {
    case 'prices':
      updatePriceDisplay(data);
      break;
    case 'trades':
      updateTradeHistory(data);
      break;
    case 'orderbook':
      updateOrderBook(data);
      break;
  }
};

Private Data Streams

Authenticated WebSocket URL: wss://ws.moondraft.com/v1/private

const authenticatedWs = new WebSocket('wss://ws.moondraft.com/v1/private');

authenticatedWs.onopen = () => {
  // Authenticate with API key
  authenticatedWs.send(JSON.stringify({
    method: 'authenticate',
    api_key: 'your-api-key',
    signature: generateSignature('your-api-secret', timestamp)
  }));
  
  // Subscribe to private channels
  authenticatedWs.send(JSON.stringify({
    method: 'subscribe',
    channels: ['orders', 'balances', 'trades']
  }));
};

SDKs and Libraries

Official SDKs

JavaScript/Node.js SDK

Installation:

npm install @moondraft/api-client

Usage:

const { MoondraftClient } = require('@moondraft/api-client');

const client = new MoondraftClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  sandbox: false
});

Python SDK

Installation:

pip install moondraft-python

Usage:

from moondraft import MoondraftClient

client = MoondraftClient(
    api_key='your-api-key',
    api_secret='your-api-secret',
    sandbox=False
)

Community Libraries

  • Go: github.com/moondraft/moondraft-go
  • Rust: crates.io/crates/moondraft
  • PHP: packagist.org/packages/moondraft/api-client
  • C#: nuget.org/packages/Moondraft.Net

Rate Limits and Best Practices

Rate Limiting

REST API Limits

  • Market Data: 100 requests/second
  • Trading: 50 requests/second
  • Account: 25 requests/second
  • Token Management: 10 requests/second

WebSocket Limits

  • Connections: 10 per API key
  • Subscriptions: 100 per connection
  • Messages: 1000/minute per connection
  • Heartbeat: 30 seconds timeout

Optimization Strategies

  • Batch Requests: Combine multiple operations when possible
  • Caching: Store frequently accessed data locally
  • WebSocket Usage: Use WebSocket for real-time data instead of polling
  • Error Handling: Implement exponential backoff for retries

Error Handling

HTTP Status Codes

Success Codes

  • 200 OK: Request successful
  • 201 Created: Resource created
  • 202 Accepted: Request accepted

Error Codes

  • 400 Bad Request: Invalid parameters
  • 401 Unauthorized: Authentication failed
  • 403 Forbidden: Insufficient permissions
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error

Error Response Format

{
  "error": {
    "code": "INSUFFICIENT_BALANCE",
    "message": "Insufficient balance for this operation",
    "details": {
      "required": 100.0,
      "available": 50.0
    }
  }
}

Testing and Development

Sandbox Environment

  • Base URL: https://api-sandbox.moondraft.com/
  • WebSocket: wss://ws-sandbox.moondraft.com/
  • Test Funds: Request test tokens for development
  • Reset Function: Reset sandbox account state

Development Tools

  • API Explorer: Interactive API documentation
  • Code Examples: Sample implementations in multiple languages
  • Postman Collection: Pre-configured API requests
  • OpenAPI Spec: Machine-readable API specification

Testing Best Practices

  • Unit Testing: Test individual API functions
  • Integration Testing: Test complete workflows
  • Load Testing: Verify performance under load
  • Error Testing: Test error handling scenarios

Security Considerations

Critical Security Measures:

  • Store API secrets in environment variables, never in code
  • Use HTTPS for all API communications
  • Implement request signing for sensitive operations
  • Validate all user inputs before API calls
  • Monitor API usage for suspicious activity

Request Signing

const crypto = require('crypto');

const generateSignature = (secret, method, path, timestamp, body = '') => {
  const message = timestamp + method.toUpperCase() + path + body;
  return crypto.createHmac('sha256', secret).update(message).digest('hex');
};

const timestamp = Date.now().toString();
const signature = generateSignature(apiSecret, 'POST', '/v1/trading/orders', timestamp, JSON.stringify(orderData));

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

API Key Management

  • Environment Variables: Store secrets in .env files
  • Key Rotation: Regularly update API keys
  • Permission Scoping: Use minimal required permissions
  • IP Restrictions: Limit access to specific IP addresses

Support and Resources

Documentation and Guides

  • API Reference: Complete endpoint documentation
  • Tutorials: Step-by-step integration guides
  • Code Examples: Working examples in multiple languages
  • Best Practices: Optimization and security guidelines

Community and Support

  • Discord: Real-time developer chat
  • GitHub: SDK repositories and issue tracking
  • Stack Overflow: Tag your questions with #moondraft

Response Times

  • Critical Issues: 2-4 hours
  • Bug Reports: 24-48 hours
  • General Support: 2-5 business days
  • Feature Requests: 1-2 weeks

Pro Tip: Start with the sandbox environment to test your integration thoroughly before moving to production. Use WebSocket streams for real-time data and implement proper error handling and retry logic for robust applications.

Remember: API integration requires proper security practices and error handling. Always validate responses, implement rate limiting on your end, and never expose API secrets in client-side code.