oddsapi

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Odds-API.io Go SDK

Go Reference CI

Official Go SDK for the Odds-API.io sports betting odds API: real-time and pre-match odds from 500+ bookmakers across 34 sports, over REST and WebSocket.

Prefer another language? See the Node.js SDK, the Python SDK or the CLI.

Quickstart

  1. Install (Go 1.22 or newer):

    go get github.com/odds-api-io/odds-api-go
    
  2. Set your API key (get one here):

    export ODDS_API_KEY="your-api-key"
    
  3. Make your first request:

    package main
    
    import (
    	"context"
    	"fmt"
    	"log"
    	"os"
    
    	oddsapi "github.com/odds-api-io/odds-api-go"
    )
    
    func main() {
    	ctx := context.Background()
    	client := oddsapi.NewClient(os.Getenv("ODDS_API_KEY"))
    
    	events, err := client.GetEvents(ctx, oddsapi.EventsParams{Sport: "football", League: "england-premier-league"})
    	if err != nil {
    		log.Fatal(err)
    	}
    	odds, err := client.GetOdds(ctx, oddsapi.OddsParams{
    		EventID:    events[0].ID.Int64(),
    		Bookmakers: []string{"Bet365", "Unibet"},
    		Markets:    []string{"ML"},
    	})
    	if err != nil {
    		log.Fatal(err)
    	}
    	fmt.Println(odds.Home, "vs", odds.Away, odds.Market("Bet365", "ML"))
    }
    

Get an API key

The odds API needs a key from a paid plan. Pick a plan at odds-api.io/pricing. Rate limits, the number of bookmakers you can select and WebSocket access depend on the plan.

Sports and bookmakers

Sport Example leagues
Football (soccer) Premier League, La Liga, Champions League
Basketball NBA, EuroLeague
American football NFL, NCAAF
Baseball MLB
Ice hockey NHL
Tennis ATP, WTA
Esports CS2, League of Legends, Dota 2
...and 27 more 34 sports in total

Odds come from 500+ bookmakers, including Bet365, DraftKings, FanDuel, Betfair, Unibet and SingBet. See the full coverage list.

Documentation

Features

  • A method for every public v3 endpoint: events, odds, odds summary, movements, value bets, arbitrage, dropping odds, historical odds and closing lines, settlement and grading, golf outrights, participants, bookmaker mappings
  • context.Context on every call, typed parameter structs and typed responses
  • oddsws: a WebSocket client with permessage-deflate, reconnects that resume from the last seq, and replay handling
  • Iterators for paginated endpoints (IterateEvents, IterateClosingLines, IterateMappings, IterateDroppingOdds, IterateHistoricalEvents) and PollUpdatedOdds for the /odds/updated delta
  • *APIError with status, server message, raw body and RetryAfter, matched by errors.Is sentinels; optional retries with backoff
  • Rate-limit headers on every response through client.LastRateLimit()
  • The API key never appears in error messages
  • No dependencies beyond the standard library for REST (oddsws uses gorilla/websocket)

Usage

ctx := context.Background()
client := oddsapi.NewClient(os.Getenv("ODDS_API_KEY"))

// Exact market names for a sport (no key needed)
markets, err := client.GetMarkets(ctx, "football")

// Upcoming and live Premier League matches
events, err := client.GetEvents(ctx, oddsapi.EventsParams{
	Sport:  "football",
	League: "england-premier-league",
	Status: []string{oddsapi.StatusPending, oddsapi.StatusLive},
})

// Odds for one match. Pass Markets to keep responses small.
odds, err := client.GetOdds(ctx, oddsapi.OddsParams{
	EventID:    events[0].ID.Int64(),
	Bookmakers: []string{"Bet365", "SingBet"},
	Markets:    []string{"ML", "Spread", "Totals"},
})
for bookmaker := range odds.Bookmakers {
	if ml := odds.Market(bookmaker, "ML"); ml != nil {
		fmt.Println(bookmaker, ml.Odds[0].Home, ml.Odds[0].Draw, ml.Odds[0].Away) // 2.10 3.40 3.20
	}
}

// Search, including in-play matches
live, err := client.SearchEvents(ctx, oddsapi.SearchEventsParams{Query: "Liverpool", Status: "live"})

Prices are oddsapi.Decimal values that keep the exact string the API sent ("2.10"); call .Float() for a float64. Every field of an odds line, including keys such as 1X, 12 and X2, is also available through line.Price("1X").

Market names must match in full: there is no Match Winner (use ML) and no bare Over/Under. Call GetMarkets(ctx, sport) to see the names a sport serves, or browse the market reference per sport (for example football). Bookmaker coverage by sport is at odds-api.io/sportsbooks.

Odds comparison and summary

// Best, average, median, worst and fair price per line across bookmakers (Growth plans and above)
summary, err := client.GetOddsSummary(ctx, oddsapi.SummaryParams{
	EventID:          123456,
	Markets:          []string{"ML", "Totals"},
	IncludeExchanges: true,
})
home := summary.Markets[0].Lines[0].Outcomes["home"]
fmt.Println(home.Best, home.BestBookmakers, home.Fair)

// Price history for one market (prematch)
history, err := client.GetOddsMovements(ctx, oddsapi.MovementsParams{
	EventID: 123456, Bookmaker: "Bet365", Market: "Totals", MarketLine: "2.5",
})
fmt.Println(history.Opening.Home, history.Latest.Home)

Polling for changes

/odds/updated returns only the market groups that changed. PollUpdatedOdds passes each X-Next-Since header back as the next since:

err := client.PollUpdatedOdds(ctx, oddsapi.UpdatedOddsParams{
	Bookmaker: "Bet365",
	Sport:     "football",
	Markets:   []string{"ML", "Spread", "Totals"}, // max 40
}, 10*time.Second, func(batch *oddsapi.UpdatedOdds) error {
	for _, event := range batch.Data {
		// merge by event, bookmaker and market name; an absent market has not changed
	}
	return nil // or oddsapi.StopIteration
})

For live odds the WebSocket is cheaper than any poll interval.

WebSocket

Package oddsws connects to wss://api.odds-api.io/v3/ws, tracks the highest seq and reconnects with lastSeq, so missed updates are replayed. The server requires permessage-deflate compression, which oddsws always negotiates. WebSocket access is a plan add-on.

import "github.com/odds-api-io/odds-api-go/oddsws"

params := oddsapi.MultiOddsParams{EventIDs: []int64{123456, 123457}, Bookmakers: []string{"Bet365"}, Markets: []string{"ML", "Totals"}}

// 1. Snapshot with its sequence number
snapshot, err := client.GetOddsSnapshot(ctx, params)

// 2. Stream from that point
stream := oddsws.New(oddsws.Config{
	APIKey:   apiKey,
	Markets:  params.Markets,                       // required for the odds channel, max 40
	Channels: []string{"odds", "scores", "status"}, // optional, default odds only
	EventIDs: params.EventIDs,                      // or Sports / Leagues, Status: "live" | "prematch"
	LastSeq:  snapshot.Seq,
})

err = stream.Run(ctx, func(m *oddsws.Message) error {
	switch m.Type {
	case oddsws.TypeCreated, oddsws.TypeUpdated:
		store[key(m.ID, m.Bookie)] = m.Markets // replace, do not merge
	case oddsws.TypeDeleted, oddsws.TypeNoMarkets:
		delete(store, key(m.ID, m.Bookie))
	case oddsws.TypeScore:
		fmt.Println(m.ID, m.Scores.Home, m.Scores.Away, m.Clock)
	case oddsws.TypeResyncRequired:
		// replay could not be served: rebuild from REST, then continue
		snap, err := client.GetOddsSnapshot(ctx, params)
		if err != nil {
			return err
		}
		stream.SetLastSeq(snap.Seq)
	}
	return nil
})

Run returns when ctx ends, when your handler returns an error, when the handshake is refused (*oddsws.HandshakeError: 400, 401, 403, 426) or when a newer connection on the same key replaced this one (*oddsws.ReplacedError, close 1008; two connections per key). Close 1012 (server restart) reconnects after a second and 1013 (cooldown) waits at least 3 seconds. stream.LastSeq() is the resume point to persist. Options: MaxReconnectAttempts, InitialReconnectDelay, MaxReconnectDelay, ReadTimeout, OnReconnect, DisableReplayComplete and a custom Dialer. For a single connection without reconnects, use oddsws.Dial and conn.Read().

Historical odds and closing lines

from := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)

// Finished events for one league (31 days per call)
past, err := client.GetHistoricalEvents(ctx, oddsapi.HistoricalEventsParams{
	Sport: "football", League: "england-premier-league", From: from, To: from.AddDate(0, 0, 30),
})

// Any range: fetched in 31-day windows
err = client.IterateHistoricalEvents(ctx, oddsapi.HistoricalEventsParams{
	Sport: "football", League: "england-premier-league", From: from.AddDate(0, -8, 0), To: from,
}, func(e oddsapi.Event) error {
	fmt.Println(e.Home, e.Away, e.Scores.Periods["ft"])
	return nil
})

// Odds for one finished event
closing, err := client.GetHistoricalOdds(ctx, oddsapi.OddsParams{
	EventID: past[0].ID.Int64(), Bookmakers: []string{"Bet365"}, Markets: []string{"ML"},
})

// Closing lines for every settled event across up to 10 leagues (paid plans; 366 days per call, 100 per page)
err = client.IterateClosingLines(ctx, oddsapi.ClosingLinesParams{
	Sport:      "football",
	Leagues:    []string{"england-premier-league", "spain-laliga"},
	From:       from,
	To:         from.AddDate(0, 2, 0),
	Markets:    []string{"ML", "Totals"},
	Bookmakers: []string{"Bet365", "SingBet"},
}, func(e oddsapi.EventOdds) error {
	fmt.Println(e.ID, e.Market("Bet365", "ML"))
	return nil
})

// Search finished events by team name
arsenal, err := client.SearchHistoricalEvents(ctx, oddsapi.SearchHistoricalEventsParams{Query: "Arsenal", Sport: "football"})

Settlement and grading

Paid plans. GetSettlements returns status, a Final flag and final scores; GradeBets grades selections against the result. Batches over 50 are split for you.

settled, err := client.GetSettlements(ctx, 74919888, 73101436)
fmt.Println(settled.Settlements, settled.NotFound)

hdp := -0.75
grades, err := client.GradeBets(ctx, []oddsapi.GradeSelection{
	{Ref: "bet-1", EventID: 74919888, Market: "ML", Side: "home"},
	{Ref: "bet-2", EventID: 74919888, Market: "Spread", Hdp: &hdp, Side: "home"},
	{Ref: "bet-3", EventID: 74919888, Market: "Correct Score", Label: "2-1"},
})
for _, g := range grades.Grades {
	fmt.Println(g.Ref, g.Result, g.Reason, g.Final) // won, lost, void, half_won, half_lost, pending, ungradeable
}

Re-send selections that are not Final, at most once a minute.

Same game parlays

Included in all paid plans. GetSgpBookmakers (GET /v3/sgp/bookmakers) returns the bookmakers that quote same game parlays right now; more are being added. List the legs of a pre-match event, then quote 2 to 10 of them. Each bookmaker answers with a Price (a Decimal) or a Status and NextAction. Branch on those two; Reason is a sentence for display and its wording can change.

const eventID = 61234567
listed, err := client.GetSgpLegs(ctx, oddsapi.SgpLegsParams{EventID: eventID, Bookmakers: []string{"DraftKings", "BetMGM"}, Markets: []string{"ML", "Totals"}})
if err != nil {
	log.Fatal(err)
}
// A bookmaker whose legs could not be checked says why; its legs all read Eligible false.
var books []string
for _, b := range listed.Bookmakers {
	if b.Status == oddsapi.SgpQuoteOK {
		books = append(books, b.Bookmaker)
	}
}
pick := func(market, side string) string {
	for _, l := range listed.Legs {
		ok := l.Market == market && l.Side == side
		for _, b := range books {
			ok = ok && l.Bookmakers[b].Eligible
		}
		if ok {
			return l.LegID
		}
	}
	return ""
}
ml, total := pick("ML", "home"), pick("Totals", "over")
if ml == "" || total == "" || len(books) == 0 {
	log.Fatal("no ML and Totals legs that these bookmakers can combine")
}

res, err := client.QuoteSgp(ctx, oddsapi.SgpQuoteParams{
	EventID:    eventID,
	Bookmakers: books,
	Legs:       []oddsapi.SgpQuoteLeg{{LegID: ml}, {LegID: total}},
})
if err != nil {
	log.Fatal(err)
}
for _, q := range res.Quotes {
	switch {
	case q.Status == oddsapi.SgpQuoteOK:
		fmt.Println(q.Bookmaker, q.Price, "vs", q.LegsMultiplied)
	case q.NextAction == oddsapi.SgpNextRetry || q.NextAction == oddsapi.SgpNextRetryLater:
		fmt.Println(q.Bookmaker, "retry in", q.RetryAfter, "s")
	default:
		fmt.Println(q.Bookmaker, q.NextAction, q.LegIDs, q.Reason)
	}
}

NextAction is one of change_legs, remove_leg (drop the legs in LegIDs), refresh_legs (call GetSgpLegs again), retry, retry_later (wait RetryAfter seconds) or choose_other_bookmaker; the SgpNext* constants name them. A quote can take up to 8 seconds, and at most 2 quotes run at once per account. See the same game parlay guide.

Outrights (golf)

Outrights are a paid add-on: PGA Tour, DP World Tour, LIV Golf and the majors. A key without the add-on gets an *APIError matching ErrForbidden, whose IsAddOnRequired() is true and whose message links to the billing page.

tournaments, err := client.GetOutrights(ctx, oddsapi.OutrightsParams{Sport: "golf", League: "pga-tour"})
odds, err := client.GetOutrightOdds(ctx, tournaments[0].ID.Int64(), "DraftKings", "Betfair Exchange")

for _, market := range odds.Bookmakers["Betfair Exchange"] {
	// Winner, Top 5, Top 5 (Incl. Ties), Top 10, Top 10 (Incl. Ties), Top 20, Top 20 (Incl. Ties), Make Cut
	for _, runner := range market.Odds {
		if runner.IsYesNo() {
			fmt.Println(market.Name, runner.Label, runner.Yes, runner.No) // Make Cut
		} else {
			fmt.Println(market.Name, runner.Label, runner.Odds, runner.LayOdds)
		}
	}
}

results, err := client.GetOutrightResults(ctx, tournaments[0].ID.Int64())
fmt.Println(results.Winners["Top 10 (Incl. Ties)"])

"Top N" settles a boundary tie under the bookmaker's dead-heat rules; "Top N (Incl. Ties)" pays it in full. They are separate markets.

Value bets, arbitrage and dropping odds

valueBets, err := client.GetValueBets(ctx, oddsapi.ValueBetsParams{Bookmaker: "Bet365", Sport: "football", IncludeEventDetails: true})
// ExpectedValue is bookmaker odds / fair odds x 100, so Edge() = ExpectedValue - 100 (103.42 = 3.42% edge)
for _, bet := range valueBets {
	if bet.Edge() >= 3 {
		fmt.Printf("%s %s %.2f%% edge\n", bet.Market.Name, bet.BetSide, bet.Edge())
	}
}

// Price gaps across your bookmakers. Prices move and bookmakers limit stakes, so check every leg before acting.
arbs, err := client.GetArbitrageBets(ctx, oddsapi.ArbitrageParams{
	Bookmakers: []string{"Bet365", "SingBet"}, Sport: "football", Markets: []string{"Totals"}, MinProfit: 1,
})
// ProfitMargin is already a percentage (2.48 = 2.48%)

// Dropping odds from sharp bookmakers (paid plans)
drops, err := client.GetDroppingOdds(ctx, oddsapi.DroppingOddsParams{
	Sport: "football", Markets: []string{"ML"}, MinDrop: 10, Sort: "recent", IncludeEventDetails: true,
})
for _, d := range drops.Data {
	fmt.Printf("%s %s: %.2f -> %.2f (-%.1f%%)\n", d.Market.Name, d.BetSide, d.Odds.Opening, d.Odds.Current, d.Odds.Drop.SinceOpening)
}

Participants, logos and mappings

teams, err := client.GetParticipants(ctx, oddsapi.ParticipantsParams{Sport: "football", Search: "Chelsea"})

// PNG crest. ParticipantLogoURL carries your key, so serve GetParticipantLogo bytes on public pages.
png, err := client.GetParticipantLogo(ctx, events[0].HomeID.Int64())

// A bookmaker's own market and outcome ids for our events (paid plans)
page, err := client.GetMappings(ctx, oddsapi.MappingsParams{Bookmaker: "Polymarket", EventID: 71515842})
err = client.IterateMappings(ctx, oddsapi.MappingsParams{Bookmaker: "Kalshi", Sport: "american-football"}, func(m oddsapi.Mapping) error {
	fmt.Println(m.EventID, m.Market, m.Side, m.MarketID, m.OutcomeID)
	return nil
})

Bookmakers

bookmakers, err := client.GetBookmakers(ctx) // Name, Active, CreatedAt, Status ("ok", "degraded", "down"), Reason
selected, err := client.SelectBookmakers(ctx, "Bet365", "SingBet")
selected, err = client.GetSelectedBookmakers(ctx)
selected, err = client.ClearSelectedBookmakers(ctx) // once every 12 hours

Methods

Area Method Endpoint
Catalogue GetSports GET /sports
GetMarkets, GetAllMarkets GET /markets
GetLeagues GET /leagues
GetBookmakers GET /bookmakers
GetSelectedBookmakers GET /bookmakers/selected
SelectBookmakers PUT /bookmakers/selected/select
ClearSelectedBookmakers PUT /bookmakers/selected/clear
Events GetEvents, IterateEvents GET /events
GetEvent GET /events/{id}
GetLiveEvents GET /events/live
SearchEvents GET /events/search
Odds GetOdds GET /odds
GetOddsMulti, GetOddsSnapshot GET /odds/multi
GetUpdatedOdds, PollUpdatedOdds GET /odds/updated
GetOddsMovements GET /odds/movements
GetOddsSummary GET /odds/summary
GetOddsSummaryMulti GET /odds/summary/multi
Analysis GetValueBets GET /value-bets
GetArbitrageBets GET /arbitrage-bets
GetDroppingOdds, IterateDroppingOdds GET /dropping-odds
Historical GetHistoricalEvents, IterateHistoricalEvents GET /historical/events
SearchHistoricalEvents GET /historical/events/search
GetHistoricalOdds GET /historical/odds
GetClosingLines, IterateClosingLines GET /historical/closing-lines
Settlement GetSettlements GET /settlements
GradeBets POST /settlements/grade
Same game parlays GetSgpBookmakers GET /sgp/bookmakers
GetSgpLegs GET /sgp/legs
QuoteSgp POST /sgp/quote
Outrights GetOutrights GET /outrights
GetOutrightOdds GET /outrights/odds
GetOutrightResults GET /outrights/results
Participants GetParticipants GET /participants
GetParticipant GET /participants/{id}
GetParticipantLogo, ParticipantLogoURL GET /participants/{id}/logo
Mappings GetMappings, IterateMappings GET /mappings
WebSocket oddsws.New(cfg).Run, oddsws.Dial wss://api.odds-api.io/v3/ws

Full parameter and response reference: docs.odds-api.io/api-reference.

Errors

Every non-2xx response is an *oddsapi.APIError with StatusCode, the server's own Message, the raw Body, RetryAfter and RateLimit. Match the status with errors.Is:

Sentinel When
ErrBadRequest 400: a parameter is missing or invalid (the message says which)
ErrUnauthorized 401
ErrForbidden 403: the plan does not include the endpoint or bookmaker, or an add-on is missing (IsAddOnRequired())
ErrNotFound 404: the message often lists what does exist
ErrRateLimited 429, with RetryAfter
ErrServer 5xx

Network failures and timeouts are returned as the underlying error (context.DeadlineExceeded, *url.Error), with the API key removed from the message.

_, err := client.GetClosingLines(ctx, params)
var apiErr *oddsapi.APIError
switch {
case errors.Is(err, oddsapi.ErrRateLimited) && errors.As(err, &apiErr):
	fmt.Println("retry in", apiErr.RetryAfter)
case errors.Is(err, oddsapi.ErrForbidden):
	fmt.Println(err)
case errors.As(err, &apiErr):
	fmt.Println(apiErr.StatusCode, apiErr.Message)
}

if rl := client.LastRateLimit(); rl != nil {
	fmt.Println(rl.Limit, rl.Remaining, rl.Reset) // from the last response
}

Configuration

client := oddsapi.NewClient(apiKey,
	oddsapi.WithBaseURL("https://api.odds-api.io/v3"), // default
	oddsapi.WithTimeout(10*time.Second),              // default client timeout
	oddsapi.WithHTTPClient(&http.Client{}),           // bring your own client, transport or proxy
	oddsapi.WithMaxRetries(2),                        // retries on 5xx, network errors and short 429 waits; 0 turns them off
	oddsapi.WithMaxRetryDelay(10*time.Second),        // a 429 asking for a longer wait is returned, not waited out
	oddsapi.WithUserAgent("my-app/1.0"),
)

Bookmaker selection changes (PUT) are never retried. The client is safe for concurrent use.

Examples

See examples/:

  • basic: upcoming matches and their odds
  • polling: keep odds current with /odds/updated
  • betting-analysis: value bets, arbitrage and dropping odds
  • websocket-feed: REST snapshot plus the WebSocket stream
  • settlement: bet grading and golf outrights
ODDS_API_KEY=your-api-key go run ./examples/basic

Plans and Limits

An API key from a paid plan is required. Rate limits, bookmaker selection and WebSocket access depend on your plan; see odds-api.io/pricing.

Resources

License

MIT © Odds-API.io

Disclaimer

This is the official Go SDK for Odds-API.io. This tool is for informational purposes only and should not be used as the sole basis for betting decisions.

Documentation

Overview

Package oddsapi is the official Go client for the Odds-API.io REST API v3: real-time and pre-match sports betting odds from 500+ bookmakers across 34 sports.

client := oddsapi.NewClient(os.Getenv("ODDS_API_KEY"))
events, err := client.GetEvents(ctx, oddsapi.EventsParams{Sport: "football", League: "england-premier-league"})

Every method takes a context.Context first. Errors returned for HTTP responses are *APIError values; use errors.Is with ErrNotFound, ErrRateLimited and the other sentinels, or errors.As to read the status and body.

Documentation: https://docs.odds-api.io/guides/sdks

Index

Examples

Constants

View Source
const (
	StatusPending   = "pending"
	StatusLive      = "live"
	StatusSettled   = "settled"
	StatusCancelled = "cancelled"
)

Event statuses.

View Source
const (
	GradeWon         = "won"
	GradeLost        = "lost"
	GradeVoid        = "void"
	GradeHalfWon     = "half_won"
	GradeHalfLost    = "half_lost"
	GradePending     = "pending"
	GradeUngradeable = "ungradeable"
)

Grade results.

View Source
const (
	SgpBookmakerLive     = "live"
	SgpBookmakerPaused   = "paused"
	SgpBookmakerDegraded = "degraded"
)

SgpBookmakerStatus values.

View Source
const (
	SgpNextChangeLegs           = "change_legs"
	SgpNextRemoveLeg            = "remove_leg"
	SgpNextRefreshLegs          = "refresh_legs"
	SgpNextRetry                = "retry"
	SgpNextRetryLater           = "retry_later"
	SgpNextChooseOtherBookmaker = "choose_other_bookmaker"
)

SgpNextAction values: what to do when a status is not "ok".

View Source
const (
	SgpQuoteOK                     = "ok"
	SgpQuoteNotCombinable          = "not_combinable"
	SgpQuoteLegUnavailable         = "leg_unavailable"
	SgpQuoteSuspended              = "suspended"
	SgpQuoteUnsupported            = "unsupported"
	SgpQuoteTimeout                = "timeout"
	SgpQuoteTemporarilyUnavailable = "temporarily_unavailable"
)

SgpQuoteStatus values. SgpLegsBookmaker.Status uses SgpQuoteOK, SgpQuoteLegUnavailable, SgpQuoteUnsupported and SgpQuoteTemporarilyUnavailable.

View Source
const DefaultBaseURL = "https://api.odds-api.io/v3"

DefaultBaseURL is the production REST endpoint.

View Source
const HistoricalWindow = 31 * 24 * time.Hour

HistoricalWindow is the longest span GET /historical/events accepts.

View Source
const Version = "0.2.1"

Version is the SDK version, sent in the User-Agent header.

Variables

View Source
var (
	ErrBadRequest   = errors.New("oddsapi: bad request")
	ErrUnauthorized = errors.New("oddsapi: invalid API key")
	ErrForbidden    = errors.New("oddsapi: forbidden")
	ErrNotFound     = errors.New("oddsapi: not found")
	ErrRateLimited  = errors.New("oddsapi: rate limit exceeded")
	ErrServer       = errors.New("oddsapi: server error")
)

Sentinel errors matched by *APIError through errors.Is.

View Source
var StopIteration = errors.New("oddsapi: stop iteration")

StopIteration can be returned from an iteration callback to stop early without an error.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status.
	StatusCode int
	// Message is the server's own message (the "error" or "message" field), or the raw body.
	Message string
	// Body is the raw response body.
	Body []byte
	// RetryAfter is how long the server asked to wait (Retry-After, or
	// X-RateLimit-Reset on a 429). Zero when not given.
	RetryAfter time.Duration
	// RateLimit holds the rate-limit headers of the response, if any.
	RateLimit *RateLimit
	// Method and URL identify the request. The URL never contains the API key.
	Method string
	URL    string
}

APIError is returned for every non-2xx response.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	oddsapi "github.com/odds-api-io/odds-api-go"
)

func main() {
	client := oddsapi.NewClient(os.Getenv("ODDS_API_KEY"))
	_, err := client.GetEvent(context.Background(), 1)

	var apiErr *oddsapi.APIError
	switch {
	case errors.Is(err, oddsapi.ErrRateLimited) && errors.As(err, &apiErr):
		fmt.Println("retry in", apiErr.RetryAfter)
	case errors.Is(err, oddsapi.ErrNotFound):
		fmt.Println("no such event")
	case errors.As(err, &apiErr):
		fmt.Println(apiErr.StatusCode, apiErr.Message)
	}
}

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is matches the sentinel for the error's status code.

func (*APIError) IsAddOnRequired

func (e *APIError) IsAddOnRequired() bool

IsAddOnRequired reports whether a 403 is about a missing plan add-on (outrights, for example); the message then links to the billing page.

type ArbitrageBet

type ArbitrageBet struct {
	ID      string `json:"id"`
	EventID ID     `json:"eventId"`
	Market  struct {
		Name  string   `json:"name"`
		Hdp   *float64 `json:"hdp,omitempty"`
		Label string   `json:"label,omitempty"`
	} `json:"market"`
	// ProfitMargin is a percentage of TotalStake (2.48 = 2.48%).
	ProfitMargin       float64        `json:"profitMargin"`
	ImpliedProbability float64        `json:"impliedProbability"`
	TotalStake         float64        `json:"totalStake"`
	Legs               []ArbitrageLeg `json:"legs"`
	OptimalStakes      []OptimalStake `json:"optimalStakes"`
	UpdatedAt          Time           `json:"updatedAt"`
	FirstSeenAt        Time           `json:"firstSeenAt,omitempty"`
	Event              *EventInfo     `json:"event,omitempty"`
}

ArbitrageBet is one entry of GET /arbitrage-bets.

type ArbitrageLeg

type ArbitrageLeg struct {
	Side               string   `json:"side"`
	Bookmaker          string   `json:"bookmaker"`
	Odds               Decimal  `json:"odds"`
	NetOdds            Decimal  `json:"netOdds,omitempty"`
	MaxStake           *float64 `json:"maxStake,omitempty"`
	OddsUpdatedAt      Time     `json:"oddsUpdatedAt,omitempty"`
	Href               string   `json:"href,omitempty"`
	DirectLink         string   `json:"directLink,omitempty"`
	Label              string   `json:"label,omitempty"`
	BookmakerFixtureID string   `json:"bookmakerFixtureId,omitempty"`
}

ArbitrageLeg is one leg of an arbitrage opportunity.

type ArbitrageParams

type ArbitrageParams struct {
	// Bookmakers, required.
	Bookmakers []string
	Sport      string
	// League requires Sport.
	League  string
	Markets []string
	// MinProfit is the minimum profit margin in percent, 0 to 100.
	MinProfit float64
	// AllCombinations returns every bookmaker combination per event, market and line.
	AllCombinations bool
	// Limit defaults to 50 on the server, max 500.
	Limit               int
	IncludeEventDetails bool
}

ArbitrageParams is GET /arbitrage-bets.

type Bookmaker

type Bookmaker struct {
	Name      string `json:"name"`
	Active    bool   `json:"active"`
	CreatedAt Time   `json:"createdAt"`
	// Status is "ok", "degraded" (no update for 60+ minutes, still served) or "down".
	Status string `json:"status"`
	// Reason is "maintenance" or "unavailable", empty when ok.
	Reason string `json:"reason,omitempty"`
}

Bookmaker is one entry of GET /bookmakers.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls the Odds-API.io REST API. It is safe for concurrent use.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient returns a Client for the given API key.

Example
package main

import (
	"os"
	"time"

	oddsapi "github.com/odds-api-io/odds-api-go"
)

func main() {
	client := oddsapi.NewClient(os.Getenv("ODDS_API_KEY"),
		oddsapi.WithTimeout(15*time.Second),
		oddsapi.WithMaxRetries(3),
	)
	_ = client
}

func (*Client) ClearSelectedBookmakers

func (c *Client) ClearSelectedBookmakers(ctx context.Context) (*SelectedBookmakers, error)

ClearSelectedBookmakers clears your selection. Allowed once every 12 hours.

func (*Client) GetAllMarkets

func (c *Client) GetAllMarkets(ctx context.Context) (map[string][]MarketInfo, error)

GetAllMarkets returns the market catalogue of every sport, keyed by sport slug.

func (*Client) GetArbitrageBets

func (c *Client) GetArbitrageBets(ctx context.Context, p ArbitrageParams) ([]ArbitrageBet, error)

GetArbitrageBets returns price gaps across your bookmakers where the best prices imply under 100% (prematch). Prices move and limits apply, so check every leg before acting.

func (*Client) GetBookmakers

func (c *Client) GetBookmakers(ctx context.Context) ([]Bookmaker, error)

GetBookmakers lists all bookmakers with their current status. No API key needed. Coverage by sport: https://odds-api.io/sportsbooks#coverage

func (*Client) GetClosingLines

func (c *Client) GetClosingLines(ctx context.Context, p ClosingLinesParams) ([]EventOdds, error)

GetClosingLines returns closing odds for every settled event across up to 10 leagues (paid plans), 100 events per page at most.

func (*Client) GetDroppingOdds

func (c *Client) GetDroppingOdds(ctx context.Context, p DroppingOddsParams) (*DroppingOddsPage, error)

GetDroppingOdds returns one page of dropping odds from sharp bookmakers (paid plans).

func (*Client) GetEvent

func (c *Client) GetEvent(ctx context.Context, id int64) (*Event, error)

GetEvent returns one event by id.

func (*Client) GetEvents

func (c *Client) GetEvents(ctx context.Context, p EventsParams) ([]Event, error)

GetEvents lists events for a sport.

func (*Client) GetHistoricalEvents

func (c *Client) GetHistoricalEvents(ctx context.Context, p HistoricalEventsParams) ([]Event, error)

GetHistoricalEvents lists finished events of one league.

func (*Client) GetHistoricalOdds

func (c *Client) GetHistoricalOdds(ctx context.Context, p OddsParams) (*EventOdds, error)

GetHistoricalOdds returns the odds of a finished event, in the /odds shape.

func (*Client) GetLeagues

func (c *Client) GetLeagues(ctx context.Context, p LeaguesParams) ([]League, error)

GetLeagues lists the leagues of a sport.

func (*Client) GetLiveEvents

func (c *Client) GetLiveEvents(ctx context.Context, sport string) ([]Event, error)

GetLiveEvents lists live events, optionally for one sport ("" for all).

func (*Client) GetMappings

func (c *Client) GetMappings(ctx context.Context, p MappingsParams) (*MappingsPage, error)

GetMappings returns a bookmaker's own event, market and outcome ids for our events (paid plans).

func (*Client) GetMarkets

func (c *Client) GetMarkets(ctx context.Context, sport string) (*MarketsResponse, error)

GetMarkets returns the exact market names a sport serves, with shape, period and whether each is served prematch and live. No API key needed. The same catalogue is browsable per sport at https://odds-api.io/markets (for example https://odds-api.io/markets/football).

func (*Client) GetOdds

func (c *Client) GetOdds(ctx context.Context, p OddsParams) (*EventOdds, error)

GetOdds returns the odds of one event.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	oddsapi "github.com/odds-api-io/odds-api-go"
)

func main() {
	ctx := context.Background()
	client := oddsapi.NewClient(os.Getenv("ODDS_API_KEY"))

	odds, err := client.GetOdds(ctx, oddsapi.OddsParams{
		EventID:    62924717,
		Bookmakers: []string{"Bet365", "SingBet"},
		Markets:    []string{"ML", "Totals"},
	})
	if err != nil {
		log.Fatal(err)
	}
	if ml := odds.Market("Bet365", "ML"); ml != nil {
		fmt.Println(ml.Odds[0].Home, ml.Odds[0].Draw, ml.Odds[0].Away)
	}
}

func (*Client) GetOddsMovements

func (c *Client) GetOddsMovements(ctx context.Context, p MovementsParams) (*OddsMovement, error)

GetOddsMovements returns the price history of one market at one bookmaker (prematch).

func (*Client) GetOddsMulti

func (c *Client) GetOddsMulti(ctx context.Context, p MultiOddsParams) ([]EventOdds, error)

GetOddsMulti returns the odds of up to 10 events in one request.

func (*Client) GetOddsSnapshot

func (c *Client) GetOddsSnapshot(ctx context.Context, p MultiOddsParams) (*OddsSnapshot, error)

GetOddsSnapshot is GetOddsMulti plus the WebSocket sequence number, so a stream can start exactly where the snapshot ends.

func (*Client) GetOddsSummary

func (c *Client) GetOddsSummary(ctx context.Context, p SummaryParams) (*EventSummary, error)

GetOddsSummary returns the best, average, median, worst and fair price per line across bookmakers (Growth plans and above).

func (*Client) GetOddsSummaryMulti

func (c *Client) GetOddsSummaryMulti(ctx context.Context, p SummaryParams) ([]EventSummary, error)

GetOddsSummaryMulti is GetOddsSummary for up to 10 events.

func (*Client) GetOutrightOdds

func (c *Client) GetOutrightOdds(ctx context.Context, id int64, bookmakers ...string) (*OutrightOdds, error)

GetOutrightOdds returns the prices of one tournament per bookmaker: Winner, Top 5/10/20, the "(Incl. Ties)" variants and Make Cut.

func (*Client) GetOutrightResults

func (c *Client) GetOutrightResults(ctx context.Context, id int64) (*OutrightResults, error)

GetOutrightResults returns final positions and winners per market for one tournament.

func (*Client) GetOutrights

func (c *Client) GetOutrights(ctx context.Context, p OutrightsParams) ([]Outright, error)

GetOutrights lists tournaments (paid add-on; without it the error matches ErrForbidden and IsAddOnRequired is true).

func (*Client) GetParticipant

func (c *Client) GetParticipant(ctx context.Context, id int64) (*Participant, error)

GetParticipant returns one participant by id.

func (c *Client) GetParticipantLogo(ctx context.Context, id int64) ([]byte, error)

GetParticipantLogo returns a participant's logo as PNG bytes. A participant without a logo gives an error matching ErrNotFound.

func (*Client) GetParticipants

func (c *Client) GetParticipants(ctx context.Context, p ParticipantsParams) ([]Participant, error)

GetParticipants lists teams and players for a sport.

func (*Client) GetSelectedBookmakers

func (c *Client) GetSelectedBookmakers(ctx context.Context) (*SelectedBookmakers, error)

GetSelectedBookmakers returns the bookmakers selected on your key.

func (*Client) GetSettlements

func (c *Client) GetSettlements(ctx context.Context, eventIDs ...int64) (*SettlementsResponse, error)

GetSettlements returns settlement records (status, final flag, final scores) for events (paid plans). More than 50 ids are split into several requests.

func (*Client) GetSgpBookmakers added in v0.2.0

func (c *Client) GetSgpBookmakers(ctx context.Context, sport string) ([]SgpBookmaker, error)

GetSgpBookmakers lists the bookmakers that can quote same game parlays. sport (a slug from GetSports) is optional. Same game parlays are enabled per key; without it the error matches ErrForbidden.

func (*Client) GetSgpLegs added in v0.2.0

func (c *Client) GetSgpLegs(ctx context.Context, p SgpLegsParams) (*SgpLegsResponse, error)

GetSgpLegs lists the legs of a pre-match event that can go into a same game parlay, with a LegID for each and whether each bookmaker can combine it. Bookmakers in the response says, per requested bookmaker, whether its legs could be checked; when its Status is not "ok", every leg reads Eligible false there.

func (*Client) GetSports

func (c *Client) GetSports(ctx context.Context) ([]Sport, error)

GetSports lists all sports. No API key needed.

func (*Client) GetUpdatedOdds

func (c *Client) GetUpdatedOdds(ctx context.Context, p UpdatedOddsParams) (*UpdatedOdds, error)

GetUpdatedOdds returns the market groups changed since p.Since for one bookmaker and sport.

func (*Client) GetValueBets

func (c *Client) GetValueBets(ctx context.Context, p ValueBetsParams) ([]ValueBet, error)

GetValueBets returns prices above a fair-odds estimate at one bookmaker.

func (*Client) GradeBets

func (c *Client) GradeBets(ctx context.Context, selections []GradeSelection) (*GradesResponse, error)

GradeBets grades bet selections against final results (paid plans) and returns one grade per selection, in order. More than 50 selections are sent in batches. Re-send selections that are not Final, at most once a minute.

func (*Client) IterateClosingLines

func (c *Client) IterateClosingLines(ctx context.Context, p ClosingLinesParams, fn func(EventOdds) error) error

IterateClosingLines calls fn for every closing line matching p, paging with limit and skip (100 per page). Return StopIteration from fn to stop.

func (*Client) IterateDroppingOdds

func (c *Client) IterateDroppingOdds(ctx context.Context, p DroppingOddsParams, fn func(DroppingOddsEntry) error) error

IterateDroppingOdds calls fn for every dropping-odds entry matching p, page by page (200 per page when Limit is 0). Return StopIteration from fn to stop.

func (*Client) IterateEvents

func (c *Client) IterateEvents(ctx context.Context, p EventsParams, pageSize int, fn func(Event) error) error

IterateEvents calls fn for every event matching p, paging with limit and skip (pageSize per request, 1000 when 0). Return StopIteration from fn to stop.

func (*Client) IterateHistoricalEvents

func (c *Client) IterateHistoricalEvents(ctx context.Context, p HistoricalEventsParams, fn func(Event) error) error

IterateHistoricalEvents calls fn for every finished event of one league over any range, fetched in 31-day windows. Return StopIteration from fn to stop.

func (*Client) IterateMappings

func (c *Client) IterateMappings(ctx context.Context, p MappingsParams, fn func(Mapping) error) error

IterateMappings calls fn for every mapping row, following NextCursor until it is empty. Return StopIteration from fn to stop.

func (*Client) LastRateLimit

func (c *Client) LastRateLimit() *RateLimit

LastRateLimit returns the rate-limit headers of the most recent response that carried them, or nil.

func (*Client) ParticipantLogoURL

func (c *Client) ParticipantLogoURL(id int64) string

ParticipantLogoURL returns the URL of a participant's PNG logo. The URL carries your API key: do not hand it to untrusted clients; proxy the bytes from GetParticipantLogo instead.

func (*Client) PollUpdatedOdds

func (c *Client) PollUpdatedOdds(ctx context.Context, p UpdatedOddsParams, interval time.Duration, fn func(*UpdatedOdds) error) error

PollUpdatedOdds polls /odds/updated every interval (10s when 0), passing each X-Next-Since back as the next Since, until ctx is done or fn returns an error. p.Since defaults to now minus 20 seconds. A page cut short by Limit is followed up at once. Returning StopIteration from fn ends it with a nil error.

func (*Client) QuoteSgp added in v0.2.0

func (c *Client) QuoteSgp(ctx context.Context, p SgpQuoteParams) (*SgpQuoteResponse, error)

QuoteSgp prices 2 to 10 legs as a same game parlay at each bookmaker. Every requested bookmaker gets one entry in Quotes, in request order; branch on Status and NextAction. A quote can take up to 8 seconds, and at most 2 run at once per account (a third gets a 429).

func (*Client) SearchEvents

func (c *Client) SearchEvents(ctx context.Context, p SearchEventsParams) ([]Event, error)

SearchEvents searches events by team or league name (up to 10 results).

func (*Client) SearchHistoricalEvents

func (c *Client) SearchHistoricalEvents(ctx context.Context, p SearchHistoricalEventsParams) ([]Event, error)

SearchHistoricalEvents searches finished events by team name across leagues.

func (*Client) SelectBookmakers

func (c *Client) SelectBookmakers(ctx context.Context, bookmakers ...string) (*SelectedBookmakers, error)

SelectBookmakers adds bookmakers to your selection. It is never retried.

type Clock

type Clock struct {
	Minute        int    `json:"minute,omitempty"`
	PlayedSeconds int    `json:"playedSeconds,omitempty"`
	Period        int    `json:"period,omitempty"`
	Running       bool   `json:"running"`
	StatusDetail  string `json:"statusDetail,omitempty"`
	Serve         string `json:"serve,omitempty"`
	InjuryTime    int    `json:"injuryTime,omitempty"`
	// PeriodStartedAt is unix seconds, only on feeds without a played clock.
	PeriodStartedAt int64 `json:"periodStartedAt,omitempty"`
}

Clock is the live clock of an event.

type ClosingLinesParams

type ClosingLinesParams struct {
	Sport string
	// Leagues, up to 10 slugs.
	Leagues []string
	// From and To span at most 366 days.
	From       time.Time
	To         time.Time
	Markets    []string
	Bookmakers []string
	// Limit is capped at 100.
	Limit int
	Skip  int
}

ClosingLinesParams is GET /historical/closing-lines.

type Decimal

type Decimal string

Decimal is a decimal price kept exactly as the API sent it ("1.85"). It decodes from a JSON string or number.

func (Decimal) Float

func (d Decimal) Float() float64

Float returns the price as a float64, or 0 when it is empty or not a number.

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts "1.85", 1.85 and null.

type DroppingOddsEntry

type DroppingOddsEntry struct {
	EventID ID `json:"eventId"`
	Event   *struct {
		Home   string    `json:"home"`
		Away   string    `json:"away"`
		Date   Time      `json:"date"`
		Sport  NamedSlug `json:"sport"`
		League NamedSlug `json:"league"`
	} `json:"event,omitempty"`
	Market struct {
		Name  string   `json:"name"`
		Hdp   *float64 `json:"hdp,omitempty"`
		Label string   `json:"label,omitempty"`
	} `json:"market"`
	BetSide string `json:"betSide"`
	Odds    struct {
		Opening float64 `json:"opening"`
		Current float64 `json:"current"`
		Drop    struct {
			SinceOpening float64  `json:"sinceOpening"`
			H12          *float64 `json:"12h"`
			H24          *float64 `json:"24h"`
			H48          *float64 `json:"48h"`
		} `json:"drop"`
	} `json:"odds"`
	// LastMovedAt and UpdatedAt are unix milliseconds.
	LastMovedAt *int64 `json:"lastMovedAt"`
	UpdatedAt   int64  `json:"updatedAt"`
}

DroppingOddsEntry is one entry of GET /dropping-odds.

type DroppingOddsPage

type DroppingOddsPage struct {
	Data []DroppingOddsEntry
	// Total is X-Total-Count, -1 when missing.
	Total int64
	// Page is X-Page and PerPage is X-Per-Page.
	Page    int64
	PerPage int64
	// UpdatedAt is X-Updated-At, unix milliseconds.
	UpdatedAt int64
}

DroppingOddsPage is a /dropping-odds response with its pagination headers.

type DroppingOddsParams

type DroppingOddsParams struct {
	Sport string
	// League requires Sport; not with Leagues.
	League  string
	Leagues []string
	Markets []string
	// TimeWindow is opening (default), 12h, 24h or 48h.
	TimeWindow string
	// Sort is drop (default), recent or kickoff.
	Sort    string
	MinDrop float64
	// Limit is max 200 (server default 50).
	Limit int
	// Page is 1-indexed.
	Page                int
	IncludeEventDetails bool
}

DroppingOddsParams is GET /dropping-odds.

type EsportsDetails

type EsportsDetails struct {
	Game   NamedSlug `json:"game"`
	League NamedSlug `json:"league"`
	Region string    `json:"region,omitempty"`
	Format *struct {
		Type  string `json:"type"`
		Games int    `json:"games"`
	} `json:"format,omitempty"`
}

EsportsDetails is attached to esports events.

type Event

type Event struct {
	ID             ID              `json:"id"`
	Home           string          `json:"home"`
	Away           string          `json:"away"`
	HomeID         ID              `json:"homeId,omitempty"`
	AwayID         ID              `json:"awayId,omitempty"`
	Date           Time            `json:"date"`
	Status         string          `json:"status"`
	Sport          NamedSlug       `json:"sport"`
	League         NamedSlug       `json:"league"`
	Scores         *Score          `json:"scores,omitempty"`
	BookmakerCount int             `json:"bookmakerCount,omitempty"`
	Clock          *Clock          `json:"clock,omitempty"`
	Esports        *EsportsDetails `json:"esports,omitempty"`
}

Event is one entry of /events, /events/live, /events/search and /historical/events.

type EventInfo

type EventInfo struct {
	Home   string `json:"home"`
	Away   string `json:"away"`
	Date   Time   `json:"date"`
	Sport  string `json:"sport"`
	League string `json:"league"`
}

EventInfo is attached with IncludeEventDetails.

type EventOdds

type EventOdds struct {
	ID     ID        `json:"id"`
	Home   string    `json:"home"`
	Away   string    `json:"away"`
	HomeID ID        `json:"homeId,omitempty"`
	AwayID ID        `json:"awayId,omitempty"`
	Date   Time      `json:"date"`
	Status string    `json:"status"`
	Sport  NamedSlug `json:"sport"`
	League NamedSlug `json:"league"`
	Scores *Score    `json:"scores,omitempty"`
	// URLs are bookmaker links for the event, keyed by bookmaker.
	URLs map[string]string `json:"urls,omitempty"`
	// BookmakerIDs are the bookmakers' own event ids, where known.
	BookmakerIDs map[string]string `json:"bookmakerIds,omitempty"`
	// Bookmakers maps bookmaker name to its markets.
	Bookmakers map[string][]Market `json:"bookmakers"`
}

EventOdds is the response of /odds, /odds/multi, /odds/updated, /historical/odds and /historical/closing-lines.

func (*EventOdds) Market

func (o *EventOdds) Market(bookmaker, name string) *Market

Market returns the named market at a bookmaker, or nil.

type EventSummary

type EventSummary struct {
	Demo       bool            `json:"demo,omitempty"`
	Message    string          `json:"message,omitempty"`
	EventID    ID              `json:"eventId"`
	Home       string          `json:"home"`
	Away       string          `json:"away"`
	Date       Time            `json:"date"`
	Status     string          `json:"status"`
	ComputedAt Time            `json:"computedAt"`
	Markets    []SummaryMarket `json:"markets"`
}

EventSummary is GET /odds/summary. Plans below Growth get Demo=true and a sample.

type EventsParams

type EventsParams struct {
	// Sport slug, required.
	Sport  string
	League string
	// ParticipantID limits to events of one team or player.
	ParticipantID int64
	// Status is any of pending, live, settled, cancelled.
	Status []string
	From   time.Time
	// To defaults to 14 days from now on the server.
	To time.Time
	// Bookmaker limits to events with odds from this bookmaker.
	Bookmaker string
	// Limit caps the response (server max 5000).
	Limit int
	Skip  int
}

EventsParams filters GET /events.

type Grade

type Grade struct {
	Ref     string `json:"ref,omitempty"`
	EventID ID     `json:"eventId"`
	Result  string `json:"result"`
	Reason  string `json:"reason,omitempty"`
	Final   bool   `json:"final"`
	Basis   *struct {
		Scope string  `json:"scope"`
		Home  float64 `json:"home"`
		Away  float64 `json:"away"`
	} `json:"basis,omitempty"`
}

Grade is the verdict for one selection.

type GradeSelection

type GradeSelection struct {
	// Ref is echoed back, up to 64 characters.
	Ref     string `json:"ref,omitempty"`
	EventID int64  `json:"eventId"`
	// Market is the market name exactly as served on /odds (case-insensitive).
	Market string `json:"market"`
	// Side is home, away, draw, over, under, yes, no, odd, even, 1x, 12, x2,
	// none, neither, or an HT/FT pair such as draw/home.
	Side string `json:"side,omitempty"`
	// Hdp is the line as served on /odds, stated for the home side.
	Hdp *float64 `json:"hdp,omitempty"`
	// Label is required for Player Props and labelled markets.
	Label string `json:"label,omitempty"`
	// TieRule is "lose" or "void".
	TieRule string `json:"tieRule,omitempty"`
}

GradeSelection is one selection to grade.

type GradesResponse

type GradesResponse struct {
	Grades []Grade `json:"grades"`
}

GradesResponse is POST /settlements/grade.

type HistoricalEventsParams

type HistoricalEventsParams struct {
	Sport  string
	League string
	// From and To span at most 31 days (see IterateHistoricalEvents for longer ranges).
	From time.Time
	To   time.Time
}

HistoricalEventsParams is GET /historical/events.

type ID

type ID int64

ID is a numeric id that decodes from a JSON number or a numeric string.

func (ID) Int64

func (id ID) Int64() int64

Int64 returns the id as an int64.

func (ID) String

func (id ID) String() string

String returns the id in base 10.

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts 123, "123" and null.

type League

type League struct {
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	EventsCount int    `json:"eventsCount,omitempty"`
}

League is one entry of GET /leagues.

type LeaguesParams

type LeaguesParams struct {
	// Sport slug, required.
	Sport string
	// All includes leagues without current events.
	All bool
}

LeaguesParams filters GET /leagues.

type Mapping

type Mapping struct {
	EventID       ID                         `json:"eventId"`
	Home          string                     `json:"home"`
	Away          string                     `json:"away"`
	Date          Time                       `json:"date"`
	Sport         NamedSlug                  `json:"sport"`
	League        NamedSlug                  `json:"league"`
	Bookmaker     string                     `json:"bookmaker"`
	Market        string                     `json:"market"`
	Label         string                     `json:"label,omitempty"`
	Hdp           *float64                   `json:"hdp,omitempty"`
	Side          string                     `json:"side"`
	NativeEventID string                     `json:"nativeEventId,omitempty"`
	MarketID      string                     `json:"marketId"`
	OutcomeID     string                     `json:"outcomeId"`
	OutcomeLabel  string                     `json:"outcomeLabel,omitempty"`
	Extra         map[string]json.RawMessage `json:"extra,omitempty"`
	Active        bool                       `json:"active"`
	FirstSeenAt   Time                       `json:"firstSeenAt"`
	LastCheckedAt Time                       `json:"lastCheckedAt"`
}

Mapping is a bookmaker's own market and outcome ids for one of our outcomes.

type MappingsPage

type MappingsPage struct {
	Data       []Mapping `json:"data"`
	NextCursor string    `json:"nextCursor,omitempty"`
}

MappingsPage is GET /mappings. NextCursor is set in bulk sync while more pages remain.

type MappingsParams

type MappingsParams struct {
	// Bookmaker, required.
	Bookmaker string
	EventID   int64
	// EventIDs, up to 10.
	EventIDs []int64
	MarketID string
	// MarketIDs, up to 10.
	MarketIDs []string
	OutcomeID string
	// Market is the exact market name as in /odds, case-sensitive.
	Market string
	Active *bool
	// Sport, League, Limit (1 to 5000) and Cursor apply to bulk sync only.
	Sport  string
	League string
	Limit  int
	Cursor string
}

MappingsParams is GET /mappings. Without EventID(s), MarketID(s) or OutcomeID it is a bulk sync that pages with Cursor.

type Market

type Market struct {
	Name      string     `json:"name"`
	UpdatedAt Time       `json:"updatedAt"`
	Odds      []OddsLine `json:"odds"`
}

Market is one market at one bookmaker.

type MarketInfo

type MarketInfo struct {
	Name string `json:"name"`
	// Shape is moneyline, line, outcomes, yesno or labelled.
	Shape string `json:"shape"`
	// Period is match, first-half, second-half, quarter, set, game or inning.
	Period   string `json:"period"`
	Prematch bool   `json:"prematch"`
	Live     bool   `json:"live"`
}

MarketInfo describes one market a sport serves.

type MarketsResponse

type MarketsResponse struct {
	Sport   NamedSlug    `json:"sport"`
	Markets []MarketInfo `json:"markets"`
}

MarketsResponse is GET /markets?sport=...

type MovementsParams

type MovementsParams struct {
	EventID   int64
	Bookmaker string
	Market    string
	// MarketLine selects a line on Spread/Totals; leave empty for the main line.
	MarketLine string
}

MovementsParams is GET /odds/movements.

type MultiOddsParams

type MultiOddsParams struct {
	// EventIDs, up to 10.
	EventIDs   []int64
	Bookmakers []string
	Markets    []string
}

MultiOddsParams is GET /odds/multi.

type NamedSlug

type NamedSlug struct {
	Name string `json:"name"`
	Slug string `json:"slug"`
}

NamedSlug is a {name, slug} pair, used for sports and leagues.

type OddsLine

type OddsLine struct {
	Hdp   *float64 `json:"hdp,omitempty"`
	Label string   `json:"label,omitempty"`
	Home  Decimal  `json:"home,omitempty"`
	Draw  Decimal  `json:"draw,omitempty"`
	Away  Decimal  `json:"away,omitempty"`
	Over  Decimal  `json:"over,omitempty"`
	Under Decimal  `json:"under,omitempty"`
	// Exactly is the push price on three-way lines.
	Exactly Decimal `json:"exactly,omitempty"`
	Yes     Decimal `json:"yes,omitempty"`
	No      Decimal `json:"no,omitempty"`
	// Odds is the price of a labelled outcome (Correct Score, Player Props, ...).
	Odds Decimal `json:"odds,omitempty"`
	// Max is the stake limit, when the bookmaker publishes one.
	Max      *float64 `json:"max,omitempty"`
	LayHome  Decimal  `json:"layHome,omitempty"`
	LayDraw  Decimal  `json:"layDraw,omitempty"`
	LayAway  Decimal  `json:"layAway,omitempty"`
	LayOver  Decimal  `json:"layOver,omitempty"`
	LayUnder Decimal  `json:"layUnder,omitempty"`
	LayYes   Decimal  `json:"layYes,omitempty"`
	LayNo    Decimal  `json:"layNo,omitempty"`
	HomeLink string   `json:"homeLink,omitempty"`
	DrawLink string   `json:"drawLink,omitempty"`
	AwayLink string   `json:"awayLink,omitempty"`

	// Fields holds every field of the line as sent, for keys such as 1X, 12, X2, odd and even.
	Fields map[string]json.RawMessage `json:"-"`
}

OddsLine is one line of a market. Which fields are set depends on the market shape. Every field the API sent, including ones without a named field here, is in Fields.

func (OddsLine) Price

func (l OddsLine) Price(key string) Decimal

Price returns the price of any outcome key ("home", "1X", "over", ...) as a Decimal.

func (*OddsLine) UnmarshalJSON

func (l *OddsLine) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the named fields and keeps every field in Fields.

type OddsMovement

type OddsMovement struct {
	EventID   ID                  `json:"eventid"`
	Bookmaker string              `json:"bookmaker"`
	Opening   OddsMovementPoint   `json:"opening"`
	Latest    OddsMovementPoint   `json:"latest"`
	Movements []OddsMovementPoint `json:"movements"`
}

OddsMovement is GET /odds/movements.

type OddsMovementPoint

type OddsMovementPoint struct {
	Home float64  `json:"home"`
	Draw *float64 `json:"draw,omitempty"`
	Away float64  `json:"away"`
	Hdp  Decimal  `json:"hdp,omitempty"`
	Max  *float64 `json:"max,omitempty"`
	// Timestamp is unix milliseconds.
	Timestamp int64 `json:"timestamp"`
}

OddsMovementPoint is one price in a movement history. On Totals the over price is in Home and the under price in Away.

type OddsParams

type OddsParams struct {
	EventID int64
	// Bookmakers by name, required, max 30.
	Bookmakers []string
	// Markets by exact name, max 40, as listed at https://odds-api.io/markets.
	// Strongly recommended: a full response can be very large.
	Markets []string
}

OddsParams is GET /odds.

type OddsSnapshot

type OddsSnapshot struct {
	Data []EventOdds
	// Seq is X-OddsAPI-Seq: pass it as LastSeq when you connect the WebSocket.
	// Zero when the server did not send it.
	Seq int64
}

OddsSnapshot is a /odds/multi response with the WebSocket sequence at that moment.

type OptimalStake

type OptimalStake struct {
	Side            string  `json:"side"`
	Bookmaker       string  `json:"bookmaker"`
	Stake           float64 `json:"stake"`
	PotentialReturn float64 `json:"potentialReturn"`
}

OptimalStake is the stake split for one leg.

type Option

type Option func(*Client)

Option configures a Client.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the API base URL (default https://api.odds-api.io/v3).

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the http.Client used for requests. Its Timeout is left as is; WithTimeout is applied only to the default client.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how often a GET or POST is retried after a 5xx, a network error, or a 429 that asks for a wait no longer than the max retry delay (default 2). Bookmaker selection changes (PUT) are never retried. Use 0 to turn retries off.

func WithMaxRetryDelay

func WithMaxRetryDelay(d time.Duration) Option

WithMaxRetryDelay sets the longest wait between retries (default 10s).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout of the default http.Client (default 10s).

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent appends a product token to the User-Agent header.

type Outright

type Outright struct {
	ID             ID        `json:"id"`
	Name           string    `json:"name"`
	Date           Time      `json:"date"`
	Status         string    `json:"status"`
	Sport          NamedSlug `json:"sport"`
	League         NamedSlug `json:"league"`
	BookmakerCount int       `json:"bookmakerCount"`
}

Outright is a tournament from GET /outrights.

type OutrightMarket

type OutrightMarket struct {
	Name      string           `json:"name"`
	UpdatedAt Time             `json:"updatedAt"`
	Odds      []OutrightRunner `json:"odds"`
}

OutrightMarket is one outright market at one bookmaker.

type OutrightOdds

type OutrightOdds struct {
	ID         ID                          `json:"id"`
	Name       string                      `json:"name"`
	Date       Time                        `json:"date"`
	Status     string                      `json:"status"`
	Sport      NamedSlug                   `json:"sport"`
	League     NamedSlug                   `json:"league"`
	Bookmakers map[string][]OutrightMarket `json:"bookmakers"`
}

OutrightOdds is GET /outrights/odds.

type OutrightResultRow

type OutrightResultRow struct {
	Label         string `json:"label"`
	ParticipantID ID     `json:"participantId"`
	// Position is nil for cut, withdrawn and disqualified.
	Position *int `json:"position"`
	Tied     bool `json:"tied"`
	// MadeCut is nil for events without a cut.
	MadeCut *bool `json:"madeCut"`
	// Status is finished, cut, withdrawn or disqualified.
	Status string `json:"status"`
}

OutrightResultRow is the final position of one participant.

type OutrightResults

type OutrightResults struct {
	ID      ID                  `json:"id"`
	Name    string              `json:"name"`
	Status  string              `json:"status"`
	Results []OutrightResultRow `json:"results"`
	// Winners lists participant ids per market name.
	Winners map[string][]ID `json:"winners"`
}

OutrightResults is GET /outrights/results.

type OutrightRunner

type OutrightRunner struct {
	Label         string  `json:"label"`
	ParticipantID ID      `json:"participantId"`
	Odds          Decimal `json:"odds,omitempty"`
	LayOdds       Decimal `json:"layOdds,omitempty"`
	Yes           Decimal `json:"yes,omitempty"`
	No            Decimal `json:"no,omitempty"`
	LayYes        Decimal `json:"layYes,omitempty"`
	LayNo         Decimal `json:"layNo,omitempty"`
}

OutrightRunner is one runner of an outright market. Winner and Top N runners have Odds (and LayOdds on exchanges); Make Cut runners have Yes/No.

func (OutrightRunner) IsYesNo

func (r OutrightRunner) IsYesNo() bool

IsYesNo reports whether the runner carries yes/no prices (Make Cut).

type OutrightsParams

type OutrightsParams struct {
	// Sport is golf today.
	Sport string
	// League is pga-tour, dp-world-tour, liv-golf or majors.
	League string
	// Status defaults to pending,live on the server.
	Status []string
}

OutrightsParams is GET /outrights.

type Participant

type Participant struct {
	ID        ID     `json:"id"`
	Name      string `json:"name"`
	Sport     string `json:"sport"`
	Game      string `json:"game,omitempty"`
	ShortCode string `json:"shortCode,omitempty"`
}

Participant is a team or player.

type ParticipantsParams

type ParticipantsParams struct {
	// Sport slug, required.
	Sport  string
	Search string
}

ParticipantsParams filters GET /participants.

type PeriodScore

type PeriodScore struct {
	Home    float64     `json:"home"`
	Away    float64     `json:"away"`
	Wickets *SideFloats `json:"wickets,omitempty"`
	Overs   *SideFloats `json:"overs,omitempty"`
}

PeriodScore is the score of one period. Wickets and overs are cricket only.

type RateLimit

type RateLimit struct {
	// Limit is X-RateLimit-Limit, or -1 when the header was missing.
	Limit int
	// Remaining is X-RateLimit-Remaining, or -1 when the header was missing.
	Remaining int
	// Reset is when the window resets (X-RateLimit-Reset), zero when unknown.
	Reset time.Time
}

RateLimit is the hourly request budget reported by the X-RateLimit-* headers.

type Score

type Score struct {
	Home    float64                `json:"home"`
	Away    float64                `json:"away"`
	Periods map[string]PeriodScore `json:"periods,omitempty"`
}

Score is an event score. Periods keys are p1..pN, ft (end of regulation), ot (after overtime), ap (after penalties), currentgame (live tennis), map1.. (esports) and inning1.. (cricket); which appear depends on sport and source.

type SearchEventsParams

type SearchEventsParams struct {
	// Query is a team or league name, at least 3 characters.
	Query string
	// Status is "upcoming" (default) or "live".
	Status string
}

SearchEventsParams is GET /events/search.

type SearchHistoricalEventsParams

type SearchHistoricalEventsParams struct {
	// Query is a team name, at least 3 characters.
	Query string
	Sport string
	// From defaults to 31 days before To; To defaults to now. Span at most 31 days.
	From time.Time
	To   time.Time
}

SearchHistoricalEventsParams is GET /historical/events/search.

type SelectedBookmakers

type SelectedBookmakers struct {
	Bookmakers []string `json:"bookmakers"`
	Count      int      `json:"count"`
	Message    string   `json:"message,omitempty"`
	Added      int      `json:"added,omitempty"`
}

SelectedBookmakers is the response of the /bookmakers/selected endpoints.

type Settlement

type Settlement struct {
	EventID ID     `json:"eventId"`
	Sport   string `json:"sport"`
	// Status is pending, live, awaiting_result, settled or cancelled.
	Status string `json:"status"`
	// Final is true when you can stop polling.
	Final     bool   `json:"final"`
	SettledAt Time   `json:"settledAt,omitempty"`
	Scores    *Score `json:"scores,omitempty"`
}

Settlement is the settlement record of one event.

type SettlementsResponse

type SettlementsResponse struct {
	Settlements []Settlement `json:"settlements"`
	NotFound    []string     `json:"notFound"`
}

SettlementsResponse is GET /settlements.

type SgpBookQuote added in v0.2.0

type SgpBookQuote struct {
	Bookmaker          string              `json:"bookmaker"`
	Status             string              `json:"status"`
	Price              Decimal             `json:"price,omitempty"`
	LegsMultiplied     Decimal             `json:"legsMultiplied,omitempty"`
	PriceAdjustmentPct string              `json:"priceAdjustmentPct,omitempty"`
	Legs               []SgpQuoteLegResult `json:"legs,omitempty"`
	// LegIDs are the legs that made the quote fail (always on leg_unavailable;
	// on not_combinable and suspended when the bookmaker names them), or on ok
	// with reason redundant_leg the legs the bookmaker ignored as implied by the others.
	LegIDs         []string       `json:"legIds,omitempty"`
	Links          *SgpQuoteLinks `json:"links,omitempty"`
	Jurisdiction   string         `json:"jurisdiction,omitempty"`
	DurationMs     int            `json:"durationMs,omitempty"`
	QuotedAt       Time           `json:"quotedAt"`
	Cached         bool           `json:"cached,omitempty"`
	CacheExpiresAt Time           `json:"cacheExpiresAt"`
	Retryable      bool           `json:"retryable,omitempty"`
	// RetryAfter is in seconds.
	RetryAfter int `json:"retryAfter,omitempty"`
	// NextAction is one of the SgpNext* values; empty on ok.
	NextAction string `json:"nextAction,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

SgpBookQuote is one bookmaker's answer: a parlay Price when Status is "ok", otherwise Retryable, NextAction and Reason say what to do. Branch on Status and NextAction; Reason is a sentence for display whose wording can change, and on "ok" the only reason is the code "redundant_leg".

type SgpBookmaker added in v0.2.0

type SgpBookmaker struct {
	Name         string   `json:"name"`
	Sports       []string `json:"sports"`
	MaxLegs      int      `json:"maxLegs"`
	Jurisdiction string   `json:"jurisdiction"`
	// Status is live, paused or degraded.
	Status string `json:"status"`
}

SgpBookmaker is a bookmaker that can quote same game parlays.

type SgpLeg added in v0.2.0

type SgpLeg struct {
	// LegID goes into SgpQuoteLeg.LegID. Copy it; do not build it by hand.
	LegID  string   `json:"legId"`
	Market string   `json:"market"`
	Hdp    *float64 `json:"hdp,omitempty"`
	Label  string   `json:"label,omitempty"`
	Side   string   `json:"side"`
	// Bookmakers is keyed by bookmaker name.
	Bookmakers map[string]SgpLegBook `json:"bookmakers"`
}

SgpLeg is one leg that can go into a parlay.

type SgpLegBook added in v0.2.0

type SgpLegBook struct {
	// Eligible reports whether the bookmaker can combine the leg into a parlay.
	Eligible bool `json:"eligible"`
	// Price is the bookmaker's current single price; empty when it does not price the leg.
	Price     Decimal `json:"price,omitempty"`
	UpdatedAt Time    `json:"updatedAt"`
}

SgpLegBook is one bookmaker's view of a leg.

type SgpLegsBookmaker added in v0.2.0

type SgpLegsBookmaker struct {
	Bookmaker string `json:"bookmaker"`
	// Status is ok, leg_unavailable, unsupported or temporarily_unavailable.
	Status    string `json:"status"`
	Retryable bool   `json:"retryable,omitempty"`
	// NextAction is SgpNextRetryLater or SgpNextChooseOtherBookmaker.
	NextAction string `json:"nextAction,omitempty"`
	// Reason is a sentence for display; branch on Status and NextAction.
	Reason string `json:"reason,omitempty"`
	// RetryAfter is in seconds.
	RetryAfter int `json:"retryAfter,omitempty"`
}

SgpLegsBookmaker says whether a requested bookmaker's legs could be checked. When Status is not "ok", every leg reads Eligible false at that bookmaker.

type SgpLegsParams added in v0.2.0

type SgpLegsParams struct {
	// EventID of a pre-match event, required.
	EventID int64
	// Bookmakers, required, max 8 per request.
	Bookmakers []string
	// Markets keeps only these market names, max 40.
	Markets []string
	// Limit defaults to 200 on the server, max 1000.
	Limit int
	Skip  int
}

SgpLegsParams is GET /sgp/legs.

type SgpLegsResponse added in v0.2.0

type SgpLegsResponse struct {
	EventID ID     `json:"eventId"`
	Date    Time   `json:"date"`
	Status  string `json:"status"`
	// Bookmakers has one entry per requested bookmaker, in request order.
	Bookmakers []SgpLegsBookmaker `json:"bookmakers"`
	Legs       []SgpLeg           `json:"legs"`
	// HasMore is true when another call with a higher Skip returns more legs.
	HasMore bool `json:"hasMore"`
}

SgpLegsResponse is GET /sgp/legs.

type SgpQuoteLeg added in v0.2.0

type SgpQuoteLeg struct {
	LegID  string   `json:"legId,omitempty"`
	Market string   `json:"market,omitempty"`
	Hdp    *float64 `json:"hdp,omitempty"`
	Label  string   `json:"label,omitempty"`
	Side   string   `json:"side,omitempty"`
	// ExpectedPrice is the single price you saw; the leg comes back with
	// PriceMoved set when the current price differs.
	ExpectedPrice string `json:"expectedPrice,omitempty"`
}

SgpQuoteLeg is one leg to quote. Give either LegID, or Market, Hdp, Label and Side exactly as served on /odds.

type SgpQuoteLegResult added in v0.2.0

type SgpQuoteLegResult struct {
	LegID string `json:"legId"`
	// Price is the current single price at this bookmaker.
	Price      Decimal  `json:"price,omitempty"`
	Hdp        *float64 `json:"hdp,omitempty"`
	PriceMoved bool     `json:"priceMoved,omitempty"`
}

SgpQuoteLegResult is a leg as priced by one bookmaker.

type SgpQuoteLinks struct {
	Desktop string `json:"desktop,omitempty"`
	Mobile  string `json:"mobile,omitempty"`
}

SgpQuoteLinks are betslip links. Either is empty when the bookmaker gives none.

type SgpQuoteParams added in v0.2.0

type SgpQuoteParams struct {
	// EventID of a pre-match event, required.
	EventID int64
	// Bookmakers, required, max 8 per request.
	Bookmakers []string
	// Legs, 2 to 10.
	Legs []SgpQuoteLeg
}

SgpQuoteParams is POST /sgp/quote.

type SgpQuoteResponse added in v0.2.0

type SgpQuoteResponse struct {
	EventID ID             `json:"eventId"`
	Quotes  []SgpBookQuote `json:"quotes"`
}

SgpQuoteResponse is POST /sgp/quote, one quote per requested bookmaker in request order.

type SideFloats

type SideFloats struct {
	Home float64 `json:"home"`
	Away float64 `json:"away"`
}

SideFloats holds a home and away value.

type Sport

type Sport = NamedSlug

Sport is one entry of GET /sports.

type SummaryExchangeQuote

type SummaryExchangeQuote struct {
	Best      float64  `json:"best"`
	Venue     string   `json:"venue"`
	Liquidity *float64 `json:"liquidity,omitempty"`
	Currency  string   `json:"currency,omitempty"`
}

SummaryExchangeQuote is the best exchange price for an outcome.

type SummaryLine

type SummaryLine struct {
	Hdp       *float64 `json:"hdp"`
	Main      bool     `json:"main"`
	Books     int      `json:"books"`
	FairBooks int      `json:"fairBooks,omitempty"`
	// Outcomes is keyed home/draw/away, over/under or yes/no.
	Outcomes map[string]SummaryOutcome `json:"outcomes"`
	Payout   *struct {
		Best    float64 `json:"best"`
		Average float64 `json:"average"`
	} `json:"payout,omitempty"`
	Exchanges map[string]SummaryExchangeQuote `json:"exchanges,omitempty"`
}

SummaryLine is one line of a summary market.

type SummaryMarket

type SummaryMarket struct {
	Name  string        `json:"name"`
	Lines []SummaryLine `json:"lines"`
}

SummaryMarket is one market of an odds summary.

type SummaryOutcome

type SummaryOutcome struct {
	Best           float64  `json:"best"`
	BestBookmakers []string `json:"bestBookmakers"`
	Average        float64  `json:"average"`
	Median         float64  `json:"median"`
	Worst          float64  `json:"worst"`
	Fair           *float64 `json:"fair,omitempty"`
	SharpFair      *float64 `json:"sharpFair,omitempty"`
	Excluded       int      `json:"excluded,omitempty"`
}

SummaryOutcome aggregates one outcome across bookmakers.

type SummaryParams

type SummaryParams struct {
	// EventID for GetOddsSummary.
	EventID int64
	// EventIDs (up to 10) for GetOddsSummaryMulti.
	EventIDs []int64
	// Markets, max 20. Server default ML,Spread,Totals.
	Markets []string
	// Lines is "main" (default) or "all".
	Lines            string
	Bookmakers       []string
	IncludeExchanges bool
}

SummaryParams is GET /odds/summary and /odds/summary/multi.

type Time

type Time struct{ time.Time }

Time is a time.Time that decodes RFC 3339 strings and treats "" and null as zero.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON writes RFC 3339, or null for the zero time.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts RFC 3339 strings, "" and null.

type UpdatedOdds

type UpdatedOdds struct {
	// Data holds only the market groups that changed: merge by event, bookmaker and market.
	Data []EventOdds
	// NextSince (X-Next-Since) is the Since of the next call.
	NextSince int64
	// ServerTime is X-Server-Time, unix seconds.
	ServerTime int64
	// UnknownMarkets lists requested market names that do not exist (X-Unknown-Markets).
	UnknownMarkets []string
}

UpdatedOdds is a /odds/updated response with its headers.

type UpdatedOddsParams

type UpdatedOddsParams struct {
	// Since is unix seconds, no more than 90 seconds old (or the previous NextSince).
	Since     int64
	Bookmaker string
	Sport     string
	// Markets by exact name, max 40.
	Markets []string
	// Limit is 1 to 10000.
	Limit int
}

UpdatedOddsParams is GET /odds/updated.

type ValueBet

type ValueBet struct {
	ID        string `json:"id"`
	EventID   ID     `json:"eventId"`
	Bookmaker string `json:"bookmaker"`
	Market    struct {
		Name string   `json:"name"`
		Hdp  *float64 `json:"hdp,omitempty"`
		Home Decimal  `json:"home"`
		Draw Decimal  `json:"draw,omitempty"`
		Away Decimal  `json:"away"`
		Max  *float64 `json:"max"`
	} `json:"market"`
	BetSide string `json:"betSide,omitempty"`
	// ExpectedValue is bookmaker odds / fair odds x 100: 103.42 is a 3.42% edge.
	ExpectedValue          float64 `json:"expectedValue"`
	ExpectedValueUpdatedAt Time    `json:"expectedValueUpdatedAt"`
	FirstSeenAt            Time    `json:"firstSeenAt,omitempty"`
	BookmakerOddsUpdatedAt Time    `json:"bookmakerOddsUpdatedAt,omitempty"`
	BookmakerOdds          struct {
		Home           Decimal `json:"home"`
		Away           Decimal `json:"away"`
		Draw           Decimal `json:"draw,omitempty"`
		Hdp            Decimal `json:"hdp,omitempty"`
		Href           string  `json:"href,omitempty"`
		HomeDirectLink string  `json:"homeDirectLink,omitempty"`
		DrawDirectLink string  `json:"drawDirectLink,omitempty"`
		AwayDirectLink string  `json:"awayDirectLink,omitempty"`
	} `json:"bookmakerOdds"`
	Event *EventInfo `json:"event,omitempty"`
}

ValueBet is one entry of GET /value-bets.

func (ValueBet) Edge

func (v ValueBet) Edge() float64

Edge returns the edge in percent (ExpectedValue - 100).

type ValueBetsParams

type ValueBetsParams struct {
	// Bookmaker, required.
	Bookmaker string
	Sport     string
	// League requires Sport.
	League              string
	IncludeEventDetails bool
}

ValueBetsParams is GET /value-bets.

Directories

Path Synopsis
examples
basic command
Upcoming Premier League matches and their odds.
Upcoming Premier League matches and their odds.
betting-analysis command
Value bets, arbitrage and dropping odds.
Value bets, arbitrage and dropping odds.
polling command
Keeps a local copy of Bet365 football odds current by polling /odds/updated.
Keeps a local copy of Bet365 football odds current by polling /odds/updated.
settlement command
Grades bets against final results and lists golf outrights.
Grades bets against final results and lists golf outrights.
websocket-feed command
REST snapshot plus the live WebSocket feed, resuming from the snapshot's seq.
REST snapshot plus the live WebSocket feed, resuming from the snapshot's seq.
Package oddsws streams real-time odds, scores and status from the Odds-API.io WebSocket feed (wss://api.odds-api.io/v3/ws).
Package oddsws streams real-time odds, scores and status from the Odds-API.io WebSocket feed (wss://api.odds-api.io/v3/ws).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL