中文

Preparation

Environment Requirements

  • Operating System Requirements:
    • Windows
    • MacOS
    • Linux
    • Solaris
  • Programming Language Version Requirements: Python 3.8 and above

Installing Python

For the best support and to reduce compatibility issues, we recommend installing the latest version of Python. Versions earlier than Python 3.8 may not run properly. You can check the version or verify installation by entering python3 -V in the console.

Installing the Latest Version of Python

  1. Visit the Python official website download page: https://www.python.org/downloads/

  2. Select the corresponding operating system, download the installation package and follow the prompts to install

Or

You can also choose to use Python distributions like Anaconda. You can directly visit the Anaconda official website individual edition download page:

https://www.anaconda.com/products/individual

Download it, and after downloading, please run the installation package and follow the prompts to complete the installation

Installing Tiger Brokers Open API Python SDK

Method 1: Install using pip (Recommended)

Enter the following command in Terminal or Command Prompt (cmd):

pip3 install tigeropen

For subsequent version upgrades, you can use the following command:

pip3 install tigeropen --upgrade

This completes the installation.

Note: If installation through the default pip official source is slow, you can choose to specify other faster mirror sources, for example:

pip install tigeropen -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
pip install tigeropen -i https://pypi.tuna.tsinghua.edu.cn/ --trusted-host pypi.tuna.tsinghua.edu.cn

Method 2: Github

The SDK project's source code is also published on GitHub. The project's GitHub address is:

https://github.com/tigerfintech/openapi-python-sdk

Installation method:

  1. Clone the project to local

  2. Run setup.py in the directory: python3 setup.py install

Method 3: Anaconda

conda install tigeropen

Installing IDE

We recommend using PyCharm as the integrated development environment

Official download address:

https://www.jetbrains.com/pycharm/download/

For Retail Users, Register through Personal Center

Before using the API, please first activate permissions. Individual users should visit the API official website to register developer identity We recommend using Chrome browser to open

Note: Opening Open API requires opening an account with Tiger Brokers and depositing funds. Developers and clients will be required to sign an API authorization agreement

You would then need to complete the registration of developer information on this page. Please fill in and submit your information.

After successful registration, you can obtain the following information on this page:

  • tiger_id: A unique ID assigned by the open platform to each developer, used to identify a developer. All API interface calls will use tiger_id.
  • account: The user's funding account, which is needed when requesting trading-related interfaces. Specifically divided into Global accounts, Standard accounts, and Paper accounts:
    • Global Account: Starts with uppercase letter U, such as: U12300123
    • Prime Account: A string of shorter numbers (5 to 10 digits), such as: 51230321
    • Paper Trading Account: 17 digits, such as: 20191106192858300

After successfully registering developer information, only funding accounts and paper accounts that have successfully deposited funds will be returned. If both the user's Global account and Standard account have successfully deposited funds, both will be returned.

Developer Registration Page: Registration can be completed with mobile phone number and verification code

Developer Information Page: The Tiger ID, live account, paper trading account, license and other information need to be used in OpenAPI.

Note: You need to save the private key part shown in the figure below locally and keep it properly to prevent leakage. If leakage is discovered, please update it promptly. The private key will not be saved on the Tiger Brokers server side, and users need to save it before refreshing the page. After the page is refreshed, the private key will automatically disappear. If the private key is not saved properly, you can replace it through the Regenerate button.

Users can save the corresponding type of private key according to the calling needs of different SDKs. The private key formats used by Java and Python SDKs are different. Java uses PKCS#8 format private keys, while Python uses PKCS#1 format. If you encounter problems when using the SDK, please first check whether the private key format is correct.

The generated configuration file tiger_openapi_config.properties file content format is as follows. Account is the default account and can be switched between live funding account and paper trading account. If it is an institutional account, you also need to configure secret_key (needs to be obtained from the institutional center).

private_key_pk1=MIICXgIBAAKBgQCodM4fM5cz+tj8SUuxxSbSMFxNHM23hftjAuXr9THweyFtTmA/mxwo9HYEhYjxCgYAJt78xbzw7aiKu+pI45O8il8ns6UL3mT59QlCKu0+FZmF2g54teyqoiol71xcM096D3ss0oJzKGt+btvlBzdcrXM6+pZqbK14ASWGE4uBEQIDAQABAoGAX5iBjFVTngzhbDIQAZ73C9qj1qLc3yPqZ+KyJbgskeLeMlCC8DWOwnMQMjqxXtAoXZexfVKdiT/lIG3JY3m6URzfYwJt5VUD9LeIcyPxuj7Eg2vxlZwJ6slT7DQ6LJCbUe1PUDlKKXYe/wEUNJ3dEJ/eFEhR8vNyFlW8DJj+az0CQQDhQwYUZIcq+9WDcSen5Sm5oS765aMAyWcOdkpokau+fZ/H9NwT0U+jaEHyswZMJBTDJ42iS8HV0MuGdtLJ7JzHAkEAv3Fq1AHHJ1Tyxtf/VWHBRfx304NFlDX87Ji7uy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OPCrEDf8CQQCkDyuhQpe0pOoLatvyGzkCxwykcVSXtltV4pfXiACD1A9bGSHwFwHV2WMCyunuKsS2rhV7MPYJ/jRvnYVzH6m8
tiger_id=20150001
account=12345678
license=TBHK
env=PROD

Token (Optional)

TBHK License (users with other licenses can ignore this): You need to generate a token. When the token expires, you need to regenerate it and download the tiger_openapi_token.properties file to your local machine. Copy the tiger_openapi_token.properties file to the directory configured in ClientConfig props_path.**

The token is valid for 30 days. If it expires, you need to go to the developer information page to regenerate and export a new token file. Before expiration, you can extend the validity period through the token refresh API interface. The SDK does not automatically refresh by default. After successful refresh, the local tiger_openapi_token.properties file will also be updated. If you need automatic token refresh, please configure client_config.token_refresh_duration to a value greater than 0, with time unit in seconds.

Additional configuration, not required:

InformationRequiredDescription
IP WhitelistNoOnly IPs in the whitelist can access API interfaces, multiple IPs separated by ";", not required
Callback URLNoCallback address for user applications, used to receive order, position, and asset change messages. Not required, users can also receive callback messages directly through the subscription interface provided by the SDK

For Institutional Users, Register through Institution Center

Institution users please visit Institution Account Center

After account opening and fund injection, you can log into the Tiger Brokers account in the institution account center, and go to "Trading Settings > Enable OpenAPI" to complete the activation process according to the steps.

You can obtain public and private keys on the basic configuration page

  • When enabling or regenerating public and private keys, you only need to click "Get Public and Private Keys" to automatically generate the key information.
  • If you don't need the keys we generate, you can choose custom, copy and paste your public key into the form to complete saving and confirmation.

Note: You need to save the private key part locally and keep it properly to prevent leakage. If leakage is discovered, please update it promptly. The private key will not be saved on Tiger Brokers‘ servers, and clients need to save or download it themselves. If clients accidentally lose or forget the private key, they can regenerate it.

Private Key Format Instructions:

  • Java SDK: Requires PKCS#8 format private key
  • Python SDK: Requires PKCS#1 format private key

Note: When SDK calls encounter exceptions, please first check private key format compatibility

The generated configuration file tiger_openapi_config.properties file content format is as follows, account is the default account, which can be switched between live trading fund account and paper trading account. For institution accounts, you also need to configure secret_key (needs to be obtained from the institution center).

private_key_pk1=MIICXgIBAAKBgQCodM4fM5cz+tj8SUuxxS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Y7CcxAyOrFe0Chdl7F9Up2JP+UgbcljebpRHN9jAm3lVQP0t4hzI/G6PsSDa/GVnAnqyVPsNDoskJtR7U9QOUopdh7/ARQ0nd0Qn94USFHy83IWVbwMmP5rPQJBAOFDBhRkhyr71YNxJ6flKbmhLvrlowDJZw52SmiRq759n8f03BPRT6NoQfKzBkwkFMMnjaJLwdXQy4Z20snsnMcCQQC/cWrUAccnVPLG1/9VYcFF/HfTg0WUNfzsmLu7K/W37TllhVPRTxDkJQ90EDdB7EwEp3WLoFdQf/E5jlpf5StnAkEApHt6Pv3ArSRCHb5MRI5Sz1bgpRd01Kg7dhXt8zka/Pdh6nHjGR1nV1xTe1I5sPNPrch95RoIKYZSdpbhB8ycFQJBAIw6wrqatst7sP2wGArtuQnPveID5QKEbUjNM64NrEZWkNVpTRUjakcDUod8nU0/jgtWsoZdI7gGj6bOPCrEDf8CQQCkDyuhQpe0pOoLatvyGzkCxwykcVSXtltV4pfXiACD1A9bGSHwFwHV2WMCyunuKsS2rhV7MPYJ/jRvnYVzH6m8
tiger_id=20150001
account=12345678
license=TBHK
env=PROD
secret_key=fcfca571-71db-35c1-9352-9a557cc8258d

After successful registration, you can obtain the following information from user profile:

  • Username: Name used when logging into the institution center
  • User ID: User ID
  • Tiger ID: Unique developer identifier (required parameter for all API calls)
  • Secret Key: Trader key, institution users need to set this key in the config.properties configuration file for secure authentication of API requests
  • Account ID: User's fund account ID, needed when requesting trading-related interfaces. Click the "Edit" button on the page to view the corresponding Account ID under the user

Special Note

Each User ID corresponds to one Tiger ID, and each Tiger ID can establish one persistent connection. If multiple persistent connections are needed, you can create multiple Users by going to User Management - Manage User Permissions to add new users, then go to the API permissions interface and click Add New User Profile to add new users.

The API request permissions for each User ID are subject to the permission settings in manage user permissions, where you can limit users' view, trading, and asset permissions for each account based on roles.


Purchase Market Data (Optional)

We provide delayed market data interfaces for free, but real-time market data requires separate purchase. Open API market data permissions are independent from APP and PC versions. Even if you have already purchased APP or PC market data, you need to separately purchase Open API market data permissions to get real-time data. Specific purchase methods are as follows:

Retail Customers

There are two purchase methods:

  1. Log into Personal Center to purchase market data

  2. In the mobile APP Tiger Trade APP - My - Market Data Permissions - OpenAPI Permissions to make purchases

Institution Customers

Purchase in Institution Center - Market Data Permissions


API Related Configuration

Before making formal interface requests, you need to complete the related configuration for API interface calls. Specific configuration information (including tigerId, account, license, etc.) can be viewed on the developer information page.

There are two configuration methods:

Method 1

Use configuration file. Export the configuration file tiger_openapi_config.properties from the developer website and place it in an appropriate system path, such as /Users/demo/props/ Then fill this path into the props_path parameter of TigerOpenClientConfig (you can also place the configuration file in the program's current startup directory, the SDK will default to the current path). Using this method, you no longer need to configure tiger_id, account, private_key and other information in the code.

Additionally, for Hong Kong stock licenses, tiger_openapi_token.properties is required, and this file also needs to be placed in the path specified by props_path.

from tigeropen.common.consts import (Language,        # Language
                                Market,           # Market
                                BarPeriod,        # K-line period
                                QuoteRight)       # Adjustment type
from tigeropen.tiger_open_config import TigerOpenClientConfig
from tigeropen.common.util.signature_utils import read_private_key
from tigeropen.quote.quote_client import QuoteClient

def get_client_config():
    """
    https://quant.itigerup.com/#developer Get developer information
    """
    # Hong Kong stock license requires props_path parameter to specify token path, such as '/Users/xxx/xxx/', if not specified, current path is used
    # Must use keyword argument to specify props_path
    client_config = TigerOpenClientConfig(props_path='/Users/demo/props/')
    return client_config

# Call the function defined above to generate user configuration ClientConfig object
client_config = get_client_config()

Method 2

Taking market data query as an example, all market data interface operations are implemented through member methods of the QuoteClient object, so you need to initialize QuoteClient before calling related market data interfaces. The specific implementation is as follows:

You need to first generate a client_config object, corresponding to client_config = get_client_config() in the following example, then pass this client_config object to QuoteClient to initialize QuoteClient, and then call specific methods of QuoteClient. The initialization methods for TradeClient and PushClient are similar.

⚠️

CAUTION

The read_private_key('fill in the path to the private key PEM file') in the following example corresponds to a PEM file that needs to be generated by yourself. First copy the PKCS#1 format private key from the developer page to a local file, then fill in the complete path of that file here (including the filename), for example path: /data0/config/private_key.pem, save the private key in private_key.pem.

from tigeropen.common.consts import (Language,        # Language
                                Market,           # Market
                                BarPeriod,        # K-line period
                                QuoteRight)       # Adjustment type
from tigeropen.tiger_open_config import TigerOpenClientConfig
from tigeropen.common.util.signature_utils import read_private_key
from tigeropen.quote.quote_client import QuoteClient

def get_client_config():
    """
    https://quant.itigerup.com/#developer Get developer information
    """
    client_config = TigerOpenClientConfig() 
    # Hong Kong stock license requires props_path parameter to specify token path, such as props_path='/Users/xxx/xxx/', if not specified, current path is used
    # client_config = TigerOpenClientConfig(props_path='.')
    client_config.private_key = read_private_key('Fill in the private key PEM file path')
    client_config.tiger_id = 'Replace with tigerid'
    client_config.account = 'Replace with account, recommend using paper trading account'
    client_config.license = 'TBSG' # license info
    #Institution account, add user secret key
    client_config.secret_key = 'Replace with user secret key'
    client_config.language = Language.zh_CN  #Optional, defaults to English if not filled'
    # client_config.timezone = 'US/Eastern' # Optional timezone setting
    return client_config

# Call the function defined above to generate user configuration ClientConfig object
client_config = get_client_config()

# Then pass the configuration parameter object to initialize QuoteClient
quote_client = QuoteClient(client_config)

# Get market data for stock 00700
stock_price = quote_client.get_stock_briefs(['00700'])

ClientConfig Common Configuration Items Introduction

Each configuration item can be set through client_config attributes after instantiating client_config = TigerOpenClientConfig(), such as client_config.timeout = 60

# Developer information (recommended to use props_path method to configure developer information)
client_config.tiger_id = 1
client_config.account = '123456'
client_config.license = 'TBSG'
client_config.private_key = read_private_key('Private key path')  # Need from tigeropen.common.util.signature_utils import read_private_key
# Private key can also be filled with string content
client_config.private_key = 'MIICWwIBAAKBgQCSW+.....private key content'

# Log level and path
client_config.log_level = logging.DEBUG  # Need import logging
client_config.log_path = '/tmp/tigerapi.log'

# Language
client_config.language = 'zh_CN'
# Timezone (if timezone is configured, interfaces involving time string parameters will be treated as that timezone's time. SDK doesn't set timezone by default, server will treat as Beijing time)
client_config.timezone = 'US/Eastern'

# Interface timeout
client_config.timeout = 15
# Timeout retry settings
# Maximum retry time in seconds
client_config.retry_max_time = 60
# Maximum retry attempts
client_config.retry_max_tries = 5

# 2FA token refresh interval in seconds. Set to 0 for no automatic refresh. Default is no refresh
client_config.token_refresh_duration = 24 * 60 * 60