API 返回每个盘口的当前赔率,且每个赔率附带上次变动的时间。API 本身不保存逐笔历史记录;如果您需要完整的变动数据,请自行存储每次请求返回的结果。
请求您需记录的比赛
将比赛放入 match_ids。如果不指定 odd_type_ids 和 odd_period_ids,响应将包含每场比赛的所有盘口和阶段。
curl -X POST https://oddfeeds.com/api/v1/feeds \
-H "Authorization: Bearer ofk_your_api_key" \
-H "Content-Type: application/json" \
-d '{"scope":"odds","match_ids":[13682297]}'const res = await fetch('https://oddfeeds.com/api/v1/feeds', {
method: 'POST',
headers: {
'Authorization': 'Bearer ofk_your_api_key',
'Content-Type': 'application/json',
},
body: JSON.stringify({"scope":"odds","match_ids":[13682297]}),
});
const feed = await res.json();import requests
res = requests.post(
'https://oddfeeds.com/api/v1/feeds',
headers={'Authorization': 'Bearer ofk_your_api_key'},
json={"scope":"odds","match_ids":[13682297]},
timeout=20,
)
feed = res.json()返回结果 · API 于 2026年11月26日 返回的结果,仅展示前几行。 实际返回结果会包含其他 ID,请在下一个请求中使用对应的 ID。
JSON 返回结果: 请求您需记录的比赛
{
"status": "ok",
"data": {
"prematch": [
{
"id": 390798263,
"active": 1,
"match_id": 13682297,
"event_id": 72533074,
"bookmaker": {
"id": 59,
"name": "Bet8"
},
"datetime": "2026-11-26T01:35:42",
"period_id": 0,
"type_id": 11,
"order": 1,
"back_lay_id": 0,
"liquidity": -1,
"hc": 0,
"hc_as_draw": 0,
"price": 1.231,
"nav": "{\"v\":1,\"scope\":\"prematch\",\"eventId\":\"18450709\",\"oddId\":\"4..."
},
{
"id": 390634623,
"active": 1,
"match_id": 13682297,
"event_id": 72531615,
"bookmaker": {
"id": 34,
"name": "Trbet"
},
"datetime": "2026-11-26T01:36:24",
"period_id": 0,
"type_id": 9,
"order": 1,
"back_lay_id": 0,
"liquidity": -1,
"hc": 2,
"hc_as_draw": 0,
"price": 1.14,
"nav": "{\"v\":1,\"scope\":\"prematch\",\"eventId\":\"42575268\",\"oddId\":\"7..."
}
],
"inplay": []
},
"time": "2026-11-26T15:28:39",
"ms": "14.74ms"
}
每次变动保存一行
每个赔率都是一行数据,带有唯一的 id。当该 id 的 price 或 datetime 与上次写入的记录不同时,写入新的一行:即每次变动保存一行。
从数据源中移除的赔率
响应中不再出现的赔率表示已封盘或关闭。在 odds_seen 中查询其 id 并记录其 closed 时间。
curl -X POST https://oddfeeds.com/api/v1/feeds \
-H "Authorization: Bearer ofk_your_api_key" \
-H "Content-Type: application/json" \
-d '{"scope":"odds_seen","odd_ids":[390798263,390634623,400751435]}'const res = await fetch('https://oddfeeds.com/api/v1/feeds', {
method: 'POST',
headers: {
'Authorization': 'Bearer ofk_your_api_key',
'Content-Type': 'application/json',
},
body: JSON.stringify({"scope":"odds_seen","odd_ids":[390798263,390634623,400751435]}),
});
const feed = await res.json();import requests
res = requests.post(
'https://oddfeeds.com/api/v1/feeds',
headers={'Authorization': 'Bearer ofk_your_api_key'},
json={"scope":"odds_seen","odd_ids":[390798263,390634623,400751435]},
timeout=20,
)
feed = res.json()返回结果 · API 于 2026年11月26日 返回的结果,仅展示前几行。
JSON 返回结果: 从数据源中移除的赔率
{
"status": "ok",
"data": [
{
"id": 390798263,
"open": "2026-11-26T01:35:42",
"seen": "2026-11-26T15:28:15",
"closed": ""
},
{
"id": 390634623,
"open": "2026-11-26T01:36:24",
"seen": "2026-11-26T15:27:23",
"closed": ""
}
],
"time": "2026-11-26T15:29:36",
"ms": "55us"
}
轮询成本说明
每次轮询都会消耗 API 密钥配额,且较长的比赛列表会计为多次请求(详见下表)。请按需轮询,切勿过度:频率翻倍将消耗双倍请求量。密钥配额详情参见 服务页面。当拒绝响应的 Retry-After 要求等待超过一小时,下方脚本将停止运行并打印 API 原始消息,而非继续等待。
| HTTP 状态码 | 含义 |
|---|---|
429 | Rate limit exceeded, 8 requests of your key already being answered, a Free key's requests for the month used up (until the 1st of the next month, UTC; the error field names the plans), Free keys busy together, or the service busy for a few seconds; check Retry-After and slow down. Retry-After: the seconds to wait before asking again, at most a day; the message names the day the month renews. Long id lists count as several requests against your per-minute limit: an odds request counts once for every 25 match ids, any other id list once for every 100 ids, and the counts multiply. One request can count as at most 40, and never as more than your key's limit for a minute. |
轮询可能遗漏的数据
单次轮询仅能获取请求时的赔率状态。若赔率在两次轮询之间变动了两次,将仅显示最新数值,而 datetime 会指出最后一次变动的时间。因此,两次请求之间发生的变化可能会遗漏。
完整轮询脚本
该脚本轮询您指定的比赛,将每次变动以 JSON 格式按行追加到文件,并记录从响应中移除的赔率的关闭时间。它从 ODDFEEDS_KEY 读取密钥,默认每分钟请求一次(可通过 ODDFEEDS_EVERY 调整)。
// Keep your own history: ask for the prices of some matches every EVERY_S seconds and
// append one JSON line per change you saw to a file. Stop it with Ctrl+C.
// ODDFEEDS_KEY=<your key> node your-own-history.mjs <file> <match id> ...
import { appendFileSync } from 'fs';
const API = process.env.ODDFEEDS_URL || 'https://oddfeeds.com/api/v1/feeds';
const [file, ...ids] = process.argv.slice(2);
const matchIds = ids.map(Number);
const EVERY_S = Number(process.env.ODDFEEDS_EVERY || 60); // as often as you need
const ROUNDS = Number(process.env.ODDFEEDS_ROUNDS || Infinity);
const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000));
const write = (line) => appendFileSync(file, `${JSON.stringify(line)}\n`);
const MAX_WAIT_S = 3600; // a longer Retry-After ends the program
// The seconds a 429 or 5xx asks to wait: Retry-After in seconds or as a date;
// anything else (none, 0, a date gone by, text) gets our own wait, longer each time.
function waitOf(res, wait) {
const v = (res.headers.get('Retry-After') || '').trim();
const s = /^\d+$/.test(v) ? Number(v) : Math.ceil((Date.parse(v) - Date.now()) / 1000);
return s >= 1 ? s : wait;
}
// One request; on 429 it waits the seconds of Retry-After, on a 5xx longer each time.
async function ask(body) {
for (let wait = 2; ; wait = Math.min(wait * 2, 60)) {
const res = await fetch(API, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ODDFEEDS_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
if (res.status === 429 || res.status >= 500) {
const s = waitOf(res, wait);
if (s > MAX_WAIT_S) {
const why = await res.json().then((f) => f.error, () => null);
throw new Error(`${res.status}: ${why || `retry after ${s} s`}`);
}
console.log(`${res.status}: waiting ${s} s`);
await sleep(s);
continue;
}
const feed = await res.json();
if (feed.status !== 'ok') throw new Error(`${res.status}: ${feed.error}`);
return feed;
}
}
const last = new Map(); // odd id -> price and datetime of the last line written for it
for (let round = 1; round <= ROUNDS; round++) {
const odds = await ask({ scope: 'odds', match_ids: matchIds });
const rows = [...odds.data.prematch, ...odds.data.inplay];
const polled = new Date().toISOString();
let lines = 0;
for (const r of rows) {
const now = `${r.price}|${r.datetime}`;
if (last.get(r.id) === now) continue;
last.set(r.id, now);
write({
id: r.id, match_id: r.match_id, bookmaker: r.bookmaker.name,
type_id: r.type_id, period_id: r.period_id, hc: r.hc,
back_lay_id: r.back_lay_id, order: r.order,
price: r.price, datetime: r.datetime, polled,
});
lines++;
}
// A price that left the answer was suspended or closed: keep when it closed.
const here = new Set(rows.map((r) => r.id));
const gone = [...last.keys()].filter((id) => !here.has(id));
for (let i = 0; i < gone.length; i += 500) {
const seen = await ask({ scope: 'odds_seen', odd_ids: gone.slice(i, i + 500) });
for (const s of seen.data) write({ id: s.id, closed: s.closed, polled });
}
for (const id of gone) last.delete(id);
console.log(`Round ${round}: ${rows.length} prices, ${lines} lines written`);
if (round < ROUNDS) await sleep(EVERY_S);
}# Keep your own history: ask for the prices of some matches every EVERY_S seconds and
# append one JSON line per change you saw to a file. Stop it with Ctrl+C.
# ODDFEEDS_KEY=<your key> python your-own-history.py <file> <match id> ...
import json
import math
import os
import re
import sys
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import requests
API = os.environ.get('ODDFEEDS_URL', 'https://oddfeeds.com/api/v1/feeds')
file = sys.argv[1]
match_ids = [int(x) for x in sys.argv[2:]]
EVERY_S = float(os.environ.get('ODDFEEDS_EVERY', 60)) # as often as you need
ROUNDS = float(os.environ.get('ODDFEEDS_ROUNDS', 'inf'))
MAX_WAIT_S = 3600 # a longer Retry-After ends the program
def wait_of(res, wait):
"""The seconds a 429 or 5xx asks to wait: Retry-After in seconds or as a date;
anything else (none, 0, a date gone by, text) gets our own wait, longer each time."""
v = res.headers.get('Retry-After', '').strip()
if re.fullmatch(r'[0-9]+', v):
s = float(v)
else:
try:
at = parsedate_to_datetime(v)
if at.tzinfo is None:
at = at.replace(tzinfo=timezone.utc)
s = math.ceil((at - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError):
s = 0
return s if s >= 1 else wait
def write(line):
with open(file, 'a') as f:
f.write(json.dumps(line) + '\n')
def ask(body):
"""One request; on 429 it waits the seconds of Retry-After, on a 5xx longer."""
wait = 2
while True:
res = requests.post(
API,
headers={'Authorization': f"Bearer {os.environ['ODDFEEDS_KEY']}"},
json=body,
timeout=20,
)
if res.status_code == 429 or res.status_code >= 500:
s = wait_of(res, wait)
if s > MAX_WAIT_S:
try:
why = res.json().get('error')
except ValueError:
why = None
raise RuntimeError(f"{res.status_code}: {why or f'retry after {s:g} s'}")
print(f"{res.status_code}: waiting {s:g} s", flush=True)
time.sleep(s)
wait = min(wait * 2, 60)
continue
feed = res.json()
if feed['status'] != 'ok':
raise RuntimeError(f"{res.status_code}: {feed['error']}")
return feed
last = {} # odd id -> price and datetime of the last line written for it
round_no = 1
while round_no <= ROUNDS:
odds = ask({'scope': 'odds', 'match_ids': match_ids})
rows = odds['data']['prematch'] + odds['data']['inplay']
polled = datetime.now(timezone.utc).isoformat()
lines = 0
for r in rows:
now = (r['price'], r['datetime'])
if last.get(r['id']) == now:
continue
last[r['id']] = now
write({'id': r['id'], 'match_id': r['match_id'],
'bookmaker': r['bookmaker']['name'],
'type_id': r['type_id'], 'period_id': r['period_id'], 'hc': r['hc'],
'back_lay_id': r['back_lay_id'], 'order': r['order'],
'price': r['price'], 'datetime': r['datetime'], 'polled': polled})
lines += 1
# A price that left the answer was suspended or closed: keep when it closed.
here = {r['id'] for r in rows}
gone = [i for i in last if i not in here]
for i in range(0, len(gone), 500):
seen = ask({'scope': 'odds_seen', 'odd_ids': gone[i:i + 500]})
for s in seen['data']:
write({'id': s['id'], 'closed': s['closed'], 'polled': polled})
for i in gone:
del last[i]
print(f"Round {round_no}: {len(rows)} prices, {lines} lines written", flush=True)
if round_no < ROUNDS:
time.sleep(EVERY_S)
round_no += 1下一步
博彩模型应用场景 介绍了量化模型还可以从 API 读取哪些数据。