Skip to content

mefai-dev/mefai-js-sdk

Repository files navigation

@mefai/sdk

CI npm version License TypeScript

Official JavaScript and TypeScript SDK for the MEFAI Engine trading API. Provides typed methods for trading operations and market data and model predictions and realtime WebSocket streams.

Installation

npm install @mefai/sdk

Quick Start

import { MefaiClient } from "@mefai/sdk";

const client = new MefaiClient({
  baseUrl: "https://api.mefai.io",
  apiKey: "your_api_key_here",
});

// Check system health
const health = await client.health();
console.log(health.status);

// Get ticker data
const ticker = await client.getTicker("BTCUSDT");
console.log(ticker.last);

Configuration

Option Type Default Description
baseUrl string http://localhost:8000 Base URL of the MEFAI Engine API
apiKey string undefined API key for authentication
timeout number 30000 Request timeout in milliseconds

Trading

// Fetch account balance
const balance = await client.getBalance();
console.log(`Available: ${balance.available} ${balance.currency}`);

// List open positions
const positions = await client.getPositions();
for (const pos of positions) {
  console.log(`${pos.symbol} ${pos.side} PnL: ${pos.unrealizedPnl}`);
}

// Place a market order
const order = await client.placeOrder({
  symbol: "BTCUSDT",
  side: "buy",
  type: "market",
  quantity: 0.01,
});
console.log(`Order ${order.orderId} filled at ${order.avgFillPrice}`);

// Close a position
const result = await client.closePosition("BTCUSDT");
console.log(`Closed with PnL: ${result.realizedPnl}`);

Market Data

// OHLCV candles
const candles = await client.getCandles("BTCUSDT", "1h", 100);

// Orderbook
const book = await client.getOrderbook("BTCUSDT", 20);

// Sentiment analysis
const sentiment = await client.getSentiment("BTCUSDT");
console.log(`Sentiment: ${sentiment.label} (${sentiment.overall})`);

// Latest news
const news = await client.getNews(10);

ML Models and Predictions

// List available models
const models = await client.listModels();

// Run a prediction
const prediction = await client.predict("lstm_v2", "BTCUSDT");
console.log(`Direction: ${prediction.direction} (${prediction.confidence}%)`);

Backtesting

const backtest = await client.runBacktest({
  strategy: "momentum_breakout",
  symbol: "BTCUSDT",
  startDate: "2024-01-01",
  endDate: "2024-12-31",
  initialCapital: 10000,
  leverage: 3,
});

console.log(`Return: ${backtest.totalReturn}%`);
console.log(`Sharpe: ${backtest.sharpeRatio}`);
console.log(`Max Drawdown: ${backtest.maxDrawdown}%`);

Signals

const signals = await client.getSignals();
for (const signal of signals) {
  console.log(`${signal.symbol} ${signal.direction} strength:${signal.strength}`);
}

Realtime WebSocket Stream

const stream = client.stream((event) => {
  switch (event.type) {
    case "ticker":
      console.log("Ticker update:", event.data);
      break;
    case "signal":
      console.log("New signal:", event.data);
      break;
    case "trade":
      console.log("Trade executed:", event.data);
      break;
  }
});

// Send a subscription message
stream.send({ subscribe: ["BTCUSDT", "ETHUSDT"] });

// Later: disconnect
stream.close();

Error Handling

The SDK provides typed error classes for different failure modes.

import {
  MefaiClient,
  ApiError,
  AuthenticationError,
  RateLimitError,
  TimeoutError,
  NetworkError,
  ValidationError,
} from "@mefai/sdk";

try {
  await client.getTicker("BTCUSDT");
} catch (err) {
  if (err instanceof AuthenticationError) {
    console.error("Bad API key");
  } else if (err instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${err.retryAfter}s`);
  } else if (err instanceof TimeoutError) {
    console.error("Request timed out");
  } else if (err instanceof ApiError) {
    console.error(`API error ${err.status}: ${err.message}`);
  }
}

License

Apache 2.0. See LICENSE for details.

About

Official JavaScript/TypeScript SDK for MEFAI Engine trading API

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors