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

valr-typescript-client

v1.0.27

Published

Official TypeScript/JavaScript SDK for VALR API - South African crypto exchange. Fully typed REST client with WebSocket support for Bitcoin, Ethereum trading. Complete API coverage for spot, futures, margin trading.

Downloads

57

Readme

VALR API TypeScript Client | Official SDK for VALR Cryptocurrency Exchange

npm version npm downloads GitHub license TypeScript Node.js Version

Official TypeScript/JavaScript SDK for VALR API - South Africa's leading cryptocurrency exchange platform.

Complete, fully-typed REST API client for VALR cryptocurrency exchange. Build Bitcoin, Ethereum, and altcoin trading bots with comprehensive TypeScript support. Perfect for algorithmic trading, portfolio management, and crypto automation.

🚀 Perfect For

  • Trading Bots - Automate your crypto trading strategies
  • Portfolio Management - Track and manage multiple wallets
  • Algorithmic Trading - Build sophisticated trading algorithms
  • Market Analysis - Access real-time market data and order books
  • DeFi Integration - Connect VALR to your DeFi applications
  • Crypto Automation - Automate deposits, withdrawals, and transfers

✨ Features

Trading & Markets

  • Spot Trading - Buy/sell Bitcoin, Ethereum, and 50+ cryptocurrencies
  • Futures Trading - Perpetual futures contracts with up to 60x leverage
  • Margin Trading - Trade with borrowed funds
  • Batch Orders - Submit up to 10 orders in a single request
  • Advanced Orders - Stop-limit, post-only, reduce-only orders
  • Conditional Orders - Take-profit and stop-loss automation

TypeScript & Developer Experience

  • 100% TypeScript - Complete type definitions for all API endpoints
  • IntelliSense Support - Auto-completion in VS Code and IDEs
  • Type-Safe Requests - Compile-time validation of all API calls
  • ESM & CommonJS - Works with modern and legacy Node.js projects
  • Zero Dependencies - Minimal dependency footprint

API Coverage

  • 147+ REST Endpoints - Complete VALR API implementation
  • WebSocket Support - Real-time market data and account updates
  • Public APIs - Market data, order books, trade history (no auth required)
  • Account APIs - Balances, transaction history, API key management
  • Wallet APIs - Crypto/fiat deposits and withdrawals

Security & Reliability

  • HMAC SHA512 Authentication - Industry-standard request signing
  • Automatic Signature Generation - No manual crypto operations needed
  • Rate Limit Handling - Built-in rate limit awareness
  • Error Types - Typed error classes for all failure scenarios
  • Subaccount Support - Manage multiple trading accounts

Package Integrity

  • Cryptographic Checksums - SHA256 verification for all builds
  • Reproducible Builds - Build from source with verification
  • Supply Chain Security - GitHub Actions provenance attestation

🪙 Supported Cryptocurrencies

Trade 50+ cryptocurrencies including:

  • Bitcoin (BTC) - BTC/ZAR, BTC/USDC, BTC/USDT pairs
  • Ethereum (ETH) - ETH/ZAR, ETH/USDC, ETH/BTC pairs
  • Major Altcoins - XRP, ADA, DOT, LINK, MATIC, SOL, AVAX, UNI
  • Stablecoins - USDC, USDT, DAI
  • DeFi Tokens - AAVE, SNX, COMP, MKR, YFI
  • Meme Coins - DOGE, SHIB
  • Perpetual Futures - BTC-PERP, ETH-PERP, and more

Full list at VALR Markets

📦 Installation

npm

npm install valr-typescript-client

yarn

yarn add valr-typescript-client

pnpm

pnpm add valr-typescript-client

bun

bun add valr-typescript-client

📚 Table of Contents

Quick Start

Public API (No Authentication Required)

import { ValrClient } from 'valr-typescript-client';

const client = new ValrClient();

// Get server time
const time = await client.public.getServerTime();
console.log('Server time:', time);

// Get market summary for all pairs
const markets = await client.public.getMarketSummary();
console.log('Markets:', markets);

// Get order book for a specific pair
const orderBook = await client.public.getOrderBook('BTCZAR');
console.log('Order book:', orderBook);

// Get currencies
const currencies = await client.public.getCurrencies();
console.log('Supported currencies:', currencies);

Authenticated API

import { ValrClient } from 'valr-typescript-client';

const client = new ValrClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
});

// Get account balances
const balances = await client.account.getBalances();
console.log('Balances:', balances);

// Place a limit order
const order = await client.trading.placeLimitOrder({
  pair: 'BTCZAR',
  side: 'BUY',
  quantity: '0.001',
  price: '500000',
  postOnly: 'POST_ONLY_REPRICE',
  customerOrderId: 'my-order-1',
});
console.log('Order placed:', order);

// Get open orders
const openOrders = await client.trading.getAllOpenOrders();
console.log('Open orders:', openOrders);

// Get trade history
const trades = await client.account.getTradeHistory({
  skip: 0,
  limit: 100,
});
console.log('Trade history:', trades);

Advanced Trading

// Place a market order
const marketOrder = await client.trading.placeMarketOrder({
  pair: 'ETHZAR',
  side: 'BUY',
  quoteAmount: '1000', // Spend 1000 ZAR
});

// Place a stop-limit order
const stopOrder = await client.trading.placeStopLimitOrder({
  pair: 'BTCZAR',
  side: 'SELL',
  quantity: '0.001',
  price: '450000',
  stopPrice: '460000',
});

// Place batch orders
const batchOrders = await client.trading.placeBatchOrders({
  requests: [
    {
      pair: 'BTCZAR',
      side: 'BUY',
      quantity: '0.001',
      price: '480000',
      postOnly: 'POST_ONLY_REPRICE',
    },
    {
      pair: 'ETHZAR',
      side: 'BUY',
      quantity: '0.01',
      price: '30000',
      postOnly: 'POST_ONLY_REPRICE',
    },
  ],
});

// Get order status
const orderStatus = await client.trading.getOrderStatus('BTCZAR', order.id);
console.log('Order status:', orderStatus);

// Cancel order
await client.trading.cancelOrder({
  pair: 'BTCZAR',
  orderId: order.id,
});

Wallets

// Get crypto deposit address
const depositAddress = await client.wallets.getCryptoDepositAddress('BTC');
console.log('Deposit to:', depositAddress.address);

// Withdraw crypto
const withdrawal = await client.wallets.withdrawCrypto({
  currency: 'BTC',
  amount: '0.001',
  address: 'bc1q...',
});
console.log('Withdrawal ID:', withdrawal.id);

// Get bank accounts
const bankAccounts = await client.wallets.getBankAccounts('ZAR');
console.log('Bank accounts:', bankAccounts);

Futures Trading

// Get open futures positions
const positions = await client.futures.getOpenPositions();
console.log('Open positions:', positions);

// Get leverage info
const leverage = await client.futures.getLeverageInfo('BTCUSDTPERP');
console.log('Current leverage:', leverage);

// Update leverage
await client.futures.updateLeverage('BTCUSDTPERP', {
  leverageMultiple: 5,
});

Subaccount Impersonation

const client = new ValrClient({
  apiKey: 'your-primary-account-api-key',
  apiSecret: 'your-primary-account-api-secret',
  subaccountId: 'subaccount-id',
});

// All requests will now be made on behalf of the subaccount
const balances = await client.account.getBalances();

// Change subaccount or clear
client.setSubaccountId('different-subaccount-id');
client.setSubaccountId(undefined); // Back to primary account

💡 Examples

Trading Bot Example

Build a simple Bitcoin DCA (Dollar Cost Averaging) bot:

import { ValrClient } from 'valr-typescript-client';

const client = new ValrClient({
  apiKey: process.env.VALR_API_KEY!,
  apiSecret: process.env.VALR_API_SECRET!,
});

// DCA Bot - Buy R1000 worth of BTC every day
async function dcaBot() {
  try {
    // Get current BTC price
    const ticker = await client.public.getMarketSummary('BTCZAR');
    console.log(`Current BTC price: R${ticker[0].lastTradedPrice}`);

    // Place market buy order for R1000
    const order = await client.trading.placeMarketOrder({
      pair: 'BTCZAR',
      side: 'BUY',
      quoteAmount: '1000', // Spend R1000
    });

    console.log(`Bought BTC: Order ID ${order.id}`);
  } catch (error) {
    console.error('DCA bot error:', error);
  }
}

// Run daily at 9 AM
setInterval(dcaBot, 24 * 60 * 60 * 1000);

Portfolio Tracking Example

Track your crypto portfolio value:

import { ValrClient } from 'valr-typescript-client';

const client = new ValrClient({
  apiKey: process.env.VALR_API_KEY!,
  apiSecret: process.env.VALR_API_SECRET!,
});

async function getPortfolioValue() {
  // Get all balances
  const balances = await client.account.getBalances();

  // Get ZAR prices for all assets
  const markets = await client.public.getMarketSummary();

  let totalValue = 0;

  for (const balance of balances) {
    if (parseFloat(balance.total) === 0) continue;

    if (balance.currency === 'ZAR') {
      totalValue += parseFloat(balance.total);
    } else {
      // Find ZAR pair for this currency
      const pair = `${balance.currency}ZAR`;
      const market = markets.find(m => m.currencyPair === pair);

      if (market) {
        const value = parseFloat(balance.total) * parseFloat(market.lastTradedPrice);
        totalValue += value;
        console.log(`${balance.currency}: ${balance.total} = R${value.toFixed(2)}`);
      }
    }
  }

  console.log(`\nTotal Portfolio Value: R${totalValue.toFixed(2)}`);
  return totalValue;
}

getPortfolioValue();

Market Analysis Example

Analyze Bitcoin order book depth:

import { ValrClient } from 'valr-typescript-client';

const client = new ValrClient();

async function analyzeOrderBook() {
  const orderBook = await client.public.getOrderBook('BTCZAR');

  // Calculate bid/ask depth
  const bidDepth = orderBook.Bids.reduce((sum, bid) =>
    sum + parseFloat(bid.quantity), 0
  );
  const askDepth = orderBook.Asks.reduce((sum, ask) =>
    sum + parseFloat(ask.quantity), 0
  );

  const bidAskRatio = bidDepth / askDepth;

  console.log(`BTC/ZAR Order Book Analysis:`);
  console.log(`Bid Depth: ${bidDepth.toFixed(4)} BTC`);
  console.log(`Ask Depth: ${askDepth.toFixed(4)} BTC`);
  console.log(`Bid/Ask Ratio: ${bidAskRatio.toFixed(2)}`);
  console.log(`Market Sentiment: ${bidAskRatio > 1 ? 'Bullish' : 'Bearish'}`);
}

analyzeOrderBook();

API Categories

The client organizes endpoints into logical categories:

  • client.public - Public market data (no auth required)
  • client.account - Account information, balances, history
  • client.trading - Order placement and management
  • client.wallets - Deposits and withdrawals
  • client.futures - Futures positions and leverage
  • client.margin - Margin trading
  • client.loans - Lending and borrowing
  • client.earn - Staking and earning products
  • client.pay - Payment functionality
  • client.bundles - Currency bundles
  • client.health - API health status

Authentication

VALR API uses HMAC SHA512 signatures for authentication. This client handles all signature generation automatically.

Getting API Keys

  1. Enable 2FA on your VALR account
  2. Navigate to Account → API Keys
  3. Create a new API key with appropriate permissions:
    • View: Read-only access to account data
    • Trade: Place and cancel orders
    • Transfer: Transfer between accounts
    • Withdraw: Withdraw funds

API Key Security

  • Never commit your API keys to version control
  • Store keys in environment variables:
    const client = new ValrClient({
      apiKey: process.env.VALR_API_KEY,
      apiSecret: process.env.VALR_API_SECRET,
    });
  • Use minimal permissions for each key
  • Regularly rotate your API keys
  • Delete unused API keys

Package Integrity & Verification

This package includes cryptographic checksums to verify package integrity and protect against supply chain attacks.

Verifying Package Checksums

After installing from npm or any registry, you can verify the package integrity:

# Using npm script (cross-platform)
npm run verify

# Or directly with Node.js
node node_modules/valr-typescript-client/scripts/verify-checksums.js

# Or on Unix systems with bash
bash node_modules/valr-typescript-client/scripts/verify-checksums.sh

This will verify that:

  • All dist/ files (the compiled JavaScript you actually execute) match the official build
  • The package hasn't been tampered with after publication
  • You're running the exact code from the GitHub release
  • Shows you the Git commit SHA of the source code it was built from

What you're verifying: The compiled JavaScript files in dist/ are what run when you use this package. The checksums prove these match the official build from GitHub Actions.

What Gets Verified

The checksum verification checks:

Distribution files (dist/) - What actually executes:

  • dist/index.js, dist/index.mjs - Compiled JavaScript (ESM/CJS)
  • dist/index.d.ts, dist/index.d.mts - TypeScript definitions
  • dist/*.map - Source maps

Source files (src/) - For transparency:

  • Original TypeScript source code
  • Allows you to inspect what the dist was built from
  • Enables reproducible builds (advanced users)

Metadata:

  • Git commit SHA - Links to exact source code on GitHub
  • Build timestamp - When the package was built
  • Package version - Version number

Security model: Checksums prove your dist/ files match the official GitHub Actions build. You can inspect the source code at the Git commit shown in the checksums.

Building from Source

If you prefer to build from source yourself:

# Clone the repository
git clone https://github.com/yashutanna/valr-typescript-client.git
cd valr-typescript-client

# Checkout a specific release
git checkout v1.0.9

# Install dependencies (use ci for reproducible builds)
npm ci

# Build
npm run build

# Run tests
npm test

Reproducible Builds (Advanced)

For maximum trust, verify the official build was created from clean source code:

# Clone and checkout the release
git clone https://github.com/yashutanna/valr-typescript-client.git
cd valr-typescript-client
git checkout v1.0.9

# Build from source
npm ci
npm run build

# Compare your build with official checksums
bash scripts/build-and-verify.sh

This attempts to reproduce the official build and compares your locally-built dist/ files with the checksums from the official release. Note that perfect reproducibility is challenging with JavaScript builds, but the script will show you any differences.

CI/CD Transparency

Every package published to npm includes:

  • CHECKSUMS.txt - SHA256 hashes of all files
  • Git commit SHA that was built
  • Build timestamp
  • Verification scripts

The checksums are available in multiple places:

  • In the repository - Committed with each release (permanent Git history)
  • GitHub Releases - Attached as an asset to every release
  • npm package - Included at node_modules/valr-typescript-client/CHECKSUMS.txt
  • GitHub Actions - Available as workflow artifacts

To verify a specific release, check the Git tag or GitHub release assets.

Error Handling

The client throws typed errors for different failure scenarios:

import {
  ValrError,
  ValrAuthenticationError,
  ValrRateLimitError,
  ValrValidationError,
  ValrApiError,
} from 'valr-typescript-client';

try {
  await client.trading.placeLimitOrder({
    pair: 'BTCZAR',
    side: 'BUY',
    quantity: '0.001',
    price: '500000',
  });
} catch (error) {
  if (error instanceof ValrAuthenticationError) {
    console.error('Authentication failed - check your API keys');
  } else if (error instanceof ValrRateLimitError) {
    console.error('Rate limit exceeded - slow down requests');
  } else if (error instanceof ValrValidationError) {
    console.error('Validation error:', error.errors);
  } else if (error instanceof ValrApiError) {
    console.error('API error:', error.statusCode, error.message);
  } else if (error instanceof ValrError) {
    console.error('VALR error:', error.message);
  } else {
    console.error('Unknown error:', error);
  }
}

Rate Limits

VALR enforces rate limits on API requests:

  • 2000 requests per minute per API key
  • 1200 requests per minute per IP address
  • Some endpoints have stricter per-second limits (e.g., order placement: 400/s)

The client automatically includes rate limit information in error responses when limits are exceeded.

TypeScript Support

The client is written in TypeScript and provides comprehensive type definitions:

import type {
  CurrencyPair,
  OrderSide,
  OrderStatus,
  Balance,
  MarketSummary,
  OrderResponse,
} from 'valr-typescript-client';

// All API responses are fully typed
const balances: Balance[] = await client.account.getBalances();
const markets: MarketSummary[] = await client.public.getMarketSummary();

// Request parameters are type-checked
await client.trading.placeLimitOrder({
  pair: 'BTCZAR', // Type: CurrencyPair
  side: 'BUY', // Type: OrderSide
  quantity: '0.001',
  price: '500000',
  postOnly: 'POST_ONLY_REPRICE', // Type-checked enum
});

Development

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Type check
npm run type-check

🤝 Contributing

Contributions are welcome! We're looking for:

  • 🐛 Bug fixes and issue reports
  • 📝 Documentation improvements
  • ✨ New feature implementations
  • 🧪 Additional test coverage
  • 🌍 Internationalization support

Please feel free to submit a Pull Request or open an issue.

Development Setup

git clone https://github.com/yashutanna/valr-typescript-client.git
cd valr-typescript-client
npm install
npm run build
npm test

🔗 Links & Resources

🆘 Support & Issues

For issues and questions:

📜 License

MIT License - see LICENSE file for details

⚠️ Disclaimer

This is an unofficial TypeScript client library for the VALR API. It is not affiliated with, endorsed by, or officially connected to VALR in any way. Use at your own risk.

Trading cryptocurrencies carries risk. Only trade with funds you can afford to lose. This software is provided "as is" without warranty of any kind.

🏷️ Keywords

valr api valr typescript valr javascript valr sdk valr client cryptocurrency trading bitcoin api ethereum api crypto exchange api south africa crypto trading bot algorithmic trading crypto automation typescript trading bot valr rest api valr websocket