@_0xboji/aster-connector-ts
v1.0.2
Published
TypeScript SDK for Aster DEX API
Maintainers
Readme
Aster DEX TypeScript SDK
A modern TypeScript SDK for the Aster DEX API.
✨ Features
- 🖋️ 100% TypeScript - Full type safety and IntelliSense support
- 🧪 Well-tested - Comprehensive test coverage
- 📦 Tree-shakeable - Import only what you need for minimal bundle size
- 🔧 Flexible Architecture - Multiple API access patterns (OOP & Functional)
- 🌐 Cross-Environment - Works in Node.js, browsers, and edge runtimes
- 🚀 Modern - Built with latest TypeScript and ES2022 features
- 📚 Well-documented - JSDoc annotations and examples
📦 Installation
npm install @_0xboji/aster-connector-tsyarn add @_0xboji/aster-connector-tspnpm add @_0xboji/aster-connector-ts🚀 Quick Start
Market Data (Public API)
import { HttpTransport, MarketClient } from "@_0xboji/aster-connector-ts";
const transport = new HttpTransport();
const client = new MarketClient({ transport });
// Get 24hr ticker
const ticker = await client.ticker24hr({ symbol: "BTCUSDT" });
console.log(`BTC Price: ${ticker.lastPrice}`);
// Get order book
const depth = await client.depth({ symbol: "BTCUSDT", limit: 10 });
console.log(`Best Bid: ${depth.bids[0][0]}`);
// Get klines
const klines = await client.klines({
symbol: "BTCUSDT",
interval: "1h",
limit: 24,
});Trading (Authenticated API)
import { HttpTransport, TradingClient } from "@_0xboji/aster-connector-ts";
const transport = new HttpTransport();
const client = new TradingClient({
transport,
apiKey: "your-api-key",
secretKey: "your-secret-key",
});
// Get account information
const account = await client.account();
console.log(`Balance: ${account.totalWalletBalance}`);
// Place a limit order
const order = await client.newOrder({
symbol: "BTCUSDT",
side: "BUY",
type: "LIMIT",
timeInForce: "GTC",
quantity: "0.001",
price: "50000",
});
console.log(`Order ID: ${order.orderId}`);
// Get open orders
const openOrders = await client.getOpenOrders({ symbol: "BTCUSDT" });
// Cancel an order
await client.cancelOrder({ symbol: "BTCUSDT", orderId: order.orderId });
// Create listen key for WebSocket user data stream
const { listenKey } = await client.newListenKey();
console.log(`Listen Key: ${listenKey}`);
// Keep-alive listen key (must be called every 30 minutes)
await client.renewListenKey();
// Close listen key when done
await client.closeListenKey();WebSocket Streams
import { WebSocketTransport } from "@_0xboji/aster-connector-ts";
const ws = new WebSocketTransport({
debug: true,
reconnect: true,
});
await ws.connect();
// Subscribe to ticker updates
const tickerSub = await ws.subscribe("btcusdt@ticker", (data) => {
console.log(`Price: ${data.c}, 24h Change: ${data.P}%`);
});
// Subscribe to trade updates
const tradeSub = await ws.subscribe("btcusdt@trade", (data) => {
console.log(`Trade: ${data.p} @ ${data.q}`);
});
// Unsubscribe when done
await tickerSub.unsubscribe();
await tradeSub.unsubscribe();
ws.disconnect();🌲 Tree-shakeable API Functions
For minimal bundle size in frontend applications, you can import individual API functions:
import { HttpTransport } from "@_0xboji/aster-connector-ts";
import { ticker24hr, depth } from "@_0xboji/aster-connector-ts/api/market";
import { account, newOrder } from "@_0xboji/aster-connector-ts/api/trading";
const transport = new HttpTransport();
// Market data
const ticker = await ticker24hr({ transport }, { symbol: "BTCUSDT" });
const orderBook = await depth({ transport }, { symbol: "BTCUSDT", limit: 10 });
// Trading (with credentials)
const context = {
transport,
apiKey: "your-api-key",
secretKey: "your-secret-key",
};
const acc = await account(context);
const order = await newOrder(context, {
symbol: "BTCUSDT",
side: "BUY",
type: "LIMIT",
price: "50000",
quantity: "0.001",
timeInForce: "GTC",
});Benefits:
- ✅ Import only what you need
- ✅ Smaller bundle size
- ✅ Better for frontend applications
- ✅ Same functionality as client classes
📖 API Documentation
Transport Layer
HttpTransport
import { HttpTransport } from "@_0xboji/aster-connector-ts";
const transport = new HttpTransport({
baseUrl: "https://fapi.asterdex.com", // optional
timeout: 10000, // optional (ms)
debug: false, // optional
headers: {}, // optional custom headers
});WebSocketTransport
import { WebSocketTransport } from "@_0xboji/aster-connector-ts";
const ws = new WebSocketTransport({
wsUrl: "wss://fstream.asterdex.com", // optional
debug: false, // optional
reconnect: true, // optional
reconnectDelay: 5000, // optional (ms)
maxReconnectAttempts: 10, // optional
});Client Classes
MarketClient (Public API)
Methods:
ping()- Test connectivitytime()- Get server timeexchangeInfo()- Get exchange trading rulesdepth(params)- Get order booktrades(params)- Get recent tradeshistoricalTrades(params)- Get historical tradesaggTrades(params)- Get aggregate tradesklines(params)- Get candlestick dataindexPriceKlines(params)- Get index price klinesmarkPriceKlines(params)- Get mark price klinesmarkPrice(params)- Get mark price and funding ratefundingRate(params)- Get funding rate historyticker24hr(params)- Get 24hr ticker statisticstickerPrice(params)- Get symbol pricebookTicker(params)- Get best bid/ask
TradingClient (Authenticated API)
Order Management:
newOrder(params)- Place a new ordernewBatchOrder(params)- Place multiple ordersqueryOrder(params)- Query order statuscancelOrder(params)- Cancel an ordercancelAllOrders(params)- Cancel all open orderscancelBatchOrders(params)- Cancel multiple orderscountdownCancelAll(params)- Auto-cancel all ordersgetOpenOrders(params)- Get current open ordersgetAllOrders(params)- Get all orders
Account & Balance:
balance()- Get account balanceaccount()- Get account informationgetPositionRisk(params)- Get position informationgetAccountTrades(params)- Get trade historygetIncomeHistory(params)- Get income history
Leverage & Margin:
changeLeverage(params)- Change leveragechangeMarginType(params)- Change margin typemodifyIsolatedPositionMargin(params)- Modify position margingetPositionMarginHistory(params)- Get margin historygetLeverageBrackets(params)- Get leverage brackets
Risk Management:
getADLQuantile(params)- Get ADL quantile estimationgetForceOrders(params)- Get liquidation ordersgetCommissionRate(params)- Get commission rate
Position Mode:
changePositionMode(params)- Change position modegetPositionMode()- Get current position modechangeMultiAssetMode(params)- Change multi-asset modegetMultiAssetMode()- Get current multi-asset mode
Listen Key (User Data Stream):
newListenKey()- Create listen key for user data streamrenewListenKey()- Keep-alive user data streamcloseListenKey()- Close user data streamgetOpenOrder(params)- Query single open order
📝 Examples
Check out the /examples directory for more detailed examples:
market-data.ts- Fetching public market datatrading.ts- Placing orders and managing positionstree-shakeable.ts- Using tree-shakeable functionswebsocket.ts- Real-time data streaming
🏗️ Architecture
This SDK is inspired by the Hyperliquid SDK architecture:
aster-connector-ts/
├── src/
│ ├── transport/ # Transport layer (HTTP, WebSocket)
│ ├── clients/ # Client classes (OOP style)
│ ├── api/ # Tree-shakeable functions
│ │ ├── market/ # Market data functions
│ │ └── trading/ # Trading functions
│ ├── types/ # TypeScript types
│ │ ├── common.ts # Common types
│ │ ├── market.ts # Market data types
│ │ └── trading.ts # Trading types
│ └── utils/ # Utilities
│ ├── signature.ts # HMAC signature generation
│ ├── formatters.ts # Data formatters
│ └── errors.ts # Error classes
├── examples/ # Usage examples
└── tests/ # Test filesDesign Principles
- Transport Pattern - Pluggable HTTP/WebSocket transports for flexibility
- Multiple API Patterns - Both OOP (client classes) and functional styles
- Tree-shaking - Import only what you need
- Type Safety - Full TypeScript support with comprehensive types
- Error Handling - Custom error classes for better debugging
🔒 Security
- Never commit your API keys to version control
- Use environment variables for credentials
- Consider using a
.envfile (add to.gitignore) - Be careful when testing on mainnet
// Good practice
const apiKey = process.env.ASTER_API_KEY;
const secretKey = process.env.ASTER_SECRET_KEY;🛠️ Development
# Install dependencies
npm install
# Build the project
npm run build
# Run type checking
npm run type-check
# Run linter
npm run lint
# Format code
npm run format
# Watch mode (development)
npm run dev🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Based on Aster Go Connector
- Built for the Aster DEX community
- Thanks to all contributors
📞 Support
- GitHub Issues: Report a bug
- Documentation: API Docs
⚠️ Disclaimer
This is an unofficial SDK. Use at your own risk. Always test thoroughly before using in production.
Made with ❤️ by the Aster DEX community
