Basic Function

About 4 min

This section provides some complete examples about the core functions of Tiger Open API Java SDK. You are able to copy the example directly to your local directory to run the examples:

Get Market Quotes

Here is a simple example of using the Tiger Open API. It demonstrates how to use Open API to get the market data. Below this example, our next sample codes will show you how to use Open API to trade, and subscribe to market data.

Besides all the basic functions demonstrated below, you can also get different types of market data and trade various products with advanced order types by using Open API. For a complete list and demonstration of the full capability of the Open API, please read the other sections of this documentation.

from tigeropen.common.consts import (Language,        # Language
                                Market,           # Market
                                BarPeriod,        # Size of each time window of the K-Line
                                QuoteRight)       # Price 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

# Almost all requests related to pulling market quote data use the methods of QuoteClient,
# first generate the client config which used to initialize QuoteClient. The config contain developer's information like tiger_id, private_key, account
def get_client_config(sandbox=False):
    """
    https://quant.itigerup.com/#developer   query developer infos
    """
    client_config = TigerOpenClientConfig(sandbox_debug=sandbox)
    # if use windows system, need to add "r", like: read_private_key(r'C:\Users\admin\tiger.pem')
    client_config.private_key = read_private_key('path of rsa private key')
    client_config.tiger_id = 'developer tiger id'
    client_config.account = 'account id, paper trading account is recommended here for testing' 
    client_config.language = Language.zh_CN  # optional, default en_US
    # client_config.timezone = 'US/Eastern' # default timezone 
    return client_config

# initialize ClientConfig 
client_config = get_client_config()

# initialize QuoteClient
quote_client = QuoteClient(client_config)

# query Stock quotes
stock_price = quote_client.get_stock_briefs(['00700'])
print(stock_price)

Response Example

  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 

Market Data Streaming

The Tiger Open API also supports receiving the market data by subscription, so you can get live streaming for market quotes via websocket. Please see the example for details. The basic idea of this example is to subscribe the market quotes for AAPL and AMD, print the results,

Please note that all APIs involved in this section is aschonynic. As a result, in most cases, you will need to implement your own callback function to handle the data being sent back.

import time
from tigeropen.push.push_client import PushClient
from tigeropen.tiger_open_config import TigerOpenClientConfig

def get_client_config(sandbox=False):
    """
    https://quant.itigerup.com/#developer Obtain developer's information
    """
    client_config = TigerOpenClientConfig(sandbox_debug=sandbox)
    client_config = TigerOpenClientConfig(sandbox_debug=sandbox)
    client_config.private_key = read_private_key('The path to .pem file which stores the private key')
    client_config.tiger_id = 'tigerid'
    client_config.account = 'account id, paper trading account is recommended here for testing' 
    return client_config

#Implement callbacks to process the data. For simplicity, we only print the result in this example
def on_quote_changed(symbol, items, hour_trading):
    """
    quote callback,its arguments(data being returned by API)are:
    symbol: symbol of the stock being subscribed
    items: list, each element of this list is a tuple, storing the actual data being returned
    hour_trading: bool, shows if the market is currently in trading hours
    """
    print(symbol, items, hour_trading)

#Implement callback function for successful subscription
def subscribe_callback(destination, content):
    """
    subscribe callback
    params:
    destination: type of subscribe.  quote, trade/asset, trade/position, trade/order
    content: callback content. if success, {'code': 0, 'message': 'success'}; if failed, code is not equal to 0
    """
    print('subscribe:{}, callback content:{}'.format(destination, content))

#Implement callback function for successful unsubscription
def unsubscribe_callback(destination, content):
    """
    params:
    destination: type of unsubscribe.  quote, trade/asset, trade/position, trade/order
    content: callback content
    """
    print('subscribe:{}, callback content:{}'.format(destination, content))

#Implement callback function for establishing connection
def connect_callback():
    """callback function for establishing connection"""
    print('connected')

def disconnect_callback():
    """callback function for disconnection. This function will print disconnect status, and try to reconnect to the server"""
    for t in range(1, 20):
        try:
            print('disconnected, reconnecting')
            push_client.connect(client_config.tiger_id, client_config.private_key)
        except:
            print('connect failed, retry')
            time.sleep(t)
        else:
            print('reconnect success')
            return
    print('reconnect failed, please check your network')

if __name__ == "__main__":
    #first, generate config file using our intergrated tool function
    client_config = get_client_config()

    #Initialize PushClient
    protocol, host, port = client_config.socket_host_port
    push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'))

    # bind callback method
    push_client.quote_changed = on_quote_changed
    # callback for subscription
    push_client.subscribe_callback = subscribe_callback
    # callback for unsubscription
    push_client.unsubscribe_callback = unsubscribe_callback
    # callback for re-establish connection
    push_client.disconnect_callback = disconnect_callback

    # establish connection
    push_client.connect(client_config.tiger_id, client_config.private_key)
    # subscribe market quotes,here we use Apple and AMD as examples
    push_client.subscribe_quote(['AAPL', 'AMD'])

    # wait for the message feed to arrive
    time.sleep(30)

    # unsubscribe
    push_client.unsubscribe_quote()
    # disconnect
    push_client.disconnect()

Place Orders

Tradingg is another core funtion of Tiger Open API. This exmaple demonstrates how to place market order for TIGR (Tiger Brokers) with Open API

from tigeropen.common.consts import (Language,        # Language
                                    Market,           # Market
                                    BarPeriod,        # Size of each time window of the K-Line
                                    QuoteRight)       # Price 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 is used to initialize TradeClient
def get_client_config(sandbox=False):
    """
    https://quant.itigerup.com/#developer Obtain or modify developer‘s information
    """
    client_config = TigerOpenClientConfig(sandbox_debug=sandbox)
    client_config.private_key = read_private_key('PEM file path')
    client_config.tiger_id = 'tiger id'
    client_config.account = 'account id'
    client_config.language = Language.zh_CN # Optional. en_US by default
    return client_config

client_config = get_client_config()

# Initialize an instance of TradeClient
trade_client = TradeClient(client_config)

from tigeropen.common.consts import Market, SecurityType, Currency
from tigeropen.common.util.contract_utils import stock_contract

# Before place an order, need to initialize a Contract. Refer to 'Operation' - 'Trade' - 'Contract'
# Approach 1: Build contract without send a request, fast and directly
contract = stock_contract(symbol='TIGR', currency='USD')
# Approach 2: request a Contract from server
contract = trade_client.get_contracts(symbol='SPY')[0]

# Supported order types
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 Order object
stock_order = market_order(account=client_config.account,             # account for place order
                            contract = contract,                      # contract that generated in first step
                            action = 'BUY',
                            quantity = 100)

# submit order. After submitting success, the Order.id will be set, this id can used to query or cancel the order
trade_client.place_order(stock_order)

print(stock_order)

Response Example

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})

Note

For other supported order types, refer to Object-Order Object section of this documentation

Last update: