tigeropen 0.3.0 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +55 -2
  2. package/dist/cjs/client/api-response.js +28 -7
  3. package/dist/cjs/client/case-convert.js +4 -3
  4. package/dist/cjs/client/http-client.js +124 -8
  5. package/dist/cjs/client/token-methods.js +42 -0
  6. package/dist/cjs/config/client-config.js +115 -16
  7. package/dist/cjs/config/config-parser.js +19 -9
  8. package/dist/cjs/config/index.js +4 -1
  9. package/dist/cjs/config/token-manager.js +54 -4
  10. package/dist/cjs/index.js +53 -2
  11. package/dist/cjs/model/enums.js +106 -7
  12. package/dist/cjs/model/order-helpers.js +149 -0
  13. package/dist/cjs/model/order-status.js +46 -0
  14. package/dist/cjs/model/quote-requests.js +11 -0
  15. package/dist/cjs/model/trade-requests.js +13 -0
  16. package/dist/cjs/push/index.js +1 -0
  17. package/dist/cjs/push/pb/OrderStatusData.js +24 -0
  18. package/dist/cjs/push/proto-message.js +6 -0
  19. package/dist/cjs/push/push-client.js +117 -19
  20. package/dist/cjs/push/push-message.js +4 -0
  21. package/dist/cjs/push/tick-util.js +172 -0
  22. package/dist/cjs/quote/quote-client.js +584 -42
  23. package/dist/cjs/trade/trade-client.js +334 -32
  24. package/dist/cjs/version.js +4 -0
  25. package/dist/esm/client/api-request.js +1 -1
  26. package/dist/esm/client/api-response.js +29 -8
  27. package/dist/esm/client/case-convert.js +4 -3
  28. package/dist/esm/client/http-client.js +128 -12
  29. package/dist/esm/client/index.js +6 -6
  30. package/dist/esm/client/token-methods.js +37 -0
  31. package/dist/esm/config/client-config.js +118 -20
  32. package/dist/esm/config/config-parser.js +19 -9
  33. package/dist/esm/config/index.js +4 -3
  34. package/dist/esm/config/token-manager.js +55 -5
  35. package/dist/esm/index.js +15 -1
  36. package/dist/esm/logger/index.js +1 -1
  37. package/dist/esm/model/contract-helpers.js +1 -1
  38. package/dist/esm/model/enums.js +104 -6
  39. package/dist/esm/model/order-helpers.js +142 -1
  40. package/dist/esm/model/order-status.js +43 -0
  41. package/dist/esm/model/quote-requests.js +10 -0
  42. package/dist/esm/model/trade-requests.js +12 -0
  43. package/dist/esm/push/index.js +6 -5
  44. package/dist/esm/push/pb/OrderStatusData.js +24 -0
  45. package/dist/esm/push/pb/PushData.js +11 -11
  46. package/dist/esm/push/pb/QuoteBasicData.js +1 -1
  47. package/dist/esm/push/pb/Response.js +1 -1
  48. package/dist/esm/push/pb/index.js +17 -17
  49. package/dist/esm/push/proto-message.js +9 -3
  50. package/dist/esm/push/push-client.js +124 -26
  51. package/dist/esm/push/push-message.js +4 -0
  52. package/dist/esm/push/tick-util.js +165 -0
  53. package/dist/esm/quote/index.js +1 -1
  54. package/dist/esm/quote/quote-client.js +553 -44
  55. package/dist/esm/signer/index.js +2 -2
  56. package/dist/esm/trade/index.js +1 -1
  57. package/dist/esm/trade/trade-client.js +303 -34
  58. package/dist/esm/version.js +1 -0
  59. package/dist/types/client/api-response.d.ts +6 -4
  60. package/dist/types/client/case-convert.d.ts +3 -1
  61. package/dist/types/client/http-client.d.ts +32 -1
  62. package/dist/types/client/token-methods.d.ts +34 -0
  63. package/dist/types/config/client-config.d.ts +22 -1
  64. package/dist/types/config/index.d.ts +3 -1
  65. package/dist/types/config/token-manager.d.ts +27 -3
  66. package/dist/types/index.d.ts +22 -1
  67. package/dist/types/model/enums.d.ts +77 -7
  68. package/dist/types/model/order-helpers.d.ts +52 -1
  69. package/dist/types/model/order-status.d.ts +14 -0
  70. package/dist/types/model/order.d.ts +127 -10
  71. package/dist/types/model/quote-requests.d.ts +356 -0
  72. package/dist/types/model/quote.d.ts +391 -4
  73. package/dist/types/model/trade-requests.d.ts +309 -0
  74. package/dist/types/model/trade.d.ts +231 -5
  75. package/dist/types/push/callbacks.d.ts +3 -7
  76. package/dist/types/push/index.d.ts +1 -0
  77. package/dist/types/push/pb/OrderStatusData.d.ts +4 -0
  78. package/dist/types/push/push-client.d.ts +36 -3
  79. package/dist/types/push/push-message.d.ts +4 -0
  80. package/dist/types/push/tick-util.d.ts +30 -0
  81. package/dist/types/quote/quote-client.d.ts +193 -15
  82. package/dist/types/trade/trade-client.d.ts +136 -18
  83. package/dist/types/version.d.ts +1 -0
  84. package/package.json +5 -2
@@ -0,0 +1,30 @@
1
+ import type { TradeTickData } from './pb/TradeTickData';
2
+ /** Returns the full exchange name for a partCode letter, or the raw code if unknown. */
3
+ export declare function getPartNameByCode(code: string): string;
4
+ /** Returns the short exchange name for a partCode letter, or the raw code if unknown. */
5
+ export declare function getPartShortNameByCode(code: string): string;
6
+ /** Resolves a raw cond character to a readable string. */
7
+ export declare function getTradeCondByCode(isUs: boolean, ch: string): string;
8
+ /** Reports whether symbol is a US stock (uppercase letters, optional dot suffix). */
9
+ export declare function isUsStockSymbol(symbol: string): boolean;
10
+ /** Single decoded tick from a push message. */
11
+ export interface PushTick {
12
+ sn: number;
13
+ time: number;
14
+ price: number;
15
+ volume: number;
16
+ tickType: string;
17
+ cond: string;
18
+ partCode: string;
19
+ partName: string;
20
+ }
21
+ /** Decoded push trade tick message — equivalent to Java TradeTick. */
22
+ export interface PushTradeTick {
23
+ symbol: string;
24
+ secType: string;
25
+ quoteLevel: string;
26
+ timestamp: number;
27
+ ticks: PushTick[];
28
+ }
29
+ /** Decodes a TradeTickData pb message into a PushTradeTick with resolved partCode/partName. */
30
+ export declare function convertTradeTick(src: TradeTickData): PushTradeTick;
@@ -5,13 +5,19 @@
5
5
  * Request parameters are written in camelCase in TypeScript and are
6
6
  * converted to snake_case on the wire automatically.
7
7
  */
8
- import type { HttpClient } from '../client/http-client';
9
- import type { MarketState, Brief, Kline, Timeline, TradeTick, Depth, OptionExpiration, OptionChain, FutureExchange, FutureContractInfo, FutureQuote, FutureKline, FinancialDailyItem, FinancialReportItem, CorporateAction, CapitalFlow, CapitalDistribution, ScannerResult, QuotePermission, FinancialDailyRequest, FinancialReportRequest, CorporateActionRequest, FutureKlineRequest, MarketScannerRequest } from '../model/quote';
8
+ import { HttpClient } from '../client/http-client';
9
+ import type { ClientConfig } from '../config/client-config';
10
+ import type { TokenManager } from '../config/token-manager';
11
+ import type { MarketState, Brief, Kline, KlineItem, Timeline, TradeTick, Depth, OptionExpiration, OptionChain, OptionChainFilter, FutureExchange, FutureContractInfo, FutureQuote, FutureKline, FutureKlineItem, FinancialDailyItem, FinancialReportItem, CorporateAction, CorporateSymbolChange, CorporateDelisting, CorporateIPO, CapitalFlow, CapitalDistribution, ScannerResult, QuotePermission, MarketScannerRequest, SymbolName, TradeMeta, StockDetail, StockBroker, StockIndustry, TradeRankItem, ShortInterest, KlineQuota, OptionAnalysis, OptionSymbol, FutureMainContractHistory, FutureTradingTime, FutureTradeTickItem, FutureDepth, WarrantBrief, WarrantFilterResult, IndustryItem, IndustryStock, TradingCalendarItem, ExchangeRate, FinancialCurrency, QuoteOvernight, MarketScannerTagGroup, FundContractInfo, FundQuote, FundHistoryQuote, FinancialDailyRequest, FinancialReportRequest, CorporateActionRequest } from '../model/quote';
12
+ import type { BriefRequest, DepthQuoteRequest, TradeTickRequest, FutureBriefRequest, SymbolsRequest, TradeMetasRequest, StockDetailsRequest, StockDelayBriefsRequest, KlineRequest, KlineByPageRequest, TimelineRequest, TimelineHistoryRequest, TradeRankRequest, ShortInterestRequest, StockBrokerRequest, StockFundamentalRequest, StockIndustryRequest, KlineQuotaRequest, QuotePermissionRequest, OptionTradeTicksRequest, OptionTimelineRequest, OptionDepthRequest, OptionSymbolsRequest, OptionAnalysisRequest, FutureContractSingleRequest, AllFutureContractsRequest, FutureContinuousContractsRequest, FutureHistoryMainContractRequest, FutureKlineRequest, FutureKlineByPageRequest, FutureTradeTicksRequest, FutureDepthRequest, FutureTradingTimesRequest, FundSymbolsRequest, FundContractsRequest, FundQuoteRequest, FundHistoryQuoteRequest, WarrantBriefsRequest, WarrantFilterRequest, IndustryListRequest, IndustryStocksRequest, TradingCalendarRequest, FinancialExchangeRateRequest, FinancialCurrencyRequest, MarketScannerTagsRequest, QuoteOvernightRequest } from '../model/quote-requests';
10
13
  /**
11
14
  * Parse an OCC-style option identifier like "AAPL 260619C00150000"
12
15
  * into its component parts.
16
+ *
17
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
18
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
13
19
  */
14
- export declare function parseOptionIdentifier(identifier: string): {
20
+ export declare function parseOptionIdentifier(identifier: string, timezone?: string): {
15
21
  symbol: string;
16
22
  expiryMs: number;
17
23
  right: string;
@@ -21,24 +27,73 @@ export declare function parseOptionIdentifier(identifier: string): {
21
27
  export declare class QuoteClient {
22
28
  private httpClient;
23
29
  constructor(httpClient: HttpClient);
30
+ /** Create a QuoteClient directly from a ClientConfig — no need to construct HttpClient manually. */
31
+ static fromConfig(config: ClientConfig): QuoteClient;
32
+ /** Call the `user_token_refresh` API and return the new token. Read-only. */
33
+ queryToken(): Promise<string>;
34
+ /** Refresh the token and update the in-memory config token. */
35
+ refreshToken(tokenManager?: TokenManager | null): Promise<void>;
36
+ /**
37
+ * Start background token auto-refresh. Returns a TokenManager to stop with `tm.stopAutoRefresh()`.
38
+ *
39
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
40
+ * @param checkIntervalMs - How often to check, in milliseconds (default 300 000 / 5 min).
41
+ * @param tokenWriter - Optional callback invoked after each successful refresh.
42
+ */
43
+ startTokenAutoRefresh(refreshDurationSecs: number, checkIntervalMs?: number, tokenWriter?: (token: string) => void): TokenManager;
24
44
  private callInto;
45
+ /**
46
+ * Some endpoints return either a list or a single object depending on the
47
+ * server response shape (future_contract_by_contract_code /
48
+ * future_continuous_contracts). Unify into an array.
49
+ */
50
+ private callIntoListOrObject;
51
+ /** Unwrap server {"items":[...]} envelope. */
52
+ private callIntoItems;
25
53
  getMarketState(market: string): Promise<MarketState[]>;
26
- getBrief(symbols: string[]): Promise<Brief[]>;
27
- getKline(symbol: string, period: string): Promise<Kline[]>;
54
+ /** Real-time stock quotes. wire: quote_real_time */
55
+ getRealTimeQuote(req: BriefRequest): Promise<Brief[]>;
56
+ /** @deprecated Use getRealTimeQuote instead. */
57
+ getBrief(req: BriefRequest): Promise<Brief[]>;
58
+ getKline(req: KlineRequest): Promise<Kline[]>;
28
59
  getTimeline(symbols: string[]): Promise<Timeline[]>;
29
- getTradeTick(symbols: string[]): Promise<TradeTick[]>;
30
- /** Depth snapshot. market is required (US / HK supported). */
31
- getQuoteDepth(symbol: string, market: string): Promise<Depth[]>;
32
- getOptionExpiration(symbol: string): Promise<OptionExpiration[]>;
33
- /** Option chain; `expiry` is "YYYY-MM-DD". */
34
- getOptionChain(symbol: string, expiry: string): Promise<OptionChain[]>;
60
+ getTimeline(req: TimelineRequest): Promise<Timeline[]>;
61
+ /** Tick-by-tick trades. wire: trade_tick */
62
+ getTradeTick(req: TradeTickRequest): Promise<TradeTick[]>;
63
+ /** Depth snapshot. wire: quote_depth */
64
+ getQuoteDepth(req: DepthQuoteRequest): Promise<Depth[]>;
65
+ getOptionExpiration(symbols: string[], market?: string): Promise<OptionExpiration[]>;
66
+ /**
67
+ * Option chain; each item is [symbol, "YYYY-MM-DD"].
68
+ *
69
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
70
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
71
+ * @param returnGreekValue - Whether to return Greeks (delta/gamma/theta/vega/rho).
72
+ * @param optionFilter - Optional filter for in-the-money status, IV range, open interest range, Greeks ranges.
73
+ */
74
+ getOptionChain(items: Array<[string, string]>, timezone?: string, returnGreekValue?: boolean, optionFilter?: OptionChainFilter): Promise<OptionChain[]>;
75
+ /**
76
+ * Option K-line by OCC-style identifier.
77
+ *
78
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
79
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
80
+ * @param limit - Maximum number of bars to return.
81
+ * @param sortDir - Sort direction ('asc' or 'desc').
82
+ */
83
+ getOptionKline(identifiers: string[], period: string, beginTime?: number, endTime?: number, timezone?: string, limit?: number, sortDir?: string): Promise<Kline[]>;
84
+ /**
85
+ * Real-time option quotes by OCC-style identifier.
86
+ *
87
+ * @param timezone - Optional IANA timezone for expiry conversion (e.g. 'America/New_York').
88
+ * If omitted, defaults to America/New_York for US symbols and Asia/Hong_Kong for .HK symbols.
89
+ */
90
+ getOptionQuote(identifiers: string[], timezone?: string): Promise<Brief[]>;
91
+ /** @deprecated Use getOptionQuote instead. */
35
92
  getOptionBrief(identifiers: string[]): Promise<Brief[]>;
36
- getOptionKline(identifier: string, period: string): Promise<Kline[]>;
37
93
  getFutureExchange(): Promise<FutureExchange[]>;
38
94
  getFutureContracts(exchange: string): Promise<FutureContractInfo[]>;
39
- getFutureRealTimeQuote(contractCodes: string[]): Promise<FutureQuote[]>;
40
- /** Futures K-line; use -1 for unbounded beginTime / endTime. */
41
- getFutureKline(req: FutureKlineRequest): Promise<FutureKline[]>;
95
+ /** Real-time futures quotes. wire: future_real_time_quote */
96
+ getFutureRealTimeQuote(req: FutureBriefRequest): Promise<FutureQuote[]>;
42
97
  getFinancialDaily(req: FinancialDailyRequest): Promise<FinancialDailyItem[]>;
43
98
  getFinancialReport(req: FinancialReportRequest): Promise<FinancialReportItem[]>;
44
99
  /**
@@ -49,4 +104,127 @@ export declare class QuoteClient {
49
104
  getCapitalDistribution(symbol: string, market: string): Promise<CapitalDistribution | undefined>;
50
105
  marketScanner(req: MarketScannerRequest): Promise<ScannerResult | undefined>;
51
106
  grabQuotePermission(): Promise<QuotePermission[]>;
107
+ /** All symbol codes (string list). wire: all_symbols */
108
+ getSymbols(req: SymbolsRequest): Promise<string[]>;
109
+ /** All symbols with names. wire: all_symbol_names */
110
+ getSymbolNames(req: SymbolsRequest): Promise<SymbolName[]>;
111
+ /** Trade meta (lot size / tick size). wire: quote_stock_trade */
112
+ getTradeMetas(req: TradeMetasRequest): Promise<TradeMeta[]>;
113
+ /** Stock details. wire: stock_detail. Server returns {items:[...]}. */
114
+ getStockDetails(req: StockDetailsRequest): Promise<StockDetail[]>;
115
+ /** Delayed stock quotes. wire: quote_delay */
116
+ getDelayedQuote(req: StockDelayBriefsRequest): Promise<Brief[]>;
117
+ /** @deprecated Use getDelayedQuote instead. */
118
+ getStockDelayBriefs(req: StockDelayBriefsRequest): Promise<Brief[]>;
119
+ /** Client-side paginated K-line fetch. Loops until totalSize bars are collected, oldest-first. */
120
+ getKlineByPage(req: KlineByPageRequest): Promise<KlineItem[]>;
121
+ /** Historical intraday timeline. wire: history_timeline */
122
+ getTimelineHistory(req: TimelineHistoryRequest): Promise<Timeline[]>;
123
+ /** Trade rank (top movers / volume). wire: trade_rank */
124
+ getTradeRank(req: TradeRankRequest): Promise<TradeRankItem[]>;
125
+ /** Short interest / shortable. wire: quote_shortable_stocks */
126
+ getShortInterest(req: ShortInterestRequest): Promise<ShortInterest[]>;
127
+ /** Broker queue. wire: stock_broker */
128
+ getStockBroker(req: StockBrokerRequest): Promise<StockBroker | undefined>;
129
+ /** Stock fundamentals (server returns grouped map). wire: stock_fundamental */
130
+ getStockFundamental(req: StockFundamentalRequest): Promise<Record<string, unknown>>;
131
+ /** Stock industry classification (array). wire: stock_industry */
132
+ getStockIndustry(req: StockIndustryRequest): Promise<StockIndustry[]>;
133
+ /** Market data permission entries. wire: get_quote_permission */
134
+ getQuotePermission(req: QuotePermissionRequest): Promise<QuotePermission[]>;
135
+ /** K-line quota usage. wire: kline_quota */
136
+ getKlineQuota(req: KlineQuotaRequest): Promise<KlineQuota[]>;
137
+ /** Option tick trades. wire: option_trade_tick
138
+ *
139
+ * Server expects `biz_content` as a top-level JSON array (matches Java's
140
+ * `BatchApiModel` and Python's `MultipleContractParams.to_openapi_dict`).
141
+ * We unwrap the request here so the array is emitted directly instead of
142
+ * `{"contracts": [...]}`. Sending it as an object triggers
143
+ * `biz param error(failed to parse parameters in 'biz_content')`.
144
+ */
145
+ getOptionTradeTicks(req: OptionTradeTicksRequest): Promise<TradeTick[]>;
146
+ /** Option intraday timeline. wire: option_timeline */
147
+ getOptionTimeline(req: OptionTimelineRequest): Promise<Timeline[]>;
148
+ /** Option depth. wire: option_depth */
149
+ getOptionDepth(req: OptionDepthRequest): Promise<Depth[]>;
150
+ /** Available option symbols. wire: option_symbol */
151
+ getOptionSymbols(req: OptionSymbolsRequest): Promise<OptionSymbol[]>;
152
+ /** Option analysis (volatility). wire: option_analysis */
153
+ getOptionAnalysis(req: OptionAnalysisRequest): Promise<OptionAnalysis[]>;
154
+ /** Single futures contract by code. wire: future_contract_by_contract_code */
155
+ getFutureContract(req: FutureContractSingleRequest): Promise<FutureContractInfo[]>;
156
+ /** All futures contracts. wire: future_contracts */
157
+ getAllFutureContracts(req: AllFutureContractsRequest): Promise<FutureContractInfo[]>;
158
+ /** Current main contract. wire: future_current_contract */
159
+ getCurrentFutureContract(req: FutureContractSingleRequest): Promise<FutureContractInfo | undefined>;
160
+ /** Continuous main contracts. wire: future_continuous_contracts */
161
+ getFutureContinuousContracts(req: FutureContinuousContractsRequest): Promise<FutureContractInfo[]>;
162
+ /** Historical main contracts. wire: future_main_contract */
163
+ getFutureHistoryMainContract(req: FutureHistoryMainContractRequest): Promise<FutureMainContractHistory[]>;
164
+ /** Futures K-line. wire: future_kline
165
+ * beginTime / endTime default to -1 when unset (server requires them present).
166
+ * Server expects `contract_codes` (plural) — normalize singular `contractCode`
167
+ * to the plural form so callers can pass either shape. */
168
+ getFutureKline(req: FutureKlineRequest): Promise<FutureKline[]>;
169
+ /** Client-side paginated futures K-line fetch. */
170
+ getFutureKlineByPage(req: FutureKlineByPageRequest): Promise<FutureKlineItem[]>;
171
+ /** Futures tick trades. wire: future_tick (API v3.0)
172
+ * Server returns {contractCode, items:[...]}; unwrap items and backfill contractCode.
173
+ * endIndex defaults to 30 when not set (consistent with Python/Go SDK). */
174
+ getFutureTradeTicks(req: FutureTradeTicksRequest): Promise<FutureTradeTickItem[]>;
175
+ /** Futures depth. wire: future_depth */
176
+ getFutureDepth(req: FutureDepthRequest): Promise<FutureDepth[]>;
177
+ /** Futures trading times (single-object response). wire: future_trading_date */
178
+ getFutureTradingTimes(req: FutureTradingTimesRequest): Promise<FutureTradingTime | undefined>;
179
+ /** Fund symbols. wire: fund_all_symbols */
180
+ getFundSymbols(req: FundSymbolsRequest): Promise<string[]>;
181
+ /** Fund contracts. wire: fund_contracts */
182
+ getFundContracts(req: FundContractsRequest): Promise<FundContractInfo[]>;
183
+ /** Fund real-time NAV. wire: fund_quote */
184
+ getFundQuote(req: FundQuoteRequest): Promise<FundQuote[]>;
185
+ /** Fund historical NAV. wire: fund_history_quote */
186
+ getFundHistoryQuote(req: FundHistoryQuoteRequest): Promise<FundHistoryQuote[]>;
187
+ /** Real-time warrant quotes. wire: warrant_briefs */
188
+ getWarrantQuote(req: WarrantBriefsRequest): Promise<WarrantBrief[]>;
189
+ /** @deprecated Use getWarrantQuote instead. */
190
+ getWarrantBriefs(req: WarrantBriefsRequest): Promise<WarrantBrief[]>;
191
+ /** Warrant filter (paged). wire: warrant_filter */
192
+ getWarrantFilter(req: WarrantFilterRequest): Promise<WarrantFilterResult | undefined>;
193
+ /** Industry list. wire: industry_list
194
+ *
195
+ * `industryLevel` is required by the server — omitting it returns
196
+ * `industry level error, all supported is: [GSECTOR, GGROUP, GIND, GSUBIND]`.
197
+ * Defaults to `GGROUP` when unset, matching Python SDK's
198
+ * `IndustryLevel.GGROUP` default.
199
+ *
200
+ * Wire fields differ from other endpoints (see `IndustryItem`): server sends
201
+ * `nameCN` / `nameEN` / `industryLevel`. This method hydrates the
202
+ * backwards-compat `name` (from `nameEN || nameCN`) and mirrors
203
+ * `industryLevel` to `level` so existing callers keep working.
204
+ */
205
+ getIndustryList(req?: IndustryListRequest): Promise<IndustryItem[]>;
206
+ /** Stocks inside an industry. wire: industry_stock_list */
207
+ getIndustryStocks(req: IndustryStocksRequest): Promise<IndustryStock[]>;
208
+ /** Corporate split (flattened). wire: corporate_action (action_type=split) */
209
+ getCorporateSplit(req: CorporateActionRequest): Promise<CorporateAction[]>;
210
+ /** Corporate dividend (flattened). wire: corporate_action (action_type=dividend) */
211
+ getCorporateDividend(req: CorporateActionRequest): Promise<CorporateAction[]>;
212
+ /** Corporate earnings calendar (flattened). wire: corporate_action (action_type=earning) */
213
+ getCorporateEarningsCalendar(req: CorporateActionRequest): Promise<CorporateAction[]>;
214
+ /** Corporate symbol change (flattened). wire: corporate_action (action_type=symbol_change) */
215
+ getCorporateSymbolChange(req: Omit<CorporateActionRequest, 'actionType'>): Promise<CorporateSymbolChange[]>;
216
+ /** Corporate delisting (flattened). wire: corporate_action (action_type=delisting) */
217
+ getCorporateDelisting(req: Omit<CorporateActionRequest, 'actionType'>): Promise<CorporateDelisting[]>;
218
+ /** Corporate IPO (flattened). wire: corporate_action (action_type=ipo) */
219
+ getCorporateIPO(req: Omit<CorporateActionRequest, 'actionType'>): Promise<CorporateIPO[]>;
220
+ /** Financial currency per symbol. wire: financial_currency */
221
+ getFinancialCurrency(req: FinancialCurrencyRequest): Promise<FinancialCurrency[]>;
222
+ /** FX rates. wire: financial_exchange_rate */
223
+ getFinancialExchangeRate(req: FinancialExchangeRateRequest): Promise<ExchangeRate[]>;
224
+ /** Trading calendar. wire: trading_calendar */
225
+ getTradingCalendar(req: TradingCalendarRequest): Promise<TradingCalendarItem[]>;
226
+ /** Available market-scanner tags. wire: market_scanner_tags */
227
+ getMarketScannerTags(req: MarketScannerTagsRequest): Promise<MarketScannerTagGroup[]>;
228
+ /** Overnight quote. wire: quote_overnight */
229
+ getQuoteOvernight(req: QuoteOvernightRequest): Promise<QuoteOvernight[]>;
52
230
  }
@@ -3,17 +3,44 @@
3
3
  *
4
4
  * All methods return strongly-typed responses; request parameters are
5
5
  * written in camelCase in TypeScript and converted to snake_case on the wire.
6
+ *
7
+ * v0.4.0: 所有查询类方法改为 Request 对象签名(OrdersRequest 等),补齐 17
8
+ * 个新方法(账户管理 / 资产分析 / 资金调拨 / 持仓划转等)。
6
9
  */
7
- import type { HttpClient } from '../client/http-client';
10
+ import { HttpClient } from '../client/http-client';
11
+ import type { ClientConfig } from '../config/client-config';
12
+ import type { TokenManager } from '../config/token-manager';
8
13
  import type { OrderRequest, Order } from '../model/order';
9
14
  import type { Contract } from '../model/contract';
10
15
  import type { Position } from '../model/position';
11
- import type { Asset, PrimeAsset, PreviewResult, PlaceOrderResult, OrderIdResult, Transaction } from '../model/trade';
16
+ import type { Asset, PrimeAsset, PreviewResult, PlaceOrderResult, OrderIdResult, Transaction, ManagedAccount, AnalyticsAsset, AggregateAssets, EstimateTradableQuantity, ForexOrderResult, SegmentFund, SegmentFundAvailableItem, SegmentFundHistoryItem, FundDetails, FundingHistoryItem, PositionTransferRecord, PositionTransferDetail, PositionTransferExternalRecord, OptionExerciseCheckResult, OptionExercisePositionPageResult, OptionExerciseRecordPageResult } from '../model/trade';
17
+ import type { OrdersRequest, GetOrderRequest, OrderTransactionsRequest, PositionsRequest, AssetsRequest, ManagedAccountsRequest, DerivativeContractsRequest, AnalyticsAssetRequest, AggregateAssetsRequest, EstimateTradableQuantityRequest, ForexOrderRequest, SegmentFundRequest, FundDetailsRequest, FundingHistoryRequest, PositionTransferRequest, PositionTransferRecordsRequest, PositionTransferDetailRequest, PositionTransferExternalRecordsRequest, OptionExerciseCheckRequest, OptionExercisePositionRequest, OptionExerciseSubmitRequest, OptionExerciseRecordsRequest, OptionExerciseCancelRequest } from '../model/trade-requests';
12
18
  /** Trading client wrapping all trade-related APIs. */
13
19
  export declare class TradeClient {
14
20
  private httpClient;
15
21
  private account;
16
- constructor(httpClient: HttpClient, account: string);
22
+ private secretKey?;
23
+ constructor(httpClient: HttpClient, account: string, secretKey?: string);
24
+ /** Create a TradeClient directly from a ClientConfig — no need to construct HttpClient manually. */
25
+ static fromConfig(config: ClientConfig, account: string, secretKey?: string): TradeClient;
26
+ /** Call the `user_token_refresh` API and return the new token. Read-only. */
27
+ queryToken(): Promise<string>;
28
+ /**
29
+ * Refresh the token: call the API, update the in-memory config token, and
30
+ * optionally persist via the provided TokenManager (file + writer callback).
31
+ *
32
+ * @param tokenManager - optional TokenManager for file persistence and writer callback
33
+ */
34
+ refreshToken(tokenManager?: TokenManager | null): Promise<void>;
35
+ /**
36
+ * Start background token auto-refresh. Returns a TokenManager that can be
37
+ * used to stop the background task via `tm.stopAutoRefresh()`.
38
+ *
39
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
40
+ * @param checkIntervalMs - How often to check, in milliseconds (default 300 000 / 5 min).
41
+ * @param tokenWriter - Optional callback invoked after each successful refresh.
42
+ */
43
+ startTokenAutoRefresh(refreshDurationSecs: number, checkIntervalMs?: number, tokenWriter?: (token: string) => void): TokenManager;
17
44
  private callInto;
18
45
  /** Strip `{items: [...]}` envelope used by most trade read endpoints. */
19
46
  private callIntoItems;
@@ -24,21 +51,112 @@ export declare class TradeClient {
24
51
  * `symbol` is the underlying (e.g. "AAPL"); `expiry` is "YYYYMMDD".
25
52
  */
26
53
  getQuoteContract(symbol: string, secType: string, expiry: string): Promise<Contract[]>;
54
+ /**
55
+ * Prepare an order request for the wire.
56
+ *
57
+ * The gateway expects `algo_params` as a `[{tag, value}, ...]` array
58
+ * (matching the Python SDK's AlgoParams.to_dict serialization), not the
59
+ * plain object shape that reads naturally in TypeScript. This helper
60
+ * normalizes the object form into the array form on outbound payloads
61
+ * so callers can pass the natural object and TWAP/VWAP orders work end
62
+ * to end without wire-format workarounds.
63
+ *
64
+ * Fields with undefined/null values are dropped; empty algoParams
65
+ * becomes an empty array rather than being stripped, matching the
66
+ * Python SDK behavior when the user passes an empty AlgoParams().
67
+ */
68
+ private marshalOrderForWire;
27
69
  placeOrder(order: OrderRequest): Promise<PlaceOrderResult | undefined>;
28
70
  previewOrder(order: OrderRequest): Promise<PreviewResult | undefined>;
29
- modifyOrder(id: number, order: OrderRequest): Promise<OrderIdResult | undefined>;
30
- cancelOrder(id: number): Promise<OrderIdResult | undefined>;
31
- getOrders(): Promise<Order[]>;
32
- getActiveOrders(): Promise<Order[]>;
33
- getInactiveOrders(): Promise<Order[]>;
34
- /**
35
- * Filled orders in a time range (ms timestamps required by the server).
36
- * Use `Date.now() - 30*24*3600*1000` for "last 30 days".
37
- */
38
- getFilledOrders(startDateMs: number, endDateMs: number): Promise<Order[]>;
39
- /** Transactions for a specific order; `symbol` and `secType` are required. */
40
- getOrderTransactions(id: number, symbol: string, secType: string): Promise<Transaction[]>;
41
- getPositions(): Promise<Position[]>;
42
- getAssets(): Promise<Asset[]>;
43
- getPrimeAssets(): Promise<PrimeAsset | undefined>;
71
+ modifyOrder(id: number | string, order: OrderRequest): Promise<OrderIdResult | undefined>;
72
+ cancelOrder(id: number | string, secretKey?: string): Promise<OrderIdResult | undefined>;
73
+ /**
74
+ * Query all historical orders. v0.4.0: optional OrdersRequest for filtering.
75
+ *
76
+ * @example
77
+ * // Default (unfiltered)
78
+ * await tc.getOrders();
79
+ * // Filter by status
80
+ * await tc.getOrders({ states: ['Filled'], limit: 100 });
81
+ */
82
+ getOrders(req?: OrdersRequest): Promise<Order[]>;
83
+ /** Query active (open) orders. v0.4.0: supports ParentId to filter attached legs. */
84
+ getActiveOrders(req?: OrdersRequest): Promise<Order[]>;
85
+ /** Query inactive/cancelled orders. */
86
+ getInactiveOrders(req?: OrdersRequest): Promise<Order[]>;
87
+ /**
88
+ * Query filled orders. v0.4.0 BREAKING: signature changed from positional
89
+ * (startDateMs, endDateMs) to OrdersRequest object.
90
+ *
91
+ * @example
92
+ * // Last 30 days
93
+ * const now = Date.now();
94
+ * await tc.getFilledOrders({ startDate: now - 30*24*3600*1000, endDate: now });
95
+ */
96
+ getFilledOrders(req?: OrdersRequest): Promise<Order[]>;
97
+ /**
98
+ * Get a single order by ID (v0.4.0 new).
99
+ * Returns `undefined` if no match.
100
+ */
101
+ getOrder(req: GetOrderRequest): Promise<Order | undefined>;
102
+ /**
103
+ * Query order transaction details. v0.4.0 BREAKING: all fields now optional
104
+ * (previously symbol/secType required).
105
+ */
106
+ getOrderTransactions(req: OrderTransactionsRequest): Promise<Transaction[]>;
107
+ /** Query positions. v0.4.0: supports Symbol / SecType / Currency / Market filters. */
108
+ getPositions(req?: PositionsRequest): Promise<Position[]>;
109
+ /** Query assets. v0.4.0: supports sub-account list and aggregation options. */
110
+ getAssets(req?: AssetsRequest): Promise<Asset[]>;
111
+ /** Query prime assets. v0.4.0: takes AssetsRequest for filters. */
112
+ getPrimeAssets(req?: AssetsRequest): Promise<PrimeAsset | undefined>;
113
+ /** Query managed sub-accounts (institutional). */
114
+ getManagedAccounts(req?: ManagedAccountsRequest): Promise<ManagedAccount[]>;
115
+ /**
116
+ * Query derivative contracts list. Same wire as getQuoteContract but accepts
117
+ * full request struct. Python: `get_derivative_contracts`.
118
+ */
119
+ getDerivativeContracts(req: DerivativeContractsRequest): Promise<Contract[]>;
120
+ /** Daily P&L / net-value / holding-value analytics. */
121
+ getAnalyticsAsset(req: AnalyticsAssetRequest): Promise<AnalyticsAsset[]>;
122
+ /** Aggregate assets (prime) by base currency. */
123
+ getAggregateAssets(req?: AggregateAssetsRequest): Promise<AggregateAssets | undefined>;
124
+ /** Estimate tradable quantity given order parameters. */
125
+ getEstimateTradableQuantity(req: EstimateTradableQuantityRequest): Promise<EstimateTradableQuantity | undefined>;
126
+ /** Place forex order (sub-account base-currency swap). */
127
+ placeForexOrder(req: ForexOrderRequest): Promise<ForexOrderResult | undefined>;
128
+ /** Query amount available for inter-segment transfer. Returns array. */
129
+ getSegmentFundAvailable(req: SegmentFundRequest): Promise<SegmentFundAvailableItem[]>;
130
+ /** Query segment fund transfer history. Server returns plain array (no items wrapper). */
131
+ getSegmentFundHistory(req: SegmentFundRequest): Promise<SegmentFundHistoryItem[]>;
132
+ /** Execute an inter-segment fund transfer. */
133
+ transferSegmentFund(req: SegmentFundRequest): Promise<SegmentFund | undefined>;
134
+ /** Cancel a pending inter-segment transfer. */
135
+ cancelSegmentFund(req: SegmentFundRequest): Promise<SegmentFund | undefined>;
136
+ /** Fund-movement details (by segment / currency / fund-type). */
137
+ getFundDetails(req: FundDetailsRequest): Promise<FundDetails[]>;
138
+ /** Funding history (wire method: `transfer_fund`).
139
+ * Server returns bare list (no items wrapper). */
140
+ getFundingHistory(req: FundingHistoryRequest): Promise<FundingHistoryItem[]>;
141
+ /**
142
+ * Internal position transfer (cross sub-account).
143
+ * @note Uses `fromAccount` / `toAccount` (not `account`).
144
+ */
145
+ transferPosition(req: PositionTransferRequest): Promise<PositionTransferRecord | undefined>;
146
+ /** Query internal position transfer records. Uses `accountId` (wire: `account_id`). */
147
+ getPositionTransferRecords(req: PositionTransferRecordsRequest): Promise<PositionTransferRecord[]>;
148
+ /** Query single internal position transfer detail by ID. */
149
+ getPositionTransferDetail(req: PositionTransferDetailRequest): Promise<PositionTransferDetail | undefined>;
150
+ /** Query external position transfer records (DWAC / FOP / etc.). */
151
+ getPositionTransferExternalRecords(req: PositionTransferExternalRecordsRequest): Promise<PositionTransferExternalRecord[]>;
152
+ /** 行权检验:预估行权/作废后正股持仓变化 (wire: option_exercise_check) */
153
+ checkOptionExercise(req: OptionExerciseCheckRequest): Promise<OptionExerciseCheckResult | undefined>;
154
+ /** 查询可行权持仓列表 (wire: option_exercise_position) */
155
+ getOptionExercisePositions(req: OptionExercisePositionRequest): Promise<OptionExercisePositionPageResult | undefined>;
156
+ /** 提交行权/作废申请 (wire: option_exercise_submit) */
157
+ submitOptionExercise(req: OptionExerciseSubmitRequest): Promise<boolean>;
158
+ /** 分页查询行权记录 (wire: option_exercise_record) */
159
+ getOptionExerciseRecords(req: OptionExerciseRecordsRequest): Promise<OptionExerciseRecordPageResult | undefined>;
160
+ /** 撤销行权申请 (wire: option_exercise_cancel) */
161
+ cancelOptionExercise(req: OptionExerciseCancelRequest): Promise<boolean>;
44
162
  }
@@ -0,0 +1 @@
1
+ export declare const SDK_VERSION = "0.4.8";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tigeropen",
3
- "version": "0.3.0",
3
+ "version": "0.5.5",
4
4
  "description": "Tiger Brokers OpenAPI TypeScript SDK for market data, trading, and real-time push",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.js",
@@ -24,12 +24,14 @@
24
24
  "url": "https://github.com/tigerfintech/openapi-typescript-sdk/issues"
25
25
  },
26
26
  "scripts": {
27
- "build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json",
27
+ "build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/fix-esm-imports.mjs",
28
28
  "build:esm": "tsc -p tsconfig.json",
29
29
  "build:cjs": "tsc -p tsconfig.cjs.json",
30
30
  "prepublishOnly": "npm run build",
31
31
  "publish:all": "npm run build && npm publish --registry https://registry.npmjs.org --access public && npm pkg set name=tigeropen && npm publish --registry https://registry.npmjs.org && npm pkg set name=@tigeropenapi/tigeropen",
32
32
  "test": "vitest run",
33
+ "test:unit": "vitest run --config vitest.config.ts",
34
+ "test:integ": "TIGER_RUN_INTEG=true vitest run --config vitest.integ.config.ts",
33
35
  "test:watch": "vitest",
34
36
  "clean": "rm -rf dist",
35
37
  "proto:generate": "protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=./src/push/pb --ts_proto_opt=esModuleInterop=true,outputEncodeMethods=true,outputJsonMethods=false,outputClientImpl=false -I=./proto ./proto/*.proto"
@@ -50,6 +52,7 @@
50
52
  "@types/node": "^25.6.0",
51
53
  "fast-check": "^3.15.0",
52
54
  "ts-proto": "^2.11.6",
55
+ "tsx": "^4.22.4",
53
56
  "typescript": "^5.3.0",
54
57
  "vitest": "^1.2.0"
55
58
  },