npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

klingex

v1.0.0

Published

Official JavaScript/TypeScript SDK for KlingEx Exchange API

Readme

KlingEx JavaScript/TypeScript SDK

Official JavaScript/TypeScript SDK for the KlingEx cryptocurrency exchange API.

Installation

npm install klingex
# or
yarn add klingex
# or
pnpm add klingex

Quick Start

import { KlingEx } from 'klingex';

// Initialize client with API key
const client = new KlingEx({
  apiKey: 'your-api-key-here'
});

// Get all markets
const markets = await client.markets.list();
console.log(markets);

// Get your balances
const balances = await client.wallet.balances();
console.log(balances);

// Place a limit order (human-readable values by default)
const order = await client.orders.submit({
  symbol: 'BTC-USDT',
  tradingPairId: 1,
  side: 'buy',
  quantity: '0.5',      // 0.5 BTC
  price: '50000.00'     // $50,000 per BTC
});
console.log(`Order placed: ${order.order_id}`);

Configuration

const client = new KlingEx({
  // Authentication (choose one)
  apiKey: 'your-api-key',      // API key authentication
  // jwt: 'your-jwt-token',    // Or JWT authentication

  // Optional settings
  baseUrl: 'https://api.klingex.io',  // API base URL
  wsUrl: 'wss://api.klingex.io/ws',   // WebSocket URL
  timeout: 30000,                      // Request timeout (ms)
  humanReadable: true,                 // Use human-readable values (default: true)
});

API Reference

Markets

// Get all trading pairs
const markets = await client.markets.list();
for (const market of markets.slice(0, 5)) {
  console.log(`${market.base_asset_symbol}-${market.quote_asset_symbol}: ${market.last_price}`);
}

// Get 24h tickers (CMC format - uses underscore "BTC_USDT")
const tickers = await client.markets.tickers();
const btcTicker = await client.markets.ticker('BTC_USDT');
console.log(`BTC_USDT: ${btcTicker?.last_price}`);

// Get orderbook (marketId is a number)
const orderbook = await client.markets.orderbook(1);
console.log('Best bid:', orderbook.bids[0]);
console.log('Best ask:', orderbook.asks[0]);

// Get OHLCV (candlestick) data
const candles = await client.markets.ohlcv(1, '1h', { limit: 100 });

// Get recent trades (marketId is a number)
const trades = await client.markets.trades(1);

Orders

// Place a limit order
const order = await client.orders.submit({
  symbol: 'BTC-USDT',
  tradingPairId: 1,
  side: 'buy',
  quantity: '1.0',
  price: '50000.00'
});

// Convenience methods
await client.orders.limitBuy('BTC-USDT', 1, '1.0', '50000.00');
await client.orders.limitSell('BTC-USDT', 1, '1.0', '55000.00');
await client.orders.marketBuy('BTC-USDT', 1, '1.0', 0.01);  // 1% slippage
await client.orders.marketSell('BTC-USDT', 1, '1.0', 0.01);

// Get open orders
const orders = await client.orders.list();
const btcOrders = await client.orders.list({ tradingPairId: 1 });

// Cancel an order
await client.orders.cancel({
  orderId: 'order-uuid',
  tradingPairId: 1
});

// Cancel all orders for a trading pair
const result = await client.orders.cancelAll(1);
console.log(`Cancelled ${result.cancelledCount} orders`);

// Get order history
const history = await client.orders.history({ limit: 100 });

Raw Values vs Human-Readable

By default, the SDK uses human-readable values (e.g., "1.5" for 1.5 BTC). To use raw base units:

// Human-readable (default)
await client.orders.submit({
  symbol: 'BTC-USDT',
  tradingPairId: 1,
  side: 'buy',
  quantity: '1.5',      // 1.5 BTC
  price: '50000.00',    // $50,000
});

// Raw base units
await client.orders.submit({
  symbol: 'BTC-USDT',
  tradingPairId: 1,
  side: 'buy',
  quantity: '150000000',  // 1.5 BTC in satoshis (8 decimals)
  price: '5000000000',    // $50,000 in base units
  rawValues: true
});

// Or configure globally
const client = new KlingEx({
  apiKey: 'your-key',
  humanReadable: false  // Use raw values by default
});

Wallet

// Get all balances
const balances = await client.wallet.balances();

// Get specific balance
const btc = await client.wallet.balance('BTC');
console.log(`Available: ${btc?.human_available} BTC`);

Invoices (Payment Processing)

// Create invoice
const invoice = await client.invoices.create({
  amount: '100.00',
  asset: 'USDT',
  description: 'Order #12345',
  webhook_url: 'https://yoursite.com/webhook',
  expires_in: 60  // minutes
});

console.log(`Payment address: ${invoice.payment_address}`);
console.log(`Invoice URL: https://klingex.io/pay/${invoice.id}`);

// List invoices
const invoices = await client.invoices.list({ status: 'pending' });

// Check status
const status = await client.invoices.status(invoice.id);

// Cancel
await client.invoices.cancel(invoice.id);

// Get PDF
const pdf = await client.invoices.pdf(invoice.id);

WebSocket (Real-time Data)

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

// Subscribe to orderbook updates
const unsubOrderbook = client.ws.orderbook('BTC-USDT', (data) => {
  console.log('Orderbook update:', data);
});

// Subscribe to trades
const unsubTrades = client.ws.trades('BTC-USDT', (data) => {
  console.log('New trade:', data);
});

// Subscribe to ticker
client.ws.ticker('BTC-USDT', (ticker) => {
  console.log(`Price: ${ticker.last_price}`);
});

// User-specific channels (requires auth)
client.ws.userOrders((order) => {
  console.log('Order update:', order);
});

client.ws.userBalances((balance) => {
  console.log('Balance update:', balance);
});

// Handle errors
client.ws.onError((error) => {
  console.error('WebSocket error:', error);
});

// Unsubscribe
unsubOrderbook();
unsubTrades();

// Disconnect
client.ws.disconnect();

Error Handling

import {
  KlingEx,
  KlingExError,
  AuthenticationError,
  RateLimitError,
  ValidationError,
  InsufficientFundsError
} from 'klingex';

try {
  await client.orders.submit({ /* ... */ });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter}s`);
  } else if (error instanceof InsufficientFundsError) {
    console.error('Not enough balance');
  } else if (error instanceof ValidationError) {
    console.error('Invalid parameters:', error.details);
  } else if (error instanceof KlingExError) {
    console.error(`API error: ${error.message} (${error.code})`);
  }
}

TypeScript Support

Full TypeScript support with type definitions included:

import type {
  Market,
  Order,
  Balance,
  Ticker,
  Orderbook,
  SubmitOrderParams
} from 'klingex';

const params: SubmitOrderParams = {
  symbol: 'BTC-USDT',
  tradingPairId: 1,
  side: 'buy',
  quantity: '1.0',
  price: '50000.00'
};

Browser Support

The SDK works in both Node.js and browsers. For browsers, make sure you have a WebSocket polyfill if needed.

<script type="module">
  import { KlingEx } from 'https://unpkg.com/klingex/dist/index.mjs';

  const client = new KlingEx({ apiKey: 'your-key' });
  const markets = await client.markets.list();
</script>

License

MIT

Support

  • Documentation: https://klingex.io/support/api-docs
  • Issues: https://github.com/Klingon-tech/klingex-js/issues
  • Email: [email protected]