-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi.ts
More file actions
547 lines (474 loc) · 21.1 KB
/
Copy pathapi.ts
File metadata and controls
547 lines (474 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/**
* Xueqiu HTTP API client
*
* ~80 endpoints reverse-engineered from xueqiu.com web interface.
* Requires valid cookie (xq_a_token) for most endpoints.
*
* Sources: pysnowball, xueqiu-api, 1dot75cm/xueqiu, go-xueqiu
*/
import { getCookie } from "./auth";
const STOCK_URL = "https://stock.xueqiu.com";
const XUEQIU_URL = "https://xueqiu.com";
const DANJUAN_URL = "https://danjuanapp.com";
const HEADERS = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "application/json",
"Origin": "https://xueqiu.com",
"Referer": "https://xueqiu.com/",
"X-Requested-With": "XMLHttpRequest",
};
async function request(path: string, params: Record<string, string | number> = {}, base = STOCK_URL, retries = 2): Promise<any> {
const cookie = getCookie();
const url = new URL(path, base);
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, String(v));
}
for (let attempt = 0; attempt <= retries; attempt++) {
const res = await fetch(url.toString(), {
headers: { ...HEADERS, Cookie: cookie },
});
if (!res.ok) {
// Retry on 429 (rate limit) and 5xx (server error)
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
continue;
}
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const data = await res.json();
if (data.error_code && data.error_code !== 0) {
throw new Error(`API error ${data.error_code}: ${data.error_description}`);
}
return data;
}
throw new Error("Request failed after retries");
}
/** Request without token (for public endpoints like quotec) */
async function requestPublic(path: string, params: Record<string, string | number> = {}, base = STOCK_URL): Promise<any> {
const url = new URL(path, base);
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, String(v));
}
const res = await fetch(url.toString(), {
headers: { ...HEADERS },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// ═══════════════════════════════════════════════════════════════
// QUOTES
// ═══════════════════════════════════════════════════════════════
/** Real-time quote (works WITHOUT token) */
export async function quote(symbols: string | string[]): Promise<any> {
const sym = Array.isArray(symbols) ? symbols.join(",") : symbols;
const data = await requestPublic("/v5/stock/realtime/quotec.json", { symbol: sym });
return data.data;
}
/** Detailed quote with PE, PB, dividend, 52w high/low */
export async function quoteDetail(symbol: string): Promise<any> {
const data = await request("/v5/stock/quote.json", { symbol, extend: "detail" });
return data.data?.quote;
}
/** Batch quote for multiple symbols */
export async function quoteBatch(symbols: string[]): Promise<any> {
const data = await request("/v5/stock/batch/quote.json", { symbol: symbols.join(",") });
return data.data;
}
/** Order book (bid/ask levels) */
export async function pankou(symbol: string): Promise<any> {
const data = await request("/v5/stock/realtime/pankou.json", { symbol });
return data.data;
}
/** Minute chart data */
export async function minute(symbol: string): Promise<any> {
const data = await request("/v5/stock/chart/minute.json", { symbol, period: "1d" });
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// KLINE
// ═══════════════════════════════════════════════════════════════
/** K-line / candlestick data */
export async function kline(
symbol: string,
period: "1m" | "5m" | "15m" | "30m" | "60m" | "120m" | "day" | "week" | "month" | "quarter" | "year" = "day",
count: number = 120,
type: "before" | "after" | "normal" = "before"
): Promise<any> {
const data = await request("/v5/stock/chart/kline.json", {
symbol,
period,
type,
begin: Date.now(),
count: -count,
indicator: "kline,pe,pb,ps,pcf,market_capital",
});
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// FINANCIALS
// ═══════════════════════════════════════════════════════════════
function detectRegion(symbol: string): "cn" | "hk" | "us" {
if (symbol.startsWith("SH") || symbol.startsWith("SZ")) return "cn";
if (/^\d{5}$/.test(symbol)) return "hk";
return "us";
}
/** Income statement */
export async function income(symbol: string, type = "all", count = 5): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/finance/${region}/income.json`, {
symbol, type, is_detail: "true", count,
});
return data.data?.list;
}
/** Balance sheet */
export async function balance(symbol: string, type = "all", count = 5): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/finance/${region}/balance.json`, {
symbol, type, is_detail: "true", count,
});
return data.data?.list;
}
/** Cash flow statement */
export async function cashflow(symbol: string, type = "all", count = 5): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/finance/${region}/cash_flow.json`, {
symbol, type, is_detail: "true", count,
});
return data.data?.list;
}
/** Key financial indicators */
export async function indicator(symbol: string, type = "all", count = 5): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/finance/${region}/indicator.json`, {
symbol, type, is_detail: "true", count,
});
return data.data?.list;
}
/** Business revenue composition */
export async function business(symbol: string): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/finance/${region}/business.json`, {
symbol, is_detail: "true", count: 5,
});
return data.data?.list;
}
// ═══════════════════════════════════════════════════════════════
// CAPITAL FLOW
// ═══════════════════════════════════════════════════════════════
/** Intraday capital flow */
export async function capitalFlow(symbol: string): Promise<any> {
const data = await request("/v5/stock/capital/flow.json", { symbol });
return data.data;
}
/** Historical daily capital flow */
export async function capitalHistory(symbol: string, count = 20): Promise<any> {
const data = await request("/v5/stock/capital/history.json", { symbol, count });
return data.data;
}
/** Capital assortment by order size */
export async function capitalAssort(symbol: string): Promise<any> {
const data = await request("/v5/stock/capital/assort.json", { symbol });
return data.data;
}
/** Margin trading data */
export async function margin(symbol: string, page = 1, size = 20): Promise<any> {
const data = await request("/v5/stock/capital/margin.json", { symbol, page, size });
return data.data;
}
/** Block transactions */
export async function blockTrans(symbol: string, page = 1, size = 20): Promise<any> {
const data = await request("/v5/stock/capital/blocktrans.json", { symbol, page, size });
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// F10 COMPANY DATA
// ═══════════════════════════════════════════════════════════════
/** Company profile */
export async function company(symbol: string): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/f10/${region}/company.json`, { symbol });
return data.data;
}
/** Top 10 shareholders */
export async function topHolders(symbol: string, circula = 0): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/f10/${region}/top_holders.json`, { symbol, circula });
return data.data;
}
/** Shareholder count history */
export async function holders(symbol: string): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/f10/${region}/holders.json`, { symbol });
return data.data;
}
/** Dividends & bonuses */
export async function bonus(symbol: string, page = 1, size = 20): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/f10/${region}/bonus.json`, { symbol, page, size });
return data.data;
}
/** Industry classification */
export async function industry(symbol: string): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/f10/${region}/industry.json`, { symbol });
return data.data;
}
/** Institutional holding changes */
export async function orgHolding(symbol: string): Promise<any> {
const region = detectRegion(symbol);
const data = await request(`/v5/stock/f10/${region}/org_holding/change.json`, { symbol });
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// REPORTS & FORECASTS
// ═══════════════════════════════════════════════════════════════
/** Earnings forecast */
export async function forecast(symbol: string): Promise<any> {
const data = await request("/stock/report/earningforecast.json", { symbol });
return data.data;
}
/** Latest research reports */
export async function reports(symbol: string): Promise<any> {
const data = await request("/stock/report/latest.json", { symbol });
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// SEARCH & DISCOVERY
// ═══════════════════════════════════════════════════════════════
/** Search stocks by keyword */
export async function search(query: string, count = 10): Promise<any> {
const data = await request("/query/v1/suggest_stock.json", { q: query, count }, XUEQIU_URL);
return data.data;
}
/** Hot stocks list */
export async function hotStocks(type: "global" | "us" | "cn" | "hk" = "cn", size = 10): Promise<any> {
const typeMap = { global: 10, us: 11, cn: 12, hk: 13 };
const data = await request("/v5/stock/hot_stock/list.json", {
type: typeMap[type], size,
});
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// MARKET INDICES
// ═══════════════════════════════════════════════════════════════
/** Major market indices */
export async function indices(): Promise<any> {
return quote([
"SH000001", // 上证指数
"SZ399001", // 深证成指
"SZ399006", // 创业板指
"SH000300", // 沪深300
"SH000016", // 上证50
"SH000905", // 中证500
]);
}
// ═══════════════════════════════════════════════════════════════
// SOCIAL / POSTS
// ═══════════════════════════════════════════════════════════════
/** News feed by category */
export async function feed(category: string = "headlines", count = 20): Promise<any> {
const catMap: Record<string, number> = {
"headlines": -1, "today": 0, "a-shares": 105, "us": 101, "hk": 102,
"funds": 104, "private": 113, "realestate": 111, "auto": 114, "live": 6,
};
const catId = catMap[category] ?? -1;
const data = await request("/v4/statuses/public_timeline_by_category.json", {
since_id: -1, max_id: -1, category: catId, count,
}, XUEQIU_URL);
const list = data.list || [];
return list.map((item: any) => {
try {
return formatPost(JSON.parse(item.data));
} catch {
return item;
}
});
}
/** Search posts/articles */
export async function searchPosts(query: string, count = 10, sort: "time" | "reply" | "relevance" = "relevance"): Promise<any> {
const data = await request("/statuses/search.json", {
q: query, count, page: 1, sort, source: "all",
}, XUEQIU_URL);
return data.data;
}
function formatPost(post: any) {
return {
id: post.id,
title: post.title,
description: (post.description || post.text || "").replace(/<[^>]+>/g, "").slice(0, 200),
author: post.user?.screen_name,
author_id: post.user?.id,
author_followers: post.user?.followers_count,
view_count: post.view_count,
reply_count: post.reply_count,
like_count: post.like_count ?? post.fav_count,
retweet_count: post.retweet_count,
created_at: post.created_at,
url: post.target ? `https://xueqiu.com${post.target}` : null,
};
}
/** Hot posts by time scope (day/week/month) */
export async function hotPosts(scope: "day" | "week" | "month" = "day", count = 10, page = 1): Promise<any> {
const data = await request("/statuses/hots.json", {
a: "1", count, page, scope, type: "status", meigu: "0",
}, XUEQIU_URL);
// Response is a direct array
return (Array.isArray(data) ? data : []).map(formatPost);
}
/** 7x24 live news feed */
export async function liveNews(count = 20): Promise<any> {
const data = await request("/statuses/livenews/list.json", {
since_id: -1, max_id: -1, count,
}, XUEQIU_URL);
return (data.items || []).map((item: any) => ({
id: item.id,
text: item.text,
created_at: item.created_at,
url: item.target,
mark: item.mark, // 1=important
view_count: item.view_count,
reply_count: item.reply_count,
}));
}
/** KOLs / hot users for a stock */
export async function stockKOLs(symbol: string, count = 10): Promise<any> {
const data = await request("/recommend/user/stock_hot_user.json", {
symbol, start: 0, count,
}, XUEQIU_URL);
return (Array.isArray(data) ? data : []).map((u: any) => ({
id: u.id,
screen_name: u.screen_name,
description: u.description,
followers_count: u.followers_count,
friends_count: u.friends_count,
status_count: u.status_count,
gender: u.gender,
province: u.province,
city: u.city,
verified: u.verified,
verified_description: u.verified_description,
url: `https://xueqiu.com/u/${u.id}`,
}));
}
/** User timeline — recent posts by a specific user */
export async function userPosts(userId: string, count = 10, page = 1): Promise<any> {
const data = await request("/statuses/user_timeline.json", {
user_id: userId, page, count,
}, XUEQIU_URL);
return (data.statuses || []).map(formatPost);
}
/** User profile */
export async function userProfile(userId: string): Promise<any> {
const data = await request("/user/show.json", { id: userId }, XUEQIU_URL);
return data;
}
/** Search users by keyword */
export async function searchUsers(query: string, count = 10, page = 1): Promise<any> {
const data = await request("/users/search.json", { q: query, count, page }, XUEQIU_URL);
return data.users ?? data;
}
/** Important-only live news (marked items) */
export async function liveNewsImportant(count = 20): Promise<any> {
const data = await request("/statuses/livenews/mark/list.json", {
since_id: -1, max_id: -1, size: count,
}, XUEQIU_URL);
return (data.items || []).map((item: any) => ({
id: item.id,
text: item.text,
created_at: item.created_at,
url: item.target,
mark: item.mark,
view_count: item.view_count,
reply_count: item.reply_count,
}));
}
/** Single post detail by ID */
export async function postDetail(postId: string): Promise<any> {
const data = await request("/statuses/show.json", { id: postId }, XUEQIU_URL);
return data;
}
// ═══════════════════════════════════════════════════════════════
// PORTFOLIO / WATCHLIST
// ═══════════════════════════════════════════════════════════════
/** List user's watchlists */
export async function watchlists(): Promise<any> {
const data = await request("/v5/stock/portfolio/list.json", { system: "true" });
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// SCREENER
// ═══════════════════════════════════════════════════════════════
/** Screen stocks by criteria */
export async function screen(
market: "SH" | "HK" | "US" = "SH",
orderby = "symbol",
page = 1,
size = 30
): Promise<any> {
const data = await request("/stock/screener/screen.json", {
category: market, orderby, order: "desc", page, size,
current: "ALL", pct: "ALL",
}, XUEQIU_URL);
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// FUND DATA (Danjuan)
// ═══════════════════════════════════════════════════════════════
/** Fund detail */
export async function fund(code: string): Promise<any> {
const data = await requestPublic(`/djapi/fund/detail/${code}`, {}, DANJUAN_URL);
return data.data;
}
/** Fund NAV history */
export async function fundNav(code: string, page = 1, size = 30): Promise<any> {
const data = await requestPublic(`/djapi/fund/nav/history/${code}`, { page, size }, DANJUAN_URL);
return data.data;
}
/** Fund growth performance */
export async function fundGrowth(code: string, period = "ty"): Promise<any> {
const data = await requestPublic(`/djapi/fund/growth/${code}`, { day: period }, DANJUAN_URL);
return data.data;
}
// ═══════════════════════════════════════════════════════════════
// PORTFOLIO (组合)
// ═══════════════════════════════════════════════════════════════
/** List user's portfolios (组合列表) */
export async function portfolios(): Promise<any> {
const data = await request("/v5/stock/portfolio/list.json", { system: "true" });
return data.data?.items ?? data.data;
}
/** Portfolio detail with current holdings (组合详情 + 持仓) */
export async function portfolioDetail(portfolioId: string): Promise<any> {
const data = await request("/v5/stock/portfolio/stock_list.json", {
portfolio_id: portfolioId,
size: 100,
});
return data.data;
}
/** Portfolio performance / net value history (组合净值走势) */
export async function portfolioPerformance(
portfolioId: string,
period: "1m" | "3m" | "6m" | "1y" | "all" = "all",
): Promise<any> {
const periodMap: Record<string, string> = {
"1m": "1month", "3m": "3month", "6m": "6month", "1y": "1year", "all": "all",
};
const data = await request("/v5/stock/portfolio/performance.json", {
portfolio_id: portfolioId,
period: periodMap[period] ?? period,
});
return data.data;
}
/** Portfolio rebalancing history (组合调仓历史) */
export async function portfolioRebalance(
portfolioId: string,
page = 1,
size = 20,
): Promise<any> {
const data = await request("/v5/stock/portfolio/rebalance/history.json", {
portfolio_id: portfolioId,
page,
size,
});
return data.data;
}