Trading

The TypeScript SDK provides a TradeClient that wraps all order-management and account endpoints. Every method returns a typed domain object. v0.4.0 changed 8 query methods (getOrders / getActiveOrders / getInactiveOrders / getFilledOrders / getOrderTransactions / getPositions / getAssets / getPrimeAssets) to Request-object signatures (breaking; all fields optional, account defaults to config account when omitted) and added 13 new methods covering account management, asset analytics, fund transfer, forex orders, etc. Request parameters are camelCase in TypeScript and are transparently converted to snake_case on the wire.

Quick Start

import {
  createClientConfig,
  HttpClient,
  TradeClient,
  limitOrder,
} from '@tigeropenapi/tigeropen';

const config = createClientConfig();
const tc = new TradeClient(new HttpClient(config), config.account);

// Query positions (v0.4.0: accepts optional Request object for filtering)
const positions = await tc.getPositions();

// Build a limit buy
const orderReq = limitOrder(config.account, 'AAPL', 'STK', 'BUY', 10, 150.0);
orderReq.market = 'US';
orderReq.currency = 'USD';
orderReq.timeInForce = 'DAY';

// Preview without placing
const preview = await tc.previewOrder(orderReq);

// Place the order
const placed = await tc.placeOrder(orderReq);
console.log('Order id:', placed?.id);

Order vs OrderRequest — query methods return Order (richer); placeOrder / previewOrder / modifyOrder accept OrderRequest. Use helper factories (marketOrder, limitOrder, stopOrder, stopLimitOrder, trailOrder) to build requests.


OrderStatus (aligned with Java SDK in v0.4.0)

v0.4.0 aligned the OrderStatus enum with the Java SDK. There are now 8 values, and the client automatically converts server-side integer codes to the string form during deserialization:

ConstantStringCode
OrderStatus.Invalid'Invalid'-2
OrderStatus.Initial'Initial'-1
OrderStatus.PendingCancel'PendingCancel'3
OrderStatus.Cancelled'Cancelled'4
OrderStatus.Submitted'Submitted'5
OrderStatus.Filled'Filled'6
OrderStatus.Inactive'Inactive'7
OrderStatus.PendingSubmit'PendingSubmit'8

Breaking: PendingNew / PartiallyFilled (Python-only derivations never returned by the server) were removed; PendingSubmit was added.

Get the numeric code with orderStatusCode(status):

import { OrderStatus, orderStatusCode } from '@tigeropenapi/tigeropen';

orderStatusCode(OrderStatus.Filled);      // 6
orderStatusCode('PendingSubmit');         // 8

Order.status values from the server are auto-normalized to the string forms above, so OrdersRequest.states filters use the string array (e.g. ['Filled', 'Submitted']).


Contract Query

getContract

tc.getContract(symbol: string, secType: string): Promise<Contract[]>

Description

Returns detailed contract information for a single symbol.

Parameters

NameTypeRequiredDescription
symbolstringYesContract symbol, e.g. 'AAPL'
secTypestringYes'STK' / 'OPT' / 'FUT' / 'WAR' / 'IOPT'

Returns

Promise<Contract[]>symbol, secType, currency, exchange, primaryExchange, localSymbol, name, market, lotSize, contractId, isEtf, marginable, shortable, tickSizes, etc.

Example

const contracts = await tc.getContract('AAPL', 'STK');

getContracts

tc.getContracts(symbols: string[], secType: string): Promise<Contract[]>

Description

Batch contract lookup.

Parameters

NameTypeRequiredDescription
symbolsstring[]YesSymbols
secTypestringYesSecurity type

Returns

Promise<Contract[]> (same shape as getContract).

Example

const contracts = await tc.getContracts(['AAPL', 'TSLA', 'MSFT'], 'STK');

getQuoteContract

tc.getQuoteContract(symbol: string, secType: string, expiry: string): Promise<Contract[]>

Description

Derivative contract lookup (options / warrants / inline warrants). Only 'OPT' / 'WAR' / 'IOPT'.

Parameters

NameTypeRequiredDescription
symbolstringYesUnderlying symbol
secTypestringYes'OPT' / 'WAR' / 'IOPT'
expirystringYes'YYYYMMDD'

Returns

Promise<Contract[]>.

Example

const cs = await tc.getQuoteContract('AAPL', 'OPT', '20260619');

Order Operations

OrderRequest Fields

Fields accepted by placeOrder / previewOrder / modifyOrder. Use helper factories to build the base and then set additional fields.

FieldTypeDescription
accountstringAccount ID (helpers fill this)
idnumberGlobal order ID (required for modify)
orderIdnumberAccount-level order ID
symbolstringContract symbol
secTypestring'STK' / 'OPT' / 'FUT' / 'WAR' / 'IOPT'
actionstring'BUY' / 'SELL'
orderTypestring'MKT' / 'LMT' / 'STP' / 'STP_LMT' / 'TRAIL' / 'AM' / 'AL' / 'TWAP' / 'VWAP' / 'OCA'
totalQuantitynumberQuantity
limitPricenumberLimit price (required for LMT / STP_LMT)
auxPricenumberStop/trigger price
trailingPercentnumberTrailing stop percent
timeInForcestring'DAY' / 'GTC' / 'GTD' / 'OPG'
outsideRthbooleanAllow extended hours
market / currencystringMarket / currency
expiry / strike / rightstringOption specifics
orderLegsOrderLegRequest[]Attached P/L legs
algoParamsAlgoParamsRequestAlgo parameters

Helper factories

import { marketOrder, limitOrder, stopOrder, stopLimitOrder, trailOrder } from '@tigeropenapi/tigeropen';

const o1 = marketOrder(account, symbol, secType, action, qty);
const o2 = limitOrder(account, symbol, secType, action, qty, price);
const o3 = stopOrder(account, symbol, secType, action, qty, auxPrice);
const o4 = stopLimitOrder(account, symbol, secType, action, qty, limit, aux);
const o5 = trailOrder(account, symbol, secType, action, qty, trailPct);

placeOrder

tc.placeOrder(order: OrderRequest): Promise<PlaceOrderResult | undefined>

Description

Submit an order to the exchange.

Returns

Promise<PlaceOrderResult | undefined>id (global), order_id (account-level, snake_case from server), subIds, orders: Order[].

Example

const order = limitOrder(config.account, 'AAPL', 'STK', 'BUY', 10, 150.0);
order.market = 'US';
order.currency = 'USD';

const placed = await tc.placeOrder(order);
console.log('id:', placed?.id, 'order_id:', (placed as any)?.order_id);

previewOrder

tc.previewOrder(order: OrderRequest): Promise<PreviewResult | undefined>

Description

Estimate commission and margin impact without submitting.

Returns

Promise<PreviewResult | undefined>isPass, commission, commissionCurrency, marginCurrency, initMargin/initMarginBefore, maintMargin/maintMarginBefore, equityWithLoan/equityWithLoanBefore, availableEE, excessLiquidity, overnightLiquidation, message.

Example

const preview = await tc.previewOrder(order);
console.log('isPass:', preview?.isPass, 'commission:', preview?.commission);

modifyOrder

tc.modifyOrder(id: number, order: OrderRequest): Promise<OrderIdResult | undefined>

Description

Modify an open order.

Parameters

NameTypeRequiredDescription
idnumberYesGlobal order ID
orderOrderRequestYesUpdated fields

Returns

Promise<OrderIdResult | undefined>.

Example

const updated = { ...order, limitPrice: 148.0 };
const mod = await tc.modifyOrder(12345, updated);

cancelOrder

tc.cancelOrder(id: number): Promise<OrderIdResult | undefined>

Description

Cancel an open order.

Parameters

NameTypeRequiredDescription
idnumberYesGlobal order ID

Returns

Promise<OrderIdResult | undefined>.

Example

const canc = await tc.cancelOrder(12345);

Order Query

OrdersRequest

Shared query parameters for getOrders / getActiveOrders / getInactiveOrders / getFilledOrders. All fields are optional (account defaults to the configured account). New in v0.4.0.

NameTypeDescription
accountstringAccount ID
secTypestring'STK' / 'OPT' / 'FUT' / 'CASH'
marketstringMarket
symbolstringContract code
startDatenumberStart (ms; wire: start_date)
endDatenumberEnd (ms; wire: end_date)
limitnumberRow limit
isBriefbooleanReturn brief fields only
statesstring[]Status filter (see OrderStatus above)
sortBystring'LATEST_CREATED' / 'LATEST_STATUS_UPDATED'
segTypestringSegment ('S' securities / 'C' futures)
langstringLanguage
pageTokenstringPage token
parentIdnumberParent order ID (only getActiveOrders)

getOrders

tc.getOrders(req?: OrdersRequest): Promise<Order[]>

v0.4.0 Breaking: changed from no-arg to optional OrdersRequest.

Description

Query all historical orders.

Parameters

See OrdersRequest above.

Returns

Promise<Order[]>id, orderId, symbol, secType, action, orderType, status, totalQuantity, filledQuantity, limitPrice, avgFillPrice, timeInForce, outsideRth, openTime, updateTime, canModify, canCancel, isOpen, etc.

Example

const orders = await tc.getOrders();

const filtered = await tc.getOrders({
  market: 'US',
  secType: 'STK',
  states: ['Filled'],
  limit: 100,
  sortBy: 'LATEST_CREATED',
});

getOrder (new in v0.4.0)

tc.getOrder(req: GetOrderRequest): Promise<Order | undefined>

Description

Fetch a single order by ID. Pass either id (global) or orderId (account-level). Wire method orders (server returns a single object).

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
idnumberOne ofGlobal order ID
orderIdnumberOne ofAccount-level order ID
isBriefbooleanNoBrief fields only
showChargesbooleanNoInclude charges
langstringNoLanguage

Returns

Promise<Order | undefined> (same fields as getOrders).

Example

const o = await tc.getOrder({ id: 123456789 });
console.log(`${o?.id} ${o?.symbol} status=${o?.status} filled=${o?.filledQuantity}/${o?.totalQuantity}`);

getActiveOrders

tc.getActiveOrders(req?: OrdersRequest): Promise<Order[]>

v0.4.0 Breaking: changed from no-arg to optional OrdersRequest (adds parentId filter).

Description

List currently open orders (not fully filled or cancelled).

Parameters

See OrdersRequest.

Returns

Promise<Order[]>.

Example

const active = await tc.getActiveOrders();
const legs = await tc.getActiveOrders({ parentId: 12345678 });

getInactiveOrders

tc.getInactiveOrders(req?: OrdersRequest): Promise<Order[]>

v0.4.0 Breaking: changed from no-arg to optional OrdersRequest.

Description

List cancelled or expired orders.

Parameters

See OrdersRequest.

Returns

Promise<Order[]>.

Example

const inactive = await tc.getInactiveOrders();
const cancelled = await tc.getInactiveOrders({
  states: ['Cancelled'],
  limit: 50,
});

getFilledOrders

tc.getFilledOrders(req?: OrdersRequest): Promise<Order[]>

v0.4.0 Breaking: changed from positional (startDateMs, endDateMs) to OrdersRequest; pass the time range via startDate / endDate (ms).

Description

List filled orders.

Parameters

See OrdersRequest. startDate / endDate are ms timestamps.

Returns

Promise<Order[]>.

Example

const filled = await tc.getFilledOrders();

const now = Date.now();
const recent = await tc.getFilledOrders({
  startDate: now - 30 * 24 * 3600 * 1000,
  endDate: now,
  limit: 200,
});

getOrderTransactions

tc.getOrderTransactions(req: OrderTransactionsRequest): Promise<Transaction[]>

v0.4.0 Breaking: changed from (orderId, symbol, secType) positional to OrderTransactionsRequest; all fields are now optional. You can query by a specific order or batch-filter by time window and symbol.

Description

Individual fill records for orders.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
orderIdnumberNoOrder ID (when querying fills of a specific order)
symbolstringNoContract code
secTypestringNoSecurity type
startDatenumberNoStart (ms)
endDatenumberNoEnd (ms)
limitnumberNoRow limit
expiry / strike / putCall-NoOption specifics
pageTokenstringNoPage token
langstringNoLanguage

Returns

Promise<Transaction[]>id, orderId, account, symbol, secType, market, currency, action, price, quantity, amount, commission, transactedAt, etc.

Example

// Fills for a specific order
const txs = await tc.getOrderTransactions({
  orderId: 123456789,
  symbol: 'AAPL',
  secType: 'STK',
});

// All fills for a symbol within a time window
const now = Date.now();
const batch = await tc.getOrderTransactions({
  symbol: 'AAPL',
  secType: 'STK',
  startDate: now - 7 * 24 * 3600 * 1000,
  endDate: now,
  limit: 100,
});

Positions & Assets

getPositions

tc.getPositions(req?: PositionsRequest): Promise<Position[]>

v0.4.0 Breaking: changed from no-arg to optional PositionsRequest with symbol / secType / currency / market / subAccounts filters.

Description

List current open positions.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
symbolstringNoContract code
secTypestringNo'STK' / 'OPT' / 'FUT' / 'CASH'
currencystringNoCurrency
marketstringNoMarket
subAccountsstring[]NoSub-account list
expiry / strike / rightstringNoOption specifics
assetQuoteTypestringNoQuote type
langstringNoLanguage

Returns

Promise<Position[]>symbol, secType, market, currency, position, positionQty, salableQty, averageCost, marketValue, realizedPnl, unrealizedPnl, todayPnl, latestPrice, lastClosePrice, identifier, name, multiplier.

Example

const ps = await tc.getPositions();
const us = await tc.getPositions({ market: 'US', secType: 'STK' });

getAssets

tc.getAssets(req?: AssetsRequest): Promise<Asset[]>

v0.4.0 Breaking: changed from no-arg to optional AssetsRequest.

Description

Account asset summary (with per-segment breakdown).

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segmentbooleanNoReturn per-segment data
marketValuebooleanNoReturn market value
subAccountsstring[]NoSub-account list
langstringNoLanguage

Returns

Promise<Asset[]>account, capability, currency, buyingPower, cashValue, netLiquidation, realizedPnL, unrealizedPnL, segments: AssetSegment[] (each with category, title, netLiquidation, cashValue, availableFunds, equityWithLoan, excessLiquidity, initMarginReq, maintMarginReq, grossPositionValue, leverage).

Example

const assets = await tc.getAssets();
const detailed = await tc.getAssets({ segment: true, marketValue: true });

getPrimeAssets

tc.getPrimeAssets(req?: AssetsRequest): Promise<PrimeAsset | undefined>

v0.4.0 Breaking: changed from no-arg to optional AssetsRequest (shared with getAssets).

Description

Prime (consolidated) account asset summary.

Parameters

See getAssets for AssetsRequest.

Returns

Promise<PrimeAsset | undefined>accountId, updateTimestamp, segments: PrimeAssetSegment[] (each with capability, category, currency, cashBalance, cashAvailableForTrade, grossPositionValue, equityWithLoan, netLiquidation, initMargin, maintainMargin, overnightMargin, buyingPower, unrealizedPL, realizedPL, currencyAssets).

Example

const pa = await tc.getPrimeAssets();
console.log(`account=${pa?.accountId} segments=${pa?.segments.length}`);

Account Management (new in v0.4.0)

getManagedAccounts

tc.getManagedAccounts(req?: ManagedAccountsRequest): Promise<ManagedAccount[]>

Description

List institutional sub-accounts managed by the current main account. Wire method accounts.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
langstringNoLanguage

Returns

Promise<ManagedAccount[]> (account / accountType / capability / status).

Example

const subs = await tc.getManagedAccounts();

getDerivativeContracts

tc.getDerivativeContracts(req: DerivativeContractsRequest): Promise<Contract[]>

Description

Batch lookup of derivative contracts by symbols + type (options / warrants / inline warrants). Same wire as getQuoteContract (quote_contract) but accepts a structured request.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
symbolsstring[]YesUnderlying symbols
secTypestringYes'OPT' / 'WAR' / 'IOPT'
expirystringNoExpiry ('YYYYMMDD')
langstringNoLanguage

Returns

Promise<Contract[]> (same fields as getContract).

Example

const cs = await tc.getDerivativeContracts({
  symbols: ['AAPL', 'TSLA'],
  secType: 'OPT',
  expiry: '20260619',
});

Asset Analytics (new in v0.4.0)

getAnalyticsAsset

tc.getAnalyticsAsset(req: AnalyticsAssetRequest): Promise<AnalyticsAsset[]>

Description

Daily analytics: holding value, cash balance, P&L, net-value index. Wire method analytics_asset.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segTypestringNoSegment
startDatestringNoStart ('yyyy-MM-dd')
endDatestringNoEnd ('yyyy-MM-dd')
langstringNoLanguage

Returns

Promise<AnalyticsAsset[]> (date / holdingValue / cashBalance / pnl / pnlRate / netValueIndex / currency / segType).

Example

const rows = await tc.getAnalyticsAsset({
  startDate: '2025-01-01',
  endDate: '2025-12-31',
});

getAggregateAssets

tc.getAggregateAssets(req?: AggregateAssetsRequest): Promise<AggregateAssets | undefined>

Description

Aggregate prime-account assets in a chosen baseCurrency (with per-currency detail). Wire method aggregate_assets.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segTypestringNoSegment
baseCurrencystringNoBase currency
langstringNoLanguage

Returns

Promise<AggregateAssets | undefined> (accountId / netLiquidation / grossPositionValue / cashBalance / baseCurrency / currencyAssets: CurrencyAsset[]).

Example

const agg = await tc.getAggregateAssets({ baseCurrency: 'USD' });

getEstimateTradableQuantity

tc.getEstimateTradableQuantity(req: EstimateTradableQuantityRequest): Promise<EstimateTradableQuantity | undefined>

Description

Estimate the maximum order quantity given the account's funds, margin, and current price. Wire method estimate_tradable_quantity.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
symbolstringYesContract code
secTypestringYesSecurity type
actionstringYes'BUY' / 'SELL'
orderTypestringNo'MKT' / 'LMT' / 'STP' / 'STP_LMT'
limitPricenumberCond.Required for LMT / STP_LMT
market / currencystringNoMarket / currency
expiry / strike / rightstringNoOption specifics
langstringNoLanguage

Returns

Promise<EstimateTradableQuantity | undefined> (tradableQuantity / maxCashBuyQuantity / maxMarginBuyQuantity / maxShortSellQuantity / maxPositionSellQty / cashBuyingPower / currency).

Example

const est = await tc.getEstimateTradableQuantity({
  symbol: 'AAPL',
  secType: 'STK',
  action: 'BUY',
  orderType: 'LMT',
  limitPrice: 150.0,
});

Fund Details & Transfers (new in v0.4.0)

getFundDetails

tc.getFundDetails(req: FundDetailsRequest): Promise<FundDetails[]>

Description

Fund-movement ledger (deposits / withdrawals / fees / interest / dividends). Wire method fund_details.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segTypesstring[]NoSegment list
fundTypestringNoFund type
currencystringNoCurrency
startDatenumberNoStart (ms)
endDatenumberNoEnd (ms)
limitnumberNoRow limit
pageTokenstringNoPage token
langstringNoLanguage

Returns

Promise<FundDetails[]> (id / account / segType / fundType / currency / amount / balance / occurTime / remark / externalId).

Example

const now = Date.now();
const rows = await tc.getFundDetails({
  startDate: now - 30 * 24 * 3600 * 1000,
  endDate: now,
  currency: 'USD',
  limit: 100,
});

getFundingHistory

tc.getFundingHistory(req: FundingHistoryRequest): Promise<FundingHistoryItem[]>

Description

Deposit / withdrawal history. Wire method transfer_fund.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segTypestringNoSegment
currencystringNoCurrency
startDatenumberNoStart (ms)
endDatenumberNoEnd (ms)
limitnumberNoRow limit
langstringNoLanguage

Returns

Promise<FundingHistoryItem[]> (id / segType / currency / status / amount / submitTime / updateTime).

Example

const rows = await tc.getFundingHistory({});

placeForexOrder

tc.placeForexOrder(req: ForexOrderRequest): Promise<ForexOrderResult | undefined>

Description

Submit a forex conversion order. Wire method place_forex_order.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segTypestringNoSegment
sourceCurrencystringYesSource currency
targetCurrencystringYesTarget currency
sourceAmountnumberNoSource amount
targetAmountnumberNoTarget amount
orderTypestringNoOrder type
langstringNoLanguage

Returns

Promise<ForexOrderResult | undefined> (id / status / sourceCurrency / targetCurrency / sourceAmount / targetAmount / rate / submitTime).

Example

const res = await tc.placeForexOrder({
  sourceCurrency: 'USD',
  sourceAmount: 10000,
  targetCurrency: 'HKD',
});

getSegmentFundAvailable

tc.getSegmentFundAvailable(req: SegmentFundRequest): Promise<SegmentFund[]>

Description

Query the amount available for inter-segment transfer. Wire method segment_fund_available.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
fromSegmentstringNoSource segment
toSegmentstringNoTarget segment
currencystringNoCurrency
langstringNoLanguage

Returns

Promise<SegmentFund[]> (fromSegment / toSegment / currency / availableAmt).

Example

const avail = await tc.getSegmentFundAvailable({
  fromSegment: 'S',
  toSegment: 'C',
  currency: 'USD',
});

getSegmentFundHistory

tc.getSegmentFundHistory(req: SegmentFundRequest): Promise<SegmentFundHistoryItem[]>

Description

Inter-segment transfer history. Wire method segment_fund_history.

Parameters

Same as SegmentFundRequest (typically filter with limit).

Returns

Promise<SegmentFundHistoryItem[]> (id / fromSegment / toSegment / currency / amount / status / submitTime / updateTime).

Example

const history = await tc.getSegmentFundHistory({ limit: 50 });

transferSegmentFund

tc.transferSegmentFund(req: SegmentFundRequest): Promise<SegmentFund | undefined>

Description

Submit an inter-segment fund transfer. Wire method transfer_segment_fund.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
fromSegmentstringYesSource segment
toSegmentstringYesTarget segment
currencystringYesCurrency
amountnumberYesAmount
langstringNoLanguage

Returns

Promise<SegmentFund | undefined> (with id / status / submitTime).

Example

const res = await tc.transferSegmentFund({
  fromSegment: 'S',
  toSegment: 'C',
  currency: 'USD',
  amount: 1000,
});

cancelSegmentFund

tc.cancelSegmentFund(req: SegmentFundRequest): Promise<SegmentFund | undefined>

Description

Cancel a pending inter-segment transfer. Wire method cancel_segment_fund.

Parameters

NameTypeRequiredDescription
idstringYesTransfer ID (from transferSegmentFund)
accountstringNoAccount ID
langstringNoLanguage

Returns

Promise<SegmentFund | undefined>.

Example

const res = await tc.cancelSegmentFund({ id: 'TX123456' });

Generic Raw API Call

When the SDK has not yet wrapped a specific API endpoint, use the HttpClient directly:

import {
  createClientConfig,
  HttpClient,
  createApiRequest,
} from '@tigeropenapi/tigeropen';

const config = createClientConfig();
const httpClient = new HttpClient(config);

const request = createApiRequest('market_state', { market: 'US' });
const resp = await httpClient.executeRequest(request);
console.log('Raw response:', resp.data);