JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 43
  • Score
    100M100P100Q65934F
  • License MIT

A TypeScript SDK with client components and server functions.

Package Exports

  • aex-sdk
  • aex-sdk/client
  • aex-sdk/client-components
  • aex-sdk/fetch
  • aex-sdk/style.css

Readme

AEX SDK

npm version License: MIT TypeScript React

A powerful TypeScript SDK for crypto exchange integration, providing both React components and server utilities for seamless trading experiences.

🚀 Features

  • 📈 Multi-Exchange Support
    • Binance
    • Bitget
    • Bybit
  • 🔧 Modular Architecture
  • 🔒 Type-Safe APIs
  • WebSocket Support
  • 🎯 React Integration

📦 Installation

npm install aex-sdk

🏗️ Architecture

The SDK is divided into several modules:

aex-sdk/
├── /              # Core utilities
├── /client        # React components
├── /fetch         # API client libraries
└── /websocket     # WebSocket implementations

🔑 Authentication

First, set up the authentication provider:

import { AexAuthProvider } from "aex-sdk";

function App() {
  return (
    <AexAuthProvider aexApiKey="your-api-key" projectId="your-project-id">
      <YourApp />
    </AexAuthProvider>
  );
}

Use the auth hook in components:

import { useAexAuth } from "aex-sdk";

function Trading() {
  const { isAuthenticated, isLoading, error, connectExchange, createOrder } =
    useAexAuth();

  // Check authentication status
  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  // Connect to an exchange
  const handleConnect = async () => {
    try {
      await connectExchange({
        exchange: "binance",
        apiKey: "your-binance-api-key",
        apiSecret: "your-binance-secret",
      });
    } catch (err) {
      console.error("Failed to connect:", err);
    }
  };

  // Place an Order
  const handleTrade = async () => {
    if (isAuthenticated) {
      await createOrder({
        symbol: "BTCUSDT",
        side: "BUY",
        type: "LIMIT",
        price: "30000",
        quantity: "0.1",
      });
    }
  };
}

📊 Market Data

Access real-time and REST market data across supported exchanges:

import {
  getTickers,
  getMarketDepth,
  getTradeHistory,
  getOpenOrders,
} from "aex-sdk/fetch";

// Get current ticker data for multiple symbols
const tickers = await getTickers({
  exchange: "binance",
  symbols: ["BTCUSDT", "ETHUSDT"],
});

// Fetch order book depth
const depth = await getMarketDepth({
  exchange: "binance",
  symbol: "BTCUSDT",
  limit: 100, // optional, defaults to 100
});

// Get recent trades
const trades = await getTradeHistory({
  exchange: "binance",
  symbol: "BTCUSDT",
  limit: 50, // optional, defaults to 50
});

// Fetch open orders
const orders = await getOpenOrders({
  exchange: "binance",
  symbol: "BTCUSDT",
});

⚡ WebSocket Integration

The SDK provides a powerful WebSocket implementation for real-time data:

Basic Usage

import { ExchangeWebSocket } from "aex-sdk";

const ws = new ExchangeWebSocket("binance", "BTCUSDT");

// Listen for order book updates using events
ws.addEventListener("orderbook", (e: CustomEvent<OrderBookData>) => {
  const { bids, asks, timestamp } = e.detail;
  console.log(`Latest BTC/USDT order book at ${new Date(timestamp)}:`, {
    topBid: bids[0]?.price,
    topAsk: asks[0]?.price,
  });
});

// Handle connection events
ws.addEventListener("open", () => console.log("Connected to Binance"));
ws.addEventListener("error", (e) => console.error("WebSocket error:", e));
ws.addEventListener("close", () => console.log("Disconnected from Binance"));

// Start the connection
ws.connect();

React Integration

import { useEffect, useState } from "react";
import { ExchangeWebSocket, OrderBookData } from "aex-sdk";

function OrderBookComponent() {
  const [orderBook, setOrderBook] = useState<OrderBookData | null>(null);

  useEffect(() => {
    const ws = new ExchangeWebSocket("binance", "BTCUSDT", {
      reconnectInterval: 3000,
      reconnectAttempts: 5,
      onMessage: (data) => setOrderBook(data),
      onError: (error) => console.error("WebSocket error:", error),
    });

    ws.connect();

    // Cleanup on unmount
    return () => ws.disconnect();
  }, []);

  return (
    <div>
      <h2>Order Book</h2>
      <div>Best Bid: {orderBook?.bids[0]?.price}</div>
      <div>Best Ask: {orderBook?.asks[0]?.price}</div>
    </div>
  );
}

Advanced Usage - Multiple Trading Pairs

const pairs = ["BTCUSDT", "ETHUSDT", "SOLUSDT"];
const connections = new Map();

pairs.forEach((pair) => {
  const ws = new ExchangeWebSocket("binance", pair, {
    onMessage: (data) => console.log(`${pair} order book update:`, data),
  });

  connections.set(pair, ws);
  ws.connect();
});

// Later, disconnect all
connections.forEach((ws) => ws.disconnect());

Error Handling and Reconnection

const ws = new ExchangeWebSocket("binance", "BTCUSDT", {
  reconnectInterval: 5000,
  reconnectAttempts: 3,
  onError: (error) => {
    console.error("WebSocket error:", error);
    // Implement your error handling logic
  },
  onClose: (event) => {
    if (event.code !== 1000) {
      console.log("Abnormal closure, attempting to reconnect");
    }
  },
});

// Check connection status before operations
if (ws.isConnected()) {
  // Perform actions that require an active connection
}

The WebSocket implementation supports multiple exchanges (Binance, Bitget, Bybit) with automatic reconnection and provides a standardized data format across all supported platforms.

🔄 Trading

Execute trades across multiple exchanges:

import { createOrder } from "aex-sdk/fetch";

// Place an order
const order = await createOrder({
  exchange: "binance",
  symbol: "BTCUSDT",
  side: "BUY",
  type: "MARKET",
  quantity: "0.1",
});

// Get order status
const status = await getOrderStatus({
  exchange: "binance",
  orderId: order.id,
});

💫 React Components

Ready-to-use UI components:

import { OrderBook, TradingView, OrderForm } from "aex-sdk/client";

function TradingInterface() {
  return (
    <div>
      <TradingView symbol="BTCUSDT" />
      <OrderBook exchange="binance" symbol="BTCUSDT" />
      <OrderForm onSubmit={handleOrderSubmit} />
    </div>
  );
}

🔧 Configuration

Configure the SDK using environment variables:

AEX_API_KEY=your-api-key
AEX_PROJECT_ID=your-project-id

📚 API Reference

Full API documentation is available in the TypeScript definition files:

  • aex-sdk/dist/types/client/index.d.ts
  • aex-sdk/dist/types/fetch/index.d.ts
  • aex-sdk/dist/types/fetch/websocket.d.ts

📝 License

MIT Licensed. See LICENSE for details.