betfairlightweight

repository·master·Indexed 19 days ago

https://github.com/betcode-org/betfair

A high-performance Python wrapper for the Betfair API-NG. It supports all betting and account operations, including market and order streaming, and utilizes C and Rust libraries for speed. The library provides the APIClient for managing authentication, SSL certificates, and session handling, with access to service namespaces for betting, account management, streaming, and historical data.

Tokens
15.2K
Snippets
63
Records
75
Agent score
65%

What's inside betfairlightweight

  1. Use Lightweight mode for raw JSON responses

    master

    Enabling lightweight=True instructs the library to return raw JSON instead of creating complex Python objects. This is significantly faster because it avoids object instantiation overhead, though the data is harder to work with. You can enable it globally during client initialization or per request.

    # Global initialization
    >>> trading = betfairlightweight.APIClient(
            "username", 
            "password", 
            app_key="app_key", 
            certs="/certs", 
            lightweight=True,
        )
    >>> trading.login()
    {'sessionToken': 'dfgrtegreg===rgrgr', 'loginStatus': 'SUCCESS'}
    
    # Per request
    >>> trading.betting.list_event_types(
            filter=filters.market_filter(
                text_query='Horse Racing'
            ),
            lightweight=True,
        )
    [{'eventType': {'id': '7', 'name': 'Horse Racing'}, 'marketCount': 328}]
  2. Initialize and log in with APIClient

    master

    To use betfairlightweight, import the library and instantiate APIClient. You can log in using SSL certificates (strongly recommended for security and 2FA) or via an interactive login method if certificates are not configured.

    Once logged in, the client maintains the session_token and session_expired status. You can use keep_alive() to maintain the session or logout() to end it.

    import betfairlightweight
    
    # Using SSL certificates (Recommended)
    trading = betfairlightweight.APIClient(
        "username", "password", app_key="app_key", certs="/certs"
    )
    trading.login()
    
    # Using interactive login (If no certificates)
    trading = betfairlightweight.APIClient(
        "username", "password", app_key="app_key"
    )
    trading.login_interactive()
    
    # Session management
    trading.keep_alive()
    trading.logout()
  3. Handle Stream Resubscription and Connection Loss

    master

    If you lose connection, you can resubscribe to avoid receiving a full image (which saves bandwidth and time). To do this, pass the initial_clk and clk from your existing StreamListener into the subscribe_to_markets call.

    streaming_unique_id = stream.subscribe_to_markets(
        market_filter=market_filter,
        market_data_filter=market_data_filter,
        conflate_ms=1000,
        initial_clk=listener.initial_clk,
        clk=listener.clk,
    )
  4. Set the locale for different Betfair endpoints

    master

    Betfair uses different endpoints depending on your country of residence. You can specify the locale during APIClient initialization to ensure you are using the correct endpoints for your region.

    >>> trading = betfairlightweight.APIClient(
            "username", 
            "password", 
            app_key="app_key", 
            locale="italy"
        )
  5. Initialize the APIClient and login

    master

    To interact with the Betfair API, instantiate an APIClient with your credentials and app key. If using SSL certificates, provide the path to the directory containing them via the certs parameter. Call .login() to establish a session.

    Required parameters for APIClient:

    • username: Your Betfair username.
    • password: Your Betfair password.
    • app_key: Your Betfair application key.
    • certs: (Optional) Path to your SSL certificates directory.
    import betfairlightweight
    
    trading = betfairlightweight.APIClient(
        "username", "password", app_key="app_key", certs="/certs"
    )
    trading.login()
  6. Implement an Order Data Stream

    master

    To monitor your own orders and matches in real-time, use subscribe_to_orders with a streaming_order_filter.

    Note: The order stream does not include matched positions; use getCurrentOrders for those. However, 'price point' matched backs and lays are available in the order cache within matched_lays and matched_backs. The streaming output also includes a matches field containing a list of bettingresources.Match objects.

    import queue
    import threading
    import betfairlightweight
    from betfairlightweight.filters import streaming_order_filter
    
    trading = betfairlightweight.APIClient("username", "password", app_key="appKey")
    trading.login()
    
    output_queue = queue.Queue()
    listener = betfairlightweight.StreamListener(output_queue=output_queue)
    stream = trading.streaming.create_stream(listener=listener)
    
    order_filter = streaming_order_filter()
    
    streaming_unique_id = stream.subscribe_to_orders(
        order_filter=order_filter,
        conflate_ms=1000,
    )
    
    t = threading.Thread(target=stream.start, daemon=True)
    t.start()
    
    while True:
        current_orders = output_queue.get()
        # current_orders.matches contains list of <bettingresources.Match>
  7. Optimize StreamListener performance for backtesting

    master

    To improve the speed of backtesting, you can configure specific settings on the StreamListener to reduce overhead.

    listener = betfairlightweight.StreamListener(
        max_latency=None,  # ignore latency errors
        output_queue=None,  # use generator rather than a queue (faster)
        lightweight=True,  # lightweight mode is faster
        update_clk=False,  # do not update clk on updates (not required when backtesting)
    )
  8. Install betfairlightweight via pip

    master

    Install the base package using pip. Note that betfairlightweight requires Python 3.9 or higher.

    For improved performance, install the [speed] extra to include ciso8601 (C-based datetime parsing) and orjson (Rust-based JSON parsing).

    $ pip install betfairlightweight
    
    # For high-performance installation with C/Rust libraries:
    $ pip install betfairlightweight[speed]
  9. Handle NEMID Login for Danish residents

    master

    Danish residents are subject to NemID requirements. To log in, you must manually replicate the login flow by posting to the login_interactive.url and extracting the ssoid from the Set-Cookie header to set the session token.

    import re
    import betfairlightweight
    
    trading = betfairlightweight.APIClient("username", "password", app_key="app_key")
    
    resp = trading.session.post(
        url=trading.login_interactive.url,
        data={
            "username": trading.username,
            "password": trading.password,
            "redirectMethod": "POST",
            "product": trading.app_key,
            "url": "https://www.betfair.com",
            "submitForm": True,
        }
    )
    session_token = re.findall(
        "ssoid=(.*?);", resp.headers["Set-Cookie"]
    )
    trading.set_session_token(session_token[0])
    
    print(trading.betting.list_event_types())
  10. Implement a Market Data Stream

    master

    To receive real-time market updates, you must create a StreamListener with a queue.Queue, initialize a stream via trading.streaming.create_stream, and define filters using streaming_market_filter and streaming_market_data_filter. You then subscribe to markets and start the stream in a separate thread to avoid blocking your main application logic.

    Key components:

    • StreamListener: Receives data and puts it into a queue.
    • streaming_market_filter: Filters markets by event_type_ids, country_codes, and market_types.
    • streaming_market_data_filter: Specifies which fields to stream and the ladder_levels.
    • subscribe_to_markets: Returns a streaming_unique_id used to identify the subscription.
    import queue
    import threading
    import betfairlightweight
    from betfairlightweight.filters import (
        streaming_market_filter,
        streaming_market_data_filter,
    )
    
    trading = betfairlightweight.APIClient("username", "password", app_key="appKey")
    trading.login()
    
    output_queue = queue.Queue()
    listener = betfairlightweight.StreamListener(output_queue=output_queue)
    stream = trading.streaming.create_stream(listener=listener)
    
    market_filter = streaming_market_filter(
        event_type_ids=["7"], country_codes=["GB"], market_types=["WIN"]
    )
    market_data_filter = streaming_market_data_filter(
        fields=["EX_BEST_OFFERS", "EX_MARKET_DEF"], ladder_levels=3
    )
    
    streaming_unique_id = stream.subscribe_to_markets(
        market_filter=market_filter,
        market_data_filter=market_data_filter,
        conflate_ms=1000,
    )
    
    t = threading.Thread(target=stream.start, daemon=True)
    t.start()
    
    while True:
        market_books = output_queue.get()
        for market_book in market_books:
            print(market_book.streaming_unique_id)
  11. Install betfairlightweight

    master

    Install the standard version of the library using pip:

    $ pip install betfairlightweight

    To enable high-performance mode using C and Rust libraries, install with the [speed] extra:

    $ pip install betfairlightweight[speed]
  12. Install performance dependencies on Windows

    master

    On Linux and macOS, betfairlightweight installs C and Rust-based libraries automatically. Windows users should install the [speed] extra to get these performance improvements. Note that Visual Studio may be required on Windows for these installations.

    $ pip install betfairlightweight[speed]