New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details โ†’ โ†’
Socket
Book a DemoSign in
Socket

asterdex-sdk

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

asterdex-sdk

Unofficial TypeScript SDK for AsterDEX cryptocurrency exchange - supporting both Spot and Futures trading with WebSocket streams

latest
Source
npmnpm
Version
1.0.0
Version published
Weekly downloads
2
-80%
Maintainers
1
Weekly downloads
ย 
Created
Source

AsterDEX TypeScript SDK (Unofficial)

License: MIT TypeScript GitHub

Unofficial TypeScript SDK for AsterDEX cryptocurrency exchange. This library provides a comprehensive, type-safe interface for both Spot and Futures trading, with support for REST API calls and real-time WebSocket streams.

โš ๏ธ Disclaimer: This is an unofficial, community-maintained SDK and is not affiliated with or endorsed by AsterDEX. Use at your own risk. For official support, please contact AsterDEX directly.

โœจ Features

  • ๐Ÿ—๏ธ Modern TypeScript - Full TypeScript support with strict type checking
  • ๐Ÿ” Complete Authentication - Support for all AsterDEX authentication types
  • ๐Ÿ“Š Spot Trading - Full spot trading API implementation (30+ methods)
  • โšก Futures Trading - Complete futures/derivatives trading support (50+ methods)
  • ๐ŸŒŠ WebSocket Streams - Real-time market data and user account updates
  • ๐Ÿ”— Web3 Integration - Native Web3 signature authentication for futures
  • ๐Ÿ’ผ Advanced Order Types - Support for LIMIT, MARKET, STOP, TAKE_PROFIT, and TRAILING_STOP orders
  • ๐ŸŽฏ Position Management - Leverage, margin type, and position margin control
  • ๐Ÿ“ˆ Market Data - Klines, order books, trades, tickers, and funding rates
  • ๐Ÿ”„ Real-Time Updates - WebSocket streams for prices, trades, liquidations, and account updates
  • ๐Ÿ›ก๏ธ Error Handling - Comprehensive error types with detailed error information
  • ๐Ÿ”ง Configurable - Flexible configuration with environment variable support
  • ๐Ÿ“š Well Documented - Complete API documentation with examples
  • ๐Ÿงช Thoroughly Tested - High test coverage with unit and integration tests

๐Ÿ“‹ SDK Coverage

This SDK provides complete coverage of the AsterDEX API:

CategoryMethodsDescription
Spot Trading30+Market data, order management, account info, withdrawals
Futures Trading50+Derivatives trading, position management, leverage control
WebSocket Streams15+Real-time price updates, trades, order book, account updates
AuthenticationMultipleAPI key, signature-based, Web3 signature for futures
Utility Functions10+Configuration, dependency checks, stream name generators

Total: 100+ methods covering all major trading operations on AsterDEX.

๐Ÿ“– Table of Contents

๐Ÿ“ฆ Installation

npm install asterdex-sdk
yarn add asterdex-sdk
pnpm add asterdex-sdk

๐Ÿš€ Quick Start

Basic Setup

import { AsterDEX } from 'asterdex-sdk';

// Initialize with API credentials
const client = new AsterDEX({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  environment: 'mainnet' // or 'testnet'
});

// Or initialize from environment variables
const client = AsterDEX.fromEnv();

Environment Variables

Set these environment variables to use AsterDEX.fromEnv():

ASTERDEX_API_KEY=your-api-key
ASTERDEX_API_SECRET=your-api-secret
ASTERDEX_ENVIRONMENT=mainnet
ASTERDEX_TIMEOUT=60000
ASTERDEX_RECV_WINDOW=5000

# Optional: Custom endpoints (override defaults for any environment)
ASTERDEX_SPOT_URL=https://custom-api.example.com
ASTERDEX_FUTURES_URL=https://custom-futures.example.com
ASTERDEX_WEBSOCKET_URL=wss://custom-ws.example.com

๐Ÿ“˜ For comprehensive configuration options, see the Configuration Guide

Simple Example

import { AsterDEX } from 'asterdex-sdk';

const client = new AsterDEX({
  apiKey: process.env.ASTERDEX_API_KEY,
  apiSecret: process.env.ASTERDEX_API_SECRET,
});

async function example() {
  try {
    // Test connectivity
    await client.ping();
    console.log('Connected to AsterDEX!');

    // Get account information
    const account = await client.spot.getAccount();
    console.log('Account balances:', account.balances);

    // Get current BTC price
    const price = await client.spot.getPrice('BTCUSDT');
    console.log('Current BTC price:', price);

    // Place a limit order
    const order = await client.spot.newOrder({
      symbol: 'BTCUSDT',
      side: 'BUY',
      type: 'LIMIT',
      timeInForce: 'GTC',
      quantity: '0.001',
      price: '35000.00'
    });
    console.log('Order placed:', order);

  } catch (error) {
    console.error('Error:', error);
  }
}

example();

๐Ÿ“š Complete API Reference

This SDK provides comprehensive access to all AsterDEX trading APIs. Below is a complete reference of all implemented methods organized by category.

๐Ÿ”ท Main SDK Methods

AsterDEX Class

The main entry point for the SDK.

MethodDescriptionReturns
new AsterDEX(config)Creates a new SDK instance with configurationAsterDEX
AsterDEX.fromEnv()Creates SDK instance from environment variablesAsterDEX
ping()Tests API connectivityPromise<{}>
getServerTime()Gets server timePromise<{serverTime: number}>
createWebSocketClient(handlers, path)Creates WebSocket client for market dataAsterWebSocketClient
createCombinedStream(handlers)Creates combined WebSocket stream clientAsterWebSocketClient
createUserDataStream(listenKey, handlers)Creates user data stream WebSocketAsterWebSocketClient
createFuturesClient(userAddr, signerAddr, privateKey)Creates Futures trading clientFuturesClient
createFuturesWebSocketClient(handlers, path)Creates Futures WebSocket clientAsterWebSocketClient
createFuturesUserDataStream(listenKey, handlers)Creates Futures user data streamAsterWebSocketClient
updateCredentials(apiKey, apiSecret)Updates API credentialsvoid
getConfig()Gets current configurationConfig

๐Ÿ“Š Spot Trading API (client.spot)

Market Data Methods

MethodDescriptionParametersReturns
getExchangeInfo()Get exchange trading rules and symbol informationNonePromise<SpotExchangeInfo>
getOrderBook(symbol, limit?)Get order book depth for a symbolsymbol: string
limit?: number
Promise<OrderBook>
getRecentTrades(symbol, limit?)Get recent trades listsymbol: string
limit?: number
Promise<Trade[]>
getHistoricalTrades(symbol, limit?, fromId?)Get historical tradessymbol: string
limit?: number
fromId?: number
Promise<Trade[]>
getAggregatedTrades(symbol, options?)Get compressed, aggregate tradessymbol: string
options?: TradeQueryOptions
Promise<AggregatedTrade[]>
getKlines(symbol, interval, options?)Get kline/candlestick datasymbol: string
interval: KlineInterval
options?: KlineOptions
Promise<Kline[]>
get24hrTicker(symbol?)Get 24hr ticker price change statisticssymbol?: stringPromise<Ticker24hr | Ticker24hr[]>
getPrice(symbol?)Get latest price for symbol(s)symbol?: stringPromise<PriceTicker | PriceTicker[]>
getBookTicker(symbol?)Get best price/qty on order booksymbol?: stringPromise<BookTicker | BookTicker[]>
getCommissionRate(symbol)Get trading fees for symbolsymbol: stringPromise<CommissionRate>

Supported Kline Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M

Trading Methods

MethodDescriptionParametersReturns
newOrder(params)Place a new orderparams: NewOrderParamsPromise<OrderAck>
cancelOrder(symbol, orderId?, origClientOrderId?)Cancel an active ordersymbol: string
orderId?: number
origClientOrderId?: string
Promise<OrderAck>
getOrder(symbol, orderId?, origClientOrderId?)Check order statussymbol: string
orderId?: number
origClientOrderId?: string
Promise<Order>
getOpenOrders(symbol?)Get all open orderssymbol?: stringPromise<Order[]>
getAllOrders(symbol, options?)Get all orders (active, canceled, filled)symbol: string
options?: OrderQueryOptions
Promise<Order[]>

Order Types Supported:

  • LIMIT - Limit order (requires: timeInForce, quantity, price)
  • MARKET - Market order (requires: quantity OR quoteOrderQty)
  • STOP - Stop-loss order (requires: quantity, price, stopPrice)
  • TAKE_PROFIT - Take-profit order (requires: quantity, price, stopPrice)
  • STOP_MARKET - Stop-loss market order (requires: quantity, stopPrice)
  • TAKE_PROFIT_MARKET - Take-profit market order (requires: quantity, stopPrice)

Time In Force Options: GTC (Good Till Cancel), IOC (Immediate or Cancel), FOK (Fill or Kill)

Account Management Methods

MethodDescriptionParametersReturns
getAccount()Get current account informationNonePromise<SpotAccount>
getMyTrades(symbol?, options?)Get account trade historysymbol?: string
options?: TradeQueryOptions
Promise<UserTrade[]>
transferAsset(params)Transfer between spot/futures accountsparams: AssetTransferParamsPromise<AssetTransferResponse>
sendToAddress(params)Transfer asset to another addressparams: SendToAddressParamsPromise<AssetTransferResponse>
getWithdrawFee(chainId, asset)Get estimated withdrawal feechainId: string
asset: string
Promise<WithdrawFee>
withdraw(params)Submit withdrawal requestparams: WithdrawParamsPromise<WithdrawResponse>
getNonce(address, userOperationType, network?)Get nonce for user operationaddress: string
userOperationType: string
network?: string
Promise<number>
createApiKey(params)Create new API keyparams: CreateApiKeyParamsPromise<ApiKeyResponse>

User Data Stream Methods

MethodDescriptionParametersReturns
startUserDataStream()Start new user data streamNonePromise<ListenKeyResponse>
keepAliveUserDataStream(listenKey)Keep user data stream alivelistenKey: stringPromise<{}>
closeUserDataStream(listenKey)Close user data streamlistenKey: stringPromise<{}>

โšก Futures Trading API (futures)

To use Futures API, first create a Futures client:

const futures = client.createFuturesClient(userAddress, signerAddress, privateKey);

Market Data Methods

MethodDescriptionParametersReturns
ping(url?)Test Futures API connectivityurl?: stringPromise<{}>
getServerTime(url?)Get Futures server timeurl?: stringPromise<{serverTime: number}>
getExchangeInfo()Get futures exchange informationNonePromise<FuturesExchangeInfo>
getOrderBook(symbol, limit?)Get futures order booksymbol: string
limit?: number
Promise<FuturesOrderBook>
getRecentTrades(symbol, limit?)Get recent futures tradessymbol: string
limit?: number
Promise<FuturesTrade[]>
getHistoricalTrades(symbol, limit?, fromId?)Get historical futures tradessymbol: string
limit?: number
fromId?: number
Promise<FuturesTrade[]>
getAggregatedTrades(symbol, options?)Get aggregated futures tradessymbol: string
options?: TradeQueryOptions
Promise<FuturesAggTrade[]>
getKlines(symbol, interval, options?)Get futures klinessymbol: string
interval: KlineInterval
options?: KlineOptions
Promise<Kline[]>
getIndexPriceKlines(pair, interval, options?)Get index price klinespair: string
interval: KlineInterval
options?: KlineOptions
Promise<Kline[]>
getMarkPriceKlines(symbol, interval, options?)Get mark price klinessymbol: string
interval: KlineInterval
options?: KlineOptions
Promise<Kline[]>
getMarkPrice(symbol?)Get mark price and funding ratesymbol?: stringPromise<FuturesMarkPrice | FuturesMarkPrice[]>
getFundingRate(symbol?, options?)Get funding rate historysymbol?: string
options?: TimeRangeOptions
Promise<FuturesFundingRate[]>
get24hrTicker(symbol?)Get 24hr futures tickersymbol?: stringPromise<Futures24hrTicker | Futures24hrTicker[]>
getPrice(symbol?)Get latest futures pricesymbol?: stringPromise<PriceTicker | PriceTicker[]>
getBookTicker(symbol?)Get best price/qty on futures booksymbol?: stringPromise<BookTicker | BookTicker[]>

Position & Account Configuration Methods

MethodDescriptionParametersReturns
changePositionMode(dualSidePosition)Change position mode (Hedge/One-way)dualSidePosition: booleanPromise<ApiSuccessResponse>
getPositionMode()Get current position modeNonePromise<FuturesPositionMode>
changeMultiAssetsMode(multiAssetsMargin)Enable/disable multi-assets modemultiAssetsMargin: booleanPromise<ApiSuccessResponse>
getMultiAssetsMode()Get current multi-assets modeNonePromise<FuturesMultiAssetsMode>
changeLeverage(params)Change initial leverageparams: FuturesLeverageParamsPromise<FuturesLeverageResponse>
changeMarginType(params)Change margin type (ISOLATED/CROSS)params: FuturesMarginTypeParamsPromise<ApiSuccessResponse>
modifyPositionMargin(params)Modify isolated position marginparams: FuturesPositionMarginParamsPromise<FuturesPositionMarginResponse>

Futures Trading Methods

MethodDescriptionParametersReturns
newOrder(params)Place new futures orderparams: FuturesNewOrderParamsPromise<FuturesOrderResponse>
newBatchOrders(params)Place multiple orders (max 5)params: FuturesBatchOrderParamsPromise<FuturesOrderResponse[]>
getOrder(symbol, orderId?, origClientOrderId?)Query order statussymbol: string
orderId?: number
origClientOrderId?: string
Promise<FuturesOrderResponse>
cancelOrder(symbol, orderId?, origClientOrderId?)Cancel active ordersymbol: string
orderId?: number
origClientOrderId?: string
Promise<FuturesOrderResponse>
cancelAllOpenOrders(symbol)Cancel all open orders for symbolsymbol: stringPromise<ApiSuccessResponse>
cancelBatchOrders(symbol, orderIdList?, origClientOrderIdList?)Cancel multiple orderssymbol: string
orderIdList?: number[]
origClientOrderIdList?: string[]
Promise<FuturesOrderResponse[]>
countdownCancelAll(params)Auto-cancel all orders after countdownparams: FuturesCountdownCancelParamsPromise<FuturesCountdownCancelResponse>
getCurrentOpenOrder(symbol, orderId?, origClientOrderId?)Query current open ordersymbol: string
orderId?: number
origClientOrderId?: string
Promise<FuturesOrderResponse>
getOpenOrders(symbol?)Get all open futures orderssymbol?: stringPromise<FuturesOrderResponse[]>
getAllOrders(symbol, options?)Get all futures orderssymbol: string
options?: OrderQueryOptions
Promise<FuturesOrderResponse[]>

Futures Order Types Supported:

  • LIMIT - Limit order
  • MARKET - Market order
  • STOP / STOP_MARKET - Stop-loss orders
  • TAKE_PROFIT / TAKE_PROFIT_MARKET - Take-profit orders
  • TRAILING_STOP_MARKET - Trailing stop order

Futures Account & Position Methods

MethodDescriptionParametersReturns
getBalance()Get futures account balanceNonePromise<FuturesBalance[]>
getAccount()Get futures account informationNonePromise<FuturesAccount>
getPositionRisk(symbol?)Get position informationsymbol?: stringPromise<FuturesPositionRisk[]>
getUserTrades(symbol, options?)Get account trade listsymbol: string
options?: TradeQueryOptions
Promise<FuturesUserTrade[]>
getIncomeHistory(options?)Get income historyoptions?: IncomeHistoryOptionsPromise<FuturesIncome[]>
getLeverageBracket(symbol?)Get leverage bracketssymbol?: stringPromise<FuturesLeverageBracket[]>
getADLQuantile(symbol?)Get ADL quantile estimationsymbol?: stringPromise<FuturesADLQuantile[]>
getForceOrders(options?)Get user's force ordersoptions?: ForceOrderOptionsPromise<FuturesForceOrder[]>
getCommissionRate(symbol)Get commission ratesymbol: stringPromise<FuturesCommissionRate>
getPositionMarginHistory(symbol, options?)Get position margin historysymbol: string
options?: PositionMarginHistoryOptions
Promise<FuturesPositionMarginHistory[]>
transferAsset(params)Transfer between futures/spotparams: FuturesTransferParamsPromise<FuturesTransferResponse>

Futures User Data Stream Methods

MethodDescriptionParametersReturns
startUserDataStream()Start futures user data streamNonePromise<FuturesListenKeyResponse>
keepAliveUserDataStream(listenKey)Keep futures stream alivelistenKey: stringPromise<{}>
closeUserDataStream(listenKey)Close futures streamlistenKey: stringPromise<{}>

Futures Authentication Helper Methods

MethodDescriptionParametersReturns
updateWeb3Credentials(userAddr, signerAddr, privateKey)Update Web3 credentialsuserAddress: string
signerAddress: string
privateKey: string
void
hasAuthentication()Check if Web3 auth configuredNoneboolean
getUserAddress()Get user addressNonestring | undefined
getSignerAddress()Get signer addressNonestring | undefined

๐ŸŒ WebSocket Streams API

WebSocket Client Methods

MethodDescriptionParametersReturns
connect()Connect to WebSocket serverNonePromise<void>
disconnect()Disconnect from serverNonevoid
subscribe(streams)Subscribe to stream(s)streams: string | string[]Promise<void>
unsubscribe(streams)Unsubscribe from stream(s)streams: string | string[]Promise<void>
listSubscriptions()List current subscriptionsNonePromise<string[]>
setProperty(property, value)Set WebSocket propertyproperty: string
value: boolean
Promise<void>
getProperty(property)Get WebSocket propertyproperty: stringPromise<any>
getState()Get connection stateNoneWebSocketState
isConnected()Check if connectedNoneboolean
getSubscriptions()Get subscription listNonestring[]

StreamUtils - Stream Name Generators

Static utility methods to generate WebSocket stream names:

MethodDescriptionParametersReturns
StreamUtils.aggTrade(symbol)Aggregate trade streamsymbol: stringstring
StreamUtils.trade(symbol)Trade streamsymbol: stringstring
StreamUtils.kline(symbol, interval)Kline/candlestick streamsymbol: string
interval: KlineInterval
string
StreamUtils.miniTicker(symbol)Mini ticker streamsymbol: stringstring
StreamUtils.ticker(symbol)24hr ticker streamsymbol: stringstring
StreamUtils.bookTicker(symbol)Best bid/ask streamsymbol: stringstring
StreamUtils.depth(symbol, levels?, updateSpeed?)Order book depth streamsymbol: string
levels?: number
updateSpeed?: '100ms'
string
StreamUtils.allMiniTicker()All market mini tickersNonestring
StreamUtils.allTicker()All market tickersNonestring
StreamUtils.allBookTicker()All market book tickersNonestring
StreamUtils.futuresMarkPrice(symbol)Futures mark price streamsymbol: stringstring
StreamUtils.allFuturesMarkPrice()All futures mark pricesNonestring
StreamUtils.futuresLiquidation(symbol)Futures liquidation streamsymbol: stringstring
StreamUtils.allFuturesLiquidation()All futures liquidationsNonestring
StreamUtils.futuresCompositeIndex(symbol)Futures composite indexsymbol: stringstring

WebSocket Event Handlers

Spot Stream Events:

  • onOpen() - Connection opened
  • onClose(code, reason) - Connection closed
  • onError(error) - Error occurred
  • onTicker(data) - 24hr ticker update
  • onMiniTicker(data) - Mini ticker update
  • onTrade(data) - Trade update
  • onAggTrade(data) - Aggregate trade update
  • onKline(data) - Kline/candlestick update
  • onDepthUpdate(data) - Order book depth update
  • onBookTicker(data) - Best bid/ask update
  • onAccountUpdate(data) - Account balance update
  • onExecutionReport(data) - Order execution update

Futures Stream Events:

  • All spot events plus:
  • onMarkPrice(data) - Mark price update
  • onLiquidation(data) - Liquidation order update
  • onOrderUpdate(data) - Futures order update
  • onAccountConfigUpdate(data) - Account config update

๐Ÿ”ง Utility Functions

Web3 Dependencies

FunctionDescriptionReturns
checkWeb3Dependencies()Check if Web3 dependencies are installed{available: boolean, missing: string[]}
getWeb3InstallationInstructions()Get Web3 installation instructionsstring

๐Ÿ“ Usage Examples

Example: Complete Spot Trading Flow

import { AsterDEX } from 'asterdex-sdk';

const client = new AsterDEX({
  apiKey: process.env.ASTERDEX_API_KEY,
  apiSecret: process.env.ASTERDEX_API_SECRET,
});

async function spotTradingExample() {
  // 1. Test connectivity
  await client.ping();
  console.log('Connected to AsterDEX!');

  // 2. Get account information
  const account = await client.spot.getAccount();
  console.log('Account balances:', account.balances);

  // 3. Get current BTC price
  const price = await client.spot.getPrice('BTCUSDT');
  console.log('Current BTC price:', price);

  // 4. Place a limit order
  const order = await client.spot.newOrder({
    symbol: 'BTCUSDT',
    side: 'BUY',
    type: 'LIMIT',
    timeInForce: 'GTC',
    quantity: '0.001',
    price: '35000.00'
  });
  console.log('Order placed:', order);

  // 5. Check order status
  const orderStatus = await client.spot.getOrder('BTCUSDT', order.orderId);
  console.log('Order status:', orderStatus);

  // 6. Get all open orders
  const openOrders = await client.spot.getOpenOrders('BTCUSDT');
  console.log('Open orders:', openOrders);
}

spotTradingExample().catch(console.error);

Example: WebSocket Real-Time Data

import { AsterDEX, StreamUtils } from 'asterdex-sdk';

const client = new AsterDEX({
  apiKey: process.env.ASTERDEX_API_KEY,
  apiSecret: process.env.ASTERDEX_API_SECRET,
});

async function websocketExample() {
  // Create WebSocket client with event handlers
  const ws = client.createWebSocketClient({
    onTicker: (data) => {
      console.log(`${data.s}: $${data.c} (${data.P}% 24h change)`);
    },
    onTrade: (data) => {
      console.log(`Trade: ${data.s} ${data.p} @ ${data.q}`);
    },
    onDepthUpdate: (data) => {
      console.log(`Depth update for ${data.s}`);
    },
    onError: (error) => {
      console.error('WebSocket error:', error);
    }
  });

  // Connect to WebSocket
  await ws.connect();

  // Subscribe to multiple streams
  await ws.subscribe([
    StreamUtils.ticker('BTCUSDT'),
    StreamUtils.trade('ETHUSDT'),
    StreamUtils.depth('BTCUSDT', 20),
    StreamUtils.kline('BTCUSDT', '1m')
  ]);

  console.log('WebSocket connected and subscribed!');
}

websocketExample().catch(console.error);

Example: User Data Stream (Account Updates)

import { AsterDEX } from 'asterdex-sdk';

const client = new AsterDEX({
  apiKey: process.env.ASTERDEX_API_KEY,
  apiSecret: process.env.ASTERDEX_API_SECRET,
});

async function userDataStreamExample() {
  // Start user data stream
  const { listenKey } = await client.spot.startUserDataStream();

  // Create user data WebSocket
  const userWs = client.createUserDataStream(listenKey, {
    onAccountUpdate: (data) => {
      console.log('Account balance update:', data.B);
    },
    onExecutionReport: (data) => {
      console.log(`Order ${data.i} status: ${data.X}`);
      console.log(`Symbol: ${data.s}, Side: ${data.S}, Price: ${data.p}`);
    }
  });

  await userWs.connect();
  console.log('User data stream connected!');

  // Keep alive every 30 minutes
  setInterval(async () => {
    await client.spot.keepAliveUserDataStream(listenKey);
    console.log('User data stream keep-alive sent');
  }, 30 * 60 * 1000);
}

userDataStreamExample().catch(console.error);

Example: Futures Trading

import { AsterDEX, checkWeb3Dependencies } from 'asterdex-sdk';

// Check Web3 dependencies
const web3Check = checkWeb3Dependencies();
if (!web3Check.available) {
  console.error('Missing Web3 dependencies:', web3Check.missing);
  process.exit(1);
}

const client = new AsterDEX({ environment: 'testnet' });

// Create Futures client with Web3 credentials
const futures = client.createFuturesClient(
  '0x1E09ae6526A70fa26E25112b858DD6927e37655E', // User address
  '0x001AA685f118954F5984eb4D000f1a184F3f4aED', // Signer address
  '0x4efec379443ff915877459330cf1a39e045bee0061398fe420924b3be2170aa1' // Private key
);

async function futuresTradingExample() {
  // Get account information
  const account = await futures.getAccount();
  console.log('Futures account balance:', account.totalWalletBalance);

  // Get mark price
  const markPrice = await futures.getMarkPrice('BTCUSDT');
  console.log('BTC mark price:', markPrice);

  // Set leverage
  await futures.changeLeverage({
    symbol: 'BTCUSDT',
    leverage: 10
  });
  console.log('Leverage set to 10x');

  // Place a futures order
  const order = await futures.newOrder({
    symbol: 'BTCUSDT',
    side: 'BUY',
    type: 'LIMIT',
    timeInForce: 'GTC',
    quantity: '0.001',
    price: '50000',
    positionSide: 'LONG'
  });
  console.log('Futures order placed:', order);

  // Get positions
  const positions = await futures.getPositionRisk();
  console.log('Current positions:', positions);
}

futuresTradingExample().catch(console.error);

Example: Futures WebSocket Streams

import { AsterDEX, StreamUtils } from 'asterdex-sdk';

const client = new AsterDEX({ environment: 'testnet' });

async function futuresWebSocketExample() {
  // Create Futures WebSocket client
  const futuresWs = client.createFuturesWebSocketClient({
    onMarkPrice: (data) => {
      console.log(`Mark price ${data.s}: $${data.p} (funding: ${data.r})`);
    },
    onLiquidation: (data) => {
      console.log(`Liquidation: ${data.o.s} ${data.o.S} ${data.o.q} @ $${data.o.p}`);
    }
  });

  await futuresWs.connect();

  // Subscribe to futures streams
  await futuresWs.subscribe([
    StreamUtils.futuresMarkPrice('BTCUSDT'),
    StreamUtils.allFuturesLiquidation(),
    StreamUtils.ticker('BTCUSDT')
  ]);

  console.log('Futures WebSocket connected!');
}

futuresWebSocketExample().catch(console.error);

Example: Advanced Order Management

import { AsterDEX } from 'asterdex-sdk';

const client = new AsterDEX({
  apiKey: process.env.ASTERDEX_API_KEY,
  apiSecret: process.env.ASTERDEX_API_SECRET,
});

async function advancedOrderExample() {
  // Place multiple order types

  // 1. Limit order
  const limitOrder = await client.spot.newOrder({
    symbol: 'BTCUSDT',
    side: 'BUY',
    type: 'LIMIT',
    timeInForce: 'GTC',
    quantity: '0.001',
    price: '35000'
  });

  // 2. Stop-loss order
  const stopLoss = await client.spot.newOrder({
    symbol: 'BTCUSDT',
    side: 'SELL',
    type: 'STOP_MARKET',
    quantity: '0.001',
    stopPrice: '33000'
  });

  // 3. Take-profit order
  const takeProfit = await client.spot.newOrder({
    symbol: 'BTCUSDT',
    side: 'SELL',
    type: 'TAKE_PROFIT_MARKET',
    quantity: '0.001',
    stopPrice: '40000'
  });

  console.log('Orders placed:', { limitOrder, stopLoss, takeProfit });

  // Monitor order status
  const orderStatus = await client.spot.getOrder('BTCUSDT', limitOrder.orderId);
  console.log('Order status:', orderStatus.status);

  // Cancel order if needed
  if (orderStatus.status === 'NEW') {
    await client.spot.cancelOrder('BTCUSDT', limitOrder.orderId);
    console.log('Order cancelled');
  }
}

advancedOrderExample().catch(console.error);

Error Handling

import {
  ApiResponseError,
  RateLimitError,
  NetworkError,
  ValidationError
} from 'asterdex-sdk';

try {
  await client.spot.newOrder({
    symbol: 'BTCUSDT',
    side: 'BUY',
    type: 'LIMIT',
    // Missing required parameters
  });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation error:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limited. Retry after:', error.retryAfter);
  } else if (error instanceof ApiResponseError) {
    console.error('API error:', error.code, error.message);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.message);
  }
}

โš™๏ธ Configuration

Basic Configuration

const client = new AsterDEX({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  environment: 'mainnet', // 'mainnet' | 'testnet'
  timeout: 60000, // Request timeout in milliseconds
  recvWindow: 5000, // Receive window for signed requests
  enableRateLimiting: true, // Enable built-in rate limiting
  retryConfig: {
    maxRetries: 3,
    retryDelay: 1000,
    backoffMultiplier: 2
  }
});

Custom Endpoints

const client = new AsterDEX({
  baseUrl: {
    spot: 'https://custom-spot-api.example.com',
    futures: 'https://custom-futures-api.example.com',
    websocket: 'wss://custom-websocket.example.com'
  }
});

๐Ÿ” Authentication

The SDK supports all AsterDEX authentication types:

  • NONE - Public endpoints, no authentication required
  • MARKET_DATA - Market data endpoints, API key required
  • USER_STREAM - User data streams, API key required
  • TRADE - Trading endpoints, API key and signature required
  • USER_DATA - Account endpoints, API key and signature required

Authentication is handled automatically based on the endpoint being called.

๐Ÿ“Š Rate Limiting

The SDK includes built-in rate limiting to prevent exceeding API limits:

  • Automatic request queuing and spacing
  • Respect for Retry-After headers
  • Configurable rate limits and backoff strategies
  • Separate limits for different endpoint types

๐ŸŒ WebSocket Features

  • Automatic reconnection with exponential backoff
  • Subscription management with easy subscribe/unsubscribe
  • Combined streams support for multiple symbols
  • User data streams for real-time account updates
  • Ping/pong handling for connection health
  • Error recovery and connection state management

๐Ÿงช Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

๐Ÿ“– Examples

Check out the examples directory for complete working examples:

  • Demo file - Complete spot/futures/websocket trading operations

๐Ÿ› ๏ธ Development

Prerequisites

  • Node.js >= 18.0.0
  • TypeScript >= 5.0.0

Setup

# Clone the repository
git clone https://github.com/methodnumber13/asterdex-sdk.git
cd asterdex-sdk

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run linting
npm run lint

Building

# Build for production
npm run build

# Build in watch mode for development
npm run dev

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Reporting Issues

Please report issues on our GitHub Issues page.

๐Ÿ“ž Support

SDK Support

  • ๐Ÿ› Issues & Bug Reports: GitHub Issues
  • ๐Ÿ’ก Feature Requests: GitHub Issues
  • ๐Ÿ“– Documentation: This README and inline code documentation

AsterDEX Platform Support

For official AsterDEX platform support:

โš ๏ธ Disclaimer

Important Notice:

  • This is an unofficial SDK and is not affiliated with or endorsed by AsterDEX
  • This SDK is provided as-is without any warranties
  • The maintainer is not responsible for any losses incurred while using this SDK
  • Trading cryptocurrencies involves significant risk and can result in financial loss
  • Always test thoroughly in a testnet environment before using in production
  • Use at your own risk

๐Ÿ“ Maintainer

This SDK is maintained by methodnumber13.

Made with โค๏ธ by the community

Keywords

asterdex

FAQs

Package last updated on 14 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts