TypeScript SDK (Beta)

老虎证券 OpenAPI TypeScript SDK,提供行情查询、交易下单、账户管理和实时推送等功能。

v0.3.0 起QuoteClient / TradeClient 所有方法均返回强类型对象(如 MarketState[]Brief[]Order[]PlaceOrderResult 等),不再是 Promise<unknown>。请求参数在 TypeScript 中全部使用 camelCase,SDK 会在发送到服务端时自动转换为 snake_case;交易查询接口的 {items: [...]} 外壳也已被 SDK 自动剥除,直接返回数组。详见本页与 quote-tstrade-tspush-ts 小节。

安装

npm install @tigeropenapi/tigeropen
# 或
yarn add @tigeropenapi/tigeropen
# 或
pnpm add @tigeropenapi/tigeropen

要求 Node.js >= 16.0.0。

配置

SDK 支持多种配置方式,优先级:环境变量 > 代码设置(含配置文件) > 自动发现配置文件 > 默认值

SDK 会自动搜索以下路径的配置文件(无需显式指定):

  1. 当前目录 ./tiger_openapi_config.properties
  2. 用户目录 ~/.tigeropen/tiger_openapi_config.properties

方式一:从 properties 配置文件加载(推荐)

import { createClientConfig } from '@tigeropenapi/tigeropen';

// 指定配置文件路径
const config = createClientConfig({
  propertiesFilePath: '/path/to/tiger_openapi_config.properties',
});

// 或不传任何参数,SDK 自动搜索默认路径
const config = createClientConfig();

配置文件格式:

tiger_id=你的开发者ID
private_key=你的RSA私钥
account=你的交易账户
license=TBUS

方式二:代码直接设置

import { createClientConfig } from '@tigeropenapi/tigeropen';

const config = createClientConfig({
  tigerId: '你的 tiger_id',
  privateKey: '你的 RSA 私钥',
  account: '你的交易账户',
});

方式三:环境变量

export TIGEROPEN_TIGER_ID=你的开发者ID
export TIGEROPEN_PRIVATE_KEY=你的RSA私钥
export TIGEROPEN_ACCOUNT=你的交易账户
export TIGEROPEN_TOKEN=你的Token  # TBHK 牌照需要

配置项说明

配置项说明必填默认值
tigerId开发者 ID-
privateKeyRSA 私钥(PK1与PK8都兼容)-
account交易账户-
license牌照类型(如 TBUS)-
language语言(zh_CN/en_US)zh_CN
timeout请求超时(秒)15
tokenTBHK 牌照 Token-

自动检测

  • 设备 ID:SDK 自动从网卡 MAC 地址获取(os.networkInterfaces()),无需手动设置
  • 动态域名:SDK 自动从域名花园获取最新服务器地址,默认启用
  • 行情服务器:SDK 自动解析独立的行情服务器地址(LICENSE-QUOTE 域名键)
  • 签名验证:SDK 内置 Tiger 公钥,自动验证 HTTP 响应签名

构造客户端

SDK 的业务客户端(QuoteClient / TradeClient)不直接接受 ClientConfig,而是接受一个 HttpClient 实例;行情客户端需使用 useQuoteServerUrl: true 选项指向行情专用服务器。

行情客户端

import {
  createClientConfig,
  HttpClient,
  QuoteClient,
} from '@tigeropenapi/tigeropen';

const config = createClientConfig();

// 行情客户端需要使用行情专用服务器
const quoteClient = new QuoteClient(
  new HttpClient(config, undefined, { useQuoteServerUrl: true }),
);

// 调用示例(v0.3.0 后返回强类型数组)
const states = await quoteClient.getMarketState('US');
console.log(states[0]?.market, states[0]?.marketStatus);

交易客户端

import {
  createClientConfig,
  HttpClient,
  TradeClient,
} from '@tigeropenapi/tigeropen';

const config = createClientConfig();

const tradeClient = new TradeClient(new HttpClient(config), config.account);

const positions = await tradeClient.getPositions();
console.log('持仓数量:', positions.length);

推送客户端

import { createClientConfig, PushClient } from '@tigeropenapi/tigeropen';

const config = createClientConfig();
const pushClient = new PushClient(config);