Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with placing bets #111

Closed
SiCKBalways opened this issue Mar 15, 2025 · 4 comments
Closed

Issue with placing bets #111

SiCKBalways opened this issue Mar 15, 2025 · 4 comments

Comments

@SiCKBalways
Copy link

Hi,

I'm working on a Python script for automated trading based on predefined options. The script successfully finds the options for prematch bets, but when it comes to live matches, it no longer detects the available options. Additionally, even if it finds the option beforehand, when it attempts to place the bet, it fails because the option is already "unavailable" at that moment.

Here is the code snippet I’m using to place the bet:

def place_bet(event_id, stake, odds, game_number, reference_id=None):
    if reference_id is None:
        reference_id = str(uuid.uuid4())

    # 🔍 **New marketUrl format according to the Cloudbet API**
    market_url = f"table_tennis.game_total_points.v2/over?total=18.5&period=default&period=game{game_number}"

    bet_payload = {
        "acceptPriceChange": "BETTER",
        "currency": "USDT",
        "eventId": str(event_id),
        "marketUrl": market_url,
        "price": str(odds),
        "referenceId": reference_id,
        "stake": str(stake),
        "side": "BACK"  # API only supports BACK bets
    }

    print(f"📡 Sending bet: {bet_payload}")

    url = "https://sports-api.cloudbet.com/pub/v3/bets/place"
    response = requests.post(url, json=bet_payload, headers=bet_headers)

    print(f"📡 API Response ({response.status_code}): {response.text}")

    if response.status_code == 200:
        print(f"✅ Bet placed successfully: {response.json()}")
        return True
    else:
        print(f"❌ Bet placement failed (code {response.status_code}): {response.text}")
        return False

    # 🔄 **Adding a 2-second delay** due to Cloudbet API rate limits
    time.sleep(2)

My Questions:
Is it possible to select and place bets the same way for live table tennis matches?
Or is automated betting restricted to only prematch options?
I would appreciate any guidance on this issue. Thanks!

@SiCKBalways
Copy link
Author

Code snippet for querying matches and finding odds:

`def get_czech_pro_table_tennis_events():
url = f"{CLOUDBET_FEED_API_URL}/competitions/table-tennis-czech-republic-t7c6e-czech-liga-pro"
response = requests.get(url, headers=headers)

print("📡 API response code:", response.status_code)

if response.status_code != 200:
    print(f"❌ Error: {response.text}")
    return []

events = response.json().get("events", [])
print(f"✅ Total number of matches: {len(events)}")

now = datetime.utcnow().replace(tzinfo=timezone.utc)  # 🌍 Ensure timezone awareness
one_hour_from_now = now + timedelta(hours=1)

filtered_events = []
for event in events:
    match_id = str(event["id"])
    team_a, team_b = event["name"].split(" v ")
    status = event.get("status", "Unknown")

    # 🔍 If the match is already live ("In Progress"), we automatically include it
    if status == "In Progress":
        print(f"✅ Live match: {team_a} vs {team_b} (ID: {match_id})")
        db.insert_match(match_id, now, team_a, team_b)  # Use current time for live matches
        filtered_events.append(event)
        continue

    # 🔍 If not live yet, check the start time
    event_time_str = event.get("startTime") or event.get("cutoffTime")
    if not event_time_str:
        print(f"⚠️ No valid time found: {match_id}, skipping.")
        continue

    try:
        event_time = datetime.fromisoformat(event_time_str.replace('Z', '+00:00')).astimezone(timezone.utc)  # 🌍 Convert to UTC
    except ValueError:
        print(f"⚠️ Invalid time format: {event_time_str} (Event ID: {match_id}), skipping.")
        continue

    # Keep only matches that start within the next hour
    if now <= event_time <= one_hour_from_now:
        db.insert_match(match_id, event_time, team_a, team_b)
        filtered_events.append(event)

print(f"✅ {len(filtered_events)} active or soon-to-start matches available.")
return filtered_events

`

`def get_event_over_18_5_odds(event_id, game_number):
url = f"{CLOUDBET_FEED_API_URL}/events/{event_id}"
response = requests.get(url, headers=headers)

if response.status_code != 200:
    print(f"❌ Error retrieving odds: {response.text}")
    return None

data = response.json()

# 🟢 Print all available markets to check what’s included
if "markets" in data:
    print(f"🔍 All available markets: {list(data['markets'].keys())}")

markets = data.get("markets", {}).get("table_tennis.game_total_points.v2", {})
submarkets = markets.get("submarkets", {})

# 🟢 Print all available submarkets to verify the expected format exists
print(f"🔍 All available submarkets: {list(submarkets.keys())}")

game_key = f"period=default&period=game{game_number}"
submarket = submarkets.get(game_key, {})

if not submarket:
    print(f"⚠️ Submarket not found ({game_key})")
    return None

for selection in submarket.get("selections", []):
    print(f"🔍 Selection: {selection['outcome']} {selection['params']} @ {selection['price']} ({selection['status']})")
    if selection["outcome"] == "over" and selection["params"] == "total=18.5" and selection["status"] == "SELECTION_ENABLED":
        return selection["price"]

print(f"⚠️ No Over 18.5 odds found (game {game_number}).")
return None

`

@kgravenreuth
Copy link
Member

Hi @SiCKBalways ,

We're investigating this issue and will get back to you soon. In the meantime, could you please raise questions in the Discussions Section going forward which we actively monitor? Thanks!

Regards,
Klaus Gravenreuth
Product & Engineering @ Cloudbet

@kgravenreuth
Copy link
Member

Hi @SiCKBalways ,

After checking further, the issue seems to be in how the marketUrl is generated when placing bets. As mentioned in the Cloudbet Trading API docs:

Market URL, is compiled from the feed data as marketKey/outcome?params

For this case, partial Feed API response is:

"table_tennis.game_total_points.v2": {
          "submarkets": {
            "period=default&period=game1": {
              "sequence": "17",
              "selections": [
                {
                  "outcome": "over",
                  "params": "game=1&total=18.5",

So the correct marketUrl should be:

table_tennis.game_total_points.v2/over?game=1&total=18.5

You are currently sending the following which fails validation:

table_tennis.game_total_points.v2/over?total=18.5&period=game1

Please try again with the correct marketUrl and let us know if you still have any issues.

Regards,
Klaus Gravenreuth
Product & Engineering @ Cloudbet

@SiCKBalways
Copy link
Author

Thank you for your answer, I brought my thread into discussion section we can continue it on the new thread because I still have questions. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants