Trade

Automate and integrate Trade operations and workflows seamlessly

Trade is a community skill for implementing trading and exchange functionality in applications, covering order management, price feeds, order book patterns, trade execution, and portfolio tracking for digital asset trading.

What Is This?

Overview

Trade provides patterns for building trading features in financial and cryptocurrency applications. It covers order management with limit, market, and stop order types for expressing trade intent, real-time price feeds using WebSocket connections to exchanges for live market data, order book rendering that displays bid and ask levels with depth visualization, trade execution through exchange APIs with order placement, cancellation, and status polling, and portfolio tracking that aggregates holdings, calculates profit and loss, and displays performance history. The skill enables developers to build trading interfaces and execution systems that interact with exchange infrastructure.

Who Should Use This

This skill serves developers building cryptocurrency trading platforms or portfolio dashboards, teams creating automated trading bots that execute strategies via exchange APIs, and engineers implementing order management systems with real-time market data.

Why Use It?

Problems It Solves

Real-time price data requires persistent WebSocket connections with reconnection and heartbeat handling. Order management must track state transitions from pending to filled, partially filled, or cancelled. Portfolio calculations need accurate cost basis tracking across multiple trades and assets. Exchange API rate limits require queuing and throttling of order operations.

Core Highlights

Order engine validates and submits limit and market orders through exchange APIs. Price feed manager maintains WebSocket connections with automatic reconnection. Portfolio calculator aggregates trade history into holdings with cost basis. Rate limiter queues API requests within exchange limits.

How to Use It?

Basic Usage

// Price feed with WebSocket
class PriceFeed {
  private ws: WebSocket | null
    = null;
  private listeners =
    new Map<string,
      Set<(price: number)
        => void>>();

  connect(baseUrl: string) {
    this.ws = new WebSocket(
      `${baseUrl}/ws/ticker`);

    this.ws.onmessage =
      (event) => {
        const data =
          JSON.parse(event.data);
        const handlers =
          this.listeners.get(
            data.symbol);
        handlers?.forEach(
          (fn) => fn(
            parseFloat(
              data.price)));
      };

    this.ws.onclose = () => {
      setTimeout(
        () => this.connect(
          baseUrl), 3000);
    };
  }

  subscribe(
    symbol: string,
    callback: (price: number)
      => void
  ) {
    if (!this.listeners
        .has(symbol)) {
      this.listeners.set(
        symbol, new Set());
    }
    this.listeners.get(symbol)!
      .add(callback);
  }
}

Real-World Examples

// Order management
interface Order {
  id: string;
  symbol: string;
  side: 'buy' | 'sell';
  type: 'market' | 'limit';
  quantity: number;
  price?: number;
  status: 'pending' | 'filled'
    | 'cancelled';
}

class OrderManager {
  private apiKey: string;
  private baseUrl: string;

  constructor(
    apiKey: string,
    baseUrl: string
  ) {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
  }

  async placeOrder(params: {
    symbol: string;
    side: 'buy' | 'sell';
    type: 'market' | 'limit';
    quantity: number;
    price?: number;
  }): Promise<Order> {
    const res = await fetch(
      `${this.baseUrl}/orders`,
      {
        method: 'POST',
        headers: {
          'Content-Type':
            'application/json',
          'X-API-Key':
            this.apiKey,
        },
        body:
          JSON.stringify(params),
      });
    return res.json();
  }

  async cancelOrder(
    orderId: string
  ): Promise<Order> {
    const res = await fetch(
      `${this.baseUrl}/orders/`
        + orderId, {
          method: 'DELETE',
          headers: {
            'X-API-Key':
              this.apiKey },
        });
    return res.json();
  }

  async getOrders(
    symbol: string
  ): Promise<Order[]> {
    const res = await fetch(
      `${this.baseUrl}/orders`
        + `?symbol=${symbol}`, {
          headers: {
            'X-API-Key':
              this.apiKey },
        });
    return res.json();
  }
}

Advanced Tips

Implement exponential backoff for WebSocket reconnection to avoid overwhelming the exchange during outages. Use local order state that optimistically updates on submission and reconciles with exchange confirmations. Queue API requests with a token bucket rate limiter matching exchange limits.

When to Use It?

Use Cases

Build a cryptocurrency trading dashboard with real-time prices and order placement. Create an automated trading bot that executes strategies based on price signals. Implement a portfolio tracker that shows holdings and performance.

Related Topics

Exchange APIs, WebSocket connections, order management, portfolio tracking, and financial data.

Important Notes

Requirements

Exchange API credentials with trading permissions enabled. WebSocket-capable runtime for real-time price feeds. Secure storage for API keys and trading credentials.

Usage Recommendations

Do: implement rate limiting that matches the exchange API limits to prevent bans. Validate order parameters on the client before submitting to the exchange. Log all order operations for audit and debugging purposes.

Don't: store exchange API secrets in client-side code where they can be extracted. Submit orders without checking sufficient balance for the trade amount. Ignore WebSocket disconnection events which can cause missed price updates.

Limitations

Exchange APIs have varying rate limits and order type support across providers. WebSocket connections may drop during high volatility periods when reliability matters most. Market orders may execute at different prices than displayed due to slippage during fast-moving markets.