中文

Place Order

place_order Place Order

TradeClient.place_order():

Description

Trading order placement interface. For guidance on selecting instruments, order types, direction, quantities, etc., please see the explanations below.

Before running your program, please review the User and Account Types and Order and Trading Rules sections of this documentation to verify that your account supports the requested order type and that trading rules permit placing orders for the specific instrument during your program's runtime. If order placement fails, first consult the Error Codes section for troubleshooting.

After a successful place_order call, the order ID in the order object parameter is populated (order.id) and can be used for subsequent queries or cancellations. At this point, this method returns the order ID, but this only indicates successful order submission, not successful order execution. Order execution is asynchronous. After submitting an order, it will proceed to the next state based on circumstances, such as being filled, rejected, etc. Therefore, it's recommended to use the get_order or get_orders methods to check the order status before performing any subsequent operations on the order.

⚠️

CAUTION

  1. Market orders (MKT) and stop orders (STP) do not support pre-market and after-hours trading. When calling the order placement interface, set outside_rth to false
  2. For shortable instruments, position locking is currently not supported, so you cannot simultaneously hold long and short positions in the same instrument
  3. For attached orders, the primary order type currently only supports limit orders
  4. Market orders (MKT) and paper trading accounts do not support setting the time_in_force parameter to GTC
  5. Paper trading accounts do not currently support orders for warrants and callable bull/bear contracts

Order Status Description

  1. How to determine partial fill status for integrated and paper trading accounts?

    When the order status is not FILLED (it could be NEW, CANCELLED, EXPIRED, or REJECTED), there's still a possibility of partial fill status, which can be determined by checking if the filled quantity is greater than 0

  2. How to determine partial fill status for global accounts?

    Order status is FILLED and the filled quantity is greater than 0

Order Status Flow:

Other Notes

  • For index options, except IWM/SPY/QQQ, only contracts with Friday expiration dates are supported for trading.
  • Direct opening of reverse positions is prohibited. For example, when currently holding 100 long shares, directly selling 200 shares (intending to establish a net short position of 100 shares) will be rejected. You must first close the existing 100 long shares, then perform a new sell operation.

Parameters

Order object (tigeropen.trade.domain.order.Order)

You can use utility functions from tigeropen.common.util.order_utils, such as limit_order(), market_order(), to generate order objects locally based on your specific order type and parameter requirements. For creation methods, see the Order Object - Construction Methods section, or use TradeClient.create_order() to request an order number from the server and then generate the order object (not recommended).

Parameters

ParameterTypeDescriptionMarket OrderLimit OrderStop OrderStop-Limit OrderTrailing Stop Order
accountstrUser authorized account: 402901RequiredRequiredRequiredRequiredRequired
order_idintOrder number, used to prevent duplicate orders. Can be obtained through the order number interface. If 0 is passed, the server will automatically generate an order number. When passing 0, duplicate order prevention is not possible, please choose carefullyOptionalOptionalOptionalOptionalOptional
symbolstrStock symbol e.g.: AAPL; (For warrants/callable bull bear contracts when sec_type, use the 5-digit number below the name in the app warrant/bull bear contract list)RequiredRequiredRequiredRequiredRequired
sec_typestrContract type (STK Stock, OPT US Stock Options, WAR HK Warrants, IOPT HK Callable Bull/Bear Contracts, FUT Futures)RequiredRequiredRequiredRequiredRequired
actionstrTrading direction BUY/SELLRequiredRequiredRequiredRequiredRequired
order_typestrOrder type. MKT (Market Order), LMT (Limit Order), STP (Stop Order), STP_LMT (Stop-Limit Order), TRAIL (Trailing Stop Order)MKTLMTSTPSTP_LMTTRAIL
quantityintOrder quantity (HK stocks, Shanghai-Hong Kong Stock Connect, warrants, callable bull/bear contracts have minimum quantity restrictions)RequiredRequiredRequiredRequiredRequired
quantity_scaleintOrder quantity offset, default is 0. For fractional shares, quantity and quantity_scale combine to represent the actual order quantity. E.g., quantity=111, quantity_scale=2, then actual quantity=111*10^(-2)=1.11Not RequiredNot RequiredNot RequiredNot RequiredNot Required
total_cash_amountfloatTotal order amount, only needed for dollar-based orders. Not needed for quantity-based ordersNot RequiredNot RequiredNot RequiredNot RequiredNot Required
limit_pricefloatLimit price, required when order_type is LMT or STP_LMTNot RequiredRequiredNot RequiredRequiredNot Required
aux_pricefloatStock order stop trigger price. Meaning is price difference. When both trailing_percent exist, overridden by trailing_percent. Required when order_type is STP or STP_LMT. When order_type is TRAIL, this is the trailing amountNot RequiredNot RequiredRequiredRequiredOptional
trailing_percentfloatTrailing stop order - stop percentage. When order_type is TRAIL, aux_price and trailing_percent are mutually exclusive, with trailing_percent taking priorityNot RequiredNot RequiredNot RequiredNot RequiredOptional
outside_rthbooltrue: Allow pre-market and after-hours trading (US stocks only), false: Don't allow, default is allow. (Market orders, stop orders, trailing stop orders are only valid during market hours and will ignore the outside_rth parameter)Not RequiredOptionalOptionalNot RequiredOptional
adjust_limitfloatPrice micro-adjustment range (default 0 means no adjustment, positive for upward adjustment, negative for downward adjustment), automatically adjusts the input price to a valid price level. E.g., 0.001 means upward adjustment not exceeding 0.1%; -0.001 means downward adjustment not exceeding 0.1%. Default 0 means no adjustmentNot RequiredOptionalOptionalOptionalOptional
marketstrMarket (US stocks: US, HK stocks: HK, Shanghai-Hong Kong Stock Connect: CN)OptionalOptionalOptionalOptionalOptional
currencystrCurrency (US stocks: USD, HK stocks: HKD, Shanghai-Hong Kong Stock Connect: CNH)OptionalOptionalOptionalOptionalOptional
time_in_forcestrOrder validity period, can only be DAY (valid for the day), GTC (valid until canceled, maximum validity 180 days), GTD (valid until specified time), default is DAYOptionalOptionalOptionalOptionalOptional
expire_timeintOrder validity end time, 13-digit timestamp accurate to seconds (required when time_in_force is GTD, invalid for other types)Not RequiredOptionalOptionalNot RequiredOptional
exchangestrExchange (US stocks: SMART, HK stocks: SEHK, Shanghai-Hong Kong Stock Connect: SEHKNTL, Shenzhen-Hong Kong Stock Connect: SEHKSZSE)OptionalOptionalOptionalOptionalOptional
expirystrExpiration date (options, warrants, callable bull/bear contracts only)OptionalOptionalOptionalOptionalOptional
strikestrStrike price (options, warrants, callable bull/bear contracts only)OptionalOptionalOptionalOptionalOptional
rightstrOption direction PUT/CALL (options, warrants, callable bull/bear contracts only)OptionalOptionalOptionalOptionalOptional
multiplierfloatMultiplier, quantity per lot (options, warrants, callable bull/bear contracts only)OptionalOptionalOptionalOptionalOptional
local_symbolstrFor warrants/callable bull bear contracts, this field is required - the 5-digit number below the name in the app warrant/bull bear contract listOptionalOptionalOptionalOptionalOptional
secret_keystrTrader key, for institutional users onlyOptionalOptionalOptionalOptionalOptional
user_markstrOrder note information, cannot be modified after placing order, returns userMark information when querying ordersOptionalOptionalOptionalOptionalOptional
  • Attached Order Parameters

    Attached Orders are orders that can achieve take-profit or stop-loss effects on the main order through attached sub-orders. The attachable sub-order types are limit orders (for take-profit) and stop-limit/stop orders (for stop-loss). Attached orders can be implemented by adding the following parameters

    ParameterTypeDescriptionAttached Stop LossAttached Take ProfitLimit/Stop/Stop-Limit (One-Cancels-All only)
    leg_typestrAttached order type. 'PROFIT' for take-profit order type, 'LOSS' for stop-loss order typeRequiredRequiredRequired
    pricefloatAttached order priceRequiredRequiredRequired
    time_in_forcestrAttached order validity period. 'DAY' (valid for the day) and 'GTC' (valid until canceled - Good-Til-Canceled)OptionalOptionalOptional
    outside_rthboolWhether attached order allows pre-market and after-hours trading (US stocks only). True allows, False doesn't allowOptionalOptionalOptional
    limit_pricefloatLimit order priceNot RequiredNot RequiredLMT and STP_LMT Required
    trailing_percentfloatTrailing stop order - stop percentage. When using trailing stop orders, you must fill in either stop loss percentage (stopLossTrailingPercent) or stop loss amount (stopLossTrailingAmount). If both are filled, the stop loss percentage takes priorityOptionalNot RequiredNot Required
    trailing_amountfloatTrailing stop order - stop amount. When using trailing stop orders, you must fill in either stop loss percentage (stopLossTrailingPercent) or stop loss amount (stopLossTrailingAmount). If both are filled, the stop loss percentage takes priorityOptionalNot RequiredNot Required
    quantityintOrder quantityRequiredRequiredRequired

  • TWAP/VWAP Order Parameters

TWAP/VWAP orders only support US stock symbols and can only be placed during market hours, pre-market orders are not supported

ParameterTypeAlgorithm ParameterDescriptionTWAPVWAP
order_typestrOrder type, TWAP/VWAPRequiredRequired
accountstrTrading accountRequiredRequired
symbolstrStock symbol e.g.: AAPLRequiredRequired
sec_typestrOnly supports STKRequiredRequired
total_quantityintOrder quantityRequiredRequired
algo_paramsAlgoParamsAlgorithm parameters, generated via tigeropen.common.util.order_utils.algo_order_paramsOptionalOptional
-intstart_timeStrategy start time (timestamp)OptionalOptional
-intend_timeStrategy end time (timestamp)OptionalOptional
-floatparticipation_rateMaximum participation rate (maximum proportion of daily average volume, 0.01-0.5)Not applicableOptional

Return

Returns order ID if successful, throws exception if failed. If order is placed successfully, the Order object's id will be populated with the actual order number.


Contract Object Examples

Contract

from tigeropen.common.util.contract_utils import stock_contract, option_contract, option_contract_by_symbol, \
    future_contract, war_contract_by_symbol, iopt_contract_by_symbol

# US stocks
contract = stock_contract(symbol='TIGR', currency='USD')

# Hong Kong stocks
contract = stock_contract(symbol='00700', currency='HKD')

# Options
contract = option_contract(identifier='AAPL  190118P00160000')
contract = option_contract_by_symbol('JD', expiry='20211015', strike=45.0, put_call='PUT', currency='USD')

# Futures
# Integrated/Simulation
from tigeropen.common.util.contract_utils import future_contract
contract = future_contract(symbol='CL2312', currency='USD')
# Global
from tigeropen.common.util.contract_utils import future_contract
contract = future_contract(symbol='CL', currency='USD', expiry='20190328', multiplier=1.0, exchange='SGX')

# Hong Kong warrants
contract = war_contract_by_symbol('01810', '20221116', 14.52, 'CALL', local_symbol='14759', multiplier=2000,
                                  currency='HKD')
# Hong Kong CBBCs
contract = iopt_contract_by_symbol('02318', '20200420', 87.4, 'CALL', local_symbol='63379', currency='HKD')

Limit Order (LMT)

limit_order

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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=0.1, quantity=1)

# Place order
oid = trade_client.place_order(order)

print(order)
# >>> Order({'account': '111111', 'id': 2498911111111111111, 'order_id': None, 'parent_id': None, 'order_time': None, 'reason': None, 'trade_time': None, 'action': 'BUY', 'quantity': 1, 'filled': 0, 'avg_fill_price': 0, 'commission': None, 'realized_pnl': None, 'trail_stop_price': None, 'limit_price': 0.1, 'aux_price': None, 'trailing_percent': None, 'percent_offset': None, 'order_type': 'LMT', 'time_in_force': None, 'outside_rth': None, 'order_legs': None, 'algo_params': None, 'secret_key': None, 'contract': AAPL/STK/USD, 'status': 'NEW', 'remaining': 1})
print(order.status)  # Order status
print(order.reason)  # If order fails, reason contains the failure reason

# If order is successful, order.id contains the order ID, which can be used for querying or canceling the order
my_order = trade_client.get_order(id=order.id)
oid = trade_client.cancel_order(id=order.id)
# Or modify the order object
trade_client.modify_order(order, limit_price=190.5)

Market Order (MKT)

market_order

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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = market_order(account=client_config.account, contract=contract, action='BUY', quantity=1)

# Place order
oid = trade_client.place_order(order)

Market Order by Amount (MKT)

market_order

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import market_order_by_amount
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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = market_order_by_amount(account=client_config.account, contract=contract, action='BUY', amount=100)

# Place order
oid = trade_client.place_order(order)

Stop Order (STP)

stop_order

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import stop_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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = stop_order(account=client_config.account, contract=contract, action='SELL', aux_price=1, quantity=1)

# Place order
oid = trade_client.place_order(order)

Stop Limit Order (STP_LMT)

stop_limit_order

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import stop_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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = stop_limit_order(account=client_config.account, contract=contract, action='SELL', limit_price=200.0, aux_price=180.0, quantity=1)

# Place order
oid = trade_client.place_order(order)

Trailing Stop Order (TRAIL)

trail_order

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import trail_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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = trail_order(account=client_config.account, contract=contract, action='SELL', quantity=1, trailing_percent=8.0, )

# Place order
oid = trade_client.place_order(order)

Attached Orders

order_leg

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)

# Limit order + attached orders (only limit orders support attached orders)
stop_loss_order_leg = order_leg('LOSS', 8.0, time_in_force='GTC',outside_rth=False)  # Attached stop loss
stop_loss_order_leg1 = order_leg('LOSS', 8.0, limit_price=7.5,outside_rth=False)  # Attached stop loss limit order
stop_loss_order_leg2 = order_leg('LOSS', 8.0, trailing_percent=0.8,outside_rth=False)  # Attached trailing stop (by percentage)
stop_loss_order_leg3 = order_leg('LOSS', 8.0, trailing_amount=2.0,outside_rth=False)  # Attached trailing stop (by amount)

profit_taker_order_leg = order_leg('PROFIT', 12.0, time_in_force='GTC',outside_rth=False)  # Attached take profit
main_order = limit_order_with_legs(account, contract, 'BUY', 100, limit_price=10.0,
order_legs=[profit_taker_order_leg, stop_loss_order_leg])
oid = trade_client.place_order(main_order)
# Query attached orders associated with the main order
order_legs = trade_client.get_open_orders(account, parent_id=main_order.id)
print(order_legs)

Main Order + Attached Stop Loss Order

Attached stop loss orders can be market orders, limit orders, or trailing stop orders

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)

# Limit order + attached orders (only limit orders support attached orders)
stop_loss_order_leg = order_leg('LOSS', 8.0, time_in_force='GTC',outside_rth=False)  # Attached stop loss market order
stop_loss_order_leg1 = order_leg('LOSS', 8.0, limit_price=7.5,outside_rth=False)  # Attached stop loss limit order
stop_loss_order_leg2 = order_leg('LOSS', 8.0, trailing_percent=0.8,outside_rth=False)  # Attached trailing stop (by percentage)
stop_loss_order_leg3 = order_leg('LOSS', 8.0, trailing_amount=2.0,outside_rth=False)  # Attached trailing stop (by amount)

main_order = limit_order_with_legs(account, contract, 'BUY', 100, limit_price=10.0,
order_legs=[stop_loss_order_leg])
oid = trade_client.place_order(main_order)
# Query attached orders associated with the main order
order_legs = trade_client.get_open_orders(account, parent_id=main_order.id)
print(order_legs)

Main Order + Attached Take Profit Order

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)

# Limit order + attached orders (only limit orders support attached orders)
profit_taker_order_leg = order_leg('PROFIT', 12.0, time_in_force='GTC',outside_rth=False)  # Attached take profit
main_order = limit_order_with_legs(account, contract, 'BUY', 100, limit_price=10.0,
order_legs=[profit_taker_order_leg])
oid = trade_client.place_order(main_order)
# Query attached orders associated with the main order
order_legs = trade_client.get_open_orders(account, parent_id=main_order.id)
print(order_legs)

Main Order + Attached Bracket Order

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)

# Limit order + attached orders (only limit orders support attached orders)
stop_loss_order_leg = order_leg('LOSS', 8.0, time_in_force='GTC',outside_rth=False)  # Attached stop loss
profit_taker_order_leg = order_leg('PROFIT', 12.0, time_in_force='GTC',outside_rth=False)  # Attached take profit
main_order = limit_order_with_legs(account, contract, 'BUY', 100, limit_price=10.0,
order_legs=[profit_taker_order_leg, stop_loss_order_leg])
oid = trade_client.place_order(main_order)
# Query attached orders associated with the main order
order_legs = trade_client.get_open_orders(account, parent_id=main_order.id)
print(order_legs)

OCA Orders

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import order_leg, oca_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='BILI', currency=Currency.USD)
# stop_loss_order_leg = order_leg('STP', price=8.0)
stop_loss_order_leg = order_leg('STP_LMT', price=8.0, limit_price=7.5,outside_rth=False)
profit_taker_order_leg = order_leg('LMT', limit_price=30.0,outside_rth=False)
my_oca_order = oca_order(client_config.account, contract, 'BUY',
                                   order_legs=[stop_loss_order_leg, profit_taker_order_leg],
                                   quantity=1000)
trade_client.place_order(my_oca_order)

Algorithmic Orders

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)
    
# Algorithmic orders
contract = stock_contract(symbol='AAPL', currency='USD')
# TWAP does not support participation_rate parameter
params = algo_order_params(start_time='2022-01-19 23:00:00', end_time='2022-11-19 23:50:00', participation_rate=0.1)
order = algo_order(account, contract, 'BUY', 1000, 'VWAP', algo_params=params, limit_price=100.0)
oid = trade_client.place_order(order)

Auction Orders

auction_limit_order Auction Limit Order auction_market_order Auction Market Order

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)

# Generate stock contract
contract = stock_contract(symbol='01810', currency='HKD')
# Auction limit order, time_in_force set to OPG means participate in pre-market auction, continue as regular order during market hours if not filled pre-market, does not participate in post-market auction; set to DAY means only valid during post-market
order = auction_limit_order(account=client_config.account, contract=contract, action='BUY', quantity=200,
                            limit_price='10', time_in_force='OPG')
# Auction market order
# order = auction_market_order(account=client_config.account, contract=contract, action='BUY', quantity=200, time_in_force='OPG')

# Place order
oid = trade_client.place_order(order)

Extended/Full Session Orders

Only supports US stocks

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.consts import TradingSessionType
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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=120, quantity=1)

# Extended hours trading
# order.trading_session_type = TradingSessionType.OVERNIGHT

# Full session trading
order.trading_session_type = TradingSessionType.FULL

# Place order
trade_client.place_order(order)
my_order = trade_client.get_order(id=order.id)
print(my_order.user_mark)

Other Examples

Placing Hong Kong Stock Orders

In Hong Kong stock trading, the order quantity must be an integer multiple of the stock's "lot size". Taking Tencent Holdings (00700) as an example, its lot size is 100 shares, so acceptable order quantities are 100, 200, 500, etc. (i.e., multiples of 100).

You can use QuoteClient.get_trade_metas in advance to get the stock's lot size to ensure the order quantity complies with the rules.

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)
quote_client = QuoteClient(client_config)

symbol = '00700'

# Get lot size
metas = quote_client.get_trade_metas([symbol])
lot_size = int(metas['lot_size'].iloc[0])

# Generate stock contract
contract = stock_contract(symbol=symbol, currency='HKD')
# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=400.0, quantity=2 * lot_size)
# Place order
oid = trade_client.place_order(order)

Placing Futures Orders

from tigeropen.common.util.contract_utils import future_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)

# Generate futures contract
contract = future_contract(symbol='CL', currency='USD')
# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=0.1, quantity=1)
# Place order
oid = trade_client.place_order(order)

Placing Options Orders

from tigeropen.common.util.contract_utils import option_contract, option_contract_by_symbol
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)
    
# Generate options contract
contract = option_contract(identifier='AAPL  190118P00160000')
# Or
contract = option_contract_by_symbol('AAPL', '20200110', strike=280.0, put_call='PUT', currency='USD')

# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=0.1, quantity=1)
# Place order
oid = trade_client.place_order(order)

Placing Option Combo Orders

from tigeropen.common.consts import ComboType
from tigeropen.common.util.contract_utils import option_contract, option_contract_by_symbol
from tigeropen.common.util.order_utils import combo_order, contract_leg
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_leg1 = contract_leg(symbol='TSLA', sec_type='OPT', expiry='20230616', strike=220, put_call='CALL',
                            action='BUY', ratio=1)
contract_leg2 = contract_leg(symbol='TSLA', sec_type='OPT', expiry='20230616', strike=225, put_call='CALL',
                            action='SELL', ratio=1)

order = combo_order(client_config.account, [contract_leg1, contract_leg2], combo_type=ComboType.VERTICAL,
                    action='BUY', quantity=1, order_type='LMT', limit_price=1.0)
res = trade_client.place_order(order)
print(res)

Placing Fund Orders

from tigeropen.common.util.contract_utils import fund_contract
from tigeropen.common.util.order_utils import market_order_by_amount
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)

# Generate fund contract
contract = fund_contract(symbol='000001', currency='USD')
# Generate order object
order = market_order_by_amount(account=client_config.account, contract=contract, action='BUY', amount=100.0)
# Place order
oid = trade_client.place_order(order)

Query Contract and Place Order

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)

# Get stock contract (not recommended)
contract = trade_client.get_contract('AAPL', sec_type=SecurityType.STK)
# Get order object (not recommended)
order = trade_client.create_order(account=client_config.account, contract=contract, action='SELL', order_type='LMT', quantity=1, limit_price=200.0)
# Place order
oid = trade_client.place_order(order)

Setting Order Attributes

Examples of using uncommon order attributes, such as user_mark

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.consts import TradingSessionType
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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=0.1, quantity=1)
# Set custom order remark (Global accounts need to contact the platform in advance to enable this feature)
order.user_mark = 'my-custom-remark'

# Set order validity to GTC
# order.time_in_force = 'GTC' 

# Extended hours trading
# order.trading_session_type = TradingSessionType.OVERNIGHT

# Full session trading
# order.trading_session_type = TradingSessionType.FULL

# Set order to GTD (good till date, valid until specified date)
#order.time_in_force = 'GTD'
#order.expire_time = 1700496000000 # Must specify expiration time
# If using time string
#from tigeropen.common.util.common_utils import date_str_to_timestamp
#order.expire_time = date_str_to_timestamp('2023-07-01 11:00:00', 'US/Eastern')

# Place order
trade_client.place_order(order)
my_order = trade_client.get_order(id=order.id)
print(my_order.user_mark)

Price Adjustment for Orders

Use contract information and PriceUtil to adjust order prices. When contracts are at different price levels, they have different precision requirements. When an inappropriate precision price is specified as the order price, it will return an error. Here we use the queried contract tick specification data and tools to correct the price.

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.price_util import PriceUtil
from tigeropen.common.consts import SecurityType
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)

# Get stock contract
contract = trade_client.get_contract(symbol='AAPL', sec_type=SecurityType.STK)
limit_price = 150.173

# Check if price matches contract tick specifications
is_price_ok = PriceUtil.match_tick_size(price, contract.tick_sizes)

# Adjust price (if is_up parameter is set to True, price adjusts upward. Default False, price adjusts downward)
# If contract price is between 1~1000 with tick size of 0.01, then 150.173 adjusts to 150.17; upward adjustment would be 150.18
limit_price = PriceUtil.fix_price_by_tick_size(price, contract.tick_sizes)

# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=limit_price, quantity=1)

# Place order
trade_client.place_order(order)

Placing Fractional Share Orders

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)

# Generate stock contract
contract = stock_contract(symbol='AAPL', currency='USD')
# Generate order object
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=170, quantity=5)
# quantity_scale set to 1, actual order quantity is 5 * 10^-1 = 0.5 shares; if quantity_scale is set to 2, actual order quantity is 5 * 10^-2 = 0.05 shares
order.quantity_scale = 1

# Place order
oid = trade_client.place_order(order)

print(order)

create_order Request to Create Order

TradeClient.create_order():

Description

Request order ID and create order object (not recommended). It's recommended to use utility functions under tigeropen.common.util.order_utils to create orders locally, such as limit_order, market_order.

Parameters

ParameterTypeDescriptionMarket OrderLimit OrderStop OrderStop Limit OrderTrailing Stop OrderAuction Limit OrderAuction Market Order
accountstrAccount ID, if not provided, returns all associated accountsOptionalOptionalOptionalOptionalOptionalOptionalOptional
contractContractContract objectRequiredRequiredRequiredRequiredRequiredRequiredRequired
actionstrBuy/Sell direction, 'BUY': Buy, 'SELL': SellRequiredRequiredRequiredRequiredRequiredRequiredRequired
order_typestrOrder type, 'MKT' Market / 'LMT' Limit / 'STP' Stop / 'STP_LMT' Stop Limit / 'TRAIL' Trailing StopMKTLMTSTPSTP_LMTTRAILALAM
quantityintOrder quantity, must be positive integerRequiredRequiredRequiredRequiredRequiredRequiredRequired
limit_pricefloatLimit order price, required when order type is LMT or STP_LMT or ALRequiredRequiredRequired
aux_pricefloatFor stop orders: stop price; For trailing stop orders: trail amountN/AN/ARequiredRequiredOptionalOptionalOptional
trail_stop_pricefloatTrailing stop order--price that triggers the stop orderN/AN/AN/AN/AN/AN/AN/A
trailing_percentfloatTrailing stop order--percentage (at least one of aux_price and trailing_percent must be filled)N/AN/AN/AN/AOptionalN/AN/A
adjust_limitfloatPrice adjustment range (default 0 means no adjustment, positive for upward, negative for downward), automatically adjusts input price to legal price levels. E.g., 0.001 means upward adjustment within 0.1%; -0.001 means downward adjustment within 0.1%. Default 0 means no adjustmentN/AOptionalOptionalOptionalOptionalN/AN/A
time_in_forcestrOrder validity period, can only be DAY (day order) or GTC (good till canceled), default is DAYOptionalOptionalOptionalOptionalOptionalOptional (HK auction orders need OPG for pre-market, DAY for post-market)Optional (HK auction orders need OPG for pre-market, DAY for post-market)
outside_rthboolTrue: Allow pre/post market trading (US stocks only), False: Don't allow, default True. (Market orders only valid during market hours, will ignore outside_rth parameter)N/AOptionalOptionalN/AOptionalRequired (Fixed as True)Required (Fixed as True)
order_legsobjectAttached order list, see examples aboveOptionalOptionalOptionalOptionalOptionalN/AN/A
algo_paramsobjectAlgorithmic order parameters, see examples aboveOptionalOptionalOptionalOptionalOptionalN/AN/A
secret_keystrFor institutional users only, trader keyOptionalOptionalOptionalOptionalOptionalOptionalOptional
user_markstrOrder remark information, cannot be modified after placing order, returns userMark info when querying orders (Global accounts need to configure developer personal information)OptionalOptionalOptionalOptionalOptionalOptionalOptional

Example

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)

place_forex_order Currency Exchange Order

TradeClient.place_forex_order(seg_type, source_currency, target_currency, source_amount)

Description

Currency exchange order, returns Order object

Parameters

ParameterTypeDescription
seg_typeSegmentTypeAccount segment. Available: SegmentType.SEC for securities; SegmentType.FUT for commodities, can be imported from tigeropen.common.consts.SegmentType
source_currencyCurrencyCurrency to be converted
target_currencyCurrencyCurrency to receive after conversion
source_amountFloatAmount of source currency to be converted

Example

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)

Return Example

Order({'account': '11111', 'id': 30323340487950336, 'order_id': 1447, 'parent_id': None, 'order_time': 1680247928000, 'reason': '', 'trade_time': 1680247928000, 'action': 'SELL', 'quantity': 50, 'filled': 0, 'avg_fill_price': 0.0, 'commission': 0.0, 'realized_pnl': 0.0, 'trail_stop_price': None, 'limit_price': 7.74991, 'aux_price': None, 'trailing_percent': None, 'percent_offset': None, 'order_type': 'LMT', 'time_in_force': 'DAY', 'outside_rth': False, 'order_legs': None, 'algo_params': None, 'algo_strategy': 'LMT', 'secret_key': None, 'liquidation': False, 'discount': 0.0, 'attr_desc': None, 'source': 'OpenApi', 'adjust_limit': None, 'sub_ids': None, 'user_mark': '', 'update_time': 1680247928000, 'expire_time': None, 'can_modify': True, 'contract': USD.HKD/FOREX/HKD, 'status': 'NEW', 'remaining': 50})