Compare commits

...

1 Commits

Author SHA1 Message Date
codex-bot 2c114e81d9 Add Gamma series catalog and event membership 2026-12-05 22:08:25 +08:00
13 changed files with 476 additions and 3 deletions
+20
View File
@@ -11,6 +11,26 @@ flowchart LR
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
main -.->|打开数据库| api["exchange crate"]
stream -.->|执行命令| api
market_http["src/market_http.rs"] -.->|读取系列与赛事目录| api
```
## Gamma 系列
依次重放[足球样例](../../docs/examples/football.jsonl)和[系列样例](../../docs/examples/gamma-series.jsonl)。`GET /series/101` 返回「模拟杯赛」和两场比赛的摘要。加 `exclude_events=true` 的系列列表可只取目录元数据。要看开放比赛的比分盘与进球数盘,查询 `GET /events?series_slug=demo-cup&closed=false`。
```mermaid
sequenceDiagram
actor C as 客户端
participant H as market_http.rs
participant E as Exchange
C->>H: GET /series?slug=demo-cup&exclude_events=true
H->>E: 查询系列目录
E-->>H: demo-cup 和数字字符串 ID 101
H-->>C: 系列列表
C->>H: GET /events?series_id=101&closed=false
H->>E: 查询系列的开放赛事及其盘口
E-->>H: 开放赛事目录
H-->>C: 赛事列表
```
## 一次命令会话
+82
View File
@@ -323,6 +323,40 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
Ok(Value::Array(rows))
}
fn series_response(engine: &Mutex<Exchange>, id: Option<&str>, query: &str) -> (u16, Value) {
let Ok(exchange) = engine.lock() else {
return (500, json!({"error":"Directory unavailable"}));
};
if let Some(id) = id {
let Ok(id) = id.parse::<i64>() else {
return (
422,
json!({"type":"validation error","error":"Invalid series id"}),
);
};
return match exchange.gamma_series_detail(id) {
Ok(Some(value)) => (200, value),
Ok(None) => (
404,
json!({"type":"not found error","error":"id not found"}),
),
Err(_) => (500, json!({"error":"Directory unavailable"})),
};
}
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query)
.map_err(|_| exchange::MarketDataError::Invalid("Invalid series query".into()))
.and_then(|fields| exchange.gamma_series(&fields));
match result {
Ok(rows) => (200, Value::Array(rows)),
Err(exchange::MarketDataError::Invalid(error)) => {
(422, json!({"type":"validation error","error":error}))
}
Err(exchange::MarketDataError::Unavailable) => {
(500, json!({"error":"Directory unavailable"}))
}
}
}
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
let mut allow = None;
@@ -335,6 +369,16 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
let (status, body) = data_page(path, params, engine);
return send(req, status, body, None);
}
let series_id = path
.strip_prefix("/series/")
.filter(|id| !id.is_empty() && !id.contains('/'));
if path == "/series" || series_id.is_some() {
if req.method() != &Method::Get {
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
}
let (status, body) = series_response(engine, series_id, params);
return send(req, status, body, None);
}
let route = path.strip_prefix('/').unwrap_or(path);
let (name, segment) = route
.split_once('/')
@@ -683,6 +727,32 @@ mod tests {
.unwrap()
.unwrap();
assert_eq!(separate["events"], json!([]));
for example in [
include_str!("../../../docs/examples/football.jsonl"),
include_str!("../../../docs/examples/gamma-series.jsonl"),
] {
for line in example.lines() {
db.execute(serde_json::from_str(line).unwrap()).unwrap();
}
}
assert!(db
.execute(json!({"op":"set_event_series","id":"series-bad-fk",
"event":"cup-a-b","series_ids":[999]}))
.is_err());
let series = db.gamma_series_detail(101).unwrap().unwrap();
let sports_event = db
.gamma_event(exchange::DirectoryKey::Slug("cup-a-b"))
.unwrap()
.unwrap();
assert_eq!(series["events"].as_array().unwrap().len(), 2);
assert_eq!(series["events"][1]["closed"], true);
assert_eq!(series["closed"], false);
assert!(series["events"][0].get("markets").is_none());
assert!(series["events"][0].get("series").is_none());
assert_eq!(sports_event["seriesSlug"], "demo-cup");
assert_eq!(sports_event["series"][1]["id"], "102");
let mut series_header = series.clone();
series_header.as_object_mut().unwrap().remove("events");
let quoted = db
.gamma_market(exchange::DirectoryKey::Slug("s"))
.unwrap()
@@ -729,6 +799,18 @@ mod tests {
("GET","/markets/slug/missing",String::new(),404,None),
("GET","/events/999999",String::new(),404,None),
("POST","/events/slug/test","{}".into(),405,None),
("GET","/series/101",String::new(),200,Some(series.clone())),
("GET","/series?slug=demo-cup&limit=0",String::new(),200,Some(json!([series]))),
("GET","/series?slug=demo-cup&slug=demo-featured&closed=false&recurrence=daily&exclude_events=true",String::new(),200,Some(json!([series_header]))),
("GET","/series?slug=demo-cup&offset=1",String::new(),200,Some(json!([]))),
("GET","/series?slug=missing",String::new(),200,Some(json!([]))),
("GET","/series/999",String::new(),404,None),
("GET","/series/invalid",String::new(),422,None),
("GET","/series?order=unknown",String::new(),422,None),
("POST","/series/101",String::new(),405,None),
("GET","/events?series_id=101&series_slug=demo-cup&closed=false",String::new(),200,Some(json!([sports_event.clone()]))),
("GET","/events?series_slug=demo-featured",String::new(),200,Some(json!([sports_event]))),
("GET","/events?series_id=101&series_slug=missing",String::new(),200,Some(json!([]))),
("GET","/market-clarifications?event_id=1&event_id=2",String::new(),200,Some(json!([]))),
("GET","/market-clarifications?event_id=0",String::new(),400,None),
("GET",note_query.as_str(),String::new(),200,Some(note)),
+24
View File
@@ -15,6 +15,12 @@ flowchart LR
queries -->|生成目录中的结果资产| assets
acct -->|回传订单的资产 ID| assets
portfolio -->|回传持仓的资产 ID| assets
api -->|迁移系列目录| series_sql["src/gamma_series.sql"]
market -->|登记系列及赛事归属| series["src/gamma_series.rs"]
series --> series_sql
series -->|复用赛事摘要| series_directory["src/gamma_directory.rs"]
series_directory -->|读取赛事及所属系列| series_events["src/gamma_events.sql"]
series_events --> series_sql
queries -->|按市场或全站查未平仓量| oi["src/open_interest.rs"]
oi -->|查各结果总份额| oisql["src/open_interest.sql"]
oisql -->|可用及挂卖份额| markschema
@@ -223,6 +229,24 @@ sequenceDiagram
E-->>C: 已退出的份额移入 CLOSED,可领取金额归零
```
## Gamma 系列与赛事
```mermaid
sequenceDiagram
actor O as 操作员
participant E as Exchange
participant D as SQLite
actor C as 目录客户端
O->>E: 注册系列和状态,再分配赛事归属
E->>D: 以事务保存系列或替换有序归属
C->>E: GET /series/101
E->>D: 在同一个读快照查系列和赛事状态
E-->>C: 系列元数据及赛事摘要
C->>E: GET /events?series_slug=demo-cup&closed=false
E->>D: 先按系列和赛事状态筛选,再分页
E-->>C: 开放赛事、各赛事的盘口和所属系列
```
## GTD 到期
```mermaid
+7
View File
@@ -21,6 +21,13 @@ pub(crate) enum Command {
active: bool,
archived: bool,
},
#[serde(rename = "upsert_series")]
UpsertSeries(crate::gamma_series::Series),
#[serde(rename = "set_event_series")]
SetEventSeries {
event: String,
series_ids: Vec<i64>,
},
#[serde(rename = "tick_size_change")]
TickSizeChange(crate::tick_changes::Change),
List {
+5 -1
View File
@@ -15,11 +15,15 @@ pub enum DirectoryKey<'a> {
pub(super) fn header(row: &Row<'_>) -> rusqlite::Result<(String, Value)> {
let key = row.get("id")?;
let event = json!({
let mut event = json!({
"id":row.get::<_,i64>("event_id")?.to_string(),"slug":row.get::<_,String>("slug")?,
"title":row.get::<_,String>("title")?,"category":row.get::<_,String>("category")?,
"active":true,"closed":row.get::<_,bool>("closed")?
});
if let Some(slug) = row.get::<_, Option<String>>("series_slug")? {
event["seriesSlug"] = json!(slug);
event["series"] = crate::gamma_series::parse_wire(row.get("series")?)?;
}
Ok((key, event))
}
+6
View File
@@ -1,4 +1,10 @@
SELECT e.id,e.event_id,e.slug,e.title,e.category,
(SELECT s.slug FROM series_events a JOIN directory_series s ON s.id=a.series
WHERE a.event=e.id ORDER BY a.position LIMIT 1) AS series_slug,
(SELECT json_group_array(json(wire)) FROM (
SELECT s.wire FROM series_events a JOIN directory_series_wire s ON s.id=a.series
WHERE a.event=e.id ORDER BY a.position
)) AS series,
COALESCE((
SELECT MIN(m.phase NOT IN ('preopen','continuous'))
FROM markets m LEFT JOIN augmented_outcomes a ON a.market=m.id
+23 -2
View File
@@ -25,6 +25,8 @@ struct Filters {
ascending: bool,
limit: i64,
offset: i64,
series_id: Option<i64>,
series_slug: Option<String>,
}
fn invalid(field: &str) -> MarketDataError {
@@ -69,6 +71,18 @@ impl Filters {
.filter(|n| *n > 0)
.ok_or_else(|| invalid(key))?,
),
"series_id" if !markets => {
f.series_id = Some(
value
.parse::<i64>()
.ok()
.filter(|id| *id > 0)
.ok_or_else(|| invalid(key))?,
);
}
"series_slug" if !markets && !value.trim().is_empty() => {
f.series_slug = Some(value.clone());
}
"slug" if !value.trim().is_empty() => f.slugs.push(value.clone()),
"condition_ids" if markets && !value.trim().is_empty() => {
f.conditions.push(value.clone())
@@ -132,7 +146,13 @@ const MARKET_FILTER: &str = "
AND (?5 IS NULL OR (m.phase NOT IN ('preopen','continuous'))=?5)
AND (?8 IS NULL OR COALESCE(v.active,1)=?8)";
const EVENT_FILTER: &str = "
WHERE (?1='[]' OR e.event_id IN (SELECT value FROM json_each(?1)))
WHERE (json_extract(?1,'$.ids')='[]' OR e.event_id IN (SELECT value FROM json_each(?1,'$.ids')))
AND ((json_extract(?1,'$.series_id') IS NULL AND json_extract(?1,'$.series_slug') IS NULL) OR EXISTS(
SELECT 1 FROM series_events a JOIN directory_series s ON s.id=a.series
WHERE a.event=e.id
AND s.id=COALESCE(json_extract(?1,'$.series_id'),s.id)
AND s.slug=COALESCE(json_extract(?1,'$.series_slug'),s.slug)
))
AND (?2='[]' OR e.slug IN (SELECT value FROM json_each(?2)))
AND (?3 IS NULL OR e.closed=?3)";
@@ -196,7 +216,8 @@ fn events(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Val
let rows = stmt
.query_map(
params![
json!(f.ids).to_string(),
json!({"ids":f.ids,"series_id":f.series_id,"series_slug":f.series_slug})
.to_string(),
json!(f.slugs).to_string(),
f.closed,
f.limit,
+245
View File
@@ -0,0 +1,245 @@
use crate::{gamma_directory::header, validation::identifier, Exchange, MarketDataError};
use anyhow::{ensure, Result};
use rusqlite::{params, Connection, Transaction};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Series {
series_id: i64,
slug: String,
ticker: Option<String>,
title: String,
series_type: Option<String>,
recurrence: Option<String>,
description: Option<String>,
image: Option<String>,
icon: Option<String>,
layout: Option<String>,
active: Option<bool>,
closed: Option<bool>,
archived: Option<bool>,
}
impl Series {
pub(crate) fn save(self, tx: &Transaction) -> Result<Value> {
ensure!(self.series_id > 0, "invalid series id");
identifier(&self.slug)?;
identifier(&self.title)?;
let ticker = self.ticker.as_deref().unwrap_or(&self.slug);
identifier(ticker)?;
let series_type = self.series_type.as_deref().unwrap_or("single");
identifier(series_type)?;
if let Some(recurrence) = &self.recurrence {
identifier(recurrence)?;
}
tx.execute(
"INSERT INTO directory_series(
id,slug,ticker,title,series_type,recurrence,description,image,icon,layout,
active,closed,archived,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,
strftime('%Y-%m-%dT%H:%M:%fZ','now'),strftime('%Y-%m-%dT%H:%M:%fZ','now'))
ON CONFLICT(id) DO UPDATE SET slug=excluded.slug,ticker=excluded.ticker,
title=excluded.title,series_type=excluded.series_type,recurrence=excluded.recurrence,
description=excluded.description,image=excluded.image,icon=excluded.icon,
layout=excluded.layout,active=excluded.active,closed=excluded.closed,
archived=excluded.archived,updated_at=excluded.updated_at",
params![
self.series_id, self.slug, ticker, self.title, series_type, self.recurrence,
self.description, self.image, self.icon, self.layout, self.active.unwrap_or(true),
self.closed.unwrap_or(false), self.archived.unwrap_or(false)
],
)?;
Ok(json!({"series_id":self.series_id.to_string()}))
}
}
pub(crate) fn assign(tx: &Transaction, event: &str, series: &[i64]) -> Result<Value> {
identifier(event)?;
ensure!(
tx.query_row(
"SELECT EXISTS(SELECT 1 FROM event_directory_ids WHERE event=?)",
[event],
|r| r.get::<_, bool>(0)
)?,
"series event not found"
);
ensure!(
series.iter().all(|id| *id > 0)
&& series.iter().collect::<HashSet<_>>().len() == series.len(),
"series ids must be positive and unique"
);
tx.execute("DELETE FROM series_events WHERE event=?", [event])?;
let mut stmt = tx.prepare_cached("INSERT INTO series_events VALUES(?,?,?)")?;
for (position, id) in series.iter().enumerate() {
stmt.execute(params![id, event, position as i64])?;
}
Ok(json!({"event":event,"series_ids":series}))
}
pub(super) fn parse_wire(raw: String) -> rusqlite::Result<Value> {
serde_json::from_str(&raw).map_err(|error| {
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(error))
})
}
fn invalid(field: &str) -> MarketDataError {
MarketDataError::Invalid(format!("Invalid series parameter: {field}"))
}
#[derive(Default)]
struct SeriesQuery {
slugs: Vec<String>,
recurrence: Option<String>,
closed: Option<bool>,
order: Option<String>,
ascending: Option<bool>,
limit: i64,
offset: i64,
exclude_events: bool,
}
impl SeriesQuery {
fn parse(fields: &[(String, String)]) -> Result<Self, MarketDataError> {
let mut query = Self::default();
for (key, value) in fields {
match key.as_str() {
"slug" if !value.trim().is_empty() => query.slugs.push(value.clone()),
"recurrence" if !value.trim().is_empty() => query.recurrence = Some(value.clone()),
"closed" => query.closed = Some(value.parse().map_err(|_| invalid(key))?),
"ascending" => query.ascending = Some(value.parse().map_err(|_| invalid(key))?),
"exclude_events" => {
query.exclude_events = value.parse().map_err(|_| invalid(key))?
}
"order" => query.order = Some(value.clone()),
"limit" | "offset" => {
let n = value
.parse::<i64>()
.ok()
.filter(|n| *n >= 0)
.ok_or_else(|| invalid(key))?;
if key == "limit" {
query.limit = n;
} else {
query.offset = n;
}
}
_ => return Err(invalid(key)),
}
}
query.limit = if query.limit == 0 {
20
} else {
query.limit.min(50)
};
Ok(query)
}
fn sort(&self) -> Result<String, MarketDataError> {
let Some(order) = &self.order else {
return Ok("id ASC".into());
};
let mut columns = Vec::new();
for field in order.split(',').map(str::trim) {
columns.push(match field {
"id" => "id",
"title" => "title",
"slug" => "slug",
"recurrence" => "recurrence",
"createdAt" => "created_at",
"updatedAt" => "updated_at",
_ => return Err(invalid("order")),
});
}
if !columns.contains(&"id") {
columns.push("id");
}
let direction = if self.ascending.unwrap_or(true) {
"ASC"
} else {
"DESC"
};
Ok(columns
.iter()
.map(|column| format!("{column} {direction}"))
.collect::<Vec<_>>()
.join(", "))
}
}
fn expand_events(db: &Connection, series: &mut [(i64, Value)]) -> rusqlite::Result<()> {
if series.is_empty() {
return Ok(());
}
let keys = series.iter().map(|(id, _)| id).collect::<Vec<_>>();
let mut children: HashMap<i64, Vec<Value>> = HashMap::new();
let mut stmt = db.prepare_cached(concat!(
"SELECT s.series,e.* FROM (",
include_str!("gamma_events.sql"),
") e
JOIN series_events s ON s.event=e.id
WHERE s.series IN (SELECT value FROM json_each(?))
ORDER BY s.series,e.event_id",
))?;
let mut rows = stmt.query([json!(keys).to_string()])?;
while let Some(row) = rows.next()? {
let (_, mut event) = header(row)?;
// Series summaries have the primary slug without a recursively embedded series array.
if let Some(object) = event.as_object_mut() {
object.remove("series");
}
children.entry(row.get(0)?).or_default().push(event);
}
for (id, item) in series {
item["events"] = Value::Array(children.remove(id).unwrap_or_default());
}
Ok(())
}
impl Exchange {
pub fn gamma_series(&self, fields: &[(String, String)]) -> Result<Vec<Value>, MarketDataError> {
let q = SeriesQuery::parse(fields)?;
let order = q.sort()?;
let tx = self.db.unchecked_transaction()?;
let sql = format!(
"SELECT id,wire FROM directory_series_wire
WHERE (?1='[]' OR slug IN (SELECT value FROM json_each(?1)))
AND (?2 IS NULL OR recurrence=?2) AND (?3 IS NULL OR closed=?3)
ORDER BY {order} LIMIT ?4 OFFSET ?5",
);
let mut rows = {
let mut stmt = tx.prepare_cached(&sql)?;
let mapped = stmt.query_map(
params![
json!(q.slugs).to_string(),
q.recurrence,
q.closed,
q.limit,
q.offset
],
|r| Ok((r.get(0)?, parse_wire(r.get(1)?)?)),
)?;
mapped.collect::<rusqlite::Result<Vec<_>>>()?
};
if !q.exclude_events {
expand_events(&tx, &mut rows)?;
}
tx.commit()?;
Ok(rows.into_iter().map(|(_, wire)| wire).collect())
}
pub fn gamma_series_detail(&self, id: i64) -> Result<Option<Value>, MarketDataError> {
let tx = self.db.unchecked_transaction()?;
let mut rows = {
let mut stmt =
tx.prepare_cached("SELECT id,wire FROM directory_series_wire WHERE id=?")?;
let mapped = stmt.query_map([id], |r| Ok((r.get(0)?, parse_wire(r.get(1)?)?)))?;
mapped.collect::<rusqlite::Result<Vec<_>>>()?
};
expand_events(&tx, &mut rows)?;
tx.commit()?;
Ok(rows.pop().map(|(_, wire)| wire))
}
}
+38
View File
@@ -0,0 +1,38 @@
BEGIN IMMEDIATE;
CREATE TABLE IF NOT EXISTS directory_series (
id INTEGER PRIMARY KEY CHECK(id>0),
slug TEXT NOT NULL UNIQUE,
ticker TEXT NOT NULL,
title TEXT NOT NULL,
series_type TEXT NOT NULL,
recurrence TEXT,
description TEXT,
image TEXT,
icon TEXT,
layout TEXT,
active INTEGER NOT NULL CHECK(active IN (0,1)),
closed INTEGER NOT NULL CHECK(closed IN (0,1)),
archived INTEGER NOT NULL CHECK(archived IN (0,1)),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS series_events (
series INTEGER NOT NULL REFERENCES directory_series(id),
event TEXT NOT NULL REFERENCES event_directory_ids(event),
position INTEGER NOT NULL,
PRIMARY KEY(series,event),
UNIQUE(event,position)
);
CREATE VIEW IF NOT EXISTS directory_series_wire AS
SELECT id,slug,title,closed,recurrence,created_at,updated_at,
json_patch(
json_object('id',CAST(id AS TEXT),'slug',slug,'ticker',ticker,'title',title,
'seriesType',series_type,'active',json(iif(active,'true','false')),
'closed',json(iif(closed,'true','false')),
'archived',json(iif(archived,'true','false')),
'createdAt',created_at,'updatedAt',updated_at),
json_object('recurrence',recurrence,'description',description,'image',image,'icon',icon,
'layout',layout)
) AS wire
FROM directory_series;
COMMIT;
+9
View File
@@ -8,6 +8,8 @@ mod depth_feed;
mod estimate;
mod expiry;
mod fees;
mod gamma_series;
mod gamma_directory;
mod gamma_list;
mod heartbeat;
@@ -153,6 +155,13 @@ impl Exchange {
if !lifecycle_ready {
db.execute_batch(include_str!("lifecycle_schema.sql"))?;
}
let series_ready: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='view' AND name='directory_series_wire')",
[], |r| r.get(0),
)?;
if !series_ready {
db.execute_batch(include_str!("gamma_series.sql"))?;
}
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
let books = Books::recover(&tx)?;
tx.commit()?;
+4
View File
@@ -43,6 +43,10 @@ pub(crate) fn apply(
}
Ok(receipt)
}
Command::UpsertSeries(series) => series.save(tx),
Command::SetEventSeries { event, series_ids } => {
crate::gamma_series::assign(tx, &event, &series_ids)
}
Command::SetMarketVisibility {
market,
active,
+7
View File
@@ -0,0 +1,7 @@
{"op":"upsert_series","id":"series-cup","series_id":101,"slug":"demo-cup","title":"模拟杯赛","recurrence":"daily"}
{"op":"upsert_series","id":"series-featured","series_id":102,"slug":"demo-featured","title":"往期焦点","recurrence":"weekly","closed":true,"archived":true}
{"op":"event","id":"series-second-event","event":"cup-c-d","title":"C 对 D","sport":"soccer","competition":"模拟杯赛","home":"C","away":"D","scheduled_at_ms":1800003600000}
{"op":"list","id":"series-second-list","market":"cup-c-d-over","rules":"常规时间总进球至少 3 个时 YES。","listing":{"event":"cup-c-d","question":"总进球是否超过 2.5?","yes_label":"Over 2.5","no_label":"Under 2.5","terms":{"period":"match","proposition":{"kind":"total_goals","over_half_units":5}},"source":"模拟终场报告","resolver":"赛事裁决员","rules_version":1}}
{"op":"close","id":"series-second-close","market":"cup-c-d-over"}
{"op":"set_event_series","id":"series-link-first","event":"cup-a-b","series_ids":[101,102]}
{"op":"set_event_series","id":"series-link-second","event":"cup-c-d","series_ids":[101]}
+6
View File
@@ -399,6 +399,12 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
本地支持 `/events/{id}`、`/events/slug/{slug}`、`/markets/{id}` 和 `/markets/slug/{slug}`。每次读取在同一 SQLite 快照组装目录、规则、当前价格和父子关系。主题盘口沿用运营方指定的顺序,未命名的预留选项在命名后才对外显示。独立盘口的 events 为空。conditionId、目录 ID 和两侧资产 ID 来自本地上架记录。目录标记 acceptingOrders 涵盖可接收限价单的盘前和连续交易阶段。无可用价格时返回 null。已裁决盘的 outcomePrices 使用兑付比例,作废盘为 0.5 和 0.5。标签展开、图像、链上标识和完整生产字段覆盖仍待对照。
### Gamma 系列与赛事归属
生产 `/series/1` 与 `/series?slug=nfl` 均返回 NFL,ID 为字符串 `"1"`。系列仍开放,返回的子赛事中已有关闭的比赛。系列内的赛事为摘要,带 `seriesSlug`,省略盘口与所属系列数组。查 `/events?series_id=1` 和 `/events?series_slug=nfl` 时,观察到相同的前三场比赛,事件中同时含 `series` 和 `seriesSlug`。系列列表按重复的 slug 参数匹配多个系列,支持 `closed`、`recurrence` 和 `exclude_events`。生产的 `limit=0` 样本返回 20 个系列,`limit=500&exclude_events=true` 返回 50 个。未知系列的详情返回 404,列表筛选返回空数组。[生产 NFL 系列](https://gamma-api.polymarket.com/series/1) · [列表规范](https://docs.polymarket.com/api-reference/series/list-series)
本地系列有独立的开放、关闭和归档状态。赛事可以有多个有序归属,第一个对应 `seriesSlug`。重放[足球样例](examples/football.jsonl)和[系列样例](examples/gamma-series.jsonl)后,`/series/101` 返回开放系列和两场赛事,其中 C 对 D 已关闭。系列页按本地赛事编号返回已登记成员,赛事列表按系列和比赛状态筛选。生产系列内嵌赛事的选取窗口及排序仍待核对。分类筛选、聊天和生产统计字段待实现。
### Gamma 列表发现与封盘筛选
本地 GET /markets 默认仅返回可接单的市场,GET /events 默认包含开放和已关闭事件。两者均支持 closed=true、false 或大小写不敏感的 any。市场列表中 any 必须与标识一起使用。每种受支持的市场标识最多传 100 个值。无标识使用 any 或无效 closed 值返回 HTTP 422。生产无筛选市场列表已读取;上述默认值和校验来自官方接口文档,组合筛选尚缺生产响应对照。[市场列表](https://docs.polymarket.com/api-reference/markets/list-markets) · [事件列表](https://docs.polymarket.com/api-reference/events/list-events) · [生产目录](https://gamma-api.polymarket.com/markets?limit=1)