# FavouriteOdds Picks API: integration guide

This guide is for developers and for the AI coding agents they use (Claude Code, Cursor, Codex,
Copilot). It is self-contained. An agent can integrate the feed from this page alone.

Machine-readable copies:
- this guide: `https://api.favouriteodds.com/data/v1/llms.txt`;
- the OpenAPI schema: `https://api.favouriteodds.com/data/v1/openapi.json`;
- the raw odds and history endpoints: `https://api.favouriteodds.com/data/v1/guide/data`.

## Copy-paste prompt for your coding agent

> Integrate the FavouriteOdds value picks into this project. Follow
> https://api.favouriteodds.com/data/v1/llms.txt exactly. The API key is in the environment
> variable `FAVOURITEODDS_API_KEY`. It is used only on our server. Never put it in browser code,
> URLs, logs or the repository. Use the REST endpoint first. Add the WebSocket client only if we
> need updates within seconds. Show each pick with its bookmaker, odds, minimum odds, edge and
> kickoff. Remove a pick as soon as the API removes it. Finish with the acceptance checklist at
> the end of the guide.

## What the feed is

The feed lists pre-match value bets at Bulgarian bookmakers: Efbet, Betano, Winbet, Inbet, Sesame
and PalmsBet. Your contract decides which of them you receive. Sports are basketball, soccer and
tennis.

Each pick is a bookmaker price that is higher than our sharp-reference fair price. Picks pass a
filter tuned for fewer bets with higher ROI. Each match shows at most one pick per idea (for
example one side pick and one totals pick).

Every pick is published into a hash-chained proof ledger before kickoff, and later settled there.
The feed is information only. There is no bet placement endpoint.

## Rules for every integration (agents: these are hard requirements)

1. **The API key stays on your server.** Send it only in the `Authorization: Bearer <key>` header.
   - Never put it in a URL or query string, browser JavaScript, a mobile app bundle, logs,
     screenshots or git.
   - A browser cannot open the WebSocket directly: browsers cannot set the header, and the key
     would leak. Websites read the feed on their server and pass picks to the page (see
     "Website integration").
2. **Merge by `id`.**
   - An `upsert` replaces the whole pick with that `id`.
   - A `remove` deletes it.
   - A `settle` carries the final result of an `id` you have already seen.
3. **Never show a pick after its `remove`, or after `kickoff`.**
4. **Prices move.** Show `min_odds`: the pick is still value only while the bookmaker offers at
   least that price. If `verification_status` is `awaiting_refresh`, show the pick as
   "re-checking" (for example greyed out), not as a fresh price.
5. **Show "18+" and a responsible-gambling notice** wherever picks are displayed to the public.

## Authentication and limits

- Base URL: `https://api.favouriteodds.com/data/v1`.
- Header on every request and on the WebSocket handshake: `Authorization: Bearer <key>`.
- Each key has a requests-per-minute quota and a maximum number of parallel WebSocket connections
  (both in your contract). REST returns `429` when you go over.
- Keys can expire or be revoked. REST then returns `401` and the stream closes with `4401`.
- Health check without a key: `GET /healthz`.

## REST or WebSocket?

| | REST `GET /opportunities` | WebSocket `/stream` |
|---|---|---|
| Best for | WordPress/PHP sites, cron jobs, simple backends, first integration | Apps, Telegram bots, trading tools that need second-level updates |
| Freshness | Poll every 30–60 s (server data refreshes every ~2 s) | Push within ~2 s |
| Removals | Absent from the next response | Explicit `remove` with a reason |
| Results | Not included | `settle` messages |
| Effort | ~20 lines | Reconnect and cursor handling |

Both return the same picks with the same fields. Start with REST. Add the WebSocket when you need
pushes, removal reasons or results.

## REST: current picks

```bash
curl -s -H "Authorization: Bearer $FAVOURITEODDS_API_KEY" \
  "https://api.favouriteodds.com/data/v1/opportunities?limit=500"
```

Query parameters:
- `source_id`: one bookmaker, e.g. `efbet`;
- `limit`: 1–500 (default 100);
- `cursor`: the previous response's `page.next_cursor`;
- `one_pick_per_group`: `false` returns every filtered pick, not one per match idea;
- `top_markets_only`: `true` returns only picks with `top_market: true` (see the pick object).
- `confirmed_only`: `true` returns only picks both references back (`confirmations` includes
  `prediction_market`). Off by default: without it you get every pick.
- `profile`: the bet volume profile, `low`, `medium` (default) or `high`. `low` gives the fewest picks with the
  highest past ROI, `high` the most picks at a lower ROI. You get the picks whose `volume_tier` is within the
  profile: `low` only `low`; `medium` `low` and `medium`; `high` all. Without it you get `medium`, the same picks
  as before profiles existed.

Response:

```json
{
  "data": [ { "...pick..." } ],
  "page": {"next_cursor": null, "has_more": false},
  "diagnostics": {"state": "healthy", "...": "..."},
  "refresh_after_seconds": 2.0
}
```

Follow `page.next_cursor` until `has_more` is false. Between polls, replace your whole list with
the latest response: a pick that is missing has been removed.

A `503` means the feed is refreshing. Keep showing your last list, marked as not fresh, and retry
after 30 s.

## The pick object

```json
{
  "id": "sharp_pick:1018",
  "source_id": "efbet",
  "sport": "basketball",
  "league": "France - Pro A",
  "home_team": "Paris",
  "away_team": "Boulazac Basket Dordogne",
  "kickoff": "2026-10-18T14:30:00+00:00",
  "kickoff_local": "2026-10-18T17:30:00+03:00",
  "market": "total",
  "period": "ot",
  "line": 171.0,
  "selection": "over",
  "market_label": "Total 171",
  "selection_label": "Over 171",
  "market_name_en": "Total 171 (incl. overtime)",
  "selection_name_en": "Over 171",
  "home_team_bg": "Париж Баскетбол",
  "away_team_bg": "Булазак Баскет",
  "league_bg": "Франция - Про А",
  "market_name_bg": "Брой точки 171 (вкл. Продължения)",
  "selection_name_bg": "Над 171",
  "top_market": false,
  "confirmations": ["sharp_reference", "prediction_market"],
  "decimal_odds": 1.84,
  "min_odds": 1.79,
  "edge_pct": 5.9,
  "event_url": "https://efbet.com/event/1231898",
  "odds_phase": "pre_match",
  "status": "current",
  "verification_status": "verified",
  "recheck_reason": null,
  "promotion_status": "promoted",
  "promotion_reason": "sharp_reference_pick",
  "observed_at": "2026-10-18T10:05:09.666122+00:00",
  "last_verified_at": "2026-10-18T10:05:09.666122+00:00",
  "first_published_at": "2026-10-18T00:44:01.354320+00:00",
  "proof": {"sequence": 11428, "event_hash": "9df10e32…16a54b", "published_at": "2026-10-17T22:01:07+00:00"}
}
```

| Field | Meaning |
|---|---|
| `id` | Stable pick identity. Merge on it. |
| `source_id` | Bookmaker: `efbet`, `betano`, `winbet`, `inbet`, `sesame`, `palmsbet`. |
| `sport`, `league`, `home_team`, `away_team`, `kickoff` | The match. `kickoff` is ISO 8601 UTC. |
| `market`, `period`, `line`, `selection` | Machine-readable bet. `market` is one of `moneyline`, `moneyline_3way`, `spread`, `total`, `team_total_home`, `team_total_away`, `set_handicap`, `game_handicap`, etc. `period`: `ft` = full time (90 min in soccer), `ot` = including overtime, `1h` = first half, `s1` = first set. `selection`: `home`, `away`, `draw`, `over`, `under`. |
| `market_label`, `selection_label` | Human-readable text for display, e.g. "Total 152.5" / "Over 152.5". |
| `market_name_en`, `selection_name_en` | Readable English market and selection, with the period spelled out, e.g. "Total 171 (incl. overtime)" / "Over 171". |
| `market_name_bg`, `selection_name_bg` | The market and selection **exactly as the bookmaker's own Bulgarian site shows them**, e.g. Efbet "Брой точки 171 (вкл. Продължения)" / "Над 171", tennis "Да Спечели". Use these so users find the bet on the bookmaker's site. `null` when the bookmaker's Bulgarian text is not known yet; it is never translated or guessed. |
| `home_team_bg`, `away_team_bg` | The teams or players as the bookmaker's Bulgarian site names them, in the same home/away order as `home_team`/`away_team`. `null` when unknown. |
| `league_bg` | The bookmaker's Bulgarian country/category and competition, joined with " - ", e.g. "Франция - Про А". `null` when unknown. |
| `kickoff_local` | The kickoff in Bulgarian time (Europe/Sofia), ISO 8601 with the offset. |
| `top_market` | `true` for picks in the strongest markets: basketball moneyline; soccer 1X2; soccer goals over (match total and away team total, full time); tennis moneyline, game handicap and set handicap. Filter with `top_markets_only`. |
| `volume_tier` | `low`, `medium` or `high`: the strictest bet volume profile this pick belongs to (profiles are nested). Filter with `profile`. |
| `badge` | `platinum` for the strongest picks (found close to kick-off), else `null`. |
| `market_performance` | The paper record of this pick's market (sport × bookmaker × market × period, optionally narrowed to an odds band, a `side`, `favourite`/underdog or an `ev_band`), flat 1 unit: `settled`, `roi_pct` with `roi_ci95`, `book_clv_pct` (closing-line value against the same bookmaker), `holdout` (the newest results by date; they are part of the full record and one of the checks that grade the market, so not an independent test), `cell_tier` (the volume tier the market earns now), `promoted`, `cell_ref` (stable id) and `updated_at` (about every 30 min). `null` while the market has no record. |
| `confirmations` | The independent references that show value on this pick: always `sharp_reference`; `prediction_market` is added when a liquid prediction market also shows at least +3% at this price (today: basketball). Show a "Confirmed by 2 references" badge, or filter with `confirmed_only`. |
| `decimal_odds` | The bookmaker's current price. |
| `min_odds` | The lowest price that still has value. Advise users not to bet below it. |
| `edge_pct` | Expected value in %: price vs our fair price. 4.0 means +4% expected return. |
| `event_url` | The bookmaker's match page (may be null). Link "Bet at Efbet" here. |
| `verification_status` | `verified`: the price was just confirmed. `awaiting_refresh`: re-checking, so show it greyed out. |
| `recheck_reason` | Why a pick is re-checking. Null when verified. |
| `observed_at` | When the bookmaker price was read. |
| `first_published_at` | When the pick was first published. |
| `proof` | Hash-chain record of the publication (sequence number and SHA-256 event hash). Anyone can check that a pick was published before kickoff and never edited. |
| `historical_performance` | Past ROI of this pick type. `status: "unavailable"` until enough results exist. |
| `promotion_reason` | `sharp_reference_pick`. A `_drop` or `_both` suffix means the price is also confirmed by a market move. A `_confirmed` suffix means a later move confirmed it. |

Ignore fields you do not know. New fields can be added without notice. Existing fields keep their
meaning.

## WebSocket: live picks

URL: `wss://api.favouriteodds.com/data/v1/stream`, with the same `Authorization` header.

1. **Subscribe** within 10 seconds of connecting. Send exactly one text message:

   ```json
   {"channels": ["opportunities"]}
   ```

   - `sources` is optional. Without it you receive every bookmaker in your contract. With it you
     receive only those listed, e.g. `"sources": ["efbet"]`.
   - `"one_pick_per_group": false` gives every filtered pick, not one per match idea.
   - `"top_markets_only": true` gives only picks with `top_market: true`.
   - `"confirmed_only": true` gives only picks whose `confirmations` include `prediction_market`.
   - `"profile": "low" | "medium" | "high"` picks the bet volume profile (default `"medium"`).
   - To resume after a disconnect, add `"cursor": "<last cursor>"`.

2. **The server sends, in order:**

   | Frame `type` | Content | What to do |
   |---|---|---|
   | `ready` | `cursor` | Nothing yet. |
   | `snapshot` | `data`: picks; `chunk_index` / `chunk_count` | First connection only. Collect the chunks. |
   | `snapshot_complete` | `row_count` | Replace your whole list with the collected snapshot. |
   | `updates` | `data`: a list of `{sequence, channel, action, published_at, data}` | Apply each item in order (below). |
   | `heartbeat` | `upstream_status`: `ok` or `degraded` | Every ~2 s. On `degraded`, mark picks as not fresh. |
   | `resync_required` | `detail` | The cursor cannot be resumed. Drop the cursor, reconnect, and take the new snapshot. |
   | `error` | `status`, `detail` | See the close codes below. |

3. **Apply each item in `updates`:**
   - `upsert`: `data` is the full pick. Insert it or replace it by `id`.
   - `remove`: delete `data.id`. A connection gets a `remove` only for a pick it was sent (in its snapshot or an
     `upsert`); right after a resume, while the stream replays the changes since your cursor, a `remove` may name
     a pick you no longer hold: ignore it. `data.reason` is one of:
     - `edge_gone`, `no_value`: the price is no longer value;
     - `stale`, `verification_expired`: the price could not be re-confirmed;
     - `market_gone`, `market_unavailable`: the bookmaker removed the market;
     - `event_starting`, `event_started`: kickoff;
     - `correlated_pick`: a better pick on the same match idea replaced it;
     - `not_top_market`: the pick is outside the top markets (only with `"top_markets_only": true`);
     - `not_confirmed`: the pick is not (or no longer) backed by both references (only with `"confirmed_only": true`);
     - `outside_profile`: the pick's `volume_tier` is outside your `profile`;
     - `better_price_elsewhere`.
   - `settle`: the final result of `data.id`.
     - `data.result` is `won`, `lost`, `void`, `half_won` or `half_lost`.
     - `data.profit_units` is the profit at 1 unit stake.
     - `data.entry_odds` is the odds at publication.
     - `data.clv_book_pct` is closing-line value: the published price compared with the same
       bookmaker's closing price.
     - Use these for your own track record.

4. **Save `cursor` after you have applied a whole frame.** Every frame carries one. When you
   reconnect, send the same subscription plus `cursor`. You then get only what you missed, with no
   new snapshot.

5. **Keepalive:** you may send the text `ping` at any time. Any other message after the
   subscription closes the connection (4422). To change the subscription, reconnect.

Close codes:

| Code | Meaning | Action |
|---|---|---|
| `1000`, `1001`, `1006`, `1013` | Network drop, server restart or timeout | Reconnect with backoff (1, 2, 4… up to 60 s) and the cursor |
| `4009` | `resync_required` | Reconnect **without** a cursor |
| `4401` | Key invalid, expired or revoked | Stop. Fix the key. |
| `4403` | Read the frame's `status`. `403`: source or scope outside your contract. `503`: temporary. | 403: stop. 503: reconnect with backoff. |
| `4422` | Invalid subscription message | Stop. Fix the message. |
| `4429` | Too many connections for this key | Close the extra connections, then retry |

A handshake rejected with HTTP 401/403 (no frame) means the key is missing or wrong.

## Reference client: Python

```python
# pip install websockets>=12
import asyncio, json, os, websockets

URL = "wss://api.favouriteodds.com/data/v1/stream"
HEADERS = {"Authorization": "Bearer " + os.environ["FAVOURITEODDS_API_KEY"]}
picks: dict[str, dict] = {}          # id -> pick (your current list)
staged: dict[str, dict] = {}         # snapshot chunks until snapshot_complete
cursor: str | None = None            # persist this in production (file/DB)


def apply(frame: dict) -> None:
    global cursor
    kind = frame.get("type")
    if kind == "snapshot":
        for p in frame["data"]:
            staged[p["id"]] = p
    elif kind == "snapshot_complete":
        picks.clear(); picks.update(staged); staged.clear()
    elif kind == "updates":
        for item in frame["data"]:
            if item.get("channel") != "opportunities":
                continue
            data = item["data"]
            if item["action"] == "upsert":
                picks[data["id"]] = data
            elif item["action"] == "remove":
                picks.pop(data["id"], None)
            elif item["action"] == "settle":
                on_result(data)
    if frame.get("cursor"):
        cursor = frame["cursor"]       # only after the whole frame was applied


def on_result(result: dict) -> None:
    print("settled", result["id"], result["result"], result["profit_units"])



async def run() -> None:
    global cursor
    delay = 1
    while True:
        try:
            async with websockets.connect(URL, additional_headers=HEADERS, max_size=2**20) as ws:
                sub = {"channels": ["opportunities"]}
                if cursor:
                    sub["cursor"] = cursor
                await ws.send(json.dumps(sub))
                delay = 1
                async for message in ws:
                    frame = json.loads(message)
                    if frame.get("type") == "resync_required":
                        cursor = None
                        break
                    if frame.get("type") == "error":
                        if frame.get("status") in (401, 403, 422):
                            raise SystemExit(f"stream stopped: {frame}")   # key/contract/subscription: needs a human
                        break                                             # temporary (e.g. 503): reconnect
                    apply(frame)
        except websockets.ConnectionClosed as exc:
            if exc.rcvd and exc.rcvd.code == 4009:
                cursor = None
        except OSError as exc:
            print("stream error:", exc)
        await asyncio.sleep(delay)
        delay = min(delay * 2, 60)


asyncio.run(run())
```

## Reference client: Node.js

```js
// npm i ws
import WebSocket from "ws";

const URL = "wss://api.favouriteodds.com/data/v1/stream";
const picks = new Map();           // id -> pick
let staged = new Map();
let cursor = null;                 // persist in production
let delay = 1000;
let stopped = false;               // key, contract or subscription problem: needs a human

function connect() {
  const ws = new WebSocket(URL, {
    headers: { Authorization: `Bearer ${process.env.FAVOURITEODDS_API_KEY}` },
  });
  ws.on("open", () => {
    delay = 1000;
    ws.send(JSON.stringify(cursor ? { channels: ["opportunities"], cursor } : { channels: ["opportunities"] }));
  });
  ws.on("message", (raw) => {
    const f = JSON.parse(raw);
    if (f.type === "resync_required") { cursor = null; return; }
    if (f.type === "error" && [401, 403, 422].includes(f.status)) { stopped = true; console.error("stream stopped:", f); return; }
    if (f.type === "snapshot") f.data.forEach((p) => staged.set(p.id, p));
    if (f.type === "snapshot_complete") { picks.clear(); staged.forEach((p, id) => picks.set(id, p)); staged = new Map(); }
    if (f.type === "updates") {
      for (const it of f.data) {
        if (it.channel !== "opportunities") continue;
        if (it.action === "upsert") picks.set(it.data.id, it.data);
        if (it.action === "remove") picks.delete(it.data.id);
        if (it.action === "settle") console.log("settled", it.data.id, it.data.result);
      }
    }
    if (f.cursor) cursor = f.cursor;
  });
  ws.on("close", (code) => {
    if (stopped || code === 4401 || code === 4422) { console.error("stream stopped:", code); return; }
    if (code === 4009) cursor = null;
    setTimeout(connect, delay);
    delay = Math.min(delay * 2, 60000);
  });
  ws.on("error", () => {});        // 'close' follows and reconnects
}
connect();
export { picks };
```

## Website integration

Read the feed on your server, then send picks to the page. Never send the key to the page.

**Option A: server-rendered or PHP/WordPress (simplest).** Fetch REST on the server, cache it for
30–60 s and render HTML:

```php
<?php
// e.g. a WordPress shortcode or template part
function fo_picks(): array {
    $cached = get_transient('fo_picks');                  // or APCu / file cache
    if ($cached !== false) return $cached;
    $res = wp_remote_get('https://api.favouriteodds.com/data/v1/opportunities?limit=500', [
        'headers' => ['Authorization' => 'Bearer ' . getenv('FAVOURITEODDS_API_KEY')],
        'timeout' => 10,
    ]);
    if (is_wp_error($res) || wp_remote_retrieve_response_code($res) !== 200) return [];
    $picks = json_decode(wp_remote_retrieve_body($res), true)['data'] ?? [];
    $picks = array_values(array_filter($picks, fn($p) => strtotime($p['kickoff']) > time()));
    set_transient('fo_picks', $picks, 45);
    return $picks;
}
foreach (fo_picks() as $p) {
    printf('<div class="pick%s"><b>%s – %s</b> %s → %s @ %.2f (min %.2f, +%.1f%%) <a href="%s" rel="nofollow sponsored">%s</a></div>',
        $p['verification_status'] === 'verified' ? '' : ' rechecking',
        esc_html($p['home_team']), esc_html($p['away_team']), esc_html($p['market_label']),
        esc_html($p['selection_label']), $p['decimal_odds'], $p['min_odds'] ?? $p['decimal_odds'],
        $p['edge_pct'], esc_url($p['event_url'] ?? '#'), esc_html(ucfirst($p['source_id'])));
}
```

**Option B: live page (React/Vue/plain JS).** Run the Node client above on your server and push
the list to browsers with Server-Sent Events. Browsers support SSE natively and need no key:

```js
// server.js (Express) — reuses `picks` from the Node client above
import express from "express";
import { picks } from "./fo-stream.js";
const app = express();
const clients = new Set();
app.get("/api/picks/stream", (req, res) => {
  res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
  res.write(`data: ${JSON.stringify([...picks.values()])}\n\n`);
  clients.add(res);
  req.on("close", () => clients.delete(res));
});
setInterval(() => {                       // push the current list every 2 s
  const body = `data: ${JSON.stringify([...picks.values()])}\n\n`;
  clients.forEach((res) => res.write(body));
}, 2000);
app.listen(3000);
```

```html
<!-- browser -->
<div id="picks"></div>
<script>
  const box = document.getElementById("picks");
  new EventSource("/api/picks/stream").onmessage = (e) => {
    const picks = JSON.parse(e.data).filter((p) => new Date(p.kickoff) > new Date());
    box.replaceChildren(...picks.map((p) => {
      const el = document.createElement("div");
      el.className = p.verification_status === "verified" ? "pick" : "pick rechecking";
      el.textContent = `${p.home_team} – ${p.away_team} · ${p.selection_label} @ ${p.decimal_odds} (min ${p.min_odds ?? p.decimal_odds}, +${p.edge_pct.toFixed(1)}%) · ${p.source_id}`;
      return el;
    }));
  };
</script>
```

Update rows in place (keyed by `id`) instead of rebuilding the list if you animate changes. This
avoids flicker.

## Telegram or Discord bot

Use the WebSocket client:
- send a message on the first `upsert` of a new `id`;
- edit or delete it on `remove`;
- reply with the result on `settle`.

Do not re-post on every `upsert`, because odds updates reuse the same `id`.

## Acceptance checklist (agents: verify each item before finishing)

- [ ] The key is read from an environment variable or secret store. `git grep` finds no key, and
      the key is in no client bundle, URL or log line.
- [ ] REST: one request returns `200` with picks, and pagination is followed until
      `has_more = false`.
- [ ] Picks are stored by `id`. An upsert replaces the pick, and a remove deletes it.
- [ ] No pick is shown after its `kickoff`.
- [ ] Each pick shows the bookmaker, match, `selection_label`, `decimal_odds`, `min_odds`,
      `edge_pct` and kickoff in the user's time zone.
- [ ] `awaiting_refresh` picks look different ("re-checking"). A degraded or 503 feed keeps the
      last list, marked as not fresh.
- [ ] WebSocket (if used):
  - reconnects with backoff;
  - resumes with the saved cursor;
  - drops the cursor on `4009` / `resync_required`;
  - stops on `4401` / `4422`.
- [ ] "18+" and a responsible-gambling notice are shown next to the picks.

Support: reply to the email that delivered your key.
