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 🙏

© 2025 – Pkg Stats / Ryan Hefner

betfair-exchange-api

v1.0.3

Published

A TypeScript client for the Betfair Exchange API

Readme

Betfair Exchange API Client

A comprehensive TypeScript library for interfacing with the Betfair Exchange API, including betting, accounts, heartbeat, and streaming functionality.

Features

  • Complete typing for all Betfair API requests and responses
  • Support for the Betting API, Accounts API, and Heartbeat API
  • Stream API client for real-time market and order data
  • Authentication via interactive and non-interactive methods
  • Comprehensive error handling
  • Machine Comprehensible Project (MCP) file for enhanced IDE support

Installation

npm install betfair-exchange-api

MCP Support

This package includes a Machine Comprehensible Project (MCP) file that provides enhanced IDE support and documentation. Upon installation, the MCP file is automatically copied to your project root directory.

The MCP file contains:

  • Detailed API documentation
  • Type definitions
  • Method signatures and parameters
  • Event documentation for the Stream API
  • Component relationships and architecture

If you're using an MCP-compatible IDE (like Cursor), you'll get enhanced:

  • Code completion
  • Documentation
  • Type inference
  • Method suggestions

The MCP file is automatically installed via the package's postinstall script. If you need to manually copy it:

cp node_modules/betfair-exchange-api/betfair-exchange-api.mcp ./

Authentication

Before using the API, you need to authenticate with your Betfair credentials:

import { BetfairClient } from 'betfair-exchange-api';

// Initialize with your application key
const client = new BetfairClient('YOUR_APP_KEY');

// Interactive authentication (username/password)
await client.authenticateInteractive('username', 'password');

// OR Non-interactive (certificate) authentication
await client.authenticateNonInteractive(
  'username', 
  'password', 
  'path/to/certificate.crt', 
  'path/to/private.key'
);

Betting API Examples

List all available sports (event types)

const eventTypes = await client.betting.listEventTypes({});
console.log(eventTypes);

List soccer events for today

const now = new Date();
const tomorrow = new Date();
tomorrow.setDate(now.getDate() + 1);

const soccerFilter = {
  eventTypeIds: ['1'], // 1 = Soccer
  marketStartTime: {
    from: now.toISOString(),
    to: tomorrow.toISOString()
  }
};

const events = await client.betting.listEvents(soccerFilter);
console.log(events);

Get market catalog for an event

const marketFilter = {
  eventIds: ['31520581'] // Replace with your event ID
};

const markets = await client.betting.listMarketCatalogue(
  marketFilter,
  ['MARKET_DESCRIPTION', 'RUNNER_DESCRIPTION', 'RUNNER_METADATA'],
  undefined,
  25 // Maximum 1000 results
);

console.log(markets);

Get market prices

const priceProjection = {
  priceData: ['EX_BEST_OFFERS', 'EX_TRADED'],
  virtualise: true
};

const marketBooks = await client.betting.listMarketBook(
  ['1.179082418'], // Replace with your market ID
  priceProjection
);

console.log(marketBooks);

Place a bet

const placeInstruction = {
  orderType: 'LIMIT',
  selectionId: 12345678, // Replace with your selection ID
  side: 'BACK',
  limitOrder: {
    size: 2.0,
    price: 3.0,
    persistenceType: 'LAPSE'
  }
};

const response = await client.betting.placeOrders(
  '1.179082418', // Replace with your market ID
  [placeInstruction],
  'my_customer_ref' // Optional customer reference
);

console.log(response);

List current orders

const currentOrders = await client.betting.listCurrentOrders();
console.log(currentOrders);

Accounts API Examples

Get account details

const accountDetails = await client.accounts.getAccountDetails();
console.log(accountDetails);

Get account funds

const accountFunds = await client.accounts.getAccountFunds();
console.log(accountFunds);

Get account statement

const statement = await client.accounts.getAccountStatement(
  undefined, // locale
  0, // fromRecord
  100, // recordCount
  {
    from: '2023-01-01T00:00:00Z',
    to: '2023-01-31T23:59:59Z'
  } // itemDateRange
);

console.log(statement);

Heartbeat API Example

// Set up the heartbeat with a 60 second timeout
const heartbeatReport = await client.heartbeat.heartbeat(60);
console.log(heartbeatReport);

Stream API Examples

The Stream API provides real-time updates for markets and orders.

import { BetfairStreamClient } from 'betfair-exchange-api';

// Create stream client with your credentials
const streamClient = new BetfairStreamClient('YOUR_APP_KEY', 'YOUR_SESSION_TOKEN');

// Set up event handlers
streamClient.on('connected', () => {
  console.log('Connected to Betfair Stream API');
});

streamClient.on('disconnected', () => {
  console.log('Disconnected from Betfair Stream API');
});

streamClient.on('marketChange', (marketChange) => {
  console.log('Market data update:', marketChange);
});

streamClient.on('orderChange', (orderChange) => {
  console.log('Order data update:', orderChange);
});

// Connect to the stream
streamClient.connect();

// After authentication succeeds, subscribe to markets
streamClient.subscribeToMarkets(
  {
    eventTypeIds: ['1'], // Soccer
    marketTypes: ['MATCH_ODDS']
  },
  {
    fields: ['EX_BEST_OFFERS', 'EX_TRADED'],
    ladderLevels: 3
  }
);

// Subscribe to orders
streamClient.subscribeToOrders({
  includeOverallPosition: true
});

// When finished
streamClient.disconnect();

Session Management

// Keep your session alive
const keepAliveResult = await client.keepAlive();

// Logout when done
const logoutResult = await client.logout();

Error Handling

All API methods throw exceptions when they fail. It's recommended to use try/catch blocks to handle errors appropriately:

try {
  const markets = await client.betting.listMarketCatalogue(marketFilter);
  // Process markets
} catch (error) {
  console.error('API Error:', error.message);
}

Notes

  • Remember to manage your session with keepAlive to prevent it from expiring
  • Be aware of API request limits to avoid getting rate limited
  • The Stream API requires an active and valid session token

License

MIT

Credits

This library is an unofficial implementation of the Betfair Exchange API. Betfair and all related trademarks are the property of The Sporting Exchange Limited.