Basic Functionality Examples
The Tiger OpenAPI Python SDK provides APIs for retrieving market data, subscribing to real-time updates, and trading.
Querying Market Data
The following minimal example retrieves a stock quote snapshot. Later examples demonstrate trading and real-time market data subscriptions.
Tiger OpenAPI also supports market data and trading for multiple instrument types and markets. After completing this guide, see the API documentation for the full method list, parameters, and examples.
The code comments explain each step so that you can adapt and run the example directly:
from tigeropen.common.consts import (Language, # Language
Market, # Market
BarPeriod, # bar period
QuoteRight) # Dividend 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
client_config = TigerOpenClientConfig(props_path='your_config_directory_path')
# Alternatively, configure the client in code
# def get_client_config():
# client_config = TigerOpenClientConfig()
# # On Windows, use a raw path string to avoid escape sequences, for example: read_private_key(r'C:\Users\admin\tiger.pem')
# client_config.private_key = read_private_key('Fill in the path of the private key PEM file')
# client_config.tiger_id = 'Replace with tiger id'
# client_config.account = 'Replace with account; a paper trading account is recommended'
# client_config.language = Language.zh_CN # Optional; defaults to English
# # client_config.timezone = 'US/Eastern' # Optional time zone setting
# return client_config
# Call the function above to create the client configuration
# client_config = get_client_config()
# Initialize QuoteClient with the configuration
quote_client = QuoteClient(client_config)
# Retrieve a stock quote snapshot
stock_price = quote_client.get_stock_briefs(['00700'])
# The method returns a pandas.DataFrame containing the current quote snapshot. See get_stock_briefs for field definitions.
print(stock_price)Example Response
symbol ask_price ask_size bid_price bid_size pre_close latest_price \
0 00700 326.4 15300 326.2 26100 321.80 326.4
latest_time volume open high low status
0 1547516984730 2593802 325.00 326.80 323.20 NORMAL
Subscribing to Market Data
Tiger OpenAPI can also stream market data and other updates over a persistent connection. This example subscribes to Apple and AMD market data, prints snapshots for one minute, unsubscribes, and disconnects.
Subscription operations are asynchronous. Register callback functions on PushClient; when the server sends an event or update, the SDK invokes the corresponding callback with the event data.
import time
from tigeropen.push.push_client import PushClient
from tigeropen.push.pb.QuoteBasicData_pb2 import QuoteBasicData
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='your_config_directory_path')
# Define callbacks. This example simply prints the received data.
def on_quote_changed(frame: QuoteBasicData):
"""
Basic market data callback.
Example payload:
symbol: "00700"
type: BASIC
timestamp: 1677742483530
serverTimestamp: 1677742483586
avgPrice: 365.37
latestPrice: 363.8
latestPriceTimestamp: 1677742483369
latestTime: "03-02 15:34:43"
preClose: 368.8
volume: 12674730
amount: 4630947968
open: 368.2
high: 369
low: 362.4
marketStatus: "Trading"
mi {
p: 363.8
a: 365.37
t: 1677742440000
v: 27300
h: 364
l: 363.6
}
"""
print(frame)
print(frame.latestPrice)
# Handle subscription success or failure
def subscribe_callback(frame):
"""
Subscription result callback.
"""
print(f'subscribe callback:{frame}')
# Handle unsubscription success or failure
def unsubscribe_callback(frame):
"""
Unsubscription result callback.
"""
print(f'unsubscribe callback:{frame}')
# Handle a successful connection
def connect_callback(frame):
"""Subscribe after every connection, including a successful reconnect."""
print('connected')
push_client.subscribe_quote(['AAPL', 'AMD'])
if __name__ == "__main__":
# Initialize PushClient
protocol, host, port = client_config.socket_host_port
push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'), use_protobuf=True)
# Register callbacks for asynchronous subscription events
push_client.quote_changed = on_quote_changed
# Bind subscription success/failure callback
push_client.subscribe_callback = subscribe_callback
# Unsubscription success/failure callback
push_client.unsubscribe_callback = unsubscribe_callback
# Default disconnect handling reconnects; restore subscriptions after acknowledgement
push_client.connect_callback = connect_callback
# Establish connection
push_client.connect(client_config.tiger_id, client_config.private_key)
# Wait for push
time.sleep(60)
# Cancel subscription
push_client.unsubscribe_quote(['AAPL', 'AMD'])
# Disconnect
push_client.disconnect()Trading Orders
The following example places an order for Tiger Brokers (TIGR) stock:
from tigeropen.common.consts import (Language, # Language
Market, # Market
BarPeriod, # bar period
QuoteRight) # Dividend adjustment type
from tigeropen.tiger_open_config import TigerOpenClientConfig
from tigeropen.common.util.signature_utils import read_private_key
from tigeropen.trade.trade_client import TradeClient
client_config = TigerOpenClientConfig(props_path='your_config_directory_path')
# Initialize TradeClient with the configuration
trade_client = TradeClient(client_config)
from tigeropen.common.consts import Market, SecurityType, Currency
from tigeropen.common.util.contract_utils import stock_contract
# Create a contract that identifies the tradable instrument. See Trading - Get Contract for details, including futures contracts.
# Method 1: Construct a stock contract locally
contract = stock_contract(symbol='TIGR', currency='USD')
# Method 2: Retrieve a stock contract from the API
contract = trade_client.get_contracts(symbol='SPY')[0]
# Import the supported order constructors
from tigeropen.common.util.order_utils import (market_order, # Market order
limit_order, # Limit order
stop_order, # Stop order
stop_limit_order, # Stop limit order
trail_order, # Trailing stop order
order_leg) # Attached order
# Create a limit order. The order stores the account, contract, and execution instructions.
stock_order = limit_order(account=client_config.account, # Global, prime, or paper trading account
contract = contract, # Contract created above
action = 'BUY',
quantity = 100,
limit_price = 100 )
# Submit the order. Its id is None before submission and becomes the global order ID after successful submission.
trade_client.place_order(stock_order)
print(stock_order)Example Response
Order({'account': '164644', 'id': 14275856193552384, 'order_id': None, 'parent_id': None, 'order_time': None, 'reason': None, 'trade_time': None, 'action': 'BUY', 'quantity': 100, 'filled': 0, 'avg_fill_price': 0, 'commission': None, 'realized_pnl': None, 'trail_stop_price': None, 'limit_price': 100, 'aux_price': None, 'trailing_percent': None, 'percent_offset': None, 'order_type': 'LMT', 'time_in_force': None, 'outside_rth': None, 'contract': SPY/STK/USD, 'status': 'NEW', 'remaining': 100})
Additional Notes
For other supported order types, see Order Object.
Updated 29 days ago
