Automated betting with the Stake API

Contents

The Stake (review, American bettors are geo-blocked) website is excellent for general sports betting but what if you developed a betting strategy which requires you to place a large number of small bets or to react to information faster than a human can navigate the website? In these situations you may want to develop a betting bot which places bets on your behalf. Fortunately Stake have an API which makes it easy to place bets programmatically with only a small amount of code.

Finding your API token

Requests to the Stake API are authenticated by a secret token unique to your account. This token can be found under the API section of your Stake settings. Simply click the “Reveal” button and copy the token that appears.

Warning: Never share this token as anyone who has access to it can steal funds from your account.

Installing Python

To find markets and place bets with Python, all you need is:

  • Python 3 to be installed on your machine. If you are on Windows you can download it here. If you are on Linux or macOS you likely have it installed already but if you don’t it can be installed with your package manager (we recommend homebrew for macOS).
  • The requests Python library. This can be installed with:
python3 -m pip install --user requests

Fetching odds for upcoming events

All Stake API requests are made as GraphQL requests to https://api.stake.com/graphql. You will always send a JSON payload with at least the keys query and variables. For example, if we wanted to list the odds for upcoming English Premier League events we would use the following code:

import requests

query = """
query SlugTournament(
  $sport: String!,
  $category: String!,
  $tournament: String!,
  $groups: [String!]!,
  $limit: Int = 10,
  $offset: Int = 0
) {
  slugTournament(sport: $sport, category: $category, tournament: $tournament) {
    fixtureList(type: active, limit: $limit, offset: $offset) {
      data {
        ... on SportFixtureDataMatch {
          competitors {
            name
          }
        }
      }
      groups(groups: $groups, status: [active]) {
        templates(limit: 3, includeEmpty: true) {
          name
          markets(limit: 1) {
            outcomes {
                id
                odds
                name
            }
          }
        }
      }
    }
  }
}
"""

request_data = {
    "operationName": "SlugTournament",
    "query": query,
    "variables": {
        "sport": "soccer",
        "category": "england",
        "tournament": "premier-league",
        "groups": ["winner"],
        "limit": 10,
        "offset": 0,
    },
}

session = requests.Session()
session.headers["x-access-token"] = YOUR_TOKEN

response = session.post("https://api.stake.com/graphql", json=request_data)
response_data = response.json()

for fixture in response_data["data"]["slugTournament"]["fixtureList"]:
    home = fixture["data"]["competitors"][0]["name"]
    away = fixture["data"]["competitors"][1]["name"]
    try:
        template = next(t for t in fixture["groups"][0]["templates"] if t["name"] == "1x2")
        market_outcomes = template["markets"][0]["outcomes"]
    except Exception:
        continue
    print(f"{home} vs {away}")
    for outcome in market_outcomes:
        print("  - {name} @ {odds}".format_map(outcome))
    print()

To run this code:

  1. Copy and paste it into a file named get_epl_odds.py.
  2. Change YOUR_TOKEN to the Stake API token for your account.
  3. In a terminal, run: python3 get_epl_odds.py.

You should see output like the following:

$ python3 get_epl_odds.py
Arsenal FC vs Newcastle United FC
  - Arsenal FC @ 1.48
  - Draw @ 4.8
  - Newcastle United FC @ 6.4

Norwich City FC vs Wolverhampton Wanderers FC
  - Norwich City FC @ 3.45
  - Draw @ 3.4
  - Wolverhampton Wanderers FC @ 2.19

Crystal Palace FC vs Aston Villa FC
  - Crystal Palace FC @ 2.22
  - Draw @ 3.35
  - Aston Villa FC @ 3.4

...

If you wanted to retrieve odds for a different sport or tournament you would change the sport, category and tournament values in the code. The easiest way to find the correct values is to navigate to the tournament of interest at stake.com and look in the URL. For example, the URL for NFL is https://stake.com/sports/american-football/usa/nfl so you would use

    "sport": "american-football",
    "category": "usa",
    "tournament": "nfl",

Placing bets

To place a bet we need to perform another GraphQL query. We can put this in a reusable function:

def place_bet(outcome_id, amount, session):
    query = """
    mutation SportBetMutation($amount: Float!, $currency: CurrencyEnum!, $outcomeIds: [String!]!) {
      sportBet(
        amount: $amount
        currency: $currency
        outcomeIds: $outcomeIds
        oddsChange: higher
      ) {
        amount
        currency
        outcomes {
          outcome {
            odds
            name
            market {
              name
              specifiers
            }
          }
        }
      }
    }
    """
    request_data = {
        "operationName": "SportBetMutation",
        "query": query,
        "variables": {
            "amount": amount,
            "currency": "btc",
            "oddsChange": "higher",
            "outcomeIds": [outcome_id],
        },
    }
    response = session.post("https://api.stake.com/graphql", json=request_data)
    response_data = response.json()
    print("bet placed:", response_data)

To call this function we need to know the id of the market outcome we wish to bet on. We can get this from the outcome variable in the code above. For example, if we wanted to place a 100 satoshi bet on Arsenal we could replace the for-loop we had earlier where we printed out the odds with the following:

    for outcome in market_outcomes:
        if outcome["name"] == "Arsenal FC":
            place_bet(outcome["id"], 0.000001, session)

If we save this modified code as bet_on_arsenal.py and run it in the terminal we should see something like:

$ python bet_on_arsenal.py
Arsenal FC vs Newcastle United FC
bet placed: {'data': {'sportBet': {'amount': 1e-06, 'currency': 'btc', 'outcomes': [{'outcome': {'odds': 1.48, 'name': 'Arsenal FC', 'market': {'name': '1x2', 'specifiers': ''}}}]}}}

Finding the right parameters for the API

Until recently Stake answered questions on how to use their API on their forum. Unfortunately scammers started tricking Stake users into revealing their API tokens and using these tokens to steal the users’ Stake deposits. As a result Stake removed many of the helpful threads from their forum and no longer answer questions about using their API. Some of the deleted forum threads can be found using the Internet Archive Wayback Machine but the best way to learn how to use the API is to use your browser’s built-in developer tools to examine the requests made by the Stake website.

To see the requests made by stake.com:

  1. Open Firefox or Chrome.
  2. Open Developer Tools with Ctrl+Shift+I (or Cmd+Opt+I on macOS).
  3. Select the Network tab.
  4. Navigate to a page of interest on stake.com or perform an operation like placing a bet.
  5. Under the Network tab, look through the “graphql” requests for the one that matches the request you are interested in. You can tell which one it is by examining the request and response data.
  6. Copy the request data into your code.

For example, if we wanted to find the request data needed to get markets for live and upcoming NFL events we would look for the following graphql request:

We would then right-click on the query, select Copy All and paste the copied JSON into our Python code. This JSON data would then be supplied to the json parameter in our requests.

Final thoughts

Although the Stake API is undocumented and it can be a bit annoying to have to reverse-engineer it from Stake’s website, since it is the same API that powers stake.com it is extremely powerful and enables automation of anything that can be done manually through the website. With a small amount of code it should be possible to build some clever betting applications. Good luck!

2 comments

  1. Dean

    Thanks, this rocks!

  2. Anonymous

    Gonna try and get it up and running on my machine. Stake had to go and make it more difficult than it really needed to be, but this helps heaps!

Leave a comment

Your email address will not be published.

EXCLUSIVE BONUSES

Only on BitEdge!

  • Free bets
  • Free spins
  • Free rolls
  • Deposit matches
Get crypto bonuses

Edge alerts

We have set up alerts when there are opportuntites to gamble crypto with the odds in your favor. We guarantee 100% privacy, your information will not be shared.

Settings