Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f991e4641 | ||
|
|
c537944241 |
No files matched your search
+2
-18
@@ -8,7 +8,6 @@
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
market_http["src/market_http.rs"] -.->|执行公开目录搜索| api
|
||||
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
|
||||
main -.->|打开数据库| api["exchange crate"]
|
||||
stream -.->|执行命令| api
|
||||
@@ -339,22 +338,7 @@ sequenceDiagram
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### Gamma 搜索
|
||||
|
||||
重放[搜索样例](../../docs/examples/gamma-search.jsonl)后,`GET /public-search?q=North+Cup&limit_per_type=1&page=1&search_profiles=true` 返回第一场比赛及公开资料。把页码改为 2 可取下一场比赛。以「前十分钟」为关键词,会从盘口问题找到父事件。加 `optimized=true` 获取精简响应。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /public-search,传关键词和页码
|
||||
H->>E: 解码参数并查询公开目录
|
||||
E-->>H: 当页事件和盘口,按需附上公开资料
|
||||
H-->>C: JSON 搜索结果
|
||||
```
|
||||
|
||||
## 查询持仓价值
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
@@ -436,7 +420,7 @@ sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /neg-risk?token_id=eb%3ANO%3Aa
|
||||
C->>H: GET /neg-risk/{token_id} 或 /neg-risk?token_id=…
|
||||
H->>E: 查询市场 a 的成员关系
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
|
||||
@@ -200,9 +200,17 @@ fn token_setting(
|
||||
.token_id
|
||||
.into(),
|
||||
};
|
||||
if token.trim().is_empty() {
|
||||
return Err(invalid);
|
||||
}
|
||||
let missing = if name == "fee-rate" {
|
||||
(404, "fee rate not found for market")
|
||||
} else {
|
||||
(404, "market not found")
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
|
||||
let unavailable = |e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => invalid,
|
||||
exchange::MarketDataError::Invalid(_) => missing,
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
};
|
||||
match name {
|
||||
@@ -210,21 +218,21 @@ fn token_setting(
|
||||
let flag = exchange
|
||||
.token_neg_risk(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "market not found"))?;
|
||||
.ok_or(missing)?;
|
||||
Ok(json!({"neg_risk":flag}))
|
||||
}
|
||||
"fee-rate" => {
|
||||
let fee = exchange
|
||||
.base_fee_bps(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "fee rate not found for market"))?;
|
||||
.ok_or(missing)?;
|
||||
Ok(json!({"base_fee":fee}))
|
||||
}
|
||||
_ => {
|
||||
let tick = exchange
|
||||
.minimum_tick_size(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "market not found"))?;
|
||||
.ok_or(missing)?;
|
||||
Ok(json!({"minimum_tick_size":tick}))
|
||||
}
|
||||
}
|
||||
@@ -325,29 +333,6 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
|
||||
if path == "/public-search" {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(params)
|
||||
.map_err(|_| exchange::MarketDataError::Invalid("Invalid search query".into()))
|
||||
.and_then(|fields| {
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| exchange::MarketDataError::Unavailable)?
|
||||
.gamma_search(&fields)
|
||||
});
|
||||
let (status, body) = match result {
|
||||
Ok(value) => (200, value),
|
||||
Err(exchange::MarketDataError::Invalid(error)) => {
|
||||
(422, json!({"type":"validation error","error":error}))
|
||||
}
|
||||
Err(exchange::MarketDataError::Unavailable) => {
|
||||
(500, json!({"error":"Search unavailable"}))
|
||||
}
|
||||
};
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let mut allow = None;
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
@@ -362,9 +347,8 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (name, segment) = route
|
||||
.split_once('/')
|
||||
.map_or((route, None), |(name, id)| (name, Some(id)));
|
||||
let is_setting = path == "/neg-risk"
|
||||
|| (matches!(name, "tick-size" | "fee-rate")
|
||||
&& !segment.is_some_and(|id| id.contains('/')));
|
||||
let is_setting = matches!(name, "neg-risk" | "tick-size" | "fee-rate")
|
||||
&& !segment.is_some_and(|id| id.contains('/'));
|
||||
let lookup = path
|
||||
.strip_prefix('/')
|
||||
.and_then(|p| p.split_once('/'))
|
||||
@@ -609,48 +593,6 @@ mod tests {
|
||||
#[test]
|
||||
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for line in include_str!("../../../docs/examples/gamma-search.jsonl").lines() {
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
let search_fields = |raw| serde_urlencoded::from_str::<Vec<(String, String)>>(raw).unwrap();
|
||||
let search_first = db
|
||||
.gamma_search(&search_fields(
|
||||
"q=North+Cup&limit_per_type=1&search_profiles=true",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(search_first["events"][0]["slug"], "north-cup");
|
||||
assert_eq!(
|
||||
search_first["events"][0]["markets"][0]["conditionId"],
|
||||
"north-cup-goals"
|
||||
);
|
||||
assert_eq!(search_first["profiles"][0]["name"], "North Cup analyst");
|
||||
assert_eq!(
|
||||
search_first["pagination"],
|
||||
json!({"hasMore":true,"totalResults":2})
|
||||
);
|
||||
let second_search = db
|
||||
.gamma_search(&search_fields(
|
||||
"q=North+Cup&limit_per_type=1&page=2&optimized=true",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(second_search["events"][0]["slug"], "north-cup-archive");
|
||||
assert_eq!(second_search["hasMore"], false);
|
||||
assert!(second_search.get("pagination").is_none());
|
||||
assert!(second_search["events"][0]["markets"][0]
|
||||
.get("conditionId")
|
||||
.is_none());
|
||||
let visible_profile = db
|
||||
.gamma_search(&search_fields("q=Pitch+observer&search_profiles=true"))
|
||||
.unwrap();
|
||||
assert!(visible_profile["profiles"][0].get("name").is_none());
|
||||
assert_eq!(
|
||||
visible_profile["profiles"][0]["displayUsernamePublic"],
|
||||
false
|
||||
);
|
||||
let by_market_text = db
|
||||
.gamma_search(&search_fields("q=%E5%89%8D%E5%8D%81%E5%88%86%E9%92%9F"))
|
||||
.unwrap();
|
||||
assert_eq!(by_market_text["events"][0]["slug"], "north-cup");
|
||||
let market = "map 2:胜者";
|
||||
db.execute(
|
||||
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
|
||||
@@ -685,6 +627,9 @@ mod tests {
|
||||
json!({"op":"list","id":"resolved-list","market":"resolved-test","rules":"resolved fixture"}),
|
||||
json!({"op":"close","id":"resolved-close","market":"resolved-test"}),
|
||||
json!({"op":"finalize","id":"resolved-final","market":"resolved-test","winner":"YES"}),
|
||||
json!({"op":"list","id":"rp-list","market":"resolved-params","rules":"resolved parameters","tick_size":"0.001","base_fees":{"maker_bps":0,"taker_bps":1000}}),
|
||||
json!({"op":"close","id":"rp-close","market":"resolved-params"}),
|
||||
json!({"op":"finalize","id":"rp-final","market":"resolved-params","winner":"YES"}),
|
||||
json!({"op":"fund","id":"v-fund","account":"unpriced-owner","cents":100}),
|
||||
json!({"op":"list","id":"v-list","market":"unpriced","rules":"valuation fixture"}),
|
||||
json!({"op":"split","id":"v-split","account":"unpriced-owner","market":"unpriced","qty":1}),
|
||||
@@ -757,14 +702,6 @@ mod tests {
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/public-search?q=North+Cup&limit_per_type=1&search_profiles=true",String::new(),200,Some(search_first)),
|
||||
("GET","/public-search?q=North+Cup&limit_per_type=1&page=2&optimized=true",String::new(),200,Some(second_search)),
|
||||
("GET","/public-search?q=Pitch+observer&search_profiles=true",String::new(),200,Some(visible_profile)),
|
||||
("GET","/public-search?q=Undisclosed+analyst&search_profiles=true",String::new(),200,Some(json!({"pagination":{"hasMore":false,"totalResults":0}}))),
|
||||
("GET","/public-search?q=%E5%89%8D%E5%8D%81%E5%88%86%E9%92%9F",String::new(),200,Some(by_market_text)),
|
||||
("GET","/public-search",String::new(),422,Some(json!({"type":"validation error","error":"query argument \"q\": empty"}))),
|
||||
("GET","/public-search?q=north&page=101",String::new(),422,None),
|
||||
("POST","/public-search",String::new(),405,None),
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
("GET","/v2/oi?condition_id=0x0000000000000000000000000000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/oi?condition=bad-hash",String::new(),400,Some(json!({"code":"invalid_request","error":"invalid condition: bad-hash","retryable":false}))),
|
||||
@@ -863,9 +800,17 @@ mod tests {
|
||||
("GET","/clob-markets/missing",String::new(),400,None),
|
||||
("POST","/clob-markets/map+2%2F1","{}".into(),405,None),
|
||||
("GET",tick_query.as_str(),String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
|
||||
("GET","/neg-risk/eb:NO:map+2%2F1",String::new(),200,Some(json!({"neg_risk":false}))),
|
||||
("GET","/neg-risk/",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/neg-risk/garbage",String::new(),404,Some(json!({"error":"market not found"}))),
|
||||
("GET","/fee-rate?token_id=garbage",String::new(),404,Some(json!({"error":"fee rate not found for market"}))),
|
||||
("GET","/tick-size/garbage",String::new(),404,Some(json!({"error":"market not found"}))),
|
||||
("GET","/neg-risk/eb:NO:resolved-params",String::new(),200,Some(json!({"neg_risk":false}))),
|
||||
("GET","/fee-rate/eb:NO:resolved-params",String::new(),200,Some(json!({"base_fee":1000}))),
|
||||
("GET","/tick-size/eb:NO:resolved-params",String::new(),200,Some(json!({"minimum_tick_size":0.001}))),
|
||||
("GET","/neg-risk?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"neg_risk":false}))),
|
||||
("GET","/neg-risk?token_id=eb%3ANO%3Amissing",String::new(),404,None),
|
||||
("GET","/neg-risk?token_id=bad",String::new(),400,None),
|
||||
("GET","/neg-risk?token_id=bad",String::new(),404,Some(json!({"error":"market not found"}))),
|
||||
("GET","/neg-risk",String::new(),400,None),
|
||||
("POST","/neg-risk",String::new(),405,None),
|
||||
("GET","/fee-rate?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"base_fee":30}))),
|
||||
|
||||
@@ -25,10 +25,6 @@ flowchart LR
|
||||
publicsql -->|预定窗口内的成交及订单| schema
|
||||
publictrades -->|标识结果资产| assets
|
||||
publictrades -->|校验事件及盘口选择| valid
|
||||
api -->|查询公开目录| gamma_search["src/gamma_search.rs"]
|
||||
market -->|登记公开资料| gamma_search
|
||||
gamma_search --> search_sql["src/gamma_search_events.sql"]
|
||||
gamma_search --> profile_schema["src/gamma_search_profiles.sql"]
|
||||
queries -->|市场持有人榜单| holders["src/holders.rs"]
|
||||
holders -->|按余额及结果分页| holderrows["src/holders.sql"]
|
||||
holderrows -->|读取含挂单预留的持仓| markschema
|
||||
@@ -1241,21 +1237,6 @@ sequenceDiagram
|
||||
|
||||
一个本地事件有可见盘口且所有可见盘口均已封盘时,目录将事件标为 closed。空事件和仍有开放子盘的事件保持开放。
|
||||
|
||||
### Gamma 公开搜索
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 客户端
|
||||
participant E as Exchange
|
||||
participant S as gamma_search.rs
|
||||
participant D as SQLite
|
||||
C->>E: GET /public-search,传关键词、状态与页码
|
||||
E->>S: 校验参数并打开统一读快照
|
||||
S->>D: 匹配赛事标题和盘口问题,统计并排序
|
||||
S->>D: 展开当页盘口及按需读取标签或公开资料
|
||||
S-->>C: 返回匹配事件和分页,或精简响应
|
||||
```
|
||||
|
||||
### 从账本查询公开成交
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -3,8 +3,6 @@ use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)]
|
||||
pub(crate) enum Command {
|
||||
#[serde(rename = "upsert_public_profile")]
|
||||
UpsertPublicProfile(crate::gamma_search::SearchProfile),
|
||||
Fund {
|
||||
account: String,
|
||||
cents: Option<i64>,
|
||||
|
||||
@@ -1,346 +0,0 @@
|
||||
use crate::{
|
||||
gamma_directory::{header, market},
|
||||
validation::{hex_id, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct SearchProfile {
|
||||
wallet: String,
|
||||
name: Option<String>,
|
||||
pseudonym: Option<String>,
|
||||
bio: Option<String>,
|
||||
profile_image: Option<String>,
|
||||
display_username_public: bool,
|
||||
}
|
||||
|
||||
impl SearchProfile {
|
||||
pub(crate) fn save(self, tx: &Transaction) -> Result<Value> {
|
||||
let wallet = self.wallet.to_ascii_lowercase();
|
||||
ensure!(hex_id(&wallet, 40), "invalid profile wallet");
|
||||
for public_label in [&self.name, &self.pseudonym].into_iter().flatten() {
|
||||
identifier(public_label)?;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO gamma_search_profiles(wallet,name,pseudonym,bio,profile_image,display_username_public)
|
||||
VALUES(?,?,?,?,?,?)
|
||||
ON CONFLICT(wallet) DO UPDATE SET name=excluded.name,pseudonym=excluded.pseudonym,
|
||||
bio=excluded.bio,profile_image=excluded.profile_image,
|
||||
display_username_public=excluded.display_username_public",
|
||||
params![wallet,self.name,self.pseudonym,self.bio,self.profile_image,self.display_username_public],
|
||||
)?;
|
||||
Ok(json!({"proxyWallet":wallet}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Search {
|
||||
phrase: String,
|
||||
tags: Vec<String>,
|
||||
excluded_tags: Vec<i64>,
|
||||
recurrence: Option<String>,
|
||||
closed: Option<bool>,
|
||||
sort_volume: bool,
|
||||
ascending: bool,
|
||||
limit: Option<i64>,
|
||||
page: i64,
|
||||
profiles: bool,
|
||||
search_tags: bool,
|
||||
optimized: bool,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.into())
|
||||
}
|
||||
|
||||
fn field_error(key: &str) -> MarketDataError {
|
||||
invalid(format!("\"{key}\" has a wrong value"))
|
||||
}
|
||||
|
||||
impl Search {
|
||||
fn parse(fields: &[(String, String)]) -> Result<Self, MarketDataError> {
|
||||
let mut q = Self::default();
|
||||
for (key, value) in fields {
|
||||
let boolean = || {
|
||||
value
|
||||
.to_ascii_lowercase()
|
||||
.parse::<bool>()
|
||||
.map_err(|_| field_error(key))
|
||||
};
|
||||
let integer = || value.parse::<i64>().map_err(|_| field_error(key));
|
||||
match key.as_str() {
|
||||
"q" => q.phrase = value.clone(),
|
||||
"events_status" => {
|
||||
q.closed = match value.as_str() {
|
||||
"active" => Some(false),
|
||||
"resolved" => Some(true),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
"events_tag" => q.tags.push(value.to_ascii_lowercase()),
|
||||
"exclude_tag_id" => q.excluded_tags.push(integer()?),
|
||||
"recurrence" => q.recurrence = Some(value.clone()),
|
||||
"sort" => q.sort_volume = value == "volume",
|
||||
"ascending" => q.ascending = boolean()?,
|
||||
"search_tags" => q.search_tags = boolean()?,
|
||||
"search_profiles" => q.profiles = boolean()?,
|
||||
"page" => q.page = integer()?,
|
||||
"limit_per_type" => q.limit = Some(integer()?),
|
||||
"optimized" => q.optimized = boolean()?,
|
||||
"cache" => {
|
||||
boolean()?;
|
||||
}
|
||||
"keep_closed_markets" => {
|
||||
integer()?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if q.phrase.is_empty() {
|
||||
return Err(invalid("query argument \"q\": empty"));
|
||||
}
|
||||
if q.page > 100 {
|
||||
return Err(invalid(
|
||||
"query argument \"page\": must be less than or equal to 100",
|
||||
));
|
||||
}
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
fn limit(&self) -> i64 {
|
||||
match self.limit {
|
||||
None => 5,
|
||||
Some(n) if n <= 0 => 50,
|
||||
Some(n) => n.min(50),
|
||||
}
|
||||
}
|
||||
|
||||
fn terms(&self) -> Vec<String> {
|
||||
self.phrase
|
||||
.split_whitespace()
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn source(
|
||||
db: &Connection,
|
||||
object: &str,
|
||||
sql: &'static str,
|
||||
empty: &'static str,
|
||||
) -> rusqlite::Result<&'static str> {
|
||||
let ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name=?)",
|
||||
[object],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(if ready { sql } else { empty })
|
||||
}
|
||||
|
||||
fn event_matches(db: &Connection, q: &Search) -> rusqlite::Result<(Vec<String>, i64)> {
|
||||
// Optional directory modules contribute data as soon as their migrations exist.
|
||||
let tags = source(
|
||||
db,
|
||||
"directory_tags",
|
||||
"SELECT id,slug FROM directory_tags",
|
||||
"SELECT NULL AS id,NULL AS slug WHERE 0",
|
||||
)?;
|
||||
let tagged_events = source(
|
||||
db,
|
||||
"event_tags",
|
||||
"SELECT tag,event FROM event_tags",
|
||||
"SELECT NULL AS tag,NULL AS event WHERE 0",
|
||||
)?;
|
||||
let recurrences = source(
|
||||
db,
|
||||
"series_events",
|
||||
"SELECT a.event,s.recurrence FROM series_events a JOIN directory_series s ON s.id=a.series",
|
||||
"SELECT NULL AS event,NULL AS recurrence WHERE 0",
|
||||
)?;
|
||||
let base = include_str!("gamma_search_events.sql")
|
||||
.replace("{directory}", include_str!("gamma_events.sql"))
|
||||
.replace("{tags}", tags)
|
||||
.replace("{tagged_events}", tagged_events)
|
||||
.replace("{recurrences}", recurrences);
|
||||
let filters = json!({"phrase":q.phrase.trim().to_ascii_lowercase(),"terms":q.terms(),"closed":q.closed.map(i64::from),
|
||||
"tags":q.tags,"excluded_tags":q.excluded_tags,"recurrence":q.recurrence}).to_string();
|
||||
let total: i64 = db
|
||||
.prepare_cached(&format!("{base} SELECT COUNT(*) FROM matching"))?
|
||||
.query_row([&filters], |r| r.get(0))?;
|
||||
let order = if q.sort_volume {
|
||||
let dir = if q.ascending { "ASC" } else { "DESC" };
|
||||
format!(
|
||||
"COALESCE((SELECT SUM(t.price*CAST(t.quantity AS REAL))
|
||||
FROM listed_markets l JOIN wallet_trade_legs t ON t.market=l.market
|
||||
JOIN execution_context c ON c.execution=t.execution AND c.taker_order=t.order_seq
|
||||
WHERE l.event=m.id),0) {dir}, m.event_id DESC"
|
||||
)
|
||||
} else {
|
||||
"m.score ASC,m.event_id DESC".into()
|
||||
};
|
||||
let mut stmt = db.prepare_cached(&format!(
|
||||
"{base} SELECT m.id FROM matching m ORDER BY {order} LIMIT ?2 OFFSET ?3"
|
||||
))?;
|
||||
let ids = stmt
|
||||
.query_map(
|
||||
params![filters, q.limit(), (q.page.max(1) - 1) * q.limit()],
|
||||
|r| r.get(0),
|
||||
)?
|
||||
.collect::<rusqlite::Result<_>>()?;
|
||||
Ok((ids, total))
|
||||
}
|
||||
|
||||
fn event_rows(db: &Connection, ids: &[String], optimized: bool) -> rusqlite::Result<Vec<Value>> {
|
||||
if ids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let keys = json!(ids).to_string();
|
||||
let mut headers = db.prepare_cached(concat!(
|
||||
include_str!("gamma_events.sql"),
|
||||
" WHERE e.id IN (SELECT value FROM json_each(?))",
|
||||
))?;
|
||||
let mut events = headers
|
||||
.query_map([&keys], header)?
|
||||
.collect::<rusqlite::Result<HashMap<_, _>>>()?;
|
||||
let mut markets = db.prepare_cached(concat!(
|
||||
include_str!("gamma_market.sql"),
|
||||
" AND COALESCE(s.event,t.event) IN (SELECT value FROM json_each(?)) AND COALESCE(v.archived,0)=0
|
||||
ORDER BY COALESCE(t.group_order,0),w.market",
|
||||
))?;
|
||||
let mut children = HashMap::<String, Vec<Value>>::new();
|
||||
let mut rows = markets.query([keys])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let mut value = market(row)?;
|
||||
if optimized {
|
||||
if let Some(object) = value.as_object_mut() {
|
||||
object.retain(|k, _| {
|
||||
matches!(
|
||||
k.as_str(),
|
||||
"active"
|
||||
| "archived"
|
||||
| "bestAsk"
|
||||
| "closed"
|
||||
| "groupItemTitle"
|
||||
| "lastTradePrice"
|
||||
| "outcomePrices"
|
||||
| "outcomes"
|
||||
| "question"
|
||||
| "slug"
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
children.entry(row.get("parent")?).or_default().push(value);
|
||||
}
|
||||
Ok(ids
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
events.remove(id).map(|mut event| {
|
||||
if optimized {
|
||||
if let Some(object) = event.as_object_mut() {
|
||||
object.retain(|k, _| {
|
||||
matches!(k.as_str(), "id" | "slug" | "title" | "closed" | "active")
|
||||
});
|
||||
}
|
||||
}
|
||||
event["markets"] = Value::Array(children.remove(id).unwrap_or_default());
|
||||
event
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn profile_rows(db: &Connection, q: &Search) -> rusqlite::Result<Vec<Value>> {
|
||||
let mut stmt = db.prepare_cached(
|
||||
"WITH visible AS (
|
||||
SELECT id,wallet,CASE WHEN display_username_public THEN name END AS public_name,
|
||||
pseudonym,bio,profile_image,display_username_public
|
||||
FROM gamma_search_profiles
|
||||
)
|
||||
SELECT wallet,public_name,pseudonym,bio,profile_image,display_username_public
|
||||
FROM visible
|
||||
WHERE NOT EXISTS(SELECT 1 FROM json_each(?1)
|
||||
WHERE instr(lower(wallet||' '||COALESCE(public_name,'')||' '||COALESCE(pseudonym,'')),value)=0)
|
||||
ORDER BY CASE WHEN lower(wallet)=?2 OR lower(public_name)=?2 OR lower(pseudonym)=?2 THEN 0 ELSE 1 END,id
|
||||
LIMIT ?3 OFFSET ?4",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![json!(q.terms()).to_string(),q.phrase.trim().to_ascii_lowercase(),
|
||||
q.limit(),(q.page.max(1)-1)*q.limit()], |r| {
|
||||
let mut profile = json!({"proxyWallet":r.get::<_,String>(0)?,"displayUsernamePublic":r.get::<_,bool>(5)?});
|
||||
for (column,key) in [(1,"name"),(2,"pseudonym"),(3,"bio"),(4,"profileImage")] {
|
||||
if let Some(value) = r.get::<_,Option<String>>(column)? { profile[key]=json!(value); }
|
||||
}
|
||||
Ok(profile)
|
||||
})?;
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
fn tag_rows(db: &Connection, q: &Search) -> rusqlite::Result<Vec<Value>> {
|
||||
let tags = source(
|
||||
db,
|
||||
"directory_tags",
|
||||
"SELECT id,slug,label FROM directory_tags",
|
||||
"SELECT NULL AS id,NULL AS slug,NULL AS label WHERE 0",
|
||||
)?;
|
||||
let assigned = source(
|
||||
db,
|
||||
"event_tags",
|
||||
"SELECT tag,event FROM event_tags",
|
||||
"SELECT NULL AS tag,NULL AS event WHERE 0",
|
||||
)?;
|
||||
let sql = format!(
|
||||
"WITH tags AS ({tags}), assigned AS ({assigned})
|
||||
SELECT CAST(t.id AS TEXT),t.slug,t.label,(SELECT count(*) FROM assigned a WHERE a.tag=t.id)
|
||||
FROM tags t WHERE NOT EXISTS(SELECT 1 FROM json_each(?1)
|
||||
WHERE instr(lower(t.slug||' '||t.label),value)=0)
|
||||
ORDER BY CASE WHEN lower(t.slug)=?2 OR lower(t.label)=?2 THEN 0 ELSE 1 END,t.id
|
||||
LIMIT ?3 OFFSET ?4"
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let rows = stmt.query_map(params![json!(q.terms()).to_string(),q.phrase.trim().to_ascii_lowercase(),
|
||||
q.limit(),(q.page.max(1)-1)*q.limit()], |r| Ok(json!({
|
||||
"id":r.get::<_,String>(0)?,"slug":r.get::<_,String>(1)?,"label":r.get::<_,String>(2)?,
|
||||
"event_count":r.get::<_,i64>(3)?
|
||||
})))?;
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_search(&self, fields: &[(String, String)]) -> Result<Value, MarketDataError> {
|
||||
let q = Search::parse(fields)?;
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let (ids, total) = event_matches(&tx, &q)?;
|
||||
let events = event_rows(&tx, &ids, q.optimized)?;
|
||||
let profiles = if q.profiles {
|
||||
profile_rows(&tx, &q)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let tags = if q.search_tags {
|
||||
tag_rows(&tx, &q)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let has_more = q.page.max(1) * q.limit() < total;
|
||||
let value = if q.optimized {
|
||||
json!({"events":(!events.is_empty()).then_some(events),"hasMore":has_more,
|
||||
"profiles":(!profiles.is_empty()).then_some(profiles),"tags":(!tags.is_empty()).then_some(tags)})
|
||||
} else {
|
||||
let mut response = json!({"pagination":{"hasMore":has_more,"totalResults":total}});
|
||||
for (key, rows) in [("events", events), ("profiles", profiles), ("tags", tags)] {
|
||||
if !rows.is_empty() {
|
||||
response[key] = Value::Array(rows);
|
||||
}
|
||||
}
|
||||
response
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
-- Bound search values are literal substrings. The directory views supply membership.
|
||||
WITH
|
||||
directory AS NOT MATERIALIZED ({directory}),
|
||||
tags AS NOT MATERIALIZED ({tags}),
|
||||
tagged_events AS NOT MATERIALIZED ({tagged_events}),
|
||||
recurrences AS NOT MATERIALIZED ({recurrences}),
|
||||
terms AS (SELECT value FROM json_each(?1,'$.terms')),
|
||||
matching AS (
|
||||
SELECT e.id,e.event_id,e.title,
|
||||
CASE
|
||||
WHEN lower(e.slug)=json_extract(?1,'$.phrase') OR lower(e.title)=json_extract(?1,'$.phrase') THEN 0
|
||||
WHEN NOT EXISTS(SELECT 1 FROM terms WHERE instr(lower(e.title||' '||e.slug),value)=0) THEN 1
|
||||
ELSE 2
|
||||
END AS score
|
||||
FROM directory e
|
||||
WHERE (json_extract(?1,'$.closed') IS NULL OR e.closed=json_extract(?1,'$.closed'))
|
||||
AND (json_extract(?1,'$.recurrence') IS NULL OR EXISTS(
|
||||
SELECT 1 FROM recurrences r WHERE r.event=e.id AND r.recurrence=json_extract(?1,'$.recurrence')
|
||||
))
|
||||
AND (json_array_length(?1,'$.tags')=0 OR EXISTS(
|
||||
SELECT 1 FROM tagged_events a JOIN tags t ON t.id=a.tag WHERE a.event=e.id
|
||||
AND lower(t.slug) IN (SELECT value FROM json_each(?1,'$.tags'))
|
||||
))
|
||||
AND NOT EXISTS(
|
||||
SELECT 1 FROM tagged_events a WHERE a.event=e.id
|
||||
AND a.tag IN (SELECT value FROM json_each(?1,'$.excluded_tags'))
|
||||
)
|
||||
AND (
|
||||
NOT EXISTS(SELECT 1 FROM terms WHERE instr(lower(e.title||' '||e.slug),value)=0) OR EXISTS(
|
||||
SELECT 1 FROM listed_markets l JOIN market_wire_metadata w ON w.market=l.market
|
||||
LEFT JOIN market_visibility v ON v.market=l.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=l.market
|
||||
WHERE l.event=e.id AND COALESCE(a.role,'')<>'placeholder'
|
||||
AND COALESCE(v.archived,0)=0 AND NOT EXISTS(
|
||||
SELECT 1 FROM terms WHERE instr(lower(w.question||' '||w.slug),value)=0
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -1,11 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS gamma_search_profiles (
|
||||
id INTEGER PRIMARY KEY,
|
||||
wallet TEXT NOT NULL UNIQUE,
|
||||
name TEXT,
|
||||
pseudonym TEXT,
|
||||
bio TEXT,
|
||||
profile_image TEXT,
|
||||
display_username_public INTEGER NOT NULL CHECK(display_username_public IN (0,1))
|
||||
);
|
||||
COMMIT;
|
||||
@@ -22,7 +22,6 @@ mod cancellation;
|
||||
mod clarifications;
|
||||
mod clob_market;
|
||||
mod command;
|
||||
mod gamma_search;
|
||||
mod inventory;
|
||||
mod kickoff;
|
||||
mod last_trades;
|
||||
@@ -34,7 +33,6 @@ mod market_stream;
|
||||
mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
|
||||
mod portfolio;
|
||||
mod prices_history;
|
||||
mod public_trades;
|
||||
@@ -86,13 +84,6 @@ impl Exchange {
|
||||
db.busy_timeout(Duration::from_secs(10))?;
|
||||
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
||||
db.execute_batch(include_str!("schema.sql"))?;
|
||||
let search_profiles_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='gamma_search_profiles')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !search_profiles_ready {
|
||||
db.execute_batch(include_str!("gamma_search_profiles.sql"))?;
|
||||
}
|
||||
let submissions_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='order_submissions')",
|
||||
[], |r| r.get(0),
|
||||
|
||||
@@ -16,7 +16,6 @@ pub(crate) fn apply(
|
||||
request_id: &str,
|
||||
) -> Result<Value> {
|
||||
match command {
|
||||
Command::UpsertPublicProfile(profile) => profile.save(tx),
|
||||
Command::Fund {
|
||||
account,
|
||||
cents,
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
{"op":"event","id":"search-a","event":"north-cup","slug":"north-cup","title":"North Cup","category":"sports"}
|
||||
{"op":"event","id":"search-b","event":"north-cup-archive","slug":"north-cup-archive","title":"North Cup Archive","category":"sports"}
|
||||
{"op":"list","id":"search-market-a","market":"north-cup-goals","rules":"以正式比赛结束记录为准。","listing":{"event":"north-cup","question":"前十分钟会进球吗?","yes_label":"会","no_label":"不会","source":"比赛记录","resolver":"操作员","rules_version":1}}
|
||||
{"op":"list","id":"search-market-b","market":"archived-north-cup-score","rules":"最终比分由赛事报告确认。","listing":{"event":"north-cup-archive","question":"最终比分是 2:1 吗?","yes_label":"是","no_label":"否","source":"赛事报告","resolver":"操作员","rules_version":1}}
|
||||
{"op":"close","id":"search-close","market":"archived-north-cup-score"}
|
||||
{"op":"upsert_public_profile","id":"search-profile-public","wallet":"0x0000000000000000000000000000000000000011","name":"North Cup analyst","display_username_public":true}
|
||||
{"op":"upsert_public_profile","id":"search-profile-hidden","wallet":"0x0000000000000000000000000000000000000022","name":"Undisclosed analyst","pseudonym":"Pitch observer","display_username_public":false}
|
||||
@@ -0,0 +1,38 @@
|
||||
[
|
||||
{"endpoint":"fee-rate","mode":"query","case":"live","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate?token_id=35090254409399344650860070211816464534198960801264823587796928404808383727584","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:31 GMT","body":{"base_fee":1000}}},
|
||||
{"endpoint":"fee-rate","mode":"query","case":"resolved_v1","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:31 GMT","body":{"base_fee":1000}}},
|
||||
{"endpoint":"fee-rate","mode":"query","case":"resolved_v2","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:31 GMT","body":{"base_fee":1000}}},
|
||||
{"endpoint":"fee-rate","mode":"query","case":"unknown","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate?token_id=123","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:31 GMT","body":{"error":"fee rate not found for market"}}},
|
||||
{"endpoint":"fee-rate","mode":"query","case":"malformed","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate?token_id=not-an-asset","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"error":"fee rate not found for market"}}},
|
||||
{"endpoint":"fee-rate","mode":"query","case":"blank","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate?token_id=","payload":null,"status":400,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"error":"Invalid token id"}}},
|
||||
{"endpoint":"fee-rate","mode":"json_path","case":"live","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate/35090254409399344650860070211816464534198960801264823587796928404808383727584","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"base_fee":1000}}},
|
||||
{"endpoint":"fee-rate","mode":"json_path","case":"resolved_v1","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate/73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"base_fee":1000}}},
|
||||
{"endpoint":"fee-rate","mode":"json_path","case":"resolved_v2","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate/759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"base_fee":1000}}},
|
||||
{"endpoint":"fee-rate","mode":"json_path","case":"unknown","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate/123","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"error":"fee rate not found for market"}}},
|
||||
{"endpoint":"fee-rate","mode":"json_path","case":"malformed","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate/not-an-asset","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"error":"fee rate not found for market"}}},
|
||||
{"endpoint":"tick-size","mode":"query","case":"live","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size?token_id=35090254409399344650860070211816464534198960801264823587796928404808383727584","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"minimum_tick_size":0.001}}},
|
||||
{"endpoint":"tick-size","mode":"query","case":"resolved_v1","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"minimum_tick_size":0.001}}},
|
||||
{"endpoint":"tick-size","mode":"query","case":"resolved_v2","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"minimum_tick_size":0.001}}},
|
||||
{"endpoint":"tick-size","mode":"query","case":"unknown","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size?token_id=123","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"tick-size","mode":"query","case":"malformed","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size?token_id=not-an-asset","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:32 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"tick-size","mode":"query","case":"blank","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size?token_id=","payload":null,"status":400,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"error":"Invalid token id"}}},
|
||||
{"endpoint":"tick-size","mode":"json_path","case":"live","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size/35090254409399344650860070211816464534198960801264823587796928404808383727584","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"minimum_tick_size":0.001}}},
|
||||
{"endpoint":"tick-size","mode":"json_path","case":"resolved_v1","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size/73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"minimum_tick_size":0.001}}},
|
||||
{"endpoint":"tick-size","mode":"json_path","case":"resolved_v2","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size/759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"minimum_tick_size":0.001}}},
|
||||
{"endpoint":"tick-size","mode":"json_path","case":"unknown","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size/123","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"tick-size","mode":"json_path","case":"malformed","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size/not-an-asset","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"neg-risk","mode":"query","case":"live","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk?token_id=35090254409399344650860070211816464534198960801264823587796928404808383727584","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"neg_risk":true}}},
|
||||
{"endpoint":"neg-risk","mode":"query","case":"resolved_v1","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk?token_id=73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"neg_risk":false}}},
|
||||
{"endpoint":"neg-risk","mode":"query","case":"resolved_v2","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk?token_id=759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"neg_risk":false}}},
|
||||
{"endpoint":"neg-risk","mode":"query","case":"unknown","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk?token_id=123","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:33 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"neg-risk","mode":"query","case":"malformed","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk?token_id=not-an-asset","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"neg-risk","mode":"query","case":"blank","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk?token_id=","payload":null,"status":400,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"Invalid token id"}}},
|
||||
{"endpoint":"neg-risk","mode":"json_path","case":"live","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk/35090254409399344650860070211816464534198960801264823587796928404808383727584","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"neg_risk":true}}},
|
||||
{"endpoint":"neg-risk","mode":"json_path","case":"resolved_v1","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk/73979342585906843441145134109923710004884703083095161594360108477170435492453","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"neg_risk":false}}},
|
||||
{"endpoint":"neg-risk","mode":"json_path","case":"resolved_v2","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk/759916398134244316868652908232832573045153963965173623897622651599218278400","payload":null,"status":200,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"neg_risk":false}}},
|
||||
{"endpoint":"neg-risk","mode":"json_path","case":"unknown","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk/123","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"neg-risk","mode":"json_path","case":"malformed","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk/not-an-asset","payload":null,"status":404,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"market not found"}}},
|
||||
{"endpoint":"fee-rate","mode":"no_query","case":"missing","response":{"method":"GET","url":"https://clob.polymarket.com/fee-rate","payload":null,"status":400,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"Invalid token id"}}},
|
||||
{"endpoint":"tick-size","mode":"no_query","case":"missing","response":{"method":"GET","url":"https://clob.polymarket.com/tick-size","payload":null,"status":400,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"Invalid token id"}}},
|
||||
{"endpoint":"neg-risk","mode":"no_query","case":"missing","response":{"method":"GET","url":"https://clob.polymarket.com/neg-risk","payload":null,"status":400,"date":"Fri, 04 Dec 2026 20:37:34 GMT","body":{"error":"Invalid token id"}}}
|
||||
]
|
||||
@@ -405,12 +405,6 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
在本地主题样例中只关闭 nvda-300 时,/markets 的结果仍有 nvda-200,/events 中的主题事件仍开放,事件详情中两个门槛盘都可见。关闭第二个门槛盘后,/events?closed=true 才返回这个事件。本地市场上架后默认 active 为 true,封盘仅更新交易状态。运营方可以通过 set_market_visibility 单独修改市场的 active 和 archived。事件仍使用原有的发布状态。封盘的事件聚合规则、默认每页 20 条和默认按数字 ID 降序都是本地约定。支持按 id、slug、市场 question 或事件 title 排序,逗号分隔多个字段;相同排序值用数字 ID 确定先后。每页使用独立读快照,分页之间如有上架或关闭,offset 可能移动。标签、链上标识、按交易量排序及官方游标分页仍待实现。
|
||||
|
||||
### Gamma 公开搜索
|
||||
|
||||
生产 `/public-search?q=nvidia` 和大写查询返回同样的前五条事件;盘口嵌在事件的 markets 数组。省略或清空 q 返回 422,未匹配时普通结果只保留 pagination。页码从 1 起算,0 和负值按第一页处理,超过 100 返回 422。省略 `limit_per_type` 的样本返回 5 条,0、负值和超过 50 的样本返回 50 条。`events_status=active` 和 `resolved` 分别缩小结果集,`closed` 在样本中按默认搜索处理。优化响应在顶层给出 hasMore,盘口和事件字段更少。启用资料和标签搜索时可单独返回匹配结果。[Gamma 搜索规范](https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles)
|
||||
|
||||
本地[样例](examples/gamma-search.jsonl)按赛事标题及盘口问题和 slug 查找,可用 `events_status`、本地成交额排序和分页。标签与系列表可用时,搜索支持对应的标签过滤、标签结果和 recurrence。显式登记的资料可供搜索,隐藏的用户名既不参与匹配也不返回。匹配采用本地字面子串和确定性排序。生产相关性算法、索引延迟、缓存及少见字段仍待核验。当前公开搜索的盘口随本地父事件返回,独立盘口仍可直接用市场目录查询。
|
||||
|
||||
### 公开成交的 Data API 入口
|
||||
|
||||
`GET /v2/trades` 读取本地成交账本,返回钱包视角的 BUY/SELL、份额数、按该结果计算的每份价格、成交秒数、结果标签和所属市场。对照 [赛事样例](examples/football.jsonl) 与 [成交样例](examples/volume.jsonl),Bob 的 NO 买单与 Alice 的 YES 买单在同一次互补撮合中成交。Bob 买入 3 份的每份价格为 0.40,Alice 买入的每份为 0.60。直接转让时买卖双方使用同一个成交价。默认只展示吃单方。对无已知吃单方的本地开盘集合竞价,taker_only=false 可查两侧的账本记录。
|
||||
@@ -477,3 +471,7 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
### 已裁决市场的公开盘口
|
||||
|
||||
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
|
||||
|
||||
### 已裁决资产的交易参数
|
||||
|
||||
生产样本中,活跃资产和两个已裁决资产都可通过路径或查询参数读取 tick-size、fee-rate 和 neg-risk。已裁决样本的基础费字段为 1000,步长为 0.001,这些值来自样本的市场配置。缺少 ID 或传空值时返回 400,非空但无法识别的 ID 返回 404,基础费接口使用自己的错误文案。本地路径接受百分号编码的结果标识。[生产响应](examples/public-token-settings.json) · [官方报价步长接口](https://docs.polymarket.com/api-reference/market-data/get-tick-size) · [官方基础费接口](https://docs.polymarket.com/api-reference/market-data/get-fee-rate)
|
||||
Reference in new issue
Block a user