### Install Tiger Open API SDK from GitHub
Source: https://docs.itigerup.com/docs/prepare
Install the Tiger Open API SDK by cloning the GitHub repository and running the setup script.
```shell
python3 setup.py install
```
--------------------------------
### Install Tiger Open API SDK via pip
Source: https://docs.itigerup.com/docs/prepare
Install the Tiger Open API SDK using pip, the recommended method. Includes commands for upgrading and using alternative mirrors for faster installation.
```shell
pip3 install tigeropen
```
```shell
pip3 install tigeropen --upgrade
```
```shell
pip install tigeropen -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
```
```shell
pip install tigeropen -i https://pypi.tuna.tsinghua.edu.cn/ --trusted-host pypi.tuna.tsinghua.edu.cn
```
--------------------------------
### Tiger Open API Configuration Properties
Source: https://docs.itigerup.com/docs/quickstart-java
This is an example of the `tiger_openapi_config.properties` file content, which stores essential API credentials such as the private key, tiger ID, account number, license type, and environment. This file needs to be downloaded after registering developer information.
```Properties
private_key_pk1=MIICXgIBAAKBgQCodM4fM5cz+tj8SUuxxSbSMFxNHM23hftjAuXr9THweyFtTmA/mxwo9HYEhYjxCgYAJt78xbzw7aiKu+pI45O8il8ns6UL3mT59QlCKu0+FZmF2g54teyqoiol71xcM096D3ss0oJzKGt+btvlBzdcrXM6+pZqbK14ASWGE4uBEQIDAQABAoGAX5iBjFVTngzhbDIQAZ73C9qj1qLc3yPqZ+KyJbgskeLeMlCC8DWOwnMQMjqxXtAoXZexfVKdiT/lIG3JY3m6URzfYwJt5VUD9LeIcyPxuj7Eg2vxlZwJ6slT7DQ6LJCbUe1PUDlKKXYe/wEUNJ3dEJ/eFEhR8vNyFlW8DJj+az0CQQDhQwYUZIcq+9WDcSen5Sm5oS765aMAyWcOdkpokau+fZ/H9NwT0U+jaEHyswZMJBTDJ42iS8HV0MuGdtLJ7JzHAkEAv3Fq1AHHJ1Tyxtf/VWHBRfx304NFlDX87Ji7uyv1t+05ZYVT0U8Q5CUPdBA3QexMBKd1i6BXUH/xOY5aX+UrZwJBAKR7ej79wK0kQh2+TESOUs9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2rhV7MPYJ/jRvnYVzH6m8
tiger_id=20150001
account=12345678
license=TBHK
env=PROD
```
--------------------------------
### Install Tiger Open API SDK via Anaconda
Source: https://docs.itigerup.com/docs/prepare
Install the Tiger Open API SDK using Anaconda, an alternative package manager for Python.
```shell
conda install tigeropen
```
--------------------------------
### Configure Maven Repositories for SDK Download
Source: https://docs.itigerup.com/docs/quickstart-java
If the SDK fails to download from the default Maven repository, this snippet provides an alternative repository configuration to add to your pom.xml. This can resolve dependency resolution issues.
```XML
sonatype-public
sonatype-public
https://oss.sonatype.org/content/groups/public/
```
--------------------------------
### Set Common ClientConfig Options (Python)
Source: https://docs.itigerup.com/docs/prepare
Provides examples of adjusting various ClientConfig attributes such as logging, language, timezone, timeouts, retry policy, and 2FA token refresh. These settings customize client behavior and help with debugging. Apply after creating the TigerOpenClientConfig instance.
```Python
# 开发者信息(推荐使用 props_path 的方式配置开发者信息)
client_config.tiger_id = 1
client_config.account = '123456'
client_config.license = 'TBSG'
client_config.private_key = read_private_key('私钥路径') # 需 from tigeropen.common.util.signature_utils import read_private_key
# 私钥也可填字符内容
client_config.private_key = 'MIICWwIBAAKBgQCSW+.....私钥内容'
# 日志级别及路径
client_config.log_level = logging.DEBUG # 需 import logging
client_config.log = '/tmp/tigerapi.log'
# 语言
client_config.language = 'zh_CN'
# 时区(如果配置了时区,涉及有时间字符串参数的接口,将会按当作该时区的时间。SDK默认不设置时区,服务端会当北京时间处理)
client_config.timezone = 'US/Eastern'
# 接口超时时间
client_config.timeout = 15
# 超时重试设置
# 最长重试时间,单位秒
client_config.retry_max_time = 60
# 最多重试次数
client_config.retry_max_tries = 5
# 2FA token 刷新间隔, 单位秒。设置为0则不自动刷新。 默认不刷新
client_config.token_refresh_duration = 24 * 60 * 60
```
--------------------------------
### Load Client Configuration from Properties File (Python)
Source: https://docs.itigerup.com/docs/prepare
Shows how to create a TigerOpenClientConfig by specifying the path to the exported properties file. This method avoids hard‑coding credentials in code and automatically loads tiger_id, account, and other settings. Suitable for environments where the config file is stored securely.
```Python
from tigeropen.common.consts import (Language, # 语言
Market, # 市场
BarPeriod, # k线周期
QuoteRight) # 复权类型
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 开发者信息获取
"""
# 港股牌照需用 props_path 参数指定token路径,如 '/Users/xxx/xxx/', 如不指定则取当前路径
# 必须使用关键字参数指定 props_path
client_config = TigerOpenClientConfig(props_path='/Users/demo/props/')
return client_config
# 调用上方定义的函数生成用户配置ClientConfig对象
client_config = get_client_config()
```
--------------------------------
### Create tiger_openapi_config.properties for SDK authentication
Source: https://docs.itigerup.com/docs/prepare-java
Define private keys, tiger ID, account, license and environment settings required by the Java SDK. Save the file as tiger_openapi_config.properties and place it in the directory configured by ClientConfig.DEFAULT_CONFIG.configFilePath.
```properties
private_key_pk1=MIICXgIBAAKBgQCodM4fM5cz+tj8SUuxxSbSMFxNHM23hftjAuXr9THweyFtTmA\/mxwo9HYEhYjxCgYAJt78xbzw7aiKu+pI45O8il8ns6UL3mT59QlCKu0+FZmF2g54teyqoiol71xcM096D3ss0oJzKGt+btvlBzdcrXM6+pZqbK14ASWGE4uBEQIDAQABAoGAX5iBjFVTngzhbDIQAZ73C9qj1qLc3yPqZ+KyJbgskeLeMlCC8DWOwnMQMjqxXtAoXZexfVKdiT\/lIG3JY3m6URzfYwJt5VUD9LeIcyPxuj7Eg2vxlZwJ6slT7DQ6LJCbUe1PUDlKKXYe\/wEUNJ3dEJ\/eFEhR8vNyFlW8DJj+az0CQQDhQwYUZIcq+9WDcSen5Sm5oS765aMAyWcOdkpokau+fZ\/H9NwT0U+jaEHyswZMJBTDJ42iS8HV0MuGdtLJ7JzHAkEAv3Fq1AHHJ1Tyxtf\/VWHBRfx304NFlDX87Ji7uyv1t+05ZYVT0U8Q5CUPdBA3QexMBKd1i6BXUH\/xOY5aX+UrZwJBAKR7ej79wK0kQh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bGSHwFwHV2WMCyunuKsS2rhV7MPYJ\/jRvnYVzH6m8
tiger_id=20150001
account=12345678
license=TBHK
env=PROD
```
--------------------------------
### Generate Tiger OpenAPI Config Properties File
Source: https://docs.itigerup.com/docs/prepare-java
This example shows the format of the tiger_openapi_config.properties file, which stores configuration settings for API access including private keys in PKCS#1 and PKCS#8 formats, and other required parameters. It's essential for SDK setups, with private keys needing secure storage; Tiger ID and account IDs are mandatory for API calls. Note that PKCS#8 is for Java SDK and PKCS#1 for Python SDK, and the secret_key is required for institutional accounts.
```properties
private_key_pk1=MIICXgIBAAKBgQCodM4fM5cz+tj8SUuxxSbSMFxNHM23hftjAuXr9THweyFtTmA/mxwo9HYEhYjxCgYAJt78xbzw7aiKu+pI45O8il8ns6UL3mT59QlCKu0+FZmF2g54teyqoiol71xcM096D3ss0oJzKGt+btvlBzdcrXM6+pZqbK14ASWGE4uBEQIDAQABAoGAX5iBjFVTngzhbDIQAZ73C9qj1qLc3yPqZ+KyJbgskeLeMlCC8DWOwnMQMjqxXtAoXZexfVKdiT/lIG3JY3m6URzfYwJt5VUD9LeIcyPxuj7Eg2vxlZwJ6slT7DQ6LJCbUe1PUDlKKXYe/wEUNJ3dEJ/eFEhR8vNyFlW8DJj+az0CQQDhQwYUZIcq+9WDcSen5Sm5oS765aMAyWcOdkpokau+fZ/H9NwT0U+jaEHyswZMJBTDJ42iS8HV0MuGdtLJ7JzHAkEAv3Fq1AHHJ1Tyxtf/VWHBRfx304NFlDX87Ji7uyv1t+05ZYVT0U8Q5CUPdBA3QexMBKd1i6BXUH/xOY5aX+UrZwJBAKR7ej79wK0kQh2+TESOUs9W4KUXdNSoO3YV7fM5Gvz3Yepx4xkdZ1dcU3tSObDzT63IfeUaCCmGUnaW4QfMnBUCQQCMOsK6mrbLe7D9sBgK7bkJz73iA+UChG1IzTOuDaxGVpDVaU0VI2pHA1KHfJ1NP44LVrKGXSO4Bo+mzjwqxA3/AkEApA8roUKXtKTqC2rb8hs5AscMpHFUl7ZbVeKX14gAg9QPWxkh8BcB1dljAsrp7irEtq4VezD2Cf40b52Fcx+pvA==
private_key_pk8=MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKh0zh8zlzP62PxJS7HFJtIwXE0czbeF+2MC5ev1MfB7IW1OYD+bHCj0dgSFiPEKBgAm3vzFvPDtqIq76kjjk7yKXyezpQveZPn1CUIq7T4VmYXaDni17KqiKiXvXFwzT3oPeyzSgnMoa35u2+UHN1ytczr6lmpsrXgBJYYTi4ERAgMBAAECgYBfmIGMVVOeDOFsMhABnvcL2qPWotzfI+pn4rIkuCyR4t4yUILwNY7CcxAyOrFe0Chdl7F9Up2JP+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
```
--------------------------------
### Add Maven Dependency for Tiger Open API Java SDK
Source: https://docs.itigerup.com/docs/quickstart-java
This snippet shows how to add the Tiger Open API Java SDK as a Maven dependency in your project's pom.xml file. This is the recommended method for obtaining and managing the SDK.
```XML
io.github.tigerbrokers
openapi-java-sdk
2.4.1
```
--------------------------------
### Build Market Orders
Source: https://docs.itigerup.com/docs/place-order-java
This snippet shows how to construct and execute market orders (MKT) for trades. It includes examples for both using the default account and specifying an account parameter. The process involves getting a contract, building the market order request, and executing it via the client.
```java
// get contract(use default account)
ContractRequest contractRequest = ContractRequest.newRequest(new ContractModel("AAPL"));
ContractResponse contractResponse = client.execute(contractRequest);
ContractItem contract = contractResponse.getItem();
// market order(use default account)
TradeOrderRequest request = TradeOrderRequest.buildMarketOrder(contract, ActionType.BUY, 10);
TradeOrderResponse response = client.execute(request);
System.out.println(JSONObject.toJSONString(response));
// get contract(use account parameter)
ContractRequest contractRequest = ContractRequest.newRequest(new ContractModel("AAPL"), "402901");
ContractResponse contractResponse = client.execute(contractRequest);
ContractItem contract = contractResponse.getItem();
// market order(use account parameter)
request = TradeOrderRequest.buildMarketOrder("402901", contract, ActionType.BUY, 10);
response = client.execute(request);
System.out.println(JSONObject.toJSONString(response));
```
--------------------------------
### Configure Maven for Tiger Open API Java SDK
Source: https://docs.itigerup.com/docs/prepare-java
Add the SDK dependency to your pom.xml and, if needed, configure the Sonatype public repository to resolve the artifact. This XML snippet should be placed within the and sections of the Maven project file.
```xml
io.github.tigerbrokers
openapi-java-sdk
2.4.1
```
```xml
sonatype-public
sonatype-public
https://oss.sonatype.org/content/groups/public/
```
--------------------------------
### Initialize TigerHttpClient in Java
Source: https://docs.itigerup.com/docs/quote-stock-java
This code snippet initializes the TigerHttpClient with default configuration and sets up a list of stock symbols for a K-line data request. It depends on the Tiger Brokers OpenAPI Java SDK. The input is a symbol list, but no actual request is made in this partial example. Limitations include requiring SDK setup and proper authentication.
```java
TigerHttpClient client = TigerHttpClient.getInstance().clientConfig(
ClientConfig.DEFAULT_CONFIG);
List symbols = new ArrayList<>();
symbols.add("AAPL");
```
--------------------------------
### Place Market Order (Python)
Source: https://docs.itigerup.com/docs/place-order
Demonstrates how to create and place a market order using the TradeClient. It showcases generating a stock contract and utilizing the market_order function, along with placing the order. Requires tigeropen library and a valid configuration file.
```Python
from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import market_order
from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
trade_client = TradeClient(client_config)
# 生成股票合约
contract = stock_contract(symbol='AAPL', currency='USD')
# 生成订单对象
order = market_order(account=client_config.account, contract=contract, action='BUY', quantity=1)
# 下单
oid = trade_client.place_order(order)
```
--------------------------------
### Place Limit Order using Python
Source: https://docs.itigerup.com/docs/place-order
Shows how to configure a TradeClient, create a stock contract, build a limit order, and submit it via the TigerOpen API. The example covers required imports, client configuration, order creation with price and quantity, and handling the returned order ID. Suitable for automating simple buy/sell limit orders.
```Python
from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import limit_order
from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
trade_client = TradeClient(client_config)
# 生成股票合约
contract = stock_contract(symbol='AAPL', currency='USD')
# 生成订单对象
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=0.1, quantity=1)
# 下单
oid = trade_client.place_order(order)
print(order)
```
--------------------------------
### Get Futures Market Data - Python
Source: https://docs.itigerup.com/docs/quote-future
Examples demonstrating how to retrieve futures market data using the Tiger Open API. This includes getting continuous contracts, trading times, and brief market data. Dependencies include tigeropen library with QuoteClient and TigerOpenClientConfig. The examples show client initialization and three main methods for futures data retrieval with pandas DataFrame outputs.
```python
from tigeropen.quote.quote_client import QuoteClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
quote_client = QuoteClient(client_config)
contracts = quote_client.get_future_continuous_contracts('CL')
```
```python
import pandas as pd
from tigeropen.quote.quote_client import QuoteClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
quote_client = QuoteClient(client_config)
times = quote_client.get_future_trading_times('CN1901', trading_date=1545049282852)
# 转换 start、end 的格式
times['zone_start'] = pd.to_datetime(times['start'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(times['zone'][0])
times['zone_end'] = pd.to_datetime(times['end'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(times['zone'][0])
print(times.to_string())
```
```python
from tigeropen.quote.quote_client import QuoteClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
quote_client = QuoteClient(client_config)
briefs = quote_client.get_future_brief(['CN1901', 'MXP1903'])
print(briefs.to_string())
```
--------------------------------
### Place Forex Order Python Example
Source: https://docs.itigerup.com/docs/place-order
Demonstrates how to place a forex order using the TigerOpen SDK. Requires importing TradeClient and configuring client settings. Takes parameters for account segment, source currency, target currency, and amount. Returns an Order object with transaction details.
```python
from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
trade_client = TradeClient(client_config)
order = trade_client.place_forex_order(seg_type='FUT', source_currency='USD', target_currency='HKD',
source_amount=50)
print(order)
```
--------------------------------
### Get Intraday Data - Java
Source: https://docs.itigerup.com/docs/quote-stock-java
Retrieves intraday data for a specified stock symbol using the Tiger Brokers Java SDK. The request includes parameters such as symbols, period, trade session, start time, and language. The response contains a list of TimelineItems with intraday data, including volume, average price, price, and time.
```Java
TigerHttpClient client = TigerHttpClient.getInstance().clientConfig(
ClientConfig.DEFAULT_CONFIG);
QuoteTimelineResponse response = client.execute(QuoteTimelineRequest.newRequest(List.of("AAPL"), 1544129760000L));
if (response.isSuccess()) {
System.out.println(Arrays.toString(response.getTimelineItems().toArray()));
} else {
System.out.println("response error:" + response.getMessage());
}
```
--------------------------------
### JSON example of market status response
Source: https://docs.itigerup.com/docs/quote-stock-java
Provides a sample JSON payload returned by the QuoteMarketResponse, illustrating fields such as market, marketStatus, status, and openTime for a US market query.
```JSON
{
"code": 0,
"message": "success",
"timestamp": 1525938835697,
"data": [
{
"market": "US",
"marketStatus": "Closed Independence Day",
"status": "CLOSING",
"openTime": "07-04 09:30:00 EDT"
}
]
}
```
--------------------------------
### Initialize QuoteClient with ClientConfig in Python
Source: https://docs.itigerup.com/docs/quickstart
Demonstrates how to initialize a QuoteClient with a ClientConfig object in Python. Includes setting up private key, tiger_id, account, and other necessary configurations.
```Python
from tigeropen.common.consts import (Language, # 语言
Market, # 市场
BarPeriod, # k线周期
QuoteRight) # 复权类型
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 开发者信息获取
"""
client_config = TigerOpenClientConfig()
# 港股牌照需用 props_path 参数指定token路径,如 props_path='/Users/xxx/xxx/', 如不指定则取当前路径
# client_config = TigerOpenClientConfig(props_path='.')
client_config.private_key = read_private_key('填写私钥PEM文件的路径')
client_config.tiger_id = '替换为tigerid'
client_config.account = '替换为账户,建议使用模拟账户'
client_config.license = 'TBSG' # license info
#机构账户,添加用户密钥
client_config.secret_key = '替换为用户密钥'
client_config.language = Language.zh_CN #可选,不填默认为英语'
# client_config.timezone = 'US/Eastern' # 可选时区设置
return client_config
# 调用上方定义的函数生成用户配置ClientConfig对象
client_config = get_client_config()
# 随后传入配置参数对象来初始化QuoteClient
quote_client = QuoteClient(client_config)
# 获取 00700 标的对应的行情数据
stock_price = quote_client.get_stock_briefs(['00700'])
```
--------------------------------
### Java example for fetching market status using TigerHttpClient
Source: https://docs.itigerup.com/docs/quote-stock-java
Demonstrates how to configure TigerHttpClient, execute a QuoteMarketRequest for a specific market (e.g., US), and process the QuoteMarketResponse. Includes success and error handling.
```Java
TigerHttpClient client = TigerHttpClient.getInstance().clientConfig(
ClientConfig.DEFAULT_CONFIG);
QuoteMarketResponse response = client.execute(QuoteMarketRequest.newRequest(Market.US));
if (response.isSuccess()) {
System.out.println(Arrays.toString(response.getMarketItems().toArray()));
} else {
System.out.println("response error:" + response.getMessage());
}
```
--------------------------------
### Build Order with SDK (Python)
Source: https://docs.itigerup.com/docs/appendix-object-detail
Demonstrates how to construct an order object locally using the SDK's order_utils. The SDK provides common parameters, and additional properties can be modified afterward. This example shows constructing a limit order.
```python
from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import (market_order, # 市价单
limit_order, # 限价单
stop_order, # 止损单
stop_limit_order, # 限价止损单
trail_order, # 移动止损单
order_leg) # 附加订单
contract = stock_contract('AAPL', currency='USD')
order = limit_order('your account', contract, 'BUY', 100, 150.5)
order.time_in_force = 'GTC' # 设置订单属性
# 后续操作...
```
--------------------------------
### Get Option Timeline Data - Java Implementation
Source: https://docs.itigerup.com/docs/quote-option-java
Java code example demonstrating how to retrieve option timeline data using OptionTimelineRequest and OptionTimelineModel classes. The code shows setting up multiple option contracts with their parameters (symbol, expiry, strike, right type) and executing the request to get minute-by-minute pricing data. Includes error handling for failed requests.
```Java
OptionTimelineModel model1 = new OptionTimelineModel();
model1.setSymbol("ALB.HK");
model1.setExpiry(1753878054000L);
model1.setStrike("117.50");
model1.setRight("CALL");
OptionTimelineModel model2 = new OptionTimelineModel();
model2.setSymbol("LNI.HK");
model2.setExpiry(1753878054000L);
model2.setStrike("17.00");
model2.setRight("PUT");
OptionTimelineRequest request = OptionTimelineRequest.of(model1, model2);
OptionTimelineResponse response = client.execute(request);
if (response.isSuccess()) {
System.out.println(JSONObject.toJSONString(response));
} else {
System.out.println("response error:" + response.getMessage());
}
```
```JSON
{
"code" : 0,
"message" : "success",
"timestamp" : 1750822293909,
"sign" : "rEiaFf1LYv32Kbu8C+AKpJ/Y9pjrux8usbFA3FFJUEP28EXHv+PnKX9RBtVLalkyrULNqDqS29zP9hF1OZAng7U9KWFQ1Gy/FcGdbypXRNeJxPgKefHt/Fe4rLweO/eWKE41ZprPZlUZX0fxfeMwqkwcTMfhpuu+HQ2/ocmMgeg=",
"timelineItems" : [ {
"lang" : null,
"symbol" : "ALB.HK",
"expiry" : 1753878054000,
"right" : "CALL",
"strike" : "117.50",
"preClose" : 2.72,
"openAndCloseTimeList" : null,
"minutes" : [{
"price" : 3.4,
"avgPrice" : 3.5235946,
"time" : 1750822140000,
"volume" : 29
}, {
"price" : 3.4,
"avgPrice" : 3.5235946,
"time" : 1750822200000,
"volume" : 0
}, {
"price" : 3.4,
"avgPrice" : 3.5235946,
"time" : 1750822260000,
"volume" : 0
} ],
"account" : null
}, {
"lang" : null,
"symbol" : "LNI.HK",
"expiry" : 1753878054000,
"right" : "PUT",
"strike" : "17.00",
"preClose" : 1.28,
"openAndCloseTimeList" : null,
"minutes" : [ {
"price" : 1.21,
"avgPrice" : 1.21,
"time" : 1750822140000,
"volume" : 0
}, {
"price" : 1.21,
"avgPrice" : 1.21,
"time" : 1750822200000,
"volume" : 0
}, {
"price" : 1.21,
"avgPrice" : 1.21,
"time" : 1750822260000,
"volume" : 0
} ],
"account" : null
} ],
"success" : true
}
```
--------------------------------
### Place Order with Legs (Python)
Source: https://docs.itigerup.com/docs/place-order
Demonstrates creating and placing an order with legs, allowing for complex order strategies. Shows the use of limit orders, legs, and other order parameters.
```Python
from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import limit_order, limit_order_with_legs, order_leg, algo_order_params,
algo_order
from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
trade_client = TradeClient(client_config)
```
--------------------------------
### Print Short Initial Margin in Python
Source: https://docs.itigerup.com/docs/trade
This Python code prints the short initial margin value of a contract. The example response includes comprehensive contract details such as symbol, currency, margin rates, and trading specifications.
```Python
print(contract.short_initial_margin)
```
--------------------------------
### Place Order using TigerOpen API in Python
Source: https://docs.itigerup.com/docs/place-order
Demonstrates how to configure the TigerOpen client, create a stock contract, build a limit buy order, and submit it via the TradeClient. Requires the tigeropen Python SDK and a properties file with credentials. Returns the placed order response.
```python
from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
trade_client = TradeClient(client_config)
contract = stock_contract(symbol='AAPL', currency='USD')
order = openapi_client.create_order(account, contract, 'BUY', 'LMT', 100, limit_price=5.0)
trade_client.place_order(order)
```
--------------------------------
### Futures Order Callback Example (JSON)
Source: https://docs.itigerup.com/docs/push-account
JSON-formatted callback example for a filled futures order. Contains contract details, execution prices, commission data, and timestamps. Demonstrates numeric vs string-quoted fields.
```json
{"id":"28875370355884032","account":"12345","symbol":"CL","identifier":"CL2312","multiplier":1000,"action":"BUY","market":"US","currency":"USD","segment":"C","secType":"FUT","orderType":"LMT","isLong":true,"totalQuantity":"1","filledQuantity":"1","avgFillPrice":77.76,"limitPrice":77.76,"status":"FILLED","outsideRth":true,"name":"WTI原油2312","source":"android","commissionAndFee":4.0,"openTime":"1669200792000","timestamp":"1669200782221"}
```
--------------------------------
### Initialize Push Client (Python)
Source: https://docs.itigerup.com/docs/push-quote
This snippet demonstrates how to initialize a PushClient object with connection details. It establishes the connection to the TigerTrade server and initializes necessary components for receiving market data.
```python
from tigeropen.push.push_client import PushClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')
# InitializePushClient
protocol, host, port = client_config.socket_host_port
push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'))
```
--------------------------------
### Place Trade Order
Source: https://docs.itigerup.com/docs/basic-java
This example demonstrates how to place a limit order for a US stock using the Open API. It shows the creation of a contract item and the trade order request.
```APIDOC
## POST /trade/order
### Description
Places a trade order (e.g., buy or sell) for a specified financial instrument. This example specifically shows placing a limit order for a US stock.
### Method
POST
### Endpoint
/trade/order
### Parameters
#### Request Body
- **contract** (ContractItem) - Required - Details of the instrument to trade (e.g., symbol, currency).
- **actionType** (ActionType) - Required - The type of action, BUY or SELL.
- **quantity** (Integer) - Required - The number of shares or units to trade.
- **limitPrice** (Double) - Required - The limit price for the order.
*Note: Other order types and parameters may be available. Refer to the full API documentation.*
### Request Example
```java
import com.alibaba.fastjson.JSONObject;
import com.tigerbrokers.stock.openapi.client.config.ClientConfig;
import com.tigerbrokers.stock.openapi.client.https.client.TigerHttpClient;
import com.tigerbrokers.stock.openapi.client.https.domain.contract.item.ContractItem;
import com.tigerbrokers.stock.openapi.client.https.request.trade.TradeOrderRequest;
import com.tigerbrokers.stock.openapi.client.https.response.trade.TradeOrderResponse;
import com.tigerbrokers.stock.openapi.client.struct.enums.ActionType;
// ... inside a method ...
ContractItem contract = ContractItem.buildStockContract("AAPL", "USD");
TradeOrderRequest request =
TradeOrderRequest.buildLimitOrder(contract, ActionType.BUY, 1, 100.0);
// Assuming 'client' is an initialized TigerHttpClient instance
// TradeOrderResponse response = client.execute(request);
// System.out.println(JSONObject.toJSONString(response));
```
### Response
#### Success Response (200)
- **orderId** (String) - The unique identifier for the placed order.
- **orderStatus** (String) - The current status of the order.
#### Response Example
```json
{
"success": true,
"message": null,
"data": {
"orderId": "1234567890",
"orderStatus": "Submitted"
}
}
```
#### Error Response (Non-200)
- **success** (Boolean) - Indicates if the request was successful.
- **message** (String) - Error message if the request failed.
```
--------------------------------
### Tiger Open API Token Properties Configuration
Source: https://docs.itigerup.com/docs/quickstart-java
This section describes the configuration for the `tiger_openapi_token.properties` file, which is used for token-based authentication. It also explains the auto-refresh mechanism for tokens and optional configurations like IP whitelisting and callback URLs.
```Properties
# Example token properties (actual content will be provided upon generation)
# token=YOUR_GENERATED_TOKEN
# token_expiry_time=YYYY-MM-DD HH:MM:SS
```
--------------------------------
### Install Homebrew on macOS
Source: https://docs.itigerup.com/docs/mcp
Command to install Homebrew on macOS if it is not already installed. Required for installing coreutils to resolve realpath command issues on macOS 12 or below.
```shell
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
--------------------------------
### Tiger API Client Configuration in Python
Source: https://docs.itigerup.com/docs/full-example
Sets up QuoteClient and TradeClient using configuration from private key, Tiger ID, and account details. Purpose: Initializes API clients for stock data retrieval and trading. Dependencies: Custom get_client_config function and logger. Inputs: File paths and IDs as strings. Outputs: Configured client instances. Limitations: Hardcoded paths need replacement with actual values.
```python
REQUEST_SIZE = 50
TARGET_QUANTITY = "target_quantity"
PRE_CLOSE = "pre_close"
LATEST_PRICE = "latest_price"
MARKET_CAPITAL = "market_capital"
SYMBOL = "symbol"
WEIGHT = "weight"
TIME = "time"
CLOSE = "close"
DATE = "date"
LOT_SIZE = "lot_size"
PRIVATE_KEY_PATH = "your private key path"
TIGER_ID = "your tiger id"
ACCOUNT = "your account"
client_config = get_client_config(private_key_path=PRIVATE_KEY_PATH, tiger_id=TIGER_ID, account=ACCOUNT)
quote_client = QuoteClient(client_config, logger=client_logger)
trade_client = TradeClient(client_config, logger=client_logger)
```