{"_id":"@ansaibty/coindcx-sdk","name":"@ansaibty/coindcx-sdk","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@ansaibty/coindcx-sdk","version":"1.0.0","description":"Official-quality TypeScript SDK for the CoinDCX REST and WebSocket APIs","author":{"name":"CoinDCX SDK Contributors"},"license":"MIT","homepage":"https://github.com/Ansaibty123/coindcx-sdk#readme","repository":{"type":"git","url":"git+https://github.com/Ansaibty123/coindcx-sdk.git"},"bugs":{"url":"https://github.com/Ansaibty123/coindcx-sdk/issues"},"publishConfig":{"access":"public"},"keywords":["coindcx","crypto","trading","api","sdk","typescript","websocket","bitcoin","exchange"],"type":"module","main":"./dist/index.cjs","module":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"import":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"require":{"types":"./dist/index.d.cts","default":"./dist/index.cjs"}}},"sideEffects":false,"engines":{"node":">=20.0.0"},"scripts":{"build":"tsup","build:watch":"tsup --watch","typecheck":"tsc --noEmit","lint":"eslint .","lint:fix":"eslint . --fix","format":"prettier --write .","format:check":"prettier --check .","test":"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage","test:ws:depth":"tsx examples/websocket-orderbook.ts","docs":"typedoc","clean":"rm -rf dist docs"},"dependencies":{"esbuild":"^0.28.1","socket.io-client":"^4.8.3","ws":"^8.18.0"},"devDependencies":{"@eslint/js":"^9.18.0","@types/node":"^22.0.0","@types/socket.io-client":"^3.0.0","@types/ws":"^8.5.13","@vitest/coverage-v8":"^2.1.9","eslint":"^9.18.0","prettier":"^3.4.2","tsup":"^8.3.6","tsx":"^4.23.5","typedoc":"^0.27.6","typescript":"^5.7.3","typescript-eslint":"^8.20.0","vitest":"^2.1.9"},"_id":"@ansaibty/coindcx-sdk@1.0.0","gitHead":"6f9dad876e37e9d3663cf607f16fb400133a7806","_nodeVersion":"24.3.0","_npmVersion":"11.4.2","dist":{"integrity":"sha512-TWYotibsDgisHmI3r8Gqc9Seg6gaDGGQNh9OH4UQKvLvOcT0PZpN8eqKHlFSg8+aj4okLMV8B2lwPbGg3RmN4w==","shasum":"1033a48bc2b0a7587f5783903582eb48a69d9cae","tarball":"https://registry.npmjs.org/@ansaibty/coindcx-sdk/-/coindcx-sdk-1.0.0.tgz","fileCount":8,"unpackedSize":445875,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCO2cKhc/KUxorh5Pd7Hu3l2DUbFHF5STDb/LK4S5WmigIgfvtlyQtrDm/QYNL+f30JpRseBkjZ12yrctl3JnT0nj0="}]},"_npmUser":{"name":"ansaibty","email":"ansaibty333@gmail.com"},"directories":{},"maintainers":[{"name":"ansaibty","email":"ansaibty333@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/coindcx-sdk_1.0.0_1785846896494_0.6352625721418099"},"_hasShrinkwrap":false}},"time":{"created":"2026-08-04T12:34:56.365Z","1.0.0":"2026-08-04T12:34:56.650Z","modified":"2026-08-04T12:34:56.817Z"},"maintainers":[{"name":"ansaibty","email":"ansaibty333@gmail.com"}],"description":"Official-quality TypeScript SDK for the CoinDCX REST and WebSocket APIs","homepage":"https://github.com/Ansaibty123/coindcx-sdk#readme","keywords":["coindcx","crypto","trading","api","sdk","typescript","websocket","bitcoin","exchange"],"repository":{"type":"git","url":"git+https://github.com/Ansaibty123/coindcx-sdk.git"},"author":{"name":"CoinDCX SDK Contributors"},"bugs":{"url":"https://github.com/Ansaibty123/coindcx-sdk/issues"},"license":"MIT","readme":"# CoinDCX SDK\n\n> **Official-quality TypeScript SDK for the CoinDCX REST and WebSocket APIs**\n\n[![npm version](https://img.shields.io/npm/v/coindcx-sdk.svg)](https://www.npmjs.com/package/coindcx-sdk)\n[![CI](https://github.com/your-org/coindcx-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/your-org/coindcx-sdk/actions/workflows/ci.yml)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)\n[![Node.js](https://img.shields.io/badge/Node.js-20%2B-green.svg)](https://nodejs.org/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n\n---\n\n## Features\n\n- ✅ **Full Spot REST API** — Markets, Orders, Wallet, User\n- ✅ **WebSocket Streams** — Ticker, Depth, Trades, Candles, Order/Balance updates\n- ✅ **Auto-authentication** — HMAC-SHA256 signing, timestamp injection, zero manual work\n- ✅ **Strongly typed** — Complete TypeScript interfaces for every request and response\n- ✅ **Robust HTTP client** — Retries, exponential backoff, rate-limit handling, timeouts\n- ✅ **WebSocket auto-reconnect** — Exponential backoff, heartbeat ping/pong, auto-resubscribe\n- ✅ **Zero magic** — Predictable, testable, dependency-injectable architecture\n- ✅ **Tree-shakeable** — ESM + CJS dual output, `sideEffects: false`\n\n---\n\n## Installation\n\n```bash\n# pnpm (recommended)\npnpm add @ansaibty123/coindcx-sdk\n\n# npm\nnpm install @ansaibty123/coindcx-sdk\n\n# yarn\nyarn add @ansaibty123/coindcx-sdk\n```\n\n**Requirements**: Node.js 20+\n\n---\n\n## Quick Start\n\n```ts\nimport { CoinDCX } from 'coindcx-sdk';\n\nconst client = new CoinDCX({\n  apiKey: process.env.COINDCX_API_KEY!,\n  apiSecret: process.env.COINDCX_API_SECRET!,\n});\n\n// Public — no auth needed\nconst ticker = await client.markets.getTicker();\nconsole.log(ticker.find(t => t.market === 'BTCUSDT'));\n\n// Private — auth injected automatically\nconst balances = await client.wallet.getBalances();\nconsole.log(balances);\n\n// Place a limit order\nconst order = await client.orders.placeOrder({\n  market: 'BTCUSDT',\n  side: 'buy',\n  order_type: 'limit_order',\n  total_quantity: 0.001,\n  price_per_unit: 60000,\n});\nconsole.log(order.id, order.status);\n\n// WebSocket stream\nawait client.ws.connect();\nclient.ws.onTicker((update) => {\n  console.log(update.market, update.price);\n});\n```\n\n---\n\n## Authentication Guide\n\nCoinDCX uses **HMAC-SHA256** request signing. The SDK handles everything automatically:\n\n1. Generates the current timestamp (milliseconds)\n2. Injects it into the request body\n3. JSON-serialises the body\n4. Signs it with your API secret using HMAC-SHA256\n5. Attaches `X-AUTH-APIKEY` and `X-AUTH-SIGNATURE` headers\n\n**You never need to sign requests manually.**\n\n### Getting API Credentials\n\n1. Go to [CoinDCX API Dashboard](https://coindcx.com/api-dashboard)\n2. Create a new API key\n3. Note the Key and Secret (the secret is only shown once)\n\n### Secure Usage\n\n```ts\n// ✅ Use environment variables — never hardcode secrets\nconst client = new CoinDCX({\n  apiKey: process.env.COINDCX_API_KEY!,\n  apiSecret: process.env.COINDCX_API_SECRET!,\n});\n\n// ❌ Never do this\nconst client = new CoinDCX({\n  apiKey: 'abc123...',\n  apiSecret: 'super-secret...',\n});\n```\n\n---\n\n## API Reference\n\n### Client Configuration\n\n```ts\nconst client = new CoinDCX({\n  apiKey: string,          // Required\n  apiSecret: string,       // Required\n  baseURL?: string,        // Default: 'https://api.coindcx.com'\n  timeout?: number,        // Default: 30_000 ms\n  retries?: number,        // Default: 3\n  logLevel?: LogLevel,     // 'silent' | 'debug' | 'info' | 'warn' | 'error'\n  fetchImpl?: typeof fetch // Custom fetch (for testing/proxy)\n});\n```\n\n---\n\n### Markets API (`client.markets`)\n\nAll public — no API key required.\n\n```ts\n// List all markets\nconst markets = await client.markets.getMarkets();\n\n// Detailed market info (fees, precision)\nconst details = await client.markets.getMarketsDetails();\n\n// 24h ticker for all markets\nconst tickers = await client.markets.getTicker();\n\n// Recent public trades\nconst trades = await client.markets.getTrades({\n  pair: 'B-BTC_USDT',\n  limit: 50,           // optional, default varies\n});\n\n// Order book depth\nconst depth = await client.markets.getDepth({ pair: 'B-BTC_USDT' });\n// depth.asks: [{ price, quantity }, ...]\n// depth.bids: [{ price, quantity }, ...]\n\n// Candlestick data\nconst candles = await client.markets.getCandles({\n  pair: 'B-BTC_USDT',\n  interval: '1h',        // '1m' | '5m' | '15m' | '1h' | '1d' | ...\n  startTime: 1700000000000,  // optional, epoch ms\n  endTime: 1700003600000,    // optional, epoch ms\n  limit: 100,            // optional\n});\n```\n\n---\n\n### Wallet API (`client.wallet`)\n\n```ts\n// All balances (currencies with non-zero balance)\nconst balances = await client.wallet.getBalances();\n\n// Specific currency balance\nconst btc = await client.wallet.getBalance('BTC');\nconsole.log(btc.balance);        // Available\nconsole.log(btc.locked_balance); // Locked in open orders\n```\n\n---\n\n### Orders API (`client.orders`)\n\n```ts\n// Place a limit order\nconst order = await client.orders.placeOrder({\n  market: 'BTCUSDT',\n  side: 'buy',                  // 'buy' | 'sell'\n  order_type: 'limit_order',   // 'limit_order' | 'market_order'\n  total_quantity: 0.001,\n  price_per_unit: 60000,       // Required for limit orders\n  client_order_id: 'my-id-1', // Optional idempotency key\n});\n\n// Place multiple orders\nconst orders = await client.orders.placeMultipleOrders([\n  { market: 'BTCUSDT', side: 'buy', order_type: 'limit_order', total_quantity: 0.001, price_per_unit: 59000 },\n  { market: 'BTCUSDT', side: 'buy', order_type: 'limit_order', total_quantity: 0.001, price_per_unit: 58000 },\n]);\n\n// Get order by ID\nconst order = await client.orders.getOrder({ id: 'order-uuid' });\n\n// Get multiple orders\nconst orders = await client.orders.getOrders({ ids: ['id1', 'id2'] });\n\n// Open orders on a market\nconst openOrders = await client.orders.getOpenOrders({ market: 'BTCUSDT' });\n\n// Open orders count\nconst { count } = await client.orders.getOpenOrdersCount({ market: 'BTCUSDT' });\n\n// Trade history\nconst history = await client.orders.getOrderHistory({\n  symbol: 'BTCUSDT',  // optional filter\n  limit: 100,         // optional, default 500\n  sort: 'desc',       // optional\n});\n\n// Cancel by ID\nawait client.orders.cancelOrder({ id: 'order-uuid' });\n\n// Cancel multiple by IDs\nawait client.orders.cancelOrdersByIds({ ids: ['id1', 'id2'] });\n\n// Cancel all on a market\nawait client.orders.cancelAllOrders({ market: 'BTCUSDT', side: 'buy' }); // side optional\n\n// Edit price\nconst updated = await client.orders.editOrderPrice({\n  id: 'order-uuid',\n  price_per_unit: 65000,\n});\n```\n\n---\n\n### User API (`client.user`)\n\n```ts\nconst profile = await client.user.profile();\nconsole.log(profile.email, profile.first_name, profile.coindcx_id);\n```\n\n---\n\n### WebSocket (`client.ws`)\n\n```ts\n// Connect first\nawait client.ws.connect();\n\n// === PUBLIC STREAMS ===\n\n// All market ticker prices\nconst unsub = client.ws.onTicker((update) => {\n  console.log(update.market, update.price);\n});\n\n// 24h price stats\nclient.ws.onPriceStats((stats) => {\n  console.log(stats.ltp, stats.change_24_hour);\n});\n\n// Order book updates\nclient.ws.onDepth('B-BTC_USDT', (depth) => {\n  console.log(depth.asks, depth.bids);\n});\n\n// New public trades\nclient.ws.onTrades('B-BTC_USDT', (trade) => {\n  console.log(trade.p, trade.q, trade.s); // price, quantity, side\n});\n\n// Candlestick updates\nclient.ws.onCandles('B-BTC_USDT', '1m', (candle) => {\n  console.log(candle.close, candle.volume);\n});\n\n// === PRIVATE STREAMS (requires apiKey + apiSecret) ===\n\nconst { coindcx_id: uid } = await client.user.profile();\n\n// Order status changes\nclient.ws.onOrderUpdate(uid, (update) => {\n  console.log(update.id, update.status, update.remaining_quantity);\n});\n\n// Balance changes\nclient.ws.onBalanceUpdate(uid, (update) => {\n  console.log(update.currency, update.balance);\n});\n\n// Your trade fills\nclient.ws.onUserTrades(uid, (trade) => {\n  console.log(trade.price, trade.quantity);\n});\n\n// Unsubscribe individual stream\nunsub();\n\n// Disconnect\nclient.ws.disconnect();\n```\n\n---\n\n## Error Handling\n\nAll errors extend `CoinDCXError` and expose structured metadata:\n\n```ts\nimport {\n  APIError,\n  AuthenticationError,\n  RateLimitError,\n  ValidationError,\n  NetworkError,\n  TimeoutError,\n} from 'coindcx-sdk';\n\ntry {\n  await client.orders.placeOrder(params);\n} catch (err) {\n  if (err instanceof AuthenticationError) {\n    console.error('Invalid API key or signature');\n  } else if (err instanceof RateLimitError) {\n    console.error(`Rate limited. Retry after ${err.retryAfter}s`);\n  } else if (err instanceof ValidationError) {\n    console.error(`Bad param: ${err.param} — ${err.message}`);\n  } else if (err instanceof APIError) {\n    console.error(`API error ${err.status}: ${err.message}`);\n    console.error('Request ID:', err.requestId);\n  } else if (err instanceof NetworkError) {\n    console.error('Network failure:', err.message);\n  } else if (err instanceof TimeoutError) {\n    console.error(`Timed out after ${err.timeoutMs}ms`);\n  }\n}\n```\n\n---\n\n## Utilities\n\n```ts\nimport {\n  formatPrice,\n  formatQuantity,\n  toTimestamp,\n  fromTimestamp,\n  percentageChange,\n  paginate,\n  collectAll,\n} from 'coindcx-sdk';\n\nformatPrice(0.00001567)           // \"0.00001567\"\nformatQuantity(1234.5678)         // \"1234.567800\"\ntoTimestamp('2024-01-01')         // 1704067200000\nfromTimestamp(1704067200000)      // Date object\npercentageChange(60000, 63000)    // 5.0\n\n// Paginate all trade history\nfor await (const page of paginate({\n  fetchPage: async (cursor, limit) =>\n    client.orders.getOrderHistory({ from_id: cursor as number, limit }),\n  getNextCursor: (items) => items.at(-1)?.id,\n  limit: 500,\n})) {\n  console.log(`Got ${page.data.length} trades`);\n}\n\n// Or collect all at once\nconst allTrades = await collectAll({\n  fetchPage: async (cursor, limit) =>\n    client.orders.getOrderHistory({ from_id: cursor as number, limit }),\n  getNextCursor: (items) => items.at(-1)?.id,\n  limit: 500,\n});\n```\n\n---\n\n## Configuration\n\n### Sandbox / Custom Base URL\n\n```ts\nconst client = new CoinDCX({\n  apiKey: '...',\n  apiSecret: '...',\n  baseURL: 'https://your-proxy.example.com', // Override for testing\n});\n```\n\n### Custom Fetch (Proxy / Testing)\n\n```ts\nimport { CoinDCX } from 'coindcx-sdk';\n\nconst client = new CoinDCX({\n  apiKey: '...',\n  apiSecret: '...',\n  fetchImpl: (url, init) => myProxyFetch(url, init),\n});\n```\n\n### Logging\n\n```ts\nconst client = new CoinDCX({\n  apiKey: '...',\n  apiSecret: '...',\n  logLevel: 'debug', // 'silent' | 'debug' | 'info' | 'warn' | 'error'\n});\n```\n\n---\n\n## Development\n\n```bash\n# Install dependencies\npnpm install\n\n# Build (ESM + CJS + type declarations)\npnpm build\n\n# Run tests\npnpm test\n\n# Run tests with coverage\npnpm test:coverage\n\n# Type checking\npnpm typecheck\n\n# Lint\npnpm lint\n\n# Generate API docs\npnpm docs\n```\n\n---\n\n## FAQ\n\n**Q: Do I need an API key for public endpoints?**\nA: No. `client.markets.*` methods work without any credentials.\n\n**Q: Why am I getting `AuthenticationError`?**\nA: Check that your API key and secret are correct and that the IP calling the API is allowed in your CoinDCX API settings.\n\n**Q: How do I run in a sandboxed environment?**\nA: CoinDCX doesn't offer an official sandbox. Use a very low price on limit orders to avoid accidental fills during testing.\n\n**Q: The WebSocket disconnects sometimes — is that normal?**\nA: Yes. The SDK will automatically reconnect with exponential backoff. You don't need to handle reconnection manually.\n\n**Q: Can I use this in the browser?**\nA: The SDK is built for Node.js 20+. Browser usage is not supported because signing requests in the browser would expose your API secret.\n\n---\n\n## License\n\nMIT © CoinDCX SDK Contributors\n\n---\n\n*This SDK is not officially affiliated with CoinDCX (Neblio Technologies Pvt. Ltd.).*\n*Use at your own risk. Never risk more than you can afford to lose.*\n","readmeFilename":"README.md","_rev":"1-a342eafc61f2ae940441e119c7e9bf0a"}