How to create a bot for tracking odds in live?

What is the API for sports events and live odds

The API for sports events and live odds is a programming interface that allows you to automatically receive structured data about matches, tournaments, teams, and current bookmaker quotes in real time. Instead of parsing HTML pages or updating information manually, the developer connects to HTTP endpoints and receives a ready-made JSON response with already normalized fields: sport type, match status, current score, betting markets, and their values.

La plataforma Sports events API-Sport provides a unified data standard for several disciplines at once: football, hockey, basketball, tennis, table tennis, esports, and other sports that are regularly added. For each match, you can get basic information, advanced statistics (for example, possession, shots, fouls), and a block of odds. oddsBase. Inside it are betting markets (market), such as 1X2, totals, handicaps, as well as a list of outcomes with numerical coefficients and a live mode indicator. This allows for building both simple line displays and complex analytical systems and bots.

For live bots, it is especially important that the structure of coefficients includes not only current values but also additional attributes: initial quotes, dynamics of changes (cambiar = −1, 0 or 1), market status (active or suspended). Together with match fields like estado, minutoDelPartidoActual, eventosEnVivo and detailed statistics, complex logic can be built: tracking sharp market movements, reacting to goals and red cards, highlighting matches with abnormal activity. Based on such an API, professional arbitrage scanners, margin monitoring systems, and personal betting assistants are already being implemented, and in the near future, the ecosystem will be supplemented with WebSocket subscriptions and AI modules for more advanced analysis.

Which API to choose for tracking live odds

When choosing an API for tracking live coefficients, it is important to evaluate not only the price and the basic set of sports but also the depth of data. For a bot, it is critical that the API supports a stable live feed, provides a detailed structure of coefficients, allows filtering matches by status and tournaments, and has clear documentation. Otherwise, you will face limitations: the inability to filter the necessary leagues, the absence of a live mode indicator in the markets, or ambiguous coefficient formats that will take a long time to normalize.

У API-Sport service the main focus is specifically on the practical tasks of developing bots and analytical panels. Each sport has its own sportSlug (for example, fútbol, baloncesto, tenis), and matches are requested through a single endpoint /v2/{sportSlug}/partidos. The response contains an array partidos, where each match has a block oddsBase with betting markets, field estado (including the value en progreso for live), current minute minutoDelPartidoActual and array eventosEnVivo. This allows you to obtain both the sports context and the current odds line with a single request, which is extremely convenient for quick analysis in the bot’s code.

Below is an example of a simple request to get the current live football matches along with the odds. The bot can call this endpoint every few seconds or minutes depending on the allowable load and strategy logic:

import requests
API_KEY = "ВАШ_API_КЛЮЧ"
BASE_URL = "https://api.api-sport.ru/v2"
headers = {
    "Authorization": API_KEY,
}
params = {
    "status": "inprogress",  # только матчи, идущие прямо сейчас
}
response = requests.get(f"{BASE_URL}/football/matches", headers=headers, params=params)
response.raise_for_status()
data = response.json()
for match in data.get("matches", []):
    print(match["id"], match["status"], match.get("currentMatchMinute"))
    for market in match.get("oddsBase", []):
        if market.get("isLive"):
            print("  Рынок:", market["name"], market["group"], "live =", market["isLive"])
            for choice in market.get("choices", []):
                print("   ", choice["name"], "=>", choice["decimal"], "изменение:", choice["change"])

This data format is convenient for subsequent filtering: you can limit the list to only the necessary tournaments through the parameter torneo_id, work with specific teams by equipo_id or gather a general pool of all current matches in the categories of interest (category_ids). With the emergence of WebSocket subscriptions based on the same set of fields, tracking the dynamics of odds will become even more accurate and less resource-intensive: the bot will receive updates as they occur, without constant polling of the server.

How to get an API key and connect to live odds data

To work with the bot for tracking odds, a personal API key is required. It is used for authorizing requests and accounting for load. In the API-Sport ecosystem, the process is as clear as possible: you register on the website, choose a suitable tariff (usually depending on the volume of requests and the set of sports), after which you receive a unique token. This token must be passed in the HTTP header. Autorización with each request to the API, including endpoints for obtaining live matches and odds.

You can obtain the key at the personal account of API-Sport. After authorization, you will see a section with your current API key, usage statistics, and a description of limits. It is recommended to store the key in environment variables or in a separate configuration file to avoid committing it to a public repository. In case of token compromise, you can always generate a new key in the dashboard and instantly disable the old one. This is an important security step, especially if the bot is deployed on an external server and operates around the clock.

Below is a basic example of connecting to the API and checking that the key works correctly. We call the endpoint /v2/deporte, to get a list of available sports, and then one live request for matches:

import os
import requests
API_KEY = os.getenv("SPORT_API_KEY")  # храните ключ в переменной окружения
BASE_URL = "https://api.api-sport.ru/v2"
headers = {"Authorization": API_KEY}
# 1. Проверяем, что ключ валиден и получаем список видов спорта
sports_resp = requests.get(f"{BASE_URL}/sport", headers=headers)
sports_resp.raise_for_status()
print("Доступные виды спорта:")
for sport in sports_resp.json():
    print("-", sport["translations"].get("ru") or sport["name"], "(slug=", sport["slug"], ")")
# 2. Пробный запрос к лайв-матчам по хоккею
params = {"status": "inprogress"}
matches_resp = requests.get(f"{BASE_URL}/ice-hockey/matches", headers=headers, params=params)
matches_resp.raise_for_status()
matches_data = matches_resp.json()
print("Найдено лайв-матчей:", matches_data.get("totalMatches"))

If both requests execute without errors and return meaningful data, you can move on to the next step — implementing the bot’s logic. At this stage, it already makes sense to think through the strategy for using the request limit: polling frequency, priority sports, and tournaments. In the future, you will be able to partially transfer the logic from periodic polling to WebSocket subscriptions and intelligent AI filters, but the foundation will always remain a correct connection to the API via a reliable key.

How to create a bot for tracking live odds in Python

Python is one of the most convenient languages for writing bots that work with sports events APIs and live odds. It has a rich ecosystem of libraries for HTTP requests, working with asynchronicity, data storage, and integration with external notification services. The architecture of a simple bot for monitoring odds looks like this: cyclic polling of the API, saving the last state of odds in memory (or in a database), detecting changes, and reacting to them (logging, alerts, generating signals for the user).

The minimal framework of a bot in Python can look like an infinite loop with a timeout, in which we request live matches for the required sport through the endpoint /v2/{sportSlug}/partidos with the parameter status=inprogress. From each match, we extract an array. oddsBase, we select the markets of interest (for example, 1X2 or totals) and save them in a dictionary, where the key is the combination (matchId, marketName, choiceName). In the next request, we compare the current odds value with the previous one, as well as the field cambiar, to understand whether there has been an increase or decrease.

Below is a simplified example of such a framework. It can be expanded by adding storage in a database, error handling, asynchrony, and integration with notification systems:

import time
import requests
API_KEY = "ВАШ_API_КЛЮЧ"
BASE_URL = "https://api.api-sport.ru/v2"
POLL_INTERVAL = 10  # частота опроса в секундах
headers = {"Authorization": API_KEY}
# Хранилище предыдущих коэффициентов: (matchId, marketName, choiceName) -> decimal
last_odds = {}

def fetch_live_matches(sport_slug: str):
    params = {"status": "inprogress"}
    resp = requests.get(f"{BASE_URL}/{sport_slug}/matches", headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json().get("matches", [])

def process_match(match):
    match_id = match["id"]
    minute = match.get("currentMatchMinute")
    for market in match.get("oddsBase", []):
        if not market.get("isLive"):
            continue
        market_name = f"{market['group']} - {market['name']}"
        for choice in market.get("choices", []):
            key = (match_id, market_name, choice["name"])
            new_decimal = choice["decimal"]
            old_decimal = last_odds.get(key)
            if old_decimal is not None and new_decimal != old_decimal:
                direction = "вырос" if new_decimal > old_decimal else "упал"
                print(f"Матч {match_id} ({minute} мин.), {market_name}, {choice['name']}: коэффициент {direction} с {old_decimal} до {new_decimal}")
            last_odds[key] = new_decimal

if __name__ == "__main__":
    while True:
        try:
            matches = fetch_live_matches("football")
            for m in matches:
                process_match(m)
        except Exception as e:
            # На продакшене лучше логировать ошибку в отдельную систему
            print("Ошибка при опросе API:", e)
        time.sleep(POLL_INTERVAL)

In practice, you will complicate this scheme: adding asynchronous polling of several sports at once, restrictions on the tournaments of interest, storing the history of odds for subsequent analysis, as well as a module that generates signals based on the match input data and the dynamics of the odds (for example, a strong line imbalance, rapid growth of totals, etc.). At the same time, access to the data remains simple thanks to a unified API and a detailed block oddsBase, and the further development of the project can be built around future WebSocket capabilities and AI analytics.

Setting up a bot to track changes in live odds and notifications

Creating a basic API polling loop is just the first step. For the bot to truly assist in making betting decisions, it is important to flexibly configure the thresholds and rules for triggering notifications. In the structure of the odds from API-Sport, there are several useful fields: the current decimal odds decimal, the initial value initialDecimal, as well as the indicator of the direction of the last change cambiar. This allows you to record not only the fact of line movement but also to assess its strength relative to the starting level. For example, if the odds for a team’s victory increased from 1.50 to 1.80, this can be considered a significant change and a signal can be sent to the user.

A practical strategy is to combine relative and absolute thresholds. The absolute threshold sets the minimum difference between the current and the last or starting odds (for example, a change of at least 0.10). The relative threshold is set in percentages (for example, an increase or decrease of more than 5–10 % from the starting value). Additionally, you can use the field приостановлено of the market: when activated, the bot can send a separate notification about the suspension of bets, which often signals an important event in the match (goal, red card, VAR check, etc.).

Below is an example of a function that is configured through parameters and determines whether to send a notification for a specific odds. In the example, the notification is simulated by outputting to the console, but in practice, you can replace this with integration with any messenger or email service:

RELATIVE_THRESHOLD = 0.05  # 5% от начального коэффициента
ABSOLUTE_THRESHOLD = 0.10  # абсолютное изменение на 0.10 и более

def should_notify(choice: dict) -> bool:
    """Определяем, стоит ли отправлять уведомление по конкретному исходу."""
    current = float(choice["decimal"])
    initial = float(choice.get("initialDecimal") or current)
    abs_diff = abs(current - initial)
    rel_diff = abs_diff / initial if initial else 0
    if abs_diff >= ABSOLUTE_THRESHOLD or rel_diff >= RELATIVE_THRESHOLD:
        return True
    # Дополнительно можно учитывать направление изменения
    # change = -1 (понижение), 0 (без изменений), 1 (повышение)
    # Например, реагировать только на сильный рост коэффициента
    if choice.get("change") == 1 and rel_diff >= 0.03:
        return True
    return False

def handle_notifications(match, market, choice):
    if not should_notify(choice):
        return
    match_id = match["id"]
    minute = match.get("currentMatchMinute")
    msg = (
        f"[АЛЕРТ] Матч {match_id}, {minute} мин."
        f"Рынок: {market['group']} - {market['name']}"
        f"Исход: {choice['name']}"
        f"Коэффициент изменился до {choice['decimal']} (старт: {choice.get('initialDecimal')})"
    )
    print(msg)

Next, you need to integrate this function into the main loop of the bot: after receiving each match and going through the live odds markets, you call handle_notifications for each outcome. As an improvement, you can add «anti-spam» — store the time of the last notification for a specific outcome and not send alerts more frequently than a specified interval. A separate module can manage delivery channels: send some events instantly, while aggregating others into periodic digests. Thanks to the fact that the API already provides a structured set of fields for markets and samples, all this logic is implemented at the code level of the bot without the need to process raw HTML from bookmaker sites.

How to filter matches and odds for a live betting bot

An effective live betting bot should not track absolutely all matches and all markets. This creates unnecessary load on the API, complicates analysis, and leads to a stream of excessive notifications. It is much more reasonable to focus on specific leagues, types of markets, and ranges of odds that correspond to your strategy. Fortunately, API-Sport allows for fine-tuning of the sample already at the query level: you can use parameters torneo_id, equipo_id, category_ids, estado and other filters in the endpoint. /v2/{sportSlug}/partidos. For example, you can immediately receive only Champions League matches and national top leagues, ignoring less significant tournaments.

Additional filtering is performed in the bot’s code based on the data array. oddsBase. Here you can implement the logic for selecting markets by group (group = «1X2», «Totals», «Handicap»), period (período = «Full-time», «1st half»), odds range (for example, from 1.50 to 3.50) and direction of change (cambiar = 1 or -1). This allows you to focus on markets with increased volatility and discard those that are of little interest to the strategy. For example, you can analyze only strong movements in totals, without paying attention to marginal changes in 1X2 outcomes.

Below is an example of a function that selects only the necessary matches and markets based on the specified conditions. It can be used within the bot before analysis and sending notifications:

TARGET_TOURNAMENTS = "7,17"  # пример: Лига чемпионов и топ-лига (ID условные)
MIN_DECIMAL = 1.5
MAX_DECIMAL = 3.5
TARGET_GROUPS = {"1X2", "Totals"}

def fetch_filtered_matches(headers):
    params = {
        "status": "inprogress",
        "tournament_id": TARGET_TOURNAMENTS,
    }
    resp = requests.get(
        "https://api.api-sport.ru/v2/football/matches",
        headers=headers,
        params=params,
        timeout=10,
    )
    resp.raise_for_status()
    return resp.json().get("matches", [])

def iter_filtered_markets(match):
    for market in match.get("oddsBase", []):
        if not market.get("isLive"):
            continue
        if market.get("group") not in TARGET_GROUPS:
            continue
        for choice in market.get("choices", []):
            dec = float(choice["decimal"])
            if MIN_DECIMAL <= dec <= MAX_DECIMAL:
                yield market, choice

This approach reduces the amount of data that the bot processes, making the system’s behavior more predictable and transparent. You can store filtering settings in a separate configuration file or even move them to the administrative panel of your own project to change the strategy without restarting the code. When further scaling — for example, when adding new sports and markets — it will be enough to expand the list sportSlug and configure new sets of filters without changing the basic logic of working with the API. api-sport.ru.

Risks and limitations when using APIs and bots for live odds with bookmakers

The use of bots to track live odds provides a significant advantage in reaction speed, but at the same time carries a number of risks and limitations. First, the data obtained through any external API always has a certain delay compared to the bookmaker’s internal systems. Even with a high update speed, the line can change in fractions of a second before the bot registers the movement and you manage to place a bet. Therefore, the API should not be considered as a «source of truth at the last moment» — it is a tool for analytics and early detection of trends, not a guarantee that you will be able to replicate every movement.

Secondly, it is important to consider the rules of specific bookmakers. Many operators stipulate in their terms a ban or restrictions on automated data collection and mass betting using scripts. Although API-Sport provides aggregated data on odds and match events, the responsibility for how you use this information lies with you. Before launching the bot, it is advisable to familiarize yourself with the legal aspects in your jurisdiction and the rules of the chosen bookmakers to avoid account blocking or other sanctions.

Thirdly, it is necessary to work competently with the technical limitations of the API itself: request limits, possible temporary unavailability, data update regulations. The bot must correctly handle network errors, response codes 4xx/5xx, not exceed the allowed RPS, and have a backup strategy in case of temporary failures (for example, increasing the polling interval or temporarily disabling certain functions). It is also worth remembering that no API and even future WebSocket channels or AI modules eliminate the financial risks associated with gambling. Any strategy should rely on bankroll management and an understanding of statistics, while bots and data from the API are merely auxiliary tools that enhance awareness but do not guarantee profit.