@ansaibty/coindcx-sdk
v1.0.0
Published
Official-quality TypeScript SDK for the CoinDCX REST and WebSocket APIs
Maintainers
Readme
CoinDCX SDK
Official-quality TypeScript SDK for the CoinDCX REST and WebSocket APIs
Features
- ✅ Full Spot REST API — Markets, Orders, Wallet, User
- ✅ WebSocket Streams — Ticker, Depth, Trades, Candles, Order/Balance updates
- ✅ Auto-authentication — HMAC-SHA256 signing, timestamp injection, zero manual work
- ✅ Strongly typed — Complete TypeScript interfaces for every request and response
- ✅ Robust HTTP client — Retries, exponential backoff, rate-limit handling, timeouts
- ✅ WebSocket auto-reconnect — Exponential backoff, heartbeat ping/pong, auto-resubscribe
- ✅ Zero magic — Predictable, testable, dependency-injectable architecture
- ✅ Tree-shakeable — ESM + CJS dual output,
sideEffects: false
Installation
# pnpm (recommended)
pnpm add @ansaibty123/coindcx-sdk
# npm
npm install @ansaibty123/coindcx-sdk
# yarn
yarn add @ansaibty123/coindcx-sdkRequirements: Node.js 20+
Quick Start
import { CoinDCX } from 'coindcx-sdk';
const client = new CoinDCX({
apiKey: process.env.COINDCX_API_KEY!,
apiSecret: process.env.COINDCX_API_SECRET!,
});
// Public — no auth needed
const ticker = await client.markets.getTicker();
console.log(ticker.find(t => t.market === 'BTCUSDT'));
// Private — auth injected automatically
const balances = await client.wallet.getBalances();
console.log(balances);
// Place a limit order
const order = await client.orders.placeOrder({
market: 'BTCUSDT',
side: 'buy',
order_type: 'limit_order',
total_quantity: 0.001,
price_per_unit: 60000,
});
console.log(order.id, order.status);
// WebSocket stream
await client.ws.connect();
client.ws.onTicker((update) => {
console.log(update.market, update.price);
});Authentication Guide
CoinDCX uses HMAC-SHA256 request signing. The SDK handles everything automatically:
- Generates the current timestamp (milliseconds)
- Injects it into the request body
- JSON-serialises the body
- Signs it with your API secret using HMAC-SHA256
- Attaches
X-AUTH-APIKEYandX-AUTH-SIGNATUREheaders
You never need to sign requests manually.
Getting API Credentials
- Go to CoinDCX API Dashboard
- Create a new API key
- Note the Key and Secret (the secret is only shown once)
Secure Usage
// ✅ Use environment variables — never hardcode secrets
const client = new CoinDCX({
apiKey: process.env.COINDCX_API_KEY!,
apiSecret: process.env.COINDCX_API_SECRET!,
});
// ❌ Never do this
const client = new CoinDCX({
apiKey: 'abc123...',
apiSecret: 'super-secret...',
});API Reference
Client Configuration
const client = new CoinDCX({
apiKey: string, // Required
apiSecret: string, // Required
baseURL?: string, // Default: 'https://api.coindcx.com'
timeout?: number, // Default: 30_000 ms
retries?: number, // Default: 3
logLevel?: LogLevel, // 'silent' | 'debug' | 'info' | 'warn' | 'error'
fetchImpl?: typeof fetch // Custom fetch (for testing/proxy)
});Markets API (client.markets)
All public — no API key required.
// List all markets
const markets = await client.markets.getMarkets();
// Detailed market info (fees, precision)
const details = await client.markets.getMarketsDetails();
// 24h ticker for all markets
const tickers = await client.markets.getTicker();
// Recent public trades
const trades = await client.markets.getTrades({
pair: 'B-BTC_USDT',
limit: 50, // optional, default varies
});
// Order book depth
const depth = await client.markets.getDepth({ pair: 'B-BTC_USDT' });
// depth.asks: [{ price, quantity }, ...]
// depth.bids: [{ price, quantity }, ...]
// Candlestick data
const candles = await client.markets.getCandles({
pair: 'B-BTC_USDT',
interval: '1h', // '1m' | '5m' | '15m' | '1h' | '1d' | ...
startTime: 1700000000000, // optional, epoch ms
endTime: 1700003600000, // optional, epoch ms
limit: 100, // optional
});Wallet API (client.wallet)
// All balances (currencies with non-zero balance)
const balances = await client.wallet.getBalances();
// Specific currency balance
const btc = await client.wallet.getBalance('BTC');
console.log(btc.balance); // Available
console.log(btc.locked_balance); // Locked in open ordersOrders API (client.orders)
// Place a limit order
const order = await client.orders.placeOrder({
market: 'BTCUSDT',
side: 'buy', // 'buy' | 'sell'
order_type: 'limit_order', // 'limit_order' | 'market_order'
total_quantity: 0.001,
price_per_unit: 60000, // Required for limit orders
client_order_id: 'my-id-1', // Optional idempotency key
});
// Place multiple orders
const orders = await client.orders.placeMultipleOrders([
{ market: 'BTCUSDT', side: 'buy', order_type: 'limit_order', total_quantity: 0.001, price_per_unit: 59000 },
{ market: 'BTCUSDT', side: 'buy', order_type: 'limit_order', total_quantity: 0.001, price_per_unit: 58000 },
]);
// Get order by ID
const order = await client.orders.getOrder({ id: 'order-uuid' });
// Get multiple orders
const orders = await client.orders.getOrders({ ids: ['id1', 'id2'] });
// Open orders on a market
const openOrders = await client.orders.getOpenOrders({ market: 'BTCUSDT' });
// Open orders count
const { count } = await client.orders.getOpenOrdersCount({ market: 'BTCUSDT' });
// Trade history
const history = await client.orders.getOrderHistory({
symbol: 'BTCUSDT', // optional filter
limit: 100, // optional, default 500
sort: 'desc', // optional
});
// Cancel by ID
await client.orders.cancelOrder({ id: 'order-uuid' });
// Cancel multiple by IDs
await client.orders.cancelOrdersByIds({ ids: ['id1', 'id2'] });
// Cancel all on a market
await client.orders.cancelAllOrders({ market: 'BTCUSDT', side: 'buy' }); // side optional
// Edit price
const updated = await client.orders.editOrderPrice({
id: 'order-uuid',
price_per_unit: 65000,
});User API (client.user)
const profile = await client.user.profile();
console.log(profile.email, profile.first_name, profile.coindcx_id);WebSocket (client.ws)
// Connect first
await client.ws.connect();
// === PUBLIC STREAMS ===
// All market ticker prices
const unsub = client.ws.onTicker((update) => {
console.log(update.market, update.price);
});
// 24h price stats
client.ws.onPriceStats((stats) => {
console.log(stats.ltp, stats.change_24_hour);
});
// Order book updates
client.ws.onDepth('B-BTC_USDT', (depth) => {
console.log(depth.asks, depth.bids);
});
// New public trades
client.ws.onTrades('B-BTC_USDT', (trade) => {
console.log(trade.p, trade.q, trade.s); // price, quantity, side
});
// Candlestick updates
client.ws.onCandles('B-BTC_USDT', '1m', (candle) => {
console.log(candle.close, candle.volume);
});
// === PRIVATE STREAMS (requires apiKey + apiSecret) ===
const { coindcx_id: uid } = await client.user.profile();
// Order status changes
client.ws.onOrderUpdate(uid, (update) => {
console.log(update.id, update.status, update.remaining_quantity);
});
// Balance changes
client.ws.onBalanceUpdate(uid, (update) => {
console.log(update.currency, update.balance);
});
// Your trade fills
client.ws.onUserTrades(uid, (trade) => {
console.log(trade.price, trade.quantity);
});
// Unsubscribe individual stream
unsub();
// Disconnect
client.ws.disconnect();Error Handling
All errors extend CoinDCXError and expose structured metadata:
import {
APIError,
AuthenticationError,
RateLimitError,
ValidationError,
NetworkError,
TimeoutError,
} from 'coindcx-sdk';
try {
await client.orders.placeOrder(params);
} catch (err) {
if (err instanceof AuthenticationError) {
console.error('Invalid API key or signature');
} else if (err instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${err.retryAfter}s`);
} else if (err instanceof ValidationError) {
console.error(`Bad param: ${err.param} — ${err.message}`);
} else if (err instanceof APIError) {
console.error(`API error ${err.status}: ${err.message}`);
console.error('Request ID:', err.requestId);
} else if (err instanceof NetworkError) {
console.error('Network failure:', err.message);
} else if (err instanceof TimeoutError) {
console.error(`Timed out after ${err.timeoutMs}ms`);
}
}Utilities
import {
formatPrice,
formatQuantity,
toTimestamp,
fromTimestamp,
percentageChange,
paginate,
collectAll,
} from 'coindcx-sdk';
formatPrice(0.00001567) // "0.00001567"
formatQuantity(1234.5678) // "1234.567800"
toTimestamp('2024-01-01') // 1704067200000
fromTimestamp(1704067200000) // Date object
percentageChange(60000, 63000) // 5.0
// Paginate all trade history
for await (const page of paginate({
fetchPage: async (cursor, limit) =>
client.orders.getOrderHistory({ from_id: cursor as number, limit }),
getNextCursor: (items) => items.at(-1)?.id,
limit: 500,
})) {
console.log(`Got ${page.data.length} trades`);
}
// Or collect all at once
const allTrades = await collectAll({
fetchPage: async (cursor, limit) =>
client.orders.getOrderHistory({ from_id: cursor as number, limit }),
getNextCursor: (items) => items.at(-1)?.id,
limit: 500,
});Configuration
Sandbox / Custom Base URL
const client = new CoinDCX({
apiKey: '...',
apiSecret: '...',
baseURL: 'https://your-proxy.example.com', // Override for testing
});Custom Fetch (Proxy / Testing)
import { CoinDCX } from 'coindcx-sdk';
const client = new CoinDCX({
apiKey: '...',
apiSecret: '...',
fetchImpl: (url, init) => myProxyFetch(url, init),
});Logging
const client = new CoinDCX({
apiKey: '...',
apiSecret: '...',
logLevel: 'debug', // 'silent' | 'debug' | 'info' | 'warn' | 'error'
});Development
# Install dependencies
pnpm install
# Build (ESM + CJS + type declarations)
pnpm build
# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Type checking
pnpm typecheck
# Lint
pnpm lint
# Generate API docs
pnpm docsFAQ
Q: Do I need an API key for public endpoints?
A: No. client.markets.* methods work without any credentials.
Q: Why am I getting AuthenticationError?
A: Check that your API key and secret are correct and that the IP calling the API is allowed in your CoinDCX API settings.
Q: How do I run in a sandboxed environment? A: CoinDCX doesn't offer an official sandbox. Use a very low price on limit orders to avoid accidental fills during testing.
Q: The WebSocket disconnects sometimes — is that normal? A: Yes. The SDK will automatically reconnect with exponential backoff. You don't need to handle reconnection manually.
Q: Can I use this in the browser? A: The SDK is built for Node.js 20+. Browser usage is not supported because signing requests in the browser would expose your API secret.
License
MIT © CoinDCX SDK Contributors
This SDK is not officially affiliated with CoinDCX (Neblio Technologies Pvt. Ltd.). Use at your own risk. Never risk more than you can afford to lose.
