/* auto-generated by NAPI-RS */ /* eslint-disable */ /** Account balance */ export declare class AccountBalance { toString(): string toJSON(): any /** Total cash */ get totalCash(): Decimal /** Maximum financing amount */ get maxFinanceAmount(): Decimal /** Remaining financing amount */ get remainingFinanceAmount(): Decimal /** Risk control level */ get riskLevel(): number /** Margin call */ get marginCall(): Decimal /** Currency */ get currency(): string /** Cash details */ get cashInfos(): Array /** Net assets */ get netAssets(): Decimal /** Initial margin */ get initMargin(): Decimal /** Maintenance margin */ get maintenanceMargin(): Decimal /** Buy power */ get buyPower(): Decimal /** Frozen transaction fees */ get frozenTransactionFees(): Array } /** Price alert management context. */ export declare class AlertContext { /** Create a new AlertContext. */ static new(config: Config): AlertContext /** List all price alerts. */ list(): Promise /** * Add a price alert for a security. * * `triggerValue` is a price or percentage string depending on `condition`. */ add(symbol: string, condition: AlertCondition, triggerValue: string, frequency: AlertFrequency): Promise /** * Update a price alert. * * Pass the [`AlertItem`] obtained from [`list`](Self::list). Set * `item.enabled` to `true` to re-enable or `false` to disable before * calling this method. */ update(item: AlertItem): Promise /** Delete one or more price alerts by ID. */ delete(alertIds: Array): Promise } /** Asset context */ export declare class AssetContext { /** Create a new `AssetContext` */ static new(config: Config): AssetContext /** Get statement data list */ statements(req?: GetStatementListRequest | undefined | null): Promise /** Get statement data download URL */ statementDownloadUrl(req: GetStatementDownloadUrlRequest): Promise } /** Brokers */ export declare class Brokers { toString(): string toJSON(): any /** Position */ get position(): number /** Broker IDs */ get brokerIds(): Array } /** Financial calendar context — earnings, dividends, splits, IPOs, macro data. */ export declare class CalendarContext { /** Create a new CalendarContext. */ static new(config: Config): CalendarContext /** * Get financial calendar events. * * `start` and `end` are date strings in `YYYY-MM-DD` format. * `market` is an optional market filter (e.g. `"HK"` or `"US"`). */ financeCalendar(category: CalendarCategory, start: string, end: string, market?: string | undefined | null): Promise } /** Candlestick */ export declare class Candlestick { toString(): string toJSON(): any /** Close price */ get close(): Decimal /** Open price */ get open(): Decimal /** Low price */ get low(): Decimal /** High price */ get high(): Decimal /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Timestamp */ get timestamp(): Date /** Trade session */ get tradeSession(): TradeSession } /** Capital distribution */ export declare class CapitalDistribution { toString(): string toJSON(): any /** Large order */ get large(): Decimal /** Medium order */ get medium(): Decimal /** Small order */ get small(): Decimal } /** Capital distribution response */ export declare class CapitalDistributionResponse { toString(): string toJSON(): any /** Time */ get timestamp(): Date /** Inflow capital data */ get capitalIn(): CapitalDistribution /** Outflow capital data */ get capitalOut(): CapitalDistribution } /** Capital flow line */ export declare class CapitalFlowLine { toString(): string toJSON(): any /** Inflow capital data */ get inflow(): Decimal /** Time */ get timestamp(): Date } /** Account balance */ export declare class CashFlow { toString(): string toJSON(): any /** Cash flow name */ get transactionFlowName(): string /** Outflow direction */ get direction(): CashFlowDirection /** Balance type */ get businessType(): BalanceType /** Cash amount */ get balance(): Decimal /** Cash currency */ get currency(): string /** Business time */ get businessTime(): Date /** Associated Stock code information */ get symbol(): string | null /** Cash flow description */ get description(): string } /** Account balance */ export declare class CashInfo { toString(): string toJSON(): any /** Withdraw cash */ get withdrawCash(): Decimal /** Available cash */ get availableCash(): Decimal /** Frozen cash */ get frozenCash(): Decimal /** Cash to be settled */ get settlingCash(): Decimal /** Currency */ get currency(): string } /** Configuration for Longport SDK */ export declare class Config { /** * Create a new `Config` using API Key authentication * * Optional environment variables are read automatically * (`LONGPORT_HTTP_URL`, `LONGPORT_LANGUAGE`, * `LONGPORT_QUOTE_WS_URL`, `LONGPORT_TRADE_WS_URL`, * `LONGPORT_ENABLE_OVERNIGHT`, `LONGPORT_PUSH_CANDLESTICK_MODE`, * `LONGPORT_PRINT_QUOTE_PACKAGES`, `LONGPORT_LOG_PATH`). Fields * set in `extra` override the corresponding environment variables. * * @param appKey Application key * @param appSecret Application secret * @param accessToken Access token * @param extra Optional extra parameters (override env variables) * * @example * ```javascript * const { Config } = require('longport'); * * const config = Config.fromApikey( * process.env.LONGPORT_APP_KEY, * process.env.LONGPORT_APP_SECRET, * process.env.LONGPORT_ACCESS_TOKEN, * ); * ``` */ static fromApikey(appKey: string, appSecret: string, accessToken: string, extra?: ExtraConfigParams | undefined | null): Config /** * Create a new `Config` from the environment (API Key authentication) * * It first gets the environment variables from the `.env` file in the * current directory. * * # Variables * * - `LONGPORT_LANGUAGE` - Language identifier, `zh-CN`, `zh-HK` or `en` * (Default: `en`) * - `LONGPORT_APP_KEY` - App key * - `LONGPORT_APP_SECRET` - App secret * - `LONGPORT_ACCESS_TOKEN` - Access token * - `LONGPORT_HTTP_URL` - HTTP endpoint url * - `LONGPORT_QUOTE_WS_URL` - Quote websocket endpoint url * - `LONGPORT_TRADE_WS_URL` - Trade websocket endpoint url * - `LONGPORT_ENABLE_OVERNIGHT` - Enable overnight quote, `true` or * `false` (Default: `false`) * - `LONGPORT_PUSH_CANDLESTICK_MODE` - `realtime` or `confirmed` (Default: * `realtime`) * - `LONGPORT_PRINT_QUOTE_PACKAGES` - Print quote packages when connected, * `true` or `false` (Default: `true`) * - `LONGPORT_LOG_PATH` - Log file directory (Default: no logs) */ static fromApikeyEnv(): Config /** * Create a new `Config` for OAuth 2.0 authentication * * OAuth 2.0 is the recommended authentication method that uses Bearer * tokens and does not require app_secret or HMAC signatures. * * Optional environment variables are read automatically * (`LONGPORT_HTTP_URL`, `LONGPORT_LANGUAGE`, * `LONGPORT_QUOTE_WS_URL`, `LONGPORT_TRADE_WS_URL`, * `LONGPORT_ENABLE_OVERNIGHT`, `LONGPORT_PUSH_CANDLESTICK_MODE`, * `LONGPORT_PRINT_QUOTE_PACKAGES`, `LONGPORT_LOG_PATH`). Fields * set in `extra` override the corresponding environment variables. * * @param oauth OAuth handle obtained from `OAuth.build(...)` * @param extra Optional extra parameters (override env variables) * * @example * ```javascript * const { OAuth, Config } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => { * console.log('Open:', url); * }); * const config = Config.fromOAuth(oauth); * ``` */ static fromOAuth(oauth: OAuth, extra?: ExtraConfigParams | undefined | null): Config /** * Gets a new `access_token` * * This method is only available when using **Legacy API Key** * authentication (i.e. `Config.fromApikey`). It is not supported for * OAuth 2.0 mode. * * @param expiredAt - The expiration time of the access token, defaults to * 90 days from now. * * @see https://open.longportapp.com/en/docs/refresh-token-api */ refreshAccessToken(expiredAt?: Date | undefined | null): Promise } /** Content context */ export declare class ContentContext { /** Create a new `ContentContext` */ static new(config: Config): ContentContext /** Get topics created by the current authenticated user */ myTopics(req?: MyTopicsRequest | undefined | null): Promise> /** Create a new topic */ createTopic(req: CreateTopicRequest): Promise /** Get discussion topics list */ topics(symbol: string): Promise> /** Get news list */ news(symbol: string): Promise> } /** Dollar-cost averaging (DCA) plan management context. */ export declare class DcaContext { /** Create a new DCAContext. */ static new(config: Config): DcaContext /** * List DCA plans. * * Pass `null` for `status` to return all plans regardless of status. */ list(status?: DCAStatus | undefined | null, symbol?: string | undefined | null): Promise /** * Create a new DCA plan. * * `dayOfWeek` is required when `frequency` is `Weekly` or `Fortnightly` * (e.g. `"Mon"`). `dayOfMonth` is required when `frequency` is * `Monthly` (e.g. `"15"`). */ create(symbol: string, amount: string, frequency: DCAFrequency, dayOfWeek: string | undefined | null, dayOfMonth: number | undefined | null, allowMargin: boolean): Promise /** Update an existing DCA plan. */ update(planId: string, amount?: string | undefined | null, frequency?: DCAFrequency | undefined | null, dayOfWeek?: string | undefined | null, dayOfMonth?: number | undefined | null, allowMargin?: boolean | undefined | null): Promise /** Pause (suspend) a DCA plan. */ pause(planId: string): Promise /** Resume a suspended DCA plan. */ resume(planId: string): Promise /** Permanently stop a DCA plan. */ stop(planId: string): Promise /** Get execution history for a DCA plan. */ history(planId: string, page: number, limit: number): Promise /** * Get DCA statistics. * * Pass `null` for `symbol` to get aggregate statistics across all plans. */ stats(symbol?: string | undefined | null): Promise /** Check DCA support for a list of securities. */ checkSupport(symbols: Array): Promise /** * Calculate the next projected trade date for a DCA plan. * * `dayOfWeek` is used for `Weekly`/`Fortnightly` frequency (e.g. `"Mon"`). * `dayOfMonth` is used for `Monthly` frequency (1–28). */ calcDate(symbol: string, frequency: DCAFrequency, dayOfWeek?: string | undefined | null, dayOfMonth?: number | undefined | null): Promise /** * Update the advance reminder hours for DCA execution notifications. * * `hours` must be one of `"1"`, `"6"`, or `"12"`. */ setReminder(hours: string): Promise } export type DCAContext = DcaContext export declare class Decimal { static E(): Decimal static E_INVERSE(): Decimal static HALF_PI(): Decimal static MAX(): Decimal static MIN(): Decimal static NEGATIVE_ONE(): Decimal static ONE(): Decimal static ONE_HUNDRED(): Decimal static ONE_THOUSAND(): Decimal static PI(): Decimal static QUARTER_PI(): Decimal static TEN(): Decimal static TWO(): Decimal static TWO_PI(): Decimal static ZERO(): Decimal constructor(value: string | number) static newWithScale(num: number, scale: number): Decimal toString(): string toNumber(): number /** Computes the absolute value. */ abs(): Decimal /** Returns the smallest integer greater than or equal to a number. */ ceil(): Decimal /** Returns the largest integer less than or equal to a number. */ floor(): Decimal /** Returns a new Decimal representing the fractional portion of the number. */ fract(): Decimal /** Returns `true` if the decimal is negative. */ isNegative(): boolean /** Returns `true` if the decimal is positive. */ isPositive(): boolean /** Returns `true` if this Decimal number is equivalent to zero. */ isZero(): boolean /** Returns the maximum of the two numbers. */ max(other: Decimal): Decimal /** Returns the minimum of the two numbers. */ min(other: Decimal): Decimal /** Strips any trailing zero’s from a Decimal and converts `-0` to `0`. */ normalize(): Decimal /** * Returns a new Decimal number with no fractional portion (i.e. an * integer). Rounding currently follows “Bankers Rounding” rules. e.g. * `6.5` -> `6`, `7.5` -> `8` */ round(): Decimal /** * Returns a new Decimal number with the specified number of decimal * points for fractional portion. Rounding currently follows “Bankers * Rounding” rules. e.g. 6.5 -> 6, 7.5 -> 8 */ roundDp(dp: number): Decimal /** * Returns a new Decimal integral with no fractional portion. This is a * true truncation whereby no rounding is performed. */ trunc(): Decimal /** Performs the `+` operation. */ add(other: Decimal): Decimal /** Performs the `-` operation. */ sub(other: Decimal): Decimal /** Performs the `*` operation. */ mul(other: Decimal): Decimal /** Performs the `/` operation. */ div(other: Decimal): Decimal /** Performs the `%` operation. */ rem(other: Decimal): Decimal /** Performs the unary `-` operation. */ neg(): Decimal /** * Returns `true` if the value of this Decimal is greater than the value of * `x`, otherwise returns `false`. */ greaterThan(other: Decimal): boolean /** * Returns `true` if the value of this Decimal is greater than or equal to * the value of `x`, otherwise returns `false`. */ greaterThanOrEqualTo(other: Decimal): boolean /** * Returns `true` if the value of this Decimal equals the value of `x`, * otherwise returns `false`. */ equals(other: Decimal): boolean /** * Returns `true` if the value of this Decimal is less than the value of * `x`, otherwise returns `false`. */ lessThan(other: Decimal): boolean /** * Returns `true` if the value of this Decimal is less than or equal to the * value of `x`, otherwise returns `false`. */ lessThanOrEqualTo(other: Decimal): boolean /** * Compares the values of two Decimals. * * Returns `-1` if the value of this Decimal is less than the value of * `x`. * * Returns `1` if the value of this Decimal is greater than the value of * `x`. * * Returns `0` if the value of this Decimal equals the value of `x`. */ comparedTo(other: Decimal): number /** Computes the sine of a number (in radians) */ sin(): Decimal /** Computes the cosine of a number (in radians) */ cos(): Decimal /** * Computes the tangent of a number (in radians). Panics upon overflow or * upon approaching a limit. */ tan(): Decimal /** The square root of a Decimal. Uses a standard Babylonian method. */ sqrt(): Decimal /** * Raise self to the given Decimal exponent: xy. If `exp` is not * whole then the approximation ey*ln(x) is used. */ pow(exp: Decimal): Decimal /** * Calculates the natural logarithm for a Decimal calculated using Taylor’s * series. */ ln(): Decimal /** Calculates the base 10 logarithm of a specified Decimal number. */ log10(): Decimal /** * The estimated exponential function, ex. Stops calculating when it is * within tolerance of roughly `0.0000002`. */ exp(): Decimal /** * The estimated exponential function, ex using the `tolerance` * provided as a hint as to when to stop calculating. A larger * tolerance will cause the number to stop calculating sooner at the * potential cost of a slightly less accurate result. */ expWithTolerance(tolerance: Decimal): Decimal /** Abramowitz Approximation of Error Function from [wikipedia](https://en.wikipedia.org/wiki/Error_function#Numerical_approximations) */ erf(): Decimal /** The Cumulative distribution function for a Normal distribution */ normCdf(): Decimal /** The Probability density function for a Normal distribution. */ normPdf(): Decimal toJSON(): any } /** Depth */ export declare class Depth { toString(): string toJSON(): any /** Position */ get position(): number /** Price */ get price(): Decimal | null /** Volume */ get volume(): number /** Number of orders */ get orderNum(): number } /** Response for estimate maximum purchase quantity */ export declare class EstimateMaxPurchaseQuantityResponse { toString(): string toJSON(): any /** Cash available quantity */ get cashMaxQty(): Decimal /** Margin available quantity */ get marginMaxQty(): Decimal } /** Trade */ export declare class Execution { toString(): string toJSON(): any /** Order ID */ get orderId(): string /** Execution ID */ get tradeId(): string /** Security code */ get symbol(): string /** Trade done time */ get tradeDoneAt(): Date /** Executed quantity */ get quantity(): Decimal /** Executed price */ get price(): Decimal } /** Filing item */ export declare class FilingItem { toString(): string toJSON(): any /** Filing ID */ get id(): string /** Title */ get title(): string /** Description */ get description(): string /** File name */ get fileName(): string /** File URLs */ get fileUrls(): Array /** Published time */ get publishedAt(): Date } /** Frozen transaction fee */ export declare class FrozenTransactionFee { toString(): string toJSON(): any /** Currency */ get currency(): string /** Frozen transaction fee amount */ get frozenTransactionFee(): Decimal } /** Fundamental data context */ export declare class FundamentalContext { /** Create a new `FundamentalContext` */ static new(config: Config): FundamentalContext /** Get financial reports */ financialReport(symbol: string, kind: FinancialReportKind, period?: FinancialReportPeriod | undefined | null): Promise /** Get analyst ratings (latest + consensus summary) */ institutionRating(symbol: string): Promise /** Get historical analyst rating details */ institutionRatingDetail(symbol: string): Promise /** Get dividend history */ dividend(symbol: string): Promise /** Get detailed dividend information */ dividendDetail(symbol: string): Promise /** Get EPS forecasts */ forecastEps(symbol: string): Promise /** Get financial consensus estimates */ consensus(symbol: string): Promise /** Get valuation metrics (PE / PB / PS / dividend yield) */ valuation(symbol: string): Promise /** Get historical valuation data */ valuationHistory(symbol: string): Promise /** Get industry peer valuation comparison */ industryValuation(symbol: string): Promise /** Get industry valuation distribution */ industryValuationDist(symbol: string): Promise /** Get company overview */ company(symbol: string): Promise /** Get executive and board member information */ executive(symbol: string): Promise /** Get major shareholders */ shareholder(symbol: string): Promise /** Get fund and ETF holders */ fundHolder(symbol: string): Promise /** Get corporate actions */ corpAction(symbol: string): Promise /** Get investor relations data */ investRelation(symbol: string): Promise /** Get operating metrics and financial report summaries */ operating(symbol: string): Promise /** Get buyback data for a security */ buyback(symbol: string): Promise /** Get stock ratings for a security */ ratings(symbol: string): Promise /** Get ranked list of top shareholders */ shareholderTop(symbol: string): Promise /** Get holding history and detail for one shareholder */ shareholderDetail(symbol: string, objectId: number): Promise /** Get valuation comparison between a security and optional peers */ valuationComparison(symbol: string, currency: string, comparisonSymbols?: Array | undefined | null): Promise /** * Get ETF asset allocation (holdings / regional / asset class / * industry) */ etfAssetAllocation(symbol: string): Promise /** List macroeconomic indicators */ macroeconomicIndicators(country?: MacroeconomicCountry | undefined | null, keyword?: string | undefined | null, offset?: number | undefined | null, limit?: number | undefined | null): Promise /** Get historical data for a macroeconomic indicator */ macroeconomic(indicatorCode: string, startDate?: string | undefined | null, endDate?: string | undefined | null, offset?: number | undefined | null, limit?: number | undefined | null): Promise } /** Fund position */ export declare class FundPosition { toString(): string toJSON(): any /** Fund ISIN code */ get symbol(): string /** Current equity */ get currentNetAssetValue(): Decimal /** Current equity time */ get netAssetValueDay(): Date /** Fund name */ get symbolName(): string /** Currency */ get currency(): string /** Net cost */ get costNetAssetValue(): Decimal /** Holding units */ get holdingUnits(): Decimal } /** Fund position channel */ export declare class FundPositionChannel { toString(): string toJSON(): any /** Account type */ get accountChannel(): string /** Fund positions */ get positions(): Array } /** Fund positions response */ export declare class FundPositionsResponse { toString(): string toJSON(): any /** Channels */ get channels(): Array } /** History market temperature response */ export declare class HistoryMarketTemperatureResponse { toString(): string toJSON(): any /** Granularity */ get granularity(): Granularity /** Records */ get records(): Array } export declare class HttpClient { /** * Create a new `HttpClient` using API Key authentication * * `LONGPORT_HTTP_URL` is read from the environment automatically. * Passing `httpUrl` overrides that value. * * @param appKey App key * @param appSecret App secret * @param accessToken Access token * @param httpUrl HTTP endpoint url override (reads * `LONGPORT_HTTP_URL` from env if omitted; falls * back to `https://openapi.longportapp.com`) */ static fromApikey(appKey: string, appSecret: string, accessToken: string, httpUrl?: string | undefined | null): HttpClient /** * Create a new `HttpClient` from environment variables (API Key mode) * * It first reads the `.env` file in the current directory. * * # Variables * * - `LONGPORT_HTTP_URL` - HTTP endpoint url * - `LONGPORT_APP_KEY` - App key * - `LONGPORT_APP_SECRET` - App secret * - `LONGPORT_ACCESS_TOKEN` - Access token */ static fromApikeyEnv(): HttpClient /** * Create a new `HttpClient` from an OAuth handle * * `LONGPORT_HTTP_URL` is read from the environment automatically. * Passing `httpUrl` overrides that value. * * @param oauth OAuth handle obtained from `OAuth.build(...)` * @param httpUrl HTTP endpoint url override (reads `LONGPORT_HTTP_URL` * from env if omitted; falls back to * `https://openapi.longportapp.com`) */ static fromOAuth(oauth: OAuth, httpUrl?: string | undefined | null): HttpClient /** Performs a HTTP request */ request(method: string, path: string, headers?: Record | undefined | null, body?: any | undefined | null): Promise } /** Intraday line */ export declare class IntradayLine { toString(): string toJSON(): any /** Close price of the minute */ get price(): Decimal /** Start time of the minute */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Average price */ get avgPrice(): Decimal } /** Issuer info */ export declare class IssuerInfo { toString(): string toJSON(): any /** Issuer ID */ get issuerId(): number /** Issuer name (zh-CN) */ get nameCn(): string /** Issuer name (en) */ get nameEn(): string /** Issuer name (zh-HK) */ get nameHk(): string } /** Margin ratio */ export declare class MarginRatio { toString(): string toJSON(): any /** Initial margin ratio */ get imFactor(): Decimal /** Maintain the initial margin ratio */ get mmFactor(): Decimal /** Forced close-out margin ratio */ get fmFactor(): Decimal } /** Market data context */ export declare class MarketContext { /** Create a new `MarketContext` */ static new(config: Config): MarketContext /** Get market trading status */ marketStatus(): Promise /** Get top broker holdings */ brokerHolding(symbol: string, period: BrokerHoldingPeriod): Promise /** Get full broker holding details */ brokerHoldingDetail(symbol: string): Promise /** Get daily holding history for a broker */ brokerHoldingDaily(symbol: string, brokerId: string): Promise /** Get A/H premium K-lines */ ahPremium(symbol: string, period: AhPremiumPeriod, count: number): Promise /** Get A/H premium intraday data */ ahPremiumIntraday(symbol: string): Promise /** Get trade statistics */ tradeStats(symbol: string): Promise /** Get market anomaly alerts */ anomaly(market: string): Promise /** Get index constituent stocks */ constituent(symbol: string): Promise /** * Get top movers (stocks with unusual price movements) across one or more * markets */ topMovers(markets: Array, sort: number, date: string | undefined | null, limit: number): Promise /** Get all available rank category keys and labels */ rankCategories(): Promise /** Get a ranked list of securities for the given category key */ rankList(key: string, needArticle: boolean): Promise } /** Market temperature */ export declare class MarketTemperature { toString(): string toJSON(): any /** Temperature value */ get temperature(): number /** Temperature description */ get description(): string /** Market valuation */ get valuation(): number /** Market sentiment */ get sentiment(): number /** Time */ get timestamp(): Date } /** Market trading days */ export declare class MarketTradingDays { toString(): string toJSON(): any /** Trading days */ get tradingDays(): Array /** Half trading days */ get halfTradingDays(): Array } /** Market trading session */ export declare class MarketTradingSession { toString(): string toJSON(): any /** Market */ get market(): Market /** Trading session */ get tradeSessions(): Array } /** Naive date type */ export declare class NaiveDate { constructor(year: number, month: number, day: number) get year(): number get month(): number get day(): number toString(): string toJSON(): any } /** Naive datetime type */ export declare class NaiveDatetime { constructor(date: NaiveDate, time: Time) get date(): NaiveDate get time(): Time toString(): string toJSON(): any } /** News item */ export declare class NewsItem { toString(): string toJSON(): any /** News ID */ get id(): string /** Title */ get title(): string /** Description */ get description(): string /** URL */ get url(): string /** Published time */ get publishedAt(): Date /** Comments count */ get commentsCount(): number /** Likes count */ get likesCount(): number /** Shares count */ get sharesCount(): number } /** * OAuth 2.0 client handle for Longport OpenAPI * * Obtain an instance via `OAuth.build(...)`. * Pass it to `Config.fromOAuth(...)` or `HttpClient.fromOAuth(...)`. * * @example * ```javascript * const { OAuth, Config } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => { * console.log('Open:', url); * }); * const config = Config.fromOAuth(oauth); * ``` */ export declare class OAuth { /** * Build an OAuth 2.0 client. * * If a valid token is already cached on disk * (`~/.longport/openapi/tokens/`) it is reused; otherwise * the browser authorization flow is started and `onOpenUrl` is called * with the authorization URL. * * @param clientId OAuth 2.0 client ID from the Longport developer * portal @param onOpenUrl Called with the authorization URL; open * it in a browser or print it however you like * @param callbackPort TCP port for the local callback server * (default: 60355). Must match one of the redirect * URIs registered for the client. * @returns OAuth handle that can be passed to `Config.fromOAuth` or * `HttpClient.fromOAuth` */ static build(clientId: string, onOpenUrl: ((err: Error | null, arg: string) => void), callbackPort?: number | undefined | null): Promise } /** Quote of option */ export declare class OptionQuote { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Latest price */ get lastDone(): Decimal /** Yesterday's close */ get prevClose(): Decimal /** Open */ get open(): Decimal /** High */ get high(): Decimal /** Low */ get low(): Decimal /** Time of latest price */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Security trading status */ get tradeStatus(): TradeStatus /** Implied volatility */ get impliedVolatility(): Decimal /** Number of open positions */ get openInterest(): number /** Exprity date */ get expiryDate(): NaiveDate /** Strike price */ get strikePrice(): Decimal /** Contract multiplier */ get contractMultiplier(): Decimal /** Option type */ get contractType(): OptionType /** Contract size */ get contractSize(): Decimal /** Option direction */ get direction(): OptionDirection /** Underlying security historical volatility of the option */ get historicalVolatility(): Decimal /** Underlying security symbol of the option */ get underlyingSymbol(): string } /** Daily option volume response */ export declare class OptionVolumeDaily { toString(): string toJSON(): any /** Security symbol */ get symbol(): string /** Daily stats */ get stats(): Array } /** One day's option volume stat */ export declare class OptionVolumeDailyStat { toString(): string toJSON(): any /** Underlying security symbol */ get symbol(): string /** Trading date */ get date(): NaiveDate /** Call volume */ get callVolume(): number /** Put volume */ get putVolume(): number /** Call open interest */ get callOpenInterest(): number /** Put open interest */ get putOpenInterest(): number /** Total options volume (calls + puts) */ get totalVolume(): number /** Total open interest (calls + puts) */ get totalOpenInterest(): number /** Put/call volume ratio */ get pcVol(): number /** Put/call open interest ratio */ get pcOi(): number } /** Order */ export declare class Order { toString(): string toJSON(): any /** Order ID */ get orderId(): string /** Order status */ get status(): OrderStatus /** Stock name */ get stockName(): string /** Submitted quantity */ get quantity(): Decimal /** Executed quantity */ get executedQuantity(): Decimal /** Submitted price */ get price(): Decimal | null /** Executed price */ get executedPrice(): Decimal | null /** Submitted time */ get submittedAt(): Date /** Order side */ get side(): OrderSide /** Security code */ get symbol(): string /** Order type */ get orderType(): OrderType /** Last done */ get lastDone(): Decimal | null /** `LIT` / `MIT` Order Trigger Price */ get triggerPrice(): Decimal | null /** Rejected Message or remark */ get msg(): string /** Order tag */ get tag(): OrderTag /** Time in force type */ get timeInForce(): TimeInForceType /** Long term order expire date */ get expireDate(): NaiveDate | null /** Last updated time */ get updatedAt(): Date | null /** Conditional order trigger time */ get triggerAt(): Date | null /** `TSMAMT` / `TSLPAMT` order trailing amount */ get trailingAmount(): Decimal | null /** `TSMPCT` / `TSLPPCT` order trailing percent */ get trailingPercent(): Decimal | null /** `TSLPAMT` / `TSLPPCT` order limit offset amount */ get limitOffset(): Decimal | null /** Conditional order trigger status */ get triggerStatus(): TriggerStatus | null /** Currency */ get currency(): string /** Enable or disable outside regular trading hours */ get outsideRth(): OutsideRTH | null /** Limit depth level */ get limitDepthLevel(): number | null /** Trigger count */ get triggerCount(): number | null /** Monitor price */ get monitorPrice(): Decimal | null /** Remark */ get remark(): string } /** Order charge detail */ export declare class OrderChargeDetail { toString(): string toJSON(): any /** Total charges amount */ get totalAmount(): Decimal /** Settlement currency */ get currency(): string /** Order charge items */ get items(): Array } /** Order charge fee */ export declare class OrderChargeFee { toString(): string toJSON(): any /** Charge code */ get code(): string /** Charge name */ get name(): string /** Charge amount */ get amount(): Decimal /** Charge currency */ get currency(): string } /** Order charge item */ export declare class OrderChargeItem { toString(): string toJSON(): any /** Charge category code */ get code(): ChargeCategoryCode /** Charge category name */ get name(): string /** Charge details */ get fees(): Array } /** Order detail */ export declare class OrderDetail { toString(): string toJSON(): any /** Order ID */ get orderId(): string /** Order status */ get status(): OrderStatus /** Stock name */ get stockName(): string /** Submitted quantity */ get quantity(): Decimal /** Executed quantity */ get executedQuantity(): Decimal /** Submitted price */ get price(): Decimal | null /** Executed price */ get executedPrice(): Decimal | null /** Submitted time */ get submittedAt(): Date /** Order side */ get side(): OrderSide /** Security code */ get symbol(): string /** Order type */ get orderType(): OrderType /** Last done */ get lastDone(): Decimal | null /** `LIT` / `MIT` Order Trigger Price */ get triggerPrice(): Decimal | null /** Rejected Message or remark */ get msg(): string /** Order tag */ get tag(): OrderTag /** Time in force type */ get timeInForce(): TimeInForceType /** Long term order expire date */ get expireDate(): NaiveDate | null /** Last updated time */ get updatedAt(): Date | null /** Conditional order trigger time */ get triggerAt(): Date | null /** `TSMAMT` / `TSLPAMT` order trailing amount */ get trailingAmount(): Decimal | null /** `TSMPCT` / `TSLPPCT` order trailing percent */ get trailingPercent(): Decimal | null /** `TSLPAMT` / `TSLPPCT` order limit offset amount */ get limitOffset(): Decimal | null /** Conditional order trigger status */ get triggerStatus(): TriggerStatus | null /** Currency */ get currency(): string /** Enable or disable outside regular trading hours */ get outsideRth(): OutsideRTH | null /** Limit depth level */ get limitDepthLevel(): number | null /** Trigger count */ get triggerCount(): number | null /** Monitor price */ get monitorPrice(): Decimal | null /** Remark */ get remark(): string /** Commission-free Status */ get freeStatus(): CommissionFreeStatus /** Commission-free amount */ get freeAmount(): Decimal | null /** Commission-free currency */ get freeCurrency(): string | null /** Deduction status */ get deductionsStatus(): DeductionStatus /** Deduction amount */ get deductionsAmount(): Decimal | null /** Deduction currency */ get deductionsCurrency(): string | null /** Platform fee deduction status */ get platformDeductedStatus(): DeductionStatus /** Platform deduction amount */ get platformDeductedAmount(): Decimal | null /** Platform deduction currency */ get platformDeductedCurrency(): string | null /** Order history details */ get history(): Array /** Order charges */ get chargeDetail(): OrderChargeDetail } /** Order history detail */ export declare class OrderHistoryDetail { toString(): string toJSON(): any /** * Executed price for executed orders, submitted price for expired, * canceled, rejected orders, etc. */ get price(): Decimal /** * Executed quantity for executed orders, remaining quantity for expired, * canceled, rejected orders, etc. */ get quantity(): Decimal /** Order status */ get status(): OrderStatus /** Execution or error message */ get msg(): string /** Occurrence time */ get time(): Date } /** My topic item (topic created by the current authenticated user) */ export declare class OwnedTopic { toString(): string toJSON(): any /** Topic ID */ get id(): string /** Title */ get title(): string /** Plain text excerpt */ get description(): string /** Markdown body */ get body(): string /** Author */ get author(): TopicAuthor /** Related stock tickers */ get tickers(): Array /** Hashtag names */ get hashtags(): Array /** Images */ get images(): Array /** Likes count */ get likesCount(): number /** Comments count */ get commentsCount(): number /** Views count */ get viewsCount(): number /** Shares count */ get sharesCount(): number /** Content type: "article" or "post" */ get topicType(): string /** URL to the full topic page */ get detailUrl(): string /** Created time */ get createdAt(): Date /** Updated time */ get updatedAt(): Date } /** Participant info */ export declare class ParticipantInfo { toString(): string toJSON(): any /** Broker IDs */ get brokerIds(): Array /** Participant name (zh-CN) */ get nameCn(): string /** Participant name (en) */ get nameEn(): string /** Participant name (zh-HK) */ get nameHk(): string } /** Portfolio analytics context — exchange rates and P&L analysis. */ export declare class PortfolioContext { /** Create a new PortfolioContext. */ static new(config: Config): PortfolioContext /** Get exchange rates for supported currencies. */ exchangeRate(): Promise /** * Get portfolio P&L analysis (summary + per-security breakdown). * * `start` and `end` are optional date strings in `YYYY-MM-DD` format. */ profitAnalysis(start?: string | undefined | null, end?: string | undefined | null): Promise /** * Get P&L detail for a specific security. * * `start` and `end` are optional date strings in `YYYY-MM-DD` format. */ profitAnalysisDetail(symbol: string, start?: string | undefined | null, end?: string | undefined | null): Promise /** * Get paginated P&L analysis grouped by market. * * All filter parameters are optional. `page` is 1-based (default 1); * `size` controls the page size (default 20). * `start` and `end` are optional date strings in `YYYY-MM-DD` format. */ profitAnalysisByMarket(market: string | undefined | null, start: string | undefined | null, end: string | undefined | null, currency: string | undefined | null, page: number, size: number): Promise /** * Get paginated P&L flow records for a security. * * `start` and `end` are optional date strings in `YYYY-MM-DD` format. */ profitAnalysisFlows(symbol: string, page: number, size: number, derivative: boolean, start?: string | undefined | null, end?: string | undefined | null): Promise } /** Quote of US pre/post market */ export declare class PrePostQuote { toString(): string toJSON(): any /** Latest price */ get lastDone(): Decimal /** Time of latest price */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** High */ get high(): Decimal /** Low */ get low(): Decimal /** Close of the last trade session */ get prevClose(): Decimal } /** Push real-time brokers */ export declare class PushBrokers { toString(): string toJSON(): any /** Ask brokers */ get askBrokers(): Array /** Bid brokers */ get bidBrokers(): Array } export declare class PushBrokersEvent { get symbol(): string get data(): PushBrokers toString(): string } /** Candlestick updated event */ export declare class PushCandlestick { toString(): string toJSON(): any /** Period type */ get period(): Period /** Candlestick */ get candlestick(): Candlestick /** Is confirmed */ get isConfirmed(): boolean } export declare class PushCandlestickEvent { get symbol(): string get data(): PushCandlestick toString(): string } /** Push real-time depth */ export declare class PushDepth { toString(): string toJSON(): any /** Ask depth */ get asks(): Array /** Bid depth */ get bids(): Array } export declare class PushDepthEvent { get symbol(): string get data(): PushDepth toString(): string } /** Order changed message */ export declare class PushOrderChanged { toString(): string toJSON(): any /** Order side */ get side(): OrderSide /** Stock name */ get stockName(): string /** Submitted quantity */ get submittedQuantity(): Decimal /** Order symbol */ get symbol(): string /** Order type */ get orderType(): OrderType /** Submitted price */ get submittedPrice(): Decimal /** Executed quantity */ get executedQuantity(): Decimal /** Executed price */ get executedPrice(): Decimal | null /** Order ID */ get orderId(): string /** Currency */ get currency(): string /** Order status */ get status(): OrderStatus /** Submitted time */ get submittedAt(): Date /** Last updated time */ get updatedAt(): Date /** Order trigger price */ get triggerPrice(): Decimal | null /** Rejected message or remark */ get msg(): string /** Order tag */ get tag(): OrderTag /** Conditional order trigger status */ get triggerStatus(): TriggerStatus | null /** Conditional order trigger time */ get triggerAt(): Date | null /** Trailing amount */ get trailingAmount(): Decimal | null /** Trailing percent */ get trailingPercent(): Decimal | null /** Limit offset amount */ get limitOffset(): Decimal | null /** Account no */ get accountNo(): string /** Last share */ get lastShare(): Decimal | null /** Last price */ get lastPrice(): Decimal | null /** Remark message */ get remark(): string } /** Push real-time quote */ export declare class PushQuote { toString(): string toJSON(): any /** Latest price */ get lastDone(): Decimal /** Open */ get open(): Decimal /** High */ get high(): Decimal /** Low */ get low(): Decimal /** Time of latest price */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Security trading status */ get tradeStatus(): TradeStatus /** Trade session */ get tradeSession(): TradeSession /** Increase volume between pushes */ get currentVolume(): number /** Increase turnover between pushes */ get currentTurnover(): Decimal } export declare class PushQuoteEvent { get symbol(): string get data(): PushQuote toString(): string } /** Push real-time trades */ export declare class PushTrades { toString(): string toJSON(): any /** Trades data */ get trades(): Array } export declare class PushTradesEvent { get symbol(): string get data(): PushTrades toString(): string } /** Quote context */ export declare class QuoteContext { static new(config: Config): QuoteContext /** Returns the member ID */ memberId(): Promise /** Returns the quote level */ quoteLevel(): Promise /** Returns the quote package details */ quotePackageDetails(): Promise> /** * Set quote callback, after receiving the quote data push, it will call * back to this function. */ setOnQuote(callback: (err: null | Error, event: PushQuoteEvent) => void): void /** * Set depth callback, after receiving the depth data push, it will call * back to this function. */ setOnDepth(callback: (err: null | Error, event: PushDepthEvent) => void): void /** * Set brokers callback, after receiving the brokers data push, it will * call back to this function. */ setOnBrokers(callback: (err: null | Error, event: PushBrokersEvent) => void): void /** * Set trades callback, after receiving the trades data push, it will call * back to this function. */ setOnTrades(callback: (err: null | Error, event: PushTradesEvent) => void): void /** * Set candlestick callback, after receiving the trades data push, it will * call back to this function. */ setOnCandlestick(callback: (err: null | Error, event: PushCandlestickEvent) => void): void /** * Subscribe * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * ctx.setOnQuote((_, event) => console.log(event.toString())); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]); * ``` */ subscribe(symbols: Array, subTypes: Array): Promise /** * Unsubscribe * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]); * await ctx.unsubscribe(["AAPL.US"], [SubType.Quote]); * ``` */ unsubscribe(symbols: Array, subTypes: Array): Promise /** Subscribe security candlesticks */ subscribeCandlesticks(symbol: string, period: Period, tradeSessions: TradeSessions): Promise> /** Unsubscribe security candlesticks */ unsubscribeCandlesticks(symbol: string, period: Period): Promise /** * Get subscription information * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]); * const resp = await ctx.subscriptions(); * console.log(resp.toString()); * ``` */ subscriptions(): Promise> /** * Get basic information of securities * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.staticInfo(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ staticInfo(symbols: Array): Promise> /** * Get quote of securities * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ quote(symbols: Array): Promise> /** * Get quote of option securities * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.optionQuote(["AAPL230317P160000.US"]); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ optionQuote(symbols: Array): Promise> /** * Get quote of warrant securities * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.warrantQuote(["21125.HK"]); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ warrantQuote(symbols: Array): Promise> /** * Get security depth * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.depth("700.HK"); * console.log(resp.toString()); * ``` */ depth(symbol: string): Promise /** * Get security brokers * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.brokers("700.HK"); * console.log(resp.toString()); * ``` */ brokers(symbol: string): Promise /** * Get participants * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.participants(); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ participants(): Promise> /** * Get security trades * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.trades("700.HK", 10); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ trades(symbol: string, count: number): Promise> /** * Get security intraday * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, TradeSessions } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.intraday("700.HK", TradeSessions.Intraday); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ intraday(symbol: string, tradeSessions: TradeSessions): Promise> /** * Get security candlesticks * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, Period, AdjustType, TradeSessions } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, TradeSessions.Intraday); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ candlesticks(symbol: string, period: Period, count: number, adjustType: AdjustType, tradeSessions: TradeSessions): Promise> /** Get security history candlesticks by offset */ historyCandlesticksByOffset(symbol: string, period: Period, adjustType: AdjustType, forward: boolean, datetime: NaiveDatetime | undefined | null, count: number, tradeSessions: TradeSessions): Promise> /** Get security history candlesticks by date */ historyCandlesticksByDate(symbol: string, period: Period, adjustType: AdjustType, start: NaiveDate | undefined | null, end: NaiveDate | undefined | null, tradeSessions: TradeSessions): Promise> /** * Get option chain expiry date list * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.optionChainExpiryDateList("AAPL.US"); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ optionChainExpiryDateList(symbol: string): Promise> /** * Get option chain info by date * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, NaiveDate } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.optionChainInfoByDate("AAPL.US", new NaiveDate(2023, 1, 20)); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ optionChainInfoByDate(symbol: string, expiryDate: NaiveDate): Promise> /** * Get warrant issuers * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.warrantIssuers(); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ warrantIssuers(): Promise> /** * Query warrant list * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, WarrantSortBy, SortOrderType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.warrantList("700.HK", WarrantSortBy.LastDone, SortOrderType.Asc); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ warrantList(symbol: string, sortBy: WarrantSortBy, sortOrder: SortOrderType, warrantType?: Array | undefined | null, issuer?: Array | undefined | null, expiryDate?: Array | undefined | null, priceType?: Array | undefined | null, status?: Array | undefined | null): Promise> /** * Get trading session of the day * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.tradingSession(); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ tradingSession(): Promise> /** * Get trading session of the day * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, Market, NaiveDate } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.tradingDays(Market.HK, new NaiveDate(2022, 1, 20), new NaiveDate(2022, 2, 20)); * console.log(resp.toString()); * ``` */ tradingDays(market: Market, begin: NaiveDate, end: NaiveDate): Promise /** * Get capital flow intraday * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.capitalFlow("700.HK"); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ capitalFlow(symbol: string): Promise> /** * Get capital distribution * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.capitalDistribution("700.HK"); * console.log(resp.toString()); * ``` */ capitalDistribution(symbol: string): Promise /** Get calc indexes */ calcIndexes(symbols: Array, indexes: Array): Promise> /** * Get watchlist * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.watchList(); * console.log(resp.toString()); * ``` */ watchlist(): Promise> /** * Create watchlist group * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const groupId = await ctx.createWatchlistGroup({ * name: "Watchlist1", * securities: ["700.HK", "BABA.US"], * }); * console.log(groupId); * ``` */ createWatchlistGroup(req: CreateWatchlistGroup): Promise /** * Delete watchlist group * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.deleteWatchlistGroup({ id: 10086 }); * ``` */ deleteWatchlistGroup(req: DeleteWatchlistGroup): Promise /** * Update watchlist group * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.updateWatchlistGroup({ * id: 10086, * name: "Watchlist2", * securities: ["700.HK", "BABA.US"], * }); * ``` */ updateWatchlistGroup(req: UpdateWatchlistGroup): Promise /** Pin or unpin watchlist securities */ updatePinned(mode: PinnedMode, symbols: Array): Promise /** Get filings list */ filings(symbol: string): Promise> /** * Get security list * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, Market, SecurityListCategory } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.securityList(Market.US, SecurityListCategory.Overnight); * console.log(resp.toString()); * ``` */ securityList(market: Market, category?: SecurityListCategory | undefined | null): Promise> /** * Get current market temperature * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, Market } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.marketTemperature(Market.HK); * console.log(resp.toString()); * ``` */ marketTemperature(market: Market): Promise /** * Get historical market temperature * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, Market, NaiveDate } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.historyMarketTemperature(Market.HK, new NaiveDate(2023, 1, 20), new NaiveDate(2023, 2, 20)); * console.log(resp.toString()); * ``` */ historyMarketTemperature(market: Market, startDate: NaiveDate, end: NaiveDate): Promise /** * Get real-time quote * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]); * await new Promise((resolve) => setTimeout(resolve, 5000)); * const resp = await ctx.realtimeQuote(["700.HK", "AAPL.US"]); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ realtimeQuote(symbols: Array): Promise> /** * Get real-time depth * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Depth]); * await new Promise((resolve) => setTimeout(resolve, 5000)); * const resp = await ctx.realtimeDepth("700.HK"); * console.log(resp.toString()); * ``` */ realtimeDepth(symbol: string): Promise /** * Get real-time brokers * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers]); * await new Promise((resolve) => setTimeout(resolve, 5000)); * const resp = await ctx.realtimeBrokers("700.HK"); * console.log(resp.toString()); * ``` */ realtimeBrokers(symbol: string): Promise /** * Get real-time trades * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, SubType } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Trade]); * await new Promise((resolve) => setTimeout(resolve, 5000)); * const resp = await ctx.realtimeTrades("700.HK", 10); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ realtimeTrades(symbol: string, count: number): Promise> /** * Get real-time candlesticks * * #### Example * * ```javascript * const { OAuth, Config, QuoteContext, Period } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = QuoteContext.new(Config.fromOAuth(oauth)); * await ctx.subscribeCandlesticks("700.HK", Period.Min_1); * await new Promise((resolve) => setTimeout(resolve, 5000)); * const resp = await ctx.realtimeCandlesticks("700.HK", Period.Min_1, 10); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ realtimeCandlesticks(symbol: string, period: Period, count: number): Promise> /** * Get short interest data for a US or HK security. * * Market is inferred from the symbol suffix (.HK → HK, otherwise US). */ shortPositions(symbol: string, count: number): Promise /** * Get short trade records for a HK or US security. * * Market is inferred from the symbol suffix (.HK → HK, otherwise US). */ shortTrades(symbol: string, count: number): Promise /** Get real-time option call/put volume */ optionVolume(symbol: string): Promise /** Get daily historical option volume */ optionVolumeDaily(symbol: string, timestamp: number, count: number): Promise } export declare class QuotePackageDetail { toString(): string toJSON(): any /** Key */ get key(): string /** Name */ get name(): string /** Description */ get description(): string /** Start time */ get startAt(): Date /** End time */ get endAt(): Date } /** Real-time quote */ export declare class RealtimeQuote { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Latest price */ get lastDone(): Decimal /** Open */ get open(): Decimal /** High */ get high(): Decimal /** Low */ get low(): Decimal /** Time of latest price */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Security trading status */ get tradeStatus(): TradeStatus } /** Screener context */ export declare class ScreenerContext { /** Create a new `ScreenerContext` */ static new(config: Config): ScreenerContext /** Get recommended built-in screener strategies */ screenerRecommendStrategies(market: string): Promise /** Get the current user's saved screener strategies */ screenerUserStrategies(market: string): Promise /** Get detail for one screener strategy by ID */ screenerStrategy(id: number): Promise /** * Search / screen securities using a strategy or custom conditions. * * When `strategyId` is given (Mode A), the strategy is fetched from the AI * endpoint and its filters drive the search. The market is taken from the * strategy response. * * When `strategyId` is `null` / `undefined` (Mode B), `conditions` must be * `ScreenerCondition` objects and `market` is used directly. * * `filter_` is stripped from every `items[].indicators[].key` in the * response before it is returned. */ screenerSearch(market: string, strategyId: number | undefined | null, conditions: Array, show: Array, page: number, size: number): Promise /** Get all available screener indicator definitions */ screenerIndicators(): Promise } /** Security */ export declare class Security { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Security name (zh-CN) */ get nameCn(): string /** Security name (en) */ get nameEn(): string /** Security name (zh-HK) */ get nameHk(): string } /** Security brokers */ export declare class SecurityBrokers { toString(): string toJSON(): any /** Ask brokers */ get askBrokers(): Array /** Bid brokers */ get bidBrokers(): Array } /** Security calc index response */ export declare class SecurityCalcIndex { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Latest price */ get lastDone(): Decimal | null /** Change value */ get changeValue(): Decimal | null /** Change ratio */ get changeRate(): Decimal | null /** Volume */ get volume(): number | null /** Turnover */ get turnover(): Decimal | null /** Year-to-date change ratio */ get ytdChangeRate(): Decimal | null /** Turnover rate */ get turnoverRate(): Decimal | null /** Total market value */ get totalMarketValue(): Decimal | null /** Capital flow */ get capitalFlow(): Decimal | null /** Amplitude */ get amplitude(): Decimal | null /** Volume ratio */ get volumeRatio(): Decimal | null /** PE (TTM) */ get peTtmRatio(): Decimal | null /** PB */ get pbRatio(): Decimal | null /** Dividend ratio (TTM) */ get dividendRatioTtm(): Decimal | null /** Five days change ratio */ get fiveDayChangeRate(): Decimal | null /** Ten days change ratio */ get tenDayChangeRate(): Decimal | null /** Half year change ratio */ get halfYearChangeRate(): Decimal | null /** Five minutes change ratio */ get fiveMinutesChangeRate(): Decimal | null /** Expiry date */ get expiryDate(): NaiveDate | null /** Strike price */ get strikePrice(): Decimal | null /** Upper bound price */ get upperStrikePrice(): Decimal | null /** Lower bound price */ get lowerStrikePrice(): Decimal | null /** Outstanding quantity */ get outstandingQty(): number | null /** Outstanding ratio */ get outstandingRatio(): Decimal | null /** Premium */ get premium(): Decimal | null /** In/out of the bound */ get itmOtm(): Decimal | null /** Implied volatility */ get impliedVolatility(): Decimal | null /** Warrant delta */ get warrantDelta(): Decimal | null /** Call price */ get callPrice(): Decimal | null /** Price interval from the call price */ get toCallPrice(): Decimal | null /** Effective leverage */ get effectiveLeverage(): Decimal | null /** Leverage ratio */ get leverageRatio(): Decimal | null /** Conversion ratio */ get conversionRatio(): Decimal | null /** Breakeven point */ get balancePoint(): Decimal | null /** Open interest */ get openInterest(): number | null /** Delta */ get delta(): Decimal | null /** Gamma */ get gamma(): Decimal | null /** * Theta * * The raw value returned by the API is annualized (scaled by 252 trading * days per year). To obtain the standard per-calendar-day theta, divide * by 252: `theta / 252`. */ get theta(): Decimal | null /** * Vega * * The raw value returned by the API is expressed per 1 percentage-point * change in implied volatility (i.e. the value has been multiplied by * 100). To obtain the standard vega (per unit change in IV), divide by * 100: `vega / 100`. */ get vega(): Decimal | null /** * Rho * * The raw value returned by the API is expressed per 1 percentage-point * change in the risk-free rate (i.e. the value has been multiplied by * 100). To obtain the standard rho (per unit change in rate), divide by * 100: `rho / 100`. */ get rho(): Decimal | null } /** Security depth */ export declare class SecurityDepth { toString(): string toJSON(): any /** Ask depth */ get asks(): Array /** Bid depth */ get bids(): Array } /** Quote of securitity */ export declare class SecurityQuote { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Latest price */ get lastDone(): Decimal /** Yesterday's close */ get prevClose(): Decimal /** Open */ get open(): Decimal /** High */ get high(): Decimal /** Low */ get low(): Decimal /** Time of latest price */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Security trading status */ get tradeStatus(): TradeStatus /** Quote of US pre market */ get preMarketQuote(): PrePostQuote | null /** Quote of US post market */ get postMarketQuote(): PrePostQuote | null /** Quote of US overnight market */ get overnightQuote(): PrePostQuote | null } /** The basic information of securities */ export declare class SecurityStaticInfo { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Security name (zh-CN) */ get nameCn(): string /** Security name (en) */ get nameEn(): string /** Security name (zh-HK) */ get nameHk(): string /** Exchange which the security belongs to */ get exchange(): string /** Trading currency */ get currency(): string /** Lot size */ get lotSize(): number /** Total shares */ get totalShares(): number /** Circulating shares */ get circulatingShares(): number /** HK shares (only HK stocks) */ get hkShares(): number /** Earnings per share */ get eps(): Decimal /** Earnings per share (TTM) */ get epsTtm(): Decimal /** Net assets per share */ get bps(): Decimal /** Dividend (per share), **not** the dividend yield (ratio). */ get dividendYield(): Decimal /** Types of supported derivatives */ get stockDerivatives(): Array /** Board */ get board(): SecurityBoard } /** Community sharelist management context. */ export declare class SharelistContext { /** Create a new SharelistContext. */ static new(config: Config): SharelistContext /** * List user's own and subscribed sharelists. * * `count` controls how many sharelists are returned per category. */ list(count: number): Promise /** Get sharelist detail including constituent stocks and subscription info. */ detail(id: number): Promise /** Get popular (trending) sharelists. */ popular(count: number): Promise /** Create a new sharelist. */ create(name: string, description?: string | undefined | null): Promise /** Delete a sharelist. */ delete(id: number): Promise /** Add securities to a sharelist. */ addSecurities(id: number, symbols: Array): Promise /** Remove securities from a sharelist. */ removeSecurities(id: number, symbols: Array): Promise /** Reorder securities in a sharelist. */ sortSecurities(id: number, symbols: Array): Promise } /** Stock position */ export declare class StockPosition { toString(): string toJSON(): any /** Stock code */ get symbol(): string /** Stock name */ get symbolName(): string /** The number of holdings */ get quantity(): Decimal /** Available quantity */ get availableQuantity(): Decimal /** Currency */ get currency(): string /** * Cost Price(According to the client's choice of average purchase or * diluted cost) */ get costPrice(): Decimal /** Market */ get market(): Market /** Initial position before market opening */ get initQuantity(): Decimal | null } /** Stock position channel */ export declare class StockPositionChannel { toString(): string toJSON(): any /** Account type */ get accountChannel(): string /** Stock positions */ get positions(): Array } /** Stock positions response */ export declare class StockPositionsResponse { toString(): string toJSON(): any /** Channels */ get channels(): Array } /** Strike price info */ export declare class StrikePriceInfo { toString(): string toJSON(): any /** Strike price */ get price(): Decimal /** Security code of call option */ get callSymbol(): string /** Security code of put option */ get putSymbol(): string /** Is standard */ get standard(): boolean } /** Response for submit order request */ export declare class SubmitOrderResponse { toString(): string toJSON(): any /** Order id */ get orderId(): string } /** Subscription */ export declare class Subscription { toString(): string toJSON(): any get symbol(): string get subTypes(): Array get candlesticks(): Array } /** Time type */ export declare class Time { constructor(hour: number, minute: number, second: number) get hour(): number get minute(): number get toString(): string toJSON(): any } /** Topic author */ export declare class TopicAuthor { toString(): string toJSON(): any /** Member ID */ get memberId(): string /** Display name */ get name(): string /** Avatar URL */ get avatar(): string } /** Topic image */ export declare class TopicImage { toString(): string toJSON(): any /** Original image URL */ get url(): string /** Small thumbnail URL */ get sm(): string /** Large image URL */ get lg(): string } /** Topic item */ export declare class TopicItem { toString(): string toJSON(): any /** Topic ID */ get id(): string /** Title */ get title(): string /** Description */ get description(): string /** URL */ get url(): string /** Published time */ get publishedAt(): Date /** Comments count */ get commentsCount(): number /** Likes count */ get likesCount(): number /** Shares count */ get sharesCount(): number } /** Trade */ export declare class Trade { toString(): string toJSON(): any /** Price */ get price(): Decimal /** Volume */ get volume(): number /** Time of trading */ get timestamp(): Date /** Trade type */ get tradeType(): string /** Trade direction */ get direction(): TradeDirection /** Trade session */ get tradeSession(): TradeSession } /** Trade context */ export declare class TradeContext { static new(config: Config): TradeContext /** * Set order changed callback, after receiving the order changed event, it * will call back to this function. */ setOnOrderChanged(callback: (err: null | Error, event: PushOrderChanged) => void): void /** * Subscribe * * #### Example * * ```javascript * const { * OAuth, Config, * TradeContext, * Decimal, * OrderSide, * TimeInForceType, * OrderType, * TopicType, * } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * ctx.setOnOrderChanged((_, event) => console.log(event.toString())); * await ctx.subscribe([TopicType.Private]); * const resp = await ctx.submitOrder({ * symbol: "700.HK", * orderType: OrderType.LO, * side: OrderSide.Buy, * timeInForce: TimeInForceType.Day, * submittedPrice: new Decimal("50"), * submittedQuantity: 200, * }); * console.log(resp.toString()); * ``` */ subscribe(topics: Array): Promise /** Unsubscribe */ unsubscribe(topics: Array): Promise /** * Get history executions * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.historyExecutions({ * symbol: "700.HK", * startAt: new Date(2022, 5, 9), * endAt: new Date(2022, 5, 12), * }); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ historyExecutions(opts?: GetHistoryExecutionsOptions | undefined | null): Promise> /** * Get today executions * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.todayExecutions({ symbol: "700.HK" }); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ todayExecutions(opts?: GetTodayExecutionsOptions | undefined | null): Promise> /** * Get history orders * * #### Example * * ```javascript * const { * OAuth, Config, * TradeContext, * OrderStatus, * OrderSide, * Market, * } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.historyOrders({ * symbol: "700.HK", * status: [OrderStatus.Filled, OrderStatus.New], * side: OrderSide.Buy, * market: Market.HK, * startAt: new Date(2022, 5, 9), * endAt: new Date(2022, 5, 12), * }); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ historyOrders(opts?: GetHistoryOrdersOptions | undefined | null): Promise> /** * Get today orders * * #### Example * * ```javascript * const { * OAuth, Config, * TradeContext, * OrderStatus, * OrderSide, * Market, * } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.todayOrders({ * symbol: "700.HK", * status: [OrderStatus.Filled, OrderStatus.New], * side: OrderSide.Buy, * market: Market.HK, * }); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ todayOrders(opts?: GetTodayOrdersOptions | undefined | null): Promise> /** * Replace order * * #### Example * * ```javascript * const { OAuth, Config, TradeContext, Decimal } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * await ctx.replaceOrder({ * orderId: "709043056541253632", * quantity: 100, * price: new Decimal("300"), * }); * ``` */ replaceOrder(opts: ReplaceOrderOptions): Promise /** * Submit order * * #### Example * * ```javascript * const { * OAuth, Config, * TradeContext, * OrderType, * OrderSide, * Decimal, * TimeInForceType, * } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.submitOrder({ * symbol: "700.HK", * orderType: OrderType.LO, * side: OrderSide.Buy, * timeInForce: TimeInForceType.Day, * submittedQuantity: 200, * submittedPrice: new Decimal("300"), * }); * console.log(resp.toString()); * ``` */ submitOrder(opts: SubmitOrderOptions): Promise /** * Cancel order * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * await ctx.cancelOrder("709043056541253632"); * ``` */ cancelOrder(orderId: string): Promise /** * Get account balance * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.accountBalance(); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ accountBalance(currency?: string | undefined | null): Promise> /** * Get cash flow * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport'); * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.cashFlow({ * startAt: new Date(2022, 5, 9), * endAt: new Date(2022, 5, 12), * }); * for (let obj of resp) { * console.log(obj.toString()); * } * ``` */ cashFlow(opts: GetCashFlowOptions): Promise> /** * Get fund positions * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.fundPositions(); * console.log(resp); * ``` */ fundPositions(symbols?: Array | undefined | null): Promise /** * Get stock positions * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.stockPositions(); * console.log(resp); * ``` */ stockPositions(symbols?: Array | undefined | null): Promise /** * Get margin ratio * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.marginRatio("700.HK"); * console.log(resp); * ``` */ marginRatio(symbol: string): Promise /** * Get order detail * * #### Example * * ```javascript * const { OAuth, Config, TradeContext } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.orderDetail("701276261045858304"); * console.log(resp); * ``` */ orderDetail(orderId: string): Promise /** * Estimating the maximum purchase quantity for Hong Kong and US stocks, * warrants, and options * * #### Example * * ```javascript * const { OAuth, Config, TradeContext, OrderType, OrderSide } = require('longport') * * const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Visit:', url)); * const ctx = TradeContext.new(Config.fromOAuth(oauth)); * const resp = await ctx.estimateMaxPurchaseQuantity({ * symbol: "700.HK", * orderType: OrderType.LO, * side: OrderSide.Buy, * }); * console.log(resp); * ``` */ estimateMaxPurchaseQuantity(opts: EstimateMaxPurchaseQuantityOptions): Promise } /** The information of trading session */ export declare class TradingSessionInfo { toString(): string toJSON(): any /** Being trading time */ get beginTime(): Time /** End trading time */ get endTime(): Time /** Trading session */ get tradeSession(): TradeSession } /** Warrant info */ export declare class WarrantInfo { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Warrant type */ get warrantType(): WarrantType /** Security name */ get name(): string /** Latest price */ get lastDone(): Decimal /** Quote change rate */ get changeRate(): Decimal /** Quote change */ get changeValue(): Decimal /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Expiry date */ get expiryDate(): NaiveDate /** Strike price */ get strikePrice(): Decimal | null /** Upper strike price */ get upperStrikePrice(): Decimal | null /** Lower strike price */ get lowerStrikePrice(): Decimal | null /** Outstanding quantity */ get outstandingQty(): number /** Outstanding ratio */ get outstandingRatio(): Decimal /** Premium */ get premium(): Decimal /** In/out of the bound */ get itmOtm(): Decimal | null /** Implied volatility */ get impliedVolatility(): Decimal | null /** Delta */ get delta(): Decimal | null /** Call price */ get callPrice(): Decimal | null /** Price interval from the call price */ get toCallPrice(): Decimal | null /** Effective leverage */ get effectiveLeverage(): Decimal | null /** Leverage ratio */ get leverageRatio(): Decimal /** Conversion ratio */ get conversionRatio(): Decimal | null /** Breakeven point */ get balancePoint(): Decimal | null /** Status */ get status(): WarrantStatus } /** Quote of warrant */ export declare class WarrantQuote { toString(): string toJSON(): any /** Security code */ get symbol(): string /** Latest price */ get lastDone(): Decimal /** Yesterday's close */ get prevClose(): Decimal /** Open */ get open(): Decimal /** High */ get high(): Decimal /** Low */ get low(): Decimal /** Time of latest price */ get timestamp(): Date /** Volume */ get volume(): number /** Turnover */ get turnover(): Decimal /** Security trading status */ get tradeStatus(): TradeStatus /** Implied volatility */ get impliedVolatility(): Decimal /** Exprity date */ get expiryDate(): NaiveDate /** Last tradalbe date */ get lastTradeDate(): NaiveDate /** Outstanding ratio */ get outstandingRatio(): Decimal /** Outstanding quantity */ get outstandingQuantity(): number /** Conversion ratio */ get conversionRatio(): Decimal /** Warrant type */ get category(): WarrantType /** Strike price */ get strikePrice(): Decimal /** Upper bound price */ get upperStrikePrice(): Decimal /** Lower bound price */ get lowerStrikePrice(): Decimal /** Call price */ get callPrice(): Decimal /** Underlying security symbol of the warrant */ get underlyingSymbol(): string } /** Watchlist group */ export declare class WatchlistGroup { toString(): string toJSON(): any /** Group id */ get id(): number /** Group name */ get name(): string /** Securities */ get securities(): Array } /** Watchlist security */ export declare class WatchlistSecurity { toString(): string toJSON(): any /** Security symbol */ get symbol(): string /** Market */ get market(): Market /** Security name */ get name(): string /** Watched price */ get watchedPrice(): Decimal | null /** Watched time */ get watchedAt(): Date /** Whether the security is pinned to the top of the group */ get isPinned(): boolean } /** Candlestick adjustment type */ export declare const enum AdjustType { /** Actual */ NoAdjust = 0, /** Adjust forward */ ForwardAdjust = 1 } /** A/H premium intraday response */ export interface AhPremiumIntraday { /** Intraday data points */ klines: Array } /** One A/H premium data point */ export interface AhPremiumKline { /** A-share price */ aprice: string /** A-share previous close */ apreclose: string /** H-share price */ hprice: string /** H-share previous close */ hpreclose: string /** CNY/HKD exchange rate */ currencyRate: string /** A/H premium rate (negative = H-share at premium) */ ahpremiumRate: string /** Price spread */ priceSpread: string /** Data point timestamp (unix seconds) */ timestamp: number } /** A/H premium K-lines response */ export interface AhPremiumKlines { /** K-line data points */ klines: Array } /** A/H premium K-line period */ export declare const enum AhPremiumPeriod { /** 1-minute */ Min1 = 0, /** 5-minute */ Min5 = 1, /** 15-minute */ Min15 = 2, /** 30-minute */ Min30 = 3, /** 60-minute */ Min60 = 4, /** Daily */ Day = 5, /** Weekly */ Week = 6, /** Monthly */ Month = 7, /** Yearly */ Year = 8 } /** Alert condition */ export declare const enum AlertCondition { /** Price rises above threshold */ PriceRise = 0, /** Price falls below threshold */ PriceFall = 1, /** Percentage rise above threshold */ PercentRise = 2, /** Percentage fall below threshold */ PercentFall = 3 } /** Alert trigger frequency */ export declare const enum AlertFrequency { /** Trigger once per day */ Daily = 0, /** Trigger every time condition is met */ EveryTime = 1, /** Trigger only once */ Once = 2 } /** One price alert */ export interface AlertItem { /** Alert ID */ id: string /** Condition: "1"=price_rise, "2"=price_fall, "3"=pct_rise, "4"=pct_fall */ indicatorId: string /** Whether the alert is active */ enabled: boolean /** Frequency: 1=daily, 2=every_time, 3=once */ frequency: number /** Scope */ scope: number /** Display text, e.g. "价格涨到 600" */ text: string /** Trigger state flags */ state: Array /** Trigger value: `{"price":"500"}` or `{"chg":"5"}` */ valueMap: any } /** Alert list response */ export interface AlertList { /** Alert groups per security */ lists: Array } /** Alert items for one security */ export interface AlertSymbolGroup { /** Security symbol */ symbol: string /** Ticker code (without market) */ code: string /** Market, e.g. `"HK"` */ market: string /** Security name */ name: string /** Latest price */ price: string /** Day change amount */ chg: string /** Day change percentage */ pChg: string /** Product type (may be empty) */ product: string /** Alert items */ indicators: Array } /** One market anomaly event (e.g. large block trade, margin buying surge) */ export interface AnomalyItem { /** Security symbol */ symbol: string /** Security name */ name: string /** Anomaly type name, e.g. `"大宗交易"`, `"融资买入"` */ alertName: string /** Time of the anomaly (unix timestamp in milliseconds) */ alertTime: number /** Change values — items are accessed as strings by the client */ changeValues: Array /** Sentiment direction: 1 = positive/up, 2 = negative/down */ emotion: number } /** Market anomaly response */ export interface AnomalyResponse { /** Whether anomaly alerts are globally disabled */ allOff: boolean /** List of market anomaly events */ changes: Array } /** One ETF asset allocation group (grouped by element type) */ export interface AssetAllocationGroup { /** Report date (e.g. `20260601`) */ reportDate: string /** Element type of this group */ assetType: ElementType /** Elements */ lists: Array } /** One element of an ETF asset allocation group */ export interface AssetAllocationItem { /** Element name */ name: string /** Security code (holdings only, e.g. `NVDA`) */ code: string /** Position ratio (e.g. `0.0861114`) */ positionRatio: string /** Security symbol (holdings only, e.g. `NVDA.US`) */ symbol: string /** Localized names (locale → name) */ nameLocales: Record /** Holding detail (holdings only) */ holdingDetail?: HoldingDetail } /** ETF asset allocation response */ export interface AssetAllocationResponse { /** Asset allocation groups */ info: Array } export declare const enum AssetType { /** Unknown */ Unknown = 0, /** Stock */ Stock = 1, /** Fund */ Fund = 2, /** Crypto */ Crypto = 3 } export declare const enum BalanceType { /** Unknown */ Unknown = 0, /** Cash */ Cash = 1, /** Stock */ Stock = 2, /** Fund */ Fund = 3 } /** Changes in broker holding over 1 / 5 / 20 / 60 day periods */ export interface BrokerHoldingChanges { /** Current value */ value?: string /** 1-day change */ chg1?: string /** 5-day change */ chg5?: string /** 20-day change */ chg20?: string /** 60-day change */ chg60?: string } /** Daily broker holding history response */ export interface BrokerHoldingDailyHistory { /** Daily broker holding records */ list: Array } /** One day's broker holding record */ export interface BrokerHoldingDailyItem { /** Date in `"2026.05.05"` format */ date: string /** Total shares held */ holding?: string /** Holding ratio */ ratio?: string /** Change vs previous day */ chg?: string } /** Full broker holding detail response */ export interface BrokerHoldingDetail { /** Full list of broker holdings */ list: Array /** Last updated (may be empty) */ updatedAt: string } /** One broker's full holding detail */ export interface BrokerHoldingDetailItem { /** Broker name */ name: string /** Participant number / broker code */ partiNumber: string /** Holding ratio changes over various periods */ ratio: BrokerHoldingChanges /** Share count changes over various periods */ shares: BrokerHoldingChanges /** Whether this is a "strengthening" broker */ strong: boolean } /** One broker entry in a top-holding list */ export interface BrokerHoldingEntry { /** Broker name */ name: string /** Participant number / broker code */ partiNumber: string /** Net change in shares held */ chg?: string /** Whether this is a "strengthening" broker */ strong: boolean } /** Broker holding lookback period */ export declare const enum BrokerHoldingPeriod { /** 1-day change */ Rct1 = 0, /** 5-day change */ Rct5 = 1, /** 20-day change */ Rct20 = 2, /** 60-day change */ Rct60 = 3 } /** Top broker holdings response */ export interface BrokerHoldingTop { /** Top brokers by net buying */ buy: Array /** Top brokers by net selling */ sell: Array /** Last updated (may be empty) */ updatedAt: string } /** Buyback data response */ export interface BuybackData { recentBuybacks?: RecentBuybacks buybackHistory: Array buybackRatios: Array } /** Historical annual buyback data item */ export interface BuybackHistoryItem { fiscalYear: string fiscalYearRange: string netBuyback: string netBuybackYield: string netBuybackGrowthRate: string currency: string } /** Buyback payout and cash-flow ratios */ export interface BuybackRatios { netBuybackPayoutRatio: string netBuybackToCashflowRatio: string } export declare const enum CalcIndex { /** Latest price */ LastDone = 0, /** Change value */ ChangeValue = 1, /** Change rate */ ChangeRate = 2, /** Volume */ Volume = 3, /** Turnover */ Turnover = 4, /** Year-to-date change ratio */ YtdChangeRate = 5, /** Turnover rate */ TurnoverRate = 6, /** Total market value */ TotalMarketValue = 7, /** Capital flow */ CapitalFlow = 8, /** Amplitude */ Amplitude = 9, /** Volume ratio */ VolumeRatio = 10, /** PE (TTM) */ PeTtmRatio = 11, /** PB */ PbRatio = 12, /** Dividend ratio (TTM) */ DividendRatioTtm = 13, /** Five days change ratio */ FiveDayChangeRate = 14, /** Ten days change ratio */ TenDayChangeRate = 15, /** Half year change ratio */ HalfYearChangeRate = 16, /** Five minutes change ratio */ FiveMinutesChangeRate = 17, /** Expiry date */ ExpiryDate = 18, /** Strike price */ StrikePrice = 19, /** Upper bound price */ UpperStrikePrice = 20, /** Lower bound price */ LowerStrikePrice = 21, /** Outstanding quantity */ OutstandingQty = 22, /** Outstanding ratio */ OutstandingRatio = 23, /** Premium */ Premium = 24, /** In/out of the bound */ ItmOtm = 25, /** Implied volatility */ ImpliedVolatility = 26, /** Warrant delta */ WarrantDelta = 27, /** Call price */ CallPrice = 28, /** Price interval from the call price */ ToCallPrice = 29, /** Effective leverage */ EffectiveLeverage = 30, /** Leverage ratio */ LeverageRatio = 31, /** Conversion ratio */ ConversionRatio = 32, /** Breakeven point */ BalancePoint = 33, /** Open interest */ OpenInterest = 34, /** Delta */ Delta = 35, /** Gamma */ Gamma = 36, /** Theta */ Theta = 37, /** Vega */ Vega = 38, /** Rho */ Rho = 39 } /** Calendar event category */ export declare const enum CalendarCategory { /** Earnings reports */ Report = 0, /** Dividend events */ Dividend = 1, /** Stock splits */ Split = 2, /** IPOs */ Ipo = 3, /** Macro-economic data releases */ MacroData = 4, /** Market closure days */ Closed = 5, /** Shareholder / analyst meetings */ Meeting = 6, /** Stock consolidations / mergers */ Merge = 7 } /** One key-value data pair in a calendar event */ export interface CalendarDataKv { /** Key (may be empty) */ key: string /** Formatted display value */ value: string /** Value type code, e.g. `"estimate_eps"` */ valueType: string /** Raw numeric value */ valueRaw: string } /** Events for one calendar date */ export interface CalendarDateGroup { /** Date string, e.g. `"2025-05-02"` */ date: string /** Total event count for this date */ count: number /** Event details */ infos: Array } /** One financial calendar event */ export interface CalendarEventInfo { /** Security symbol */ symbol: string /** Market, e.g. `"HK"` */ market: string /** Event content description */ content: string /** Security name */ counterName: string /** Date type label, e.g. `"盘前"` */ dateType: string /** Event date string, e.g. `"2025.05.02"` */ date: string /** Chart UID (may be empty) */ chartUid: string /** Structured data key-value pairs */ dataKv: Array /** Event type code, e.g. `"financial"` */ eventType: string /** Event datetime (unix timestamp string) */ datetime: string /** Icon URL */ icon: string /** Importance star rating (0–3) */ star: number /** Internal event ID */ id: string /** Financial market session time string */ financialMarketTime: string /** Currency */ currency: string /** Activity type code */ activityType: string } /** Finance calendar response */ export interface CalendarEventsResponse { /** Start date of the query window */ date: string /** Per-day event groups */ list: Array } export declare const enum CashFlowDirection { /** Unknown */ Unknown = 0, /** Out */ Out = 1, /** In */ In = 2 } /** Charge category code */ export declare const enum ChargeCategoryCode { /** Unknown */ Unknown = 0, /** Broker */ Broker = 1, /** Third */ Third = 2 } /** Commission-free Status */ export declare const enum CommissionFreeStatus { /** Unknown */ Unknown = 0, /** None */ None = 1, /** Commission-free amount to be calculated */ Calculated = 2, /** Pending commission-free */ Pending = 3, /** Commission-free applied */ Ready = 4 } /** Company overview response */ export interface CompanyOverview { /** Short name */ name: string /** Full legal name */ companyName: string /** Founding date */ founded: string /** Listing date */ listingDate: string /** Primary listing market */ market: string /** Market region code */ region: string /** Registered address */ address: string /** Office address */ officeAddress: string /** Website */ website: string /** IPO price */ issuePrice?: string /** Shares offered at IPO */ sharesOffered: string /** Chairman */ chairman: string /** Company secretary */ secretary: string /** Auditing institution */ auditInst: string /** Company category */ category: string /** Fiscal year end */ yearEnd: string /** Number of employees */ employees: string /** Phone number */ phone: string /** Fax number */ fax: string /** Email */ email: string /** Legal representative */ legalRepr: string /** CEO / MD */ manager: string /** Business licence number */ busLicense: string /** Accounting firm */ accountingFirm: string /** Securities representative */ securitiesRep: string /** Legal counsel */ legalCounsel: string /** Postal code */ zipCode: string /** Exchange ticker */ ticker: string /** Logo URL */ icon: string /** Business profile */ profile: string /** ADS ratio */ adsRatio: string /** Industry sector code */ sector: number } /** Consensus estimate for one metric */ export interface ConsensusDetail { /** Metric key */ key: string /** Display name */ name: string /** Metric description */ description: string /** Actual value */ actual?: string /** Consensus estimate */ estimate?: string /** Actual minus estimate */ compValue?: string /** Beat/miss description */ compDesc: string /** Comparison code */ comp: string /** Whether actual results are published */ isReleased: boolean } /** Consensus report for one fiscal period */ export interface ConsensusReport { /** Fiscal year */ fiscalYear: number /** Fiscal period code */ fiscalPeriod: string /** Human-readable period label */ periodText: string /** Per-metric consensus details */ details: Array } /** One constituent stock of an index */ export interface ConstituentStock { /** Security symbol */ symbol: string /** Security name */ name: string /** Latest price */ lastDone?: string /** Previous close */ prevClose?: string /** Net capital inflow today */ inflow?: string /** Turnover amount */ balance?: string /** Trading volume (shares) */ amount?: string /** Total shares outstanding */ totalShares?: string /** Tags, e.g. `["领涨龙头"]` */ tags: Array /** Brief description */ intro: string /** Market, e.g. `"HK"` */ market: string /** Circulating shares */ circulatingShares?: string /** Whether this is a delayed quote */ delay: boolean /** Day change percentage */ chg?: string /** Raw trade status code */ tradeStatus: number } /** One corporate action event */ export interface CorpActionItem { /** Internal ID */ id: string /** Date in YYYYMMDD format */ date: string /** Short display date */ dateStr: string /** Date type label */ dateType: string /** Time zone description */ dateZone: string /** Event category */ actType: string /** Description */ actDesc: string /** Machine-readable action code */ action: string /** Whether recent */ recent: boolean /** Whether delayed */ isDelay: boolean /** Delay content */ delayContent: string /** Associated live stream */ live?: CorpActionLive } /** Live stream for a corp action */ export interface CorpActionLive { /** Stream ID */ id: string /** Status code (may be integer or string in API) */ status: string /** Start time */ startedAt: string /** Title */ name: string /** Icon URL */ icon: string } /** Corporate actions response */ export interface CorpActions { /** Corporate action events */ items: Array } /** Options for creating a topic */ export interface CreateTopicRequest { /** Topic title (required) */ title: string /** Topic body in Markdown format (required) */ body: string /** Content type: "article" (long-form) or "post" (short post, default) */ topicType?: string /** Related stock tickers, format: {symbol}.{market}, max 10 */ tickers?: Array /** Hashtag names, max 5 */ hashtags?: Array } /** An request to create a watchlist group */ export interface CreateWatchlistGroup { /** Group name */ name: string /** Securities */ securities?: Array } /** Result of a DCA date calculation */ export interface DcaCalcDateResult { /** Next projected trade date (unix timestamp string) */ tradeDate: string } /** Result of creating or updating a DCA plan */ export interface DcaCreateResult { /** The plan ID */ planId: string } /** DCA investment frequency */ export declare const enum DCAFrequency { /** Daily investment */ Daily = 0, /** Weekly investment */ Weekly = 1, /** Fortnightly (every two weeks) investment */ Fortnightly = 2, /** Monthly investment */ Monthly = 3 } /** One DCA execution record */ export interface DcaHistoryRecord { /** Execution time */ createdAt: string /** Associated order ID */ orderId: string /** Status */ status: string /** Action type */ action: string /** Order type */ orderType: string /** Executed quantity */ executedQty?: string /** Executed price */ executedPrice?: string /** Executed amount */ executedAmount?: string /** Rejection reason (if any) */ rejectedReason: string /** Security symbol */ symbol: string } /** DCA execution history response */ export interface DcaHistoryResponse { /** Execution history records */ records: Array /** Whether more records exist */ hasMore: boolean } /** Response for DCA list and write operations */ export interface DcaList { /** DCA plans */ plans: Array } /** One DCA (dollar-cost averaging) investment plan */ export interface DcaPlan { /** Plan ID */ planId: string /** Plan status */ status: DCAStatus /** Security symbol */ symbol: string /** Member ID */ memberId: string /** Account ID */ aaid: string /** Account channel */ accountChannel: string /** Display account */ displayAccount: string /** Market */ market: Market /** Investment amount per period */ perInvestAmount: string /** Investment frequency */ investFrequency: DCAFrequency /** Day of week for weekly plans (e.g. `"Mon"`) */ investDayOfWeek: string /** Day of month for monthly plans */ investDayOfMonth: string /** Whether margin finance is allowed */ allowMarginFinance: boolean /** Reminder time */ alterHours: string /** Creation time */ createdAt: string /** Last updated time */ updatedAt: string /** Next investment date */ nextTrdDate: string /** Security name */ stockName: string /** Cumulative invested amount */ cumAmount?: string /** Number of completed investment periods */ issueNumber: number /** Average cost */ averageCost?: string /** Cumulative profit/loss */ cumProfit?: string } /** DCA statistics response */ export interface DcaStats { /** Number of active plans */ activeCount: string /** Number of finished plans */ finishedCount: string /** Number of suspended plans */ suspendedCount: string /** Nearest upcoming plans */ nearestPlans: Array /** Days until next investment */ restDays: string /** Total invested amount */ totalAmount?: string /** Total profit/loss */ totalProfit?: string } /** DCA plan status */ export declare const enum DCAStatus { /** Active plan */ Active = 0, /** Suspended plan */ Suspended = 1, /** Finished plan */ Finished = 2 } /** DCA support info for one security */ export interface DcaSupportInfo { /** Security symbol */ symbol: string /** Whether DCA is supported for this security */ supportRegularSaving: boolean } /** Response for DCA support check */ export interface DcaSupportList { /** Support info per security */ infos: Array } /** Deduction status */ export declare const enum DeductionStatus { /** Unknown */ Unknown = 0, /** Pending Settlement */ None = 1, /** Settled with no data */ NoData = 2, /** Settled and pending distribution */ Pending = 3, /** Settled and distributed */ Done = 4 } /** An request to delete a watchlist group */ export interface DeleteWatchlistGroup { /** Group id */ id: number /** Move securities in this group to the default group */ purge: boolean } /** Derivative type */ export declare const enum DerivativeType { /** US stock options */ Option = 0, /** HK warrants */ Warrant = 1 } /** A single dividend event */ export interface DividendItem { /** Security symbol */ symbol: string /** Internal record ID */ id: string /** Human-readable description */ desc: string /** Record / book-close date */ recordDate: string /** Ex-dividend date */ exDate: string /** Payment date */ paymentDate: string } /** Dividend history response */ export interface DividendList { /** List of dividend events */ list: Array } /** ETF asset allocation element type */ export declare const enum ElementType { /** Unknown */ Unknown = 0, /** Holdings */ Holdings = 1, /** Regional */ Regional = 2, /** Asset class */ AssetClass = 3, /** Industry */ Industry = 4 } /** Options for get cash flow request */ export interface EstimateMaxPurchaseQuantityOptions { symbol: string orderType: OrderType side: OrderSide price?: Decimal currency?: string orderId?: string fractionalShares: boolean } /** One currency exchange rate */ export interface ExchangeRate { /** Average rate (base_currency / other_currency) */ averageRate: number /** Base currency, e.g. `"USD"` */ baseCurrency: string /** Bid rate */ bidRate: number /** Offer rate */ offerRate: number /** Other currency, e.g. `"HKD"` */ otherCurrency: string } /** Response for exchange rate query */ export interface ExchangeRates { /** List of exchange rates */ exchanges: Array } /** Executives for one security */ export interface ExecutiveGroup { /** Security symbol */ symbol: string /** Company wiki URL */ forwardUrl: string /** Total executives */ total: number /** Individual executives */ professionals: Array } /** Executive list response */ export interface ExecutiveList { /** Groups of executives per security */ professionalList: Array } /** * Optional extra parameters shared by `Config.fromApikey` and * `Config.fromOAuth`. All fields are optional. */ export interface ExtraConfigParams { /** HTTP API url (default: "https://openapi.longportapp.com") */ httpUrl?: string /** * Websocket url for quote API (default: * "wss://openapi-quote.longportapp.com/v2") */ quoteWsUrl?: string /** * Websocket url for trade API (default: * "wss://openapi-trade.longportapp.com/v2") */ tradeWsUrl?: string /** Language identifier (default: Language.EN) */ language?: Language /** Enable overnight (default: false) */ enableOvernight?: boolean /** Push candlesticks mode (default: PushCandlestickMode.Realtime) */ pushCandlestickMode?: PushCandlestickMode /** * Enable printing the opened quote packages when connected to the server * (default: true). Set to `false` to suppress the output. */ enablePrintQuotePackages?: boolean /** Set the path of the log files (Default: `no logs`) */ logPath?: string } /** Filter warrant expiry date type */ export declare const enum FilterWarrantExpiryDate { /** Less than 3 months */ LT_3 = 0, /** 3 - 6 months */ Between_3_6 = 1, /** 6 - 12 months */ Between_6_12 = 2, /** Greater than 12 months */ GT_12 = 3 } /** Filter warrant in/out of the bounds type */ export declare const enum FilterWarrantInOutBoundsType { /** In bounds */ In = 0, /** Out bounds */ Out = 1 } /** Financial consensus estimates response */ export interface FinancialConsensus { /** Per-period consensus reports */ list: Array /** Index of most recently released period */ currentIndex: number /** Reporting currency */ currency: string /** Available period types */ optPeriods: Array /** Currently returned period type */ currentPeriod: string } /** Financial report kind */ export declare const enum FinancialReportKind { /** Income statement */ IncomeStatement = 0, /** Balance sheet */ BalanceSheet = 1, /** Cash flow statement */ CashFlow = 2, /** All statements */ All = 3 } /** Financial report period type */ export declare const enum FinancialReportPeriod { /** Annual report */ Annual = 0, /** Semi-annual report */ SemiAnnual = 1, /** Q1 report */ Q1 = 2, /** Q2 report */ Q2 = 3, /** Q3 report */ Q3 = 4, /** Full quarterly report */ QuarterlyFull = 5, /** Three-quarter report (first three quarters) */ ThreeQ = 6 } /** * Financial reports response. * The `list` field is a nested object keyed by report kind. */ export interface FinancialReports { /** Raw nested financial data object */ list: any } export declare const enum FlowDirection { /** Unknown */ Unknown = 0, /** Buy */ Buy = 1, /** Sell */ Sell = 2 } /** One profit-analysis flow record */ export interface FlowItem { executedDate: string /** Execution timestamp as a JSON value string */ executedTimestamp: string code: string direction: FlowDirection executedQuantity?: string executedPrice?: string executedCost?: string describe: string } /** EPS forecast response */ export interface ForecastEps { /** EPS forecast snapshots */ items: Array } /** One EPS forecast snapshot */ export interface ForecastEpsItem { /** Median EPS estimate */ forecastEpsMedian?: string /** Mean EPS estimate */ forecastEpsMean?: string /** Lowest EPS estimate */ forecastEpsLowest?: string /** Highest EPS estimate */ forecastEpsHighest?: string /** Total forecasting institutions */ institutionTotal: number /** Institutions that raised their estimate */ institutionUp: number /** Institutions that lowered their estimate */ institutionDown: number /** Forecast window start (ms timestamp) */ forecastStartDate: number /** Forecast window end (ms timestamp) */ forecastEndDate: number } /** A fund or ETF holding the security */ export interface FundHolder { /** Ticker code */ code: string /** Symbol */ symbol: string /** Currency */ currency: string /** Name */ name: string /** Position ratio % */ positionRatio: string /** Report date */ reportDate: string } /** Fund/ETF holders response */ export interface FundHolders { /** Funds and ETFs holding the queried security */ lists: Array } /** Options for get cash flow request */ export interface GetCashFlowOptions { /** Start time */ startAt: Date /** End time */ endAt: Date /** Business type */ businessType?: BalanceType /** Security symbol */ symbol?: string /** Page number */ page?: number /** Page size */ size?: number } /** Options for get history executions request */ export interface GetHistoryExecutionsOptions { /** Security symbol */ symbol?: string /** Start time */ startAt?: Date /** End time */ endAt?: Date } /** Options for get history orders request */ export interface GetHistoryOrdersOptions { /** Security symbol */ symbol?: string /** Order status */ status?: Array /** Order side */ side?: OrderSide /** Market */ market?: Market /** Start time */ startAt?: Date /** End time */ endAt?: Date } /** Options for getting a statement download URL */ export interface GetStatementDownloadUrlRequest { /** File key obtained from the list statements endpoint */ fileKey: string } /** Response for get statement download URL */ export interface GetStatementDownloadUrlResponse { /** Presigned download URL */ url: string } /** Options for listing statements */ export interface GetStatementListRequest { /** Statement type: Daily (1) or Monthly (2) */ statementType?: StatementType /** Start date for pagination */ startDate?: number /** Number of results (default 20) */ limit?: number } /** Response for get statement list */ export interface GetStatementListResponse { /** List of statement items */ list: Array } /** Options for get today executions request */ export interface GetTodayExecutionsOptions { /** Security symbol */ symbol?: string /** Order id */ orderId?: string } /** Options for get today orders request */ export interface GetTodayOrdersOptions { /** Security symbol */ symbol?: string /** Order status */ status?: Array /** Order side */ side?: OrderSide /** Market */ market?: Market /** Order id */ orderId?: string } /** Data granularity */ export declare const enum Granularity { /** Unknown */ Unknown = 0, /** Daily */ Daily = 1, /** Weekly */ Weekly = 2, /** Monthly */ Monthly = 3 } /** Holding detail of an ETF asset allocation element (holdings only) */ export interface HoldingDetail { /** Industry ID */ industryId: string /** Industry name */ industryName: string /** Index counter ID (e.g. `BK/US/CP99000`) */ index: string /** Index name */ indexName: string /** Holding type (e.g. `E` for stock) */ holdingType: string /** Holding type name */ holdingTypeName: string } /** Index constituents response */ export interface IndexConstituents { /** Number of constituent stocks that fell today */ fallNum: number /** Number of constituent stocks unchanged today */ flatNum: number /** Number of constituent stocks that rose today */ riseNum: number /** Constituent stock details */ stocks: Array } /** Industry valuation distribution response */ export interface IndustryValuationDist { /** PE distribution */ pe?: ValuationDist /** PB distribution */ pb?: ValuationDist /** PS distribution */ ps?: ValuationDist } /** Historical valuation snapshot for a peer */ export interface IndustryValuationHistory { /** Unix timestamp string */ date: string /** PE ratio */ pe?: string /** PB ratio */ pb?: string /** PS ratio */ ps?: string } /** Valuation data for one peer security */ export interface IndustryValuationItem { /** Security symbol */ symbol: string /** Company name */ name: string /** Reporting currency */ currency: string /** Total assets */ assets?: string /** Book value per share */ bps?: string /** Earnings per share */ eps?: string /** Dividends per share */ dps?: string /** Dividend yield */ divYld?: string /** Dividend payout ratio */ divPayoutRatio?: string /** 5-year avg dividends per share */ fiveYAvgDps?: string /** PE ratio */ pe?: string /** Historical snapshots */ history: Array } /** Industry peer valuation comparison response */ export interface IndustryValuationList { /** Peer securities */ list: Array } /** Combined analyst rating response */ export interface InstitutionRating { /** Latest rating snapshot */ latest: InstitutionRatingLatest /** Consensus summary */ summary: InstitutionRatingSummary } /** Historical analyst rating detail response */ export interface InstitutionRatingDetail { /** Currency symbol */ ccySymbol: string /** Historical rating distribution time-series */ evaluate: InstitutionRatingDetailEvaluate /** Historical target price time-series */ target: InstitutionRatingDetailTarget } /** Historical rating distribution time-series */ export interface InstitutionRatingDetailEvaluate { /** Weekly rating snapshots */ list: Array } /** One weekly rating distribution snapshot */ export interface InstitutionRatingDetailEvaluateItem { /** Number of "Buy" ratings */ buy: number /** Date in `"2021/05/14"` format */ date: string /** Number of "Hold" ratings */ hold: number /** Number of "Sell" ratings */ sell: number /** Number of "Strong Buy" / "Outperform" ratings */ strongBuy: number /** Number of "No Opinion" ratings */ noOpinion: number /** Number of "Underperform" ratings */ under: number } /** Historical target price time-series */ export interface InstitutionRatingDetailTarget { /** Prediction accuracy ratio (may be null) */ dataPercent?: string /** Overall prediction accuracy */ predictionAccuracy?: string /** Last updated display string */ updatedAt: string /** Weekly target price snapshots */ list: Array } /** One weekly target price snapshot */ export interface InstitutionRatingDetailTargetItem { /** Average target price */ avgTarget?: string /** Date string */ date: string /** Highest target price */ maxTarget?: string /** Lowest target price */ minTarget?: string /** Whether the stock reached the target */ meet: boolean /** Actual stock price */ price?: string /** Unix timestamp string */ timestamp: string } /** Latest analyst rating snapshot */ export interface InstitutionRatingLatest { /** Rating distribution counts */ evaluate: RatingEvaluate /** Target price range */ target: RatingTarget /** Industry classification ID */ industryId: number /** Industry name */ industryName: string /** Rank within the industry */ industryRank: number /** Total securities in the industry */ industryTotal: number /** Mean analyst count */ industryMean: number /** Median analyst count */ industryMedian: number } /** Consensus summary */ export interface InstitutionRatingSummary { /** Currency symbol */ ccySymbol: string /** Change vs previous period */ change?: string /** Simplified rating distribution */ evaluate: RatingSummaryEvaluate /** Consensus recommendation */ recommend: InstitutionRecommend /** Consensus target price */ target?: string /** Last updated display string */ updatedAt: string } export declare const enum InstitutionRecommend { /** Unknown */ Unknown = 0, /** Strong buy */ StrongBuy = 1, /** Buy */ Buy = 2, /** Hold */ Hold = 3, /** Sell */ Sell = 4, /** Strong sell */ StrongSell = 5, /** Underperform */ Underperform = 6, /** No opinion */ NoOpinion = 7 } /** Investor relations response */ export interface InvestRelations { /** Link to IR page */ forwardUrl: string /** Securities with a stake */ investSecurities: Array } /** A security in which the company has a stake */ export interface InvestSecurity { /** Company ID */ companyId: string /** Company name */ companyName: string /** Company name in English */ companyNameEn: string /** Company name in Simplified Chinese */ companyNameZhcn: string /** Security symbol */ symbol: string /** Currency */ currency: string /** Percentage held */ percentOfShares?: string /** Shareholder rank */ sharesRank: string /** Market value of holding */ sharesValue?: string } export declare const enum Language { /** zh-CN */ ZH_CN = 0, /** zh-HK */ ZH_HK = 1, /** en */ EN = 2 } /** One historical data point for a macroeconomic indicator */ export interface Macroeconomic { period: string /** Release datetime (unix timestamp in seconds; null if unset) */ releaseAt?: number actualValue: string previousValue: string forecastValue: string revisedValue: string /** Next release datetime (unix timestamp in seconds; null if unset) */ nextReleaseAt?: number unit: string unitPrefix: string } /** Country code for filtering macroeconomic indicators */ export declare const enum MacroeconomicCountry { /** Hong Kong SAR China */ HongKong = 0, /** China (Mainland) */ China = 1, /** United States */ UnitedStates = 2, /** Euro Zone */ EuroZone = 3, /** Japan */ Japan = 4, /** Singapore */ Singapore = 5 } /** Metadata for one macroeconomic indicator */ export interface MacroeconomicIndicator { indicatorCode: string sourceOrg: string country: string name: string adjustmentFactor: string periodicity: string category: string describe: string importance: number /** Start date of data coverage (unix timestamp in seconds; null if unset) */ startDate?: number } /** Response for macroeconomic_indicators */ export interface MacroeconomicIndicatorListResponse { data: Array count: number } /** Response for macroeconomic */ export interface MacroeconomicResponse { info: MacroeconomicIndicator data: Array count: number } export declare const enum Market { /** Unknown */ Unknown = 0, /** US market */ US = 1, /** HK market */ HK = 2, /** CN market */ CN = 3, /** SG market */ SG = 4, /** Crypto market */ Crypto = 5 } /** Market trading status response */ export interface MarketStatusResponse { /** Per-market trading status items */ marketTime: Array } /** Trading status for one market */ export interface MarketTimeItem { /** Market */ market: Market /** * Raw market trade status code. See the market status definition for the * complete code table. */ tradeStatus: number /** Current market time (unix timestamp string) */ timestamp: string /** Delayed-quote market trade status code */ delayTradeStatus: number /** Delayed-quote market time (unix timestamp string) */ delayTimestamp: string /** Sub-status code */ subStatus: number /** Delayed-quote sub-status code */ delaySubStatus: number } /** Localized text in simplified Chinese, traditional Chinese, and English */ export interface MultiLanguageText { english: string simplifiedChinese: string traditionalChinese: string } /** Options for listing topics created by the current authenticated user */ export interface MyTopicsRequest { /** Page number (default 1) */ page?: number /** Records per page, range 1~500 (default 50) */ size?: number /** Filter by topic type: "article" or "post"; empty returns all */ topicType?: string } /** Key financial metrics from an operating report */ export interface OperatingFinancial { /** Ticker code */ code: string /** Currency */ currency: string /** Company name */ name: string /** Region */ region: string /** Report period code */ report: string /** Indicators */ indicators: Array } /** One financial indicator */ export interface OperatingIndicator { /** Field key */ fieldName: string /** Display name */ indicatorName: string /** Formatted value */ indicatorValue: string /** Year-over-year change */ yoy?: string } /** One operating summary report */ export interface OperatingItem { /** Report ID */ id: string /** Period code */ report: string /** Title */ title: string /** Management discussion text */ txt: string /** Whether most recent */ latest: boolean /** Community page URL */ webUrl: string /** Key financial metrics */ financial: OperatingFinancial } /** Operating metrics response */ export interface OperatingList { /** Operating summary reports */ list: Array } /** Option direction */ export declare const enum OptionDirection { /** Unknown */ Unknown = 0, /** Put */ Put = 1, /** Call */ Call = 2 } /** Option type */ export declare const enum OptionType { /** Unknown */ Unknown = 0, /** American */ American = 1, /** Europe */ Europe = 2 } /** Option volume stats response */ export interface OptionVolumeStats { /** Security symbol */ symbol: string /** Total call volume */ callVolume: number /** Total put volume */ putVolume: number } export declare const enum OrderSide { /** Unknown */ Unknown = 0, /** Buy */ Buy = 1, /** Sell */ Sell = 2 } export declare const enum OrderStatus { /** Unknown */ Unknown = 0, /** Not reported */ NotReported = 1, /** Not reported (Replaced Order) */ ReplacedNotReported = 2, /** Not reported (Protected Order) */ ProtectedNotReported = 3, /** Not reported (Conditional Order) */ VarietiesNotReported = 4, /** Filled */ Filled = 5, /** Wait To New */ WaitToNew = 6, /** New */ New = 7, /** Wait To Replace */ WaitToReplace = 8, /** Pending Replace */ PendingReplace = 9, /** Replaced */ Replaced = 10, /** Partial Filled */ PartialFilled = 11, /** Wait To Cancel */ WaitToCancel = 12, /** Pending Cancel */ PendingCancel = 13, /** Rejected */ Rejected = 14, /** Canceled */ Canceled = 15, /** Expired */ Expired = 16, /** Partial Withdrawal */ PartialWithdrawal = 17 } /** Order tag */ export declare const enum OrderTag { /** Unknown */ Unknown = 0, /** Normal Order */ Normal = 1, /** Long term Order */ LongTerm = 2, /** Grey Order */ Grey = 3, /** Force Selling */ MarginCall = 4, /** OTC */ Offline = 5, /** Option Exercise Long */ Creditor = 6, /** Option Exercise Short */ Debtor = 7, /** Wavier Of Option Exercise */ NonExercise = 8, /** Trade Allocation */ AllocatedSub = 9 } export declare const enum OrderType { /** Unknown */ Unknown = 0, /** Limit Order */ LO = 1, /** Enhanced Limit Order */ ELO = 2, /** Market Order */ MO = 3, /** At-auction Order */ AO = 4, /** At-auction Limit Order */ ALO = 5, /** Odd Lots */ ODD = 6, /** Limit If Touched */ LIT = 7, /** Market If Touched */ MIT = 8, /** Trailing Limit If Touched (Trailing Amount) */ TSLPAMT = 9, /** Trailing Limit If Touched (Trailing Percent) */ TSLPPCT = 10, /** Trailing Market If Touched (Trailing Amount) */ TSMAMT = 11, /** Trailing Market If Touched (Trailing Percent) */ TSMPCT = 12, /** Special Limit Order */ SLO = 13 } /** Enable or disable outside regular trading hours */ export declare const enum OutsideRTH { /** Unknown */ Unknown = 0, /** Regular trading hour only */ RTHOnly = 1, /** Any time */ AnyTime = 2, /** Overnight */ Overnight = 3 } /** Candlestick period */ export declare const enum Period { /** Unknown */ Unknown = 0, /** One Minute */ Min_1 = 1, /** Two Minutes */ Min_2 = 2, /** Three Minutes */ Min_3 = 3, /** Five Minutes */ Min_5 = 4, /** Ten Minutes */ Min_10 = 5, /** Fifteen Minutes */ Min_15 = 6, /** Twenty Minutes */ Min_20 = 7, /** Thirty Minutes */ Min_30 = 8, /** Forty-Five Minutes */ Min_45 = 9, /** One Hour */ Min_60 = 10, /** Two Hours */ Min_120 = 11, /** Three Hours */ Min_180 = 12, /** Four Hours */ Min_240 = 13, /** Daily */ Day = 14, /** Weekly */ Week = 15, /** Monthly */ Month = 16, /** Quarterly */ Quarter = 17, /** Yearly */ Year = 18 } /** Pinned mode for watchlist securities */ export declare const enum PinnedMode { /** Pin (add) securities to the top */ Add = 0, /** Unpin (remove) securities from the top */ Remove = 1 } /** One executive / board member */ export interface Professional { /** Internal wiki ID */ id: string /** Full name */ name: string /** Name in Simplified Chinese */ nameZhcn: string /** Name in English */ nameEn: string /** Job title */ title: string /** Biography */ biography: string /** Photo URL */ photo: string /** Wiki profile URL */ wikiUrl: string } /** Combined profit analysis response */ export interface ProfitAnalysis { /** Summary overview */ summary: ProfitAnalysisSummary /** Per-security breakdown */ sublist: ProfitAnalysisSublist } /** P&L analysis grouped by market */ export interface ProfitAnalysisByMarket { /** Total P&L across all returned items */ profit?: string /** Whether more pages are available */ hasMore: boolean /** Per-security P&L items for the requested market/page */ stockItems: Array } /** One security entry in a by-market P&L response */ export interface ProfitAnalysisByMarketItem { /** Security symbol (ticker code) */ code: string /** Security name */ name: string /** Market, e.g. `"HK"`, `"US"` */ market: string /** Profit/loss amount */ profit?: string } /** Detailed profit analysis for one security */ export interface ProfitAnalysisDetail { /** Total profit/loss */ profit?: string /** Underlying stock P&L details */ underlyingDetails: ProfitDetails /** Derivative P&L details */ derivativePnlDetails: ProfitDetails /** Security name */ name: string /** Last updated time (unix timestamp string) */ updatedAt: string /** Last updated date string */ updatedDate: string /** Currency */ currency: string /** Default detail tab: 0 = underlying, 1 = derivative */ defaultTag: number /** Query start time (unix timestamp string) */ start: string /** Query end time (unix timestamp string) */ end: string /** Query start date string */ startDate: string /** Query end date string */ endDate: string } /** Profit-analysis flows response */ export interface ProfitAnalysisFlows { flowsList: Array hasMore: boolean } /** P&L for one security */ export interface ProfitAnalysisItem { /** Security name */ name: string /** Market */ market: string /** Whether still holding */ isHolding: boolean /** Profit/loss amount */ profit?: string /** Profit/loss rate */ profitRate?: string /** Number of completed trades */ clearanceTimes: number /** Asset type */ itemType: AssetType /** Currency */ currency: string /** Security symbol */ symbol: string /** Holding period display string */ holdingPeriod: string /** Ticker code */ securityCode: string /** ISIN (for funds) */ isin: string /** Underlying stock P&L */ underlyingProfit?: string /** Derivatives P&L */ derivativesProfit?: string /** P&L in order currency */ orderProfit?: string } /** Per-security P&L breakdown */ export interface ProfitAnalysisSublist { /** Start time (unix timestamp string) */ start: string /** End time (unix timestamp string) */ end: string /** Start date string */ startDate: string /** End date string */ endDate: string /** Last updated time (unix timestamp string) */ updatedAt: string /** Last updated date string */ updatedDate: string /** Per-security items */ items: Array } /** Account-level P&L summary */ export interface ProfitAnalysisSummary { /** Account currency */ currency: string /** Current total asset value */ currentTotalAsset?: string /** Query start date string */ startDate: string /** Query end date string */ endDate: string /** Start time (unix timestamp string) */ startTime: string /** End time (unix timestamp string) */ endTime: string /** Ending asset value */ endingAssetValue?: string /** Initial asset value */ initialAssetValue?: string /** Total invested amount */ investAmount?: string /** Whether any trades occurred */ isTraded: boolean /** Total profit/loss */ sumProfit?: string /** Total profit/loss rate */ sumProfitRate?: string /** Per-asset-type breakdown */ profits: ProfitSummaryBreakdown } /** One P&L detail line item (credit, debit, or fee) */ export interface ProfitDetailEntry { /** Description */ describe: string /** Amount */ amount?: string } /** Detailed P&L breakdown for one asset class */ export interface ProfitDetails { /** Current holding market value */ holdingValue?: string /** Total profit/loss */ profit?: string /** Cumulative credited amount */ cumulativeCreditedAmount?: string /** Credit detail entries */ creditedDetails: Array /** Cumulative debited amount */ cumulativeDebitedAmount?: string /** Debit detail entries */ debitedDetails: Array /** Cumulative fee amount */ cumulativeFeeAmount?: string /** Fee detail entries */ feeDetails: Array /** Short position holding value */ shortHoldingValue?: string /** Long position holding value */ longHoldingValue?: string /** Opening position market value at period start */ holdingValueAtBeginning?: string /** Closing position market value at period end */ holdingValueAtEnding?: string } /** P&L breakdown by asset type */ export interface ProfitSummaryBreakdown { /** Stock P&L */ stock?: string /** Fund P&L */ fund?: string /** Crypto P&L */ crypto?: string /** Money market fund P&L */ mmf?: string /** Other P&L */ other?: string /** Cumulative transaction amount */ cumulativeTransactionAmount?: string /** Total number of orders */ tradeOrderNum: string /** Total number of traded securities */ tradeStockNum: string /** IPO P&L */ ipo?: string /** IPO hits */ ipoHit: number /** IPO subscriptions */ ipoSubscription: number /** Per-category summary info */ summaryInfo: Array } /** P&L summary for one asset category */ export interface ProfitSummaryInfo { /** Asset type */ assetType: AssetType /** Security with the maximum profit */ profitMax: string /** Name of the max-profit security */ profitMaxName: string /** Security with the maximum loss */ lossMax: string /** Name of the max-loss security */ lossMaxName: string } export declare const enum PushCandlestickMode { /** Realtime mode */ Realtime = 0, /** Confirmed mode */ Confirmed = 1 } /** Rank categories response. `data` is a JSON string. */ export interface RankCategoriesResponse { /** Raw rank categories data (JSON string) */ data: string } /** One ranked security item. */ export interface RankListItem { /** Symbol (e.g. `"MU.US"`) */ symbol: string /** Ticker code */ code: string /** Security name */ name: string /** Latest price */ lastDone: string /** Price change ratio */ chg: string /** Absolute price change */ change: string /** Net inflow */ inflow: string /** Market cap */ marketCap: string /** Industry name */ industry: string /** Pre/post market price */ prePostPrice: string /** Pre/post market change */ prePostChg: string /** Amplitude */ amplitude: string /** 5-day change */ fiveDayChg: string /** Turnover rate */ turnoverRate: string /** Volume ratio */ volumeRate: string /** P/B ratio (TTM) */ pbTtm: string } /** Rank list response. */ export interface RankListResponse { /** Whether delayed / BMP data */ bmp: boolean /** Ranked security items */ lists: Array } /** Analyst rating distribution counts */ export interface RatingEvaluate { /** Number of "Buy" ratings */ buy: number /** Number of "Strong Buy" / "Outperform" ratings */ over: number /** Number of "Hold" ratings */ hold: number /** Number of "Underperform" ratings */ under: number /** Number of "Sell" ratings */ sell: number /** Number of "No Opinion" ratings */ noOpinion: number /** Total analyst count */ total: number /** Window start (unix timestamp string) */ startDate: string /** Window end (unix timestamp string) */ endDate: string } /** Simplified rating distribution */ export interface RatingSummaryEvaluate { /** Number of "Buy" ratings */ buy: number /** Date of the update */ date: string /** Number of "Hold" ratings */ hold: number /** Number of "Sell" ratings */ sell: number /** Number of "Strong Buy" ratings */ strongBuy: number /** Number of "Underperform" ratings */ under: number } /** Analyst target price range */ export interface RatingTarget { /** Highest price target */ highestPrice?: string /** Lowest price target */ lowestPrice?: string /** Previous close price */ prevClose?: string /** Window start */ startDate: string /** Window end */ endDate: string } /** TTM buyback summary */ export interface RecentBuybacks { currency: string netBuybackTtm: string netBuybackYieldTtm: string } /** Options for replace order request */ export interface ReplaceOrderOptions { /** Order id */ orderId: string /** Replaced quantity */ quantity: Decimal /** Replaced price */ price?: Decimal /** Trigger price (`LIT` / `MIT` Order Required) */ triggerPrice?: Decimal /** Limit offset amount (`TSLPAMT` / `TSLPPCT` Required) */ limitOffset?: Decimal /** Trailing amount (`TSLPAMT` / `TSMAMT` Required) */ trailingAmount?: Decimal /** Trailing percent (`TSLPPCT` / `TSMAPCT` Required) */ trailingPercent?: Decimal /** Limit depth level */ limitDepthLevel?: number /** Trigger count */ triggerCount?: number /** Monitor price */ monitorPrice?: Decimal /** Remark (Maximum 64 characters) */ remark?: string } /** A filter condition for screener_search Mode B. */ export interface ScreenerCondition { /** Indicator key without filter_ prefix, e.g. "pettm", "roe", "macd_day" */ key: string /** Lower bound (empty = no lower bound) */ min: string /** Upper bound (empty = no upper bound) */ max: string /** * Technical indicator params as JSON string (empty object "{}" for * fundamental indicators) */ techValues: string } /** Screener indicator definitions response. `data` is a JSON string. */ export interface ScreenerIndicatorsResponse { /** Raw indicator definitions data (JSON string) */ data: string } /** Recommended screener strategies response. `data` is a JSON string. */ export interface ScreenerRecommendStrategiesResponse { /** Raw recommended strategies data (JSON string) */ data: string } /** Screener search results response. `data` is a JSON string. */ export interface ScreenerSearchResponse { /** Raw search results data (JSON string) */ data: string } /** Single screener strategy response. `data` is a JSON string. */ export interface ScreenerStrategyResponse { /** Raw strategy detail data (JSON string) */ data: string } /** User screener strategies response. `data` is a JSON string. */ export interface ScreenerUserStrategiesResponse { /** Raw user strategies data (JSON string) */ data: string } /** Securities update mode */ export declare const enum SecuritiesUpdateMode { /** Add securities */ Add = 0, /** Remove securities */ Remove = 1, /** Replace securities */ Replace = 2 } /** Security board */ export declare const enum SecurityBoard { /** Unknown */ Unknown = 0, /** US Main Board */ USMain = 1, /** US Pink Board */ USPink = 2, /** Dow Jones Industrial Average */ USDJI = 3, /** Nasdsaq Index */ USNSDQ = 4, /** US Industry Board */ USSector = 5, /** US Option */ USOption = 6, /** US Sepecial Option */ USOptionS = 7, /** Hong Kong Equity Securities */ HKEquity = 8, /** HK PreIPO Security */ HKPreIPO = 9, /** HK Warrant */ HKWarrant = 10, /** Hang Seng Index */ HKHS = 11, /** HK Industry Board */ HKSector = 12, /** SH Main Board(Connect) */ SHMainConnect = 13, /** SH Main Board(Non Connect) */ SHMainNonConnect = 14, /** SH Science and Technology Innovation Board */ SHSTAR = 15, /** CN Index */ CNIX = 16, /** CN Industry Board */ CNSector = 17, /** SZ Main Board(Connect) */ SZMainConnect = 18, /** SZ Main Board(Non Connect) */ SZMainNonConnect = 19, /** SZ Gem Board(Connect) */ SZGEMConnect = 20, /** SZ Gem Board(Non Connect) */ SZGEMNonConnect = 21, /** SG Main Board */ SGMain = 22, /** Singapore Straits Index */ STI = 23, /** SG Industry Board */ SGSector = 24, /** S&P 500 Index */ SPXIndex = 25, /** CBOE Volatility Index */ VIXIndex = 26 } /** Security list category */ export declare const enum SecurityListCategory { /** Overnight */ Overnight = 0 } /** One major shareholder */ export interface Shareholder { /** Internal ID */ shareholderId: string /** Name */ shareholderName: string /** Institution type */ institutionType: string /** Percentage held */ percentOfShares?: string /** Change in shares held */ sharesChanged?: string /** Report date */ reportDate: string /** Cross-holdings */ stocks: Array } /** Shareholder detail response. `data` is a JSON string. */ export interface ShareholderDetailResponse { /** Raw shareholder detail data (JSON string) */ data: string } /** Shareholder list response */ export interface ShareholderList { /** Major shareholders */ shareholderList: Array /** Link to full shareholder page */ forwardUrl: string /** Total returned */ total: number } /** A cross-held security */ export interface ShareholderStock { /** Symbol */ symbol: string /** Ticker code */ code: string /** Market */ market: string /** Day change */ chg: string } /** Top-shareholder list response. `data` is a JSON string. */ export interface ShareholderTopResponse { /** Raw top-shareholder data (JSON string) */ data: string } /** Sharelist detail response */ export interface SharelistDetail { /** Sharelist info */ sharelist: SharelistInfo /** Subscription scopes */ scopes: SharelistScopes } /** Sharelist information */ export interface SharelistInfo { /** Sharelist ID */ id: number /** Name */ name: string /** Description */ description: string /** Cover image URL */ cover: string /** Number of subscribers */ subscribersCount: number /** Creation time (unix timestamp) */ createdAt: number /** Last stock edit time (unix timestamp) */ editedAt: number /** YTD change percentage */ thisYearChg?: string /** Creator info */ creator: any /** Constituent stocks */ stocks: Array /** Whether the current user is subscribed */ subscribed: boolean /** Day change percentage */ chg?: string /** Sharelist type: 0=regular, 3=official, 4=industry */ sharelistType: number /** Industry code (for industry sharelists) */ industryCode: string } /** Response for sharelist list and popular queries */ export interface SharelistList { /** User's own and followed sharelists */ sharelists: Array /** Subscribed sharelists (may be absent in popular response) */ subscribedSharelists: Array /** Pagination cursor for subscribed list */ tailMark: string } /** Sharelist subscription scopes */ export interface SharelistScopes { /** Whether the current user is subscribed */ subscription: boolean /** Whether the current user is the creator */ isSelf: boolean } /** Stock in a sharelist */ export interface SharelistStock { /** Security symbol */ symbol: string /** Security name */ name: string /** Market, e.g. `"HK"` */ market: string /** Ticker code */ code: string /** Brief description */ intro: string /** Unread change log category */ unreadChangeLogCategory: string /** Day change percentage */ change?: string /** Latest price */ lastDone?: string /** Trade status code */ tradeStatus?: number /** Whether delayed quote */ latency?: boolean } /** One short-position data point (unified for US and HK markets). */ export interface ShortPositionsItem { /** Trading date (RFC 3339) */ timestamp: string /** Short ratio */ rate: string /** Closing price */ close: string /** [US] Number of short shares outstanding */ currentSharesShort: string /** [US] Average daily share volume */ avgDailyShareVolume: string /** [US] Days to cover ratio */ daysToCover: string /** [HK] Short sale amount (HKD) */ amount: string /** [HK] Short position balance */ balance: string /** [HK] Cost / closing price */ cost: string } /** Short interest / positions response (HK or US). */ export interface ShortPositionsResponse { /** Short position data points */ data: Array } /** One short-trade data point (unified for US and HK markets). */ export interface ShortTradesItem { /** Trading date (RFC 3339) */ timestamp: string /** Short ratio */ rate: string /** Closing price */ close: string /** [US] NYSE short amount */ nusAmount: string /** [US] NY short amount */ nyAmount: string /** [US] Total short amount */ totalAmount: string /** [HK] Short sale amount */ amount: string /** [HK] Short position balance */ balance: string } /** Short trade records response (HK or US). */ export interface ShortTradesResponse { /** Short trade data points */ data: Array } /** Sort order type */ export declare const enum SortOrderType { /** Ascending */ Ascending = 0, /** Descending */ Descending = 1 } /** Statement item */ export interface StatementItem { /** Statement date (integer, e.g. 20250301) */ dt: number /** File key used to request the download URL */ fileKey: string } /** Statement type enum */ export declare const enum StatementType { /** Daily statement */ Daily = 1, /** Monthly statement */ Monthly = 2 } /** * Stock ratings response. * * `ratingsJson` contains the full nested ratings structure as a JSON string. */ export interface StockRatings { styleTxtName: string scaleTxtName: string reportPeriodTxt: string /** Composite score as a JSON string */ multiScore: string multiLetter: string multiScoreChange: number industryName: string industryRank: number /** Full ratings array as a JSON string */ ratingsJson: string } /** Options for submit order request */ export interface SubmitOrderOptions { /** Security code */ symbol: string /** Order type */ orderType: OrderType /** Order side */ side: OrderSide /** Submitted quantity */ submittedQuantity: Decimal /** Time in force type */ timeInForce: TimeInForceType /** Submitted price */ submittedPrice?: Decimal /** Trigger price (`LIT` / `MIT` Required) */ triggerPrice?: Decimal /** Limit offset amount (`TSLPAMT` / `TSLPPCT` Required) */ limitOffset?: Decimal /** Trailing amount (`TSLPAMT` / `TSMAMT` Required) */ trailingAmount?: Decimal /** Trailing percent (`TSLPPCT` / `TSMAPCT` Required) */ trailingPercent?: Decimal /** * Long term order expire date (Required when `time_in_force` is * `GoodTilDate`) */ expireDate?: NaiveDate /** Enable or disable outside regular trading hours */ outsideRth?: OutsideRTH /** Limit depth level */ limitDepthLevel?: number /** Trigger count */ triggerCount?: number /** Monitor price */ monitorPrice?: Decimal /** Remark (Maximum 64 characters) */ remark?: string } /** Quote type of subscription */ export declare const enum SubType { /** Quote */ Quote = 0, /** Depth */ Depth = 1, /** Brokers */ Brokers = 2, /** Trade */ Trade = 3 } /** Time in force type */ export declare const enum TimeInForceType { /** Unknown */ Unknown = 0, /** Day Order */ Day = 1, /** Good Til Canceled Order */ GoodTilCanceled = 2, /** Good Til Date Order */ GoodTilDate = 3 } /** Topic type */ export declare const enum TopicType { /** Private notification for trade */ Private = 0 } /** One top-movers event entry. */ export interface TopMoversEvent { /** Event time (RFC 3339) */ timestamp: string /** Alert reason description */ alertReason: string /** Alert type code */ alertType: number /** Stock information */ stock: TopMoversStock /** Associated news post (JSON string) */ post: string } /** Top movers response. */ export interface TopMoversResponse { /** Top-mover events */ events: Array /** Pagination cursor for next page (JSON string) */ nextParams: string } /** Stock information within a top-movers event. */ export interface TopMoversStock { /** Symbol (e.g. `"NVDA.US"`) */ symbol: string /** Ticker code */ code: string /** Security name */ name: string /** Full name */ fullName: string /** Price change (decimal ratio) */ change: string /** Latest price */ lastDone: string /** Market code */ market: string /** Labels / tags */ labels: Array /** Logo URL */ logo: string } /** Trade direction */ export declare const enum TradeDirection { /** Neutral */ Neutral = 0, /** Down */ Down = 1, /** Up */ Up = 2 } /** Trade volume at one price level */ export interface TradePriceLevel { /** Buy volume at this price */ buyAmount: string /** Neutral (unknown direction) volume at this price */ neutralAmount: string /** Price level */ price: string /** Sell volume at this price */ sellAmount: string } /** Trade session */ export declare const enum TradeSession { /** Intraday */ Intraday = 0, /** Pre-Market */ Pre = 1, /** Post-Market */ Post = 2, /** Overnight */ Overnight = 3 } /** Trade sessions */ export declare const enum TradeSessions { /** Intraday */ Intraday = 0, /** All */ All = 1 } /** Summary trade statistics */ export interface TradeStatistics { /** Volume-weighted average price */ avgprice: string /** Total buy volume (shares) */ buy: string /** Total neutral / unknown-direction volume */ neutral: string /** Previous close price */ preclose: string /** Total sell volume (shares) */ sell: string /** Data timestamp (unix timestamp string) */ timestamp: string /** Total trading volume (shares) */ totalAmount: string /** Unix timestamps for the last 5 trading days */ tradeDate: Array /** Total number of trades */ tradesCount: string } /** Trade statistics response */ export interface TradeStatsResponse { /** Summary statistics */ statistics: TradeStatistics /** Per-price-level breakdown */ trades: Array } export declare const enum TradeStatus { /** Normal */ Normal = 0, /** Suspension */ Halted = 1, /** Delisted */ Delisted = 2, /** Fuse */ Fuse = 3, /** Prepare List */ PrepareList = 4, /** Code Moved */ CodeMoved = 5, /** To Be Opened */ ToBeOpened = 6, /** Split Stock Halts */ SplitStockHalts = 7, /** Expired */ Expired = 8, /** Warrant To BeListed */ WarrantPrepareList = 9, /** Warrant To BeListed */ Suspend = 10 } /** Trigger status */ export declare const enum TriggerStatus { /** Unknown */ Unknown = 0, /** Deactive */ Deactive = 1, /** Active */ Active = 2, /** Released */ Released = 3 } /** An request to update a watchlist group */ export interface UpdateWatchlistGroup { /** Group id */ id: number /** Group name */ name?: string /** Securities */ securities?: Array /** Securities Update mode */ mode: SecuritiesUpdateMode } /** One security's valuation comparison item. */ export interface ValuationComparisonItem { /** Symbol (e.g. `"AAPL.US"`) */ symbol: string /** Security name */ name: string /** Currency */ currency: string /** Market capitalisation */ marketValue: string /** Latest closing price */ priceClose: string /** P/E ratio */ pe: string /** P/B ratio */ pb: string /** P/S ratio */ ps: string /** Return on equity */ roe: string /** Earnings per share */ eps: string /** Book value per share */ bps: string /** Dividends per share */ dps: string /** Dividend yield */ divYld: string /** Total assets */ assets: string /** Historical valuation points */ history: Array } /** Valuation comparison response. */ export interface ValuationComparisonResponse { /** Valuation comparison items */ list: Array } /** Valuation metrics response */ export interface ValuationData { /** Valuation metrics */ metrics: ValuationMetricsData } /** Distribution statistics for one valuation metric */ export interface ValuationDist { /** Minimum value */ low?: string /** Maximum value */ high?: string /** Median value */ median?: string /** Current value */ value?: string /** Percentile ranking */ ranking?: string /** Ordinal rank index */ rankIndex: string /** Total securities in industry */ rankTotal: string } /** Historical valuation container */ export interface ValuationHistoryData { /** Historical metrics */ metrics: ValuationHistoryMetrics } /** Historical data for one valuation metric */ export interface ValuationHistoryMetric { /** Description */ desc: string /** High */ high?: string /** Low */ low?: string /** Median */ median?: string /** Data points */ list: Array } /** Historical metrics container */ export interface ValuationHistoryMetrics { /** PE history */ pe?: ValuationHistoryMetric /** PB history */ pb?: ValuationHistoryMetric /** PS history */ ps?: ValuationHistoryMetric } /** One historical valuation data point. */ export interface ValuationHistoryPoint { /** Date (RFC 3339) */ date: string /** P/E ratio */ pe: string /** P/B ratio */ pb: string /** P/S ratio */ ps: string } /** Historical valuation response */ export interface ValuationHistoryResponse { /** Historical valuation data */ history: ValuationHistoryData } /** Historical time-series for one valuation metric */ export interface ValuationMetricData { /** Description */ desc: string /** Historical high */ high?: string /** Historical low */ low?: string /** Historical median */ median?: string /** Data points */ list: Array } /** Valuation metrics container */ export interface ValuationMetricsData { /** PE ratio history */ pe?: ValuationMetricData /** PB ratio history */ pb?: ValuationMetricData /** PS ratio history */ ps?: ValuationMetricData /** Dividend yield history */ dvdYld?: ValuationMetricData } /** One valuation data point */ export interface ValuationPoint { /** Unix timestamp (seconds) */ timestamp: number /** Metric value */ value?: string } /** Warrant sort by */ export declare const enum WarrantSortBy { /** Last done */ LastDone = 0, /** Change rate */ ChangeRate = 1, /** Change value */ ChangeValue = 2, /** Volume */ Volume = 3, /** Turnover */ Turnover = 4, /** Expiry date */ ExpiryDate = 5, /** Strike price */ StrikePrice = 6, /** Upper strike price */ UpperStrikePrice = 7, /** Lower strike price */ LowerStrikePrice = 8, /** Outstanding quantity */ OutstandingQuantity = 9, /** Outstanding ratio */ OutstandingRatio = 10, /** Premium */ Premium = 11, /** In/out of the bound */ ItmOtm = 12, /** Implied volatility */ ImpliedVolatility = 13, /** Greek value delta */ Delta = 14, /** Call price */ CallPrice = 15, /** Price interval from the call price */ ToCallPrice = 16, /** Effective leverage */ EffectiveLeverage = 17, /** Leverage ratio */ LeverageRatio = 18, /** Conversion ratio */ ConversionRatio = 19, /** Breakeven point */ BalancePoint = 20, /** Status */ Status = 21 } /** Warrant status */ export declare const enum WarrantStatus { /** Suspend */ Suspend = 0, /** Prepare List */ PrepareList = 1, /** Normal */ Normal = 2 } /** Warrant type */ export declare const enum WarrantType { /** Unknown */ Unknown = 0, /** Call */ Call = 1, /** Put */ Put = 2, /** Bull */ Bull = 3, /** Bear */ Bear = 4, /** Inline */ Inline = 5 }