Trading

The Go SDK exposes all trading endpoints through TradeClient. Every method returns a strongly-typed struct from the model package. Place / modify / preview use the request struct model.OrderRequest (snake_case json tags that match the server); starting with v0.3.0, all read methods accept a matching Request struct (every field optional; leaving Account empty auto-fills the default account).

A complete runnable example:

package main

import (
	"fmt"
	"log"

	"github.com/tigerfintech/openapi-go-sdk/client"
	"github.com/tigerfintech/openapi-go-sdk/config"
	"github.com/tigerfintech/openapi-go-sdk/model"
	"github.com/tigerfintech/openapi-go-sdk/trade"
)

func main() {
	cfg, err := config.NewClientConfig()
	if err != nil {
		log.Fatal(err)
	}

	tc := trade.NewTradeClient(client.NewHttpClient(cfg), cfg.Account)

	// Positions
	positions, err := tc.Positions(model.PositionsRequest{})
	if err != nil {
		log.Fatal(err)
	}
	for _, p := range positions {
		fmt.Printf("%s qty=%.2f avgCost=%.2f marketValue=%.2f\n",
			p.Symbol, p.PositionQty, p.AverageCost, p.MarketValue)
	}

	// Build and preview a limit order
	order := model.LimitOrder(cfg.Account, "AAPL", "STK", "BUY", 10, 150.0)
	preview, err := tc.PreviewOrder(order)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("isPass=%v commission=%.2f initMargin=%.2f\n",
		preview.IsPass, preview.Commission, preview.InitMargin)

	// Place the order
	placed, err := tc.PlaceOrder(order)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("order id=%d orderId=%d\n", placed.ID, placed.OrderID)
}

Contract queries

Contract — single contract

tc.Contract(symbol, secType string) ([]model.Contract, error)

Description

Fetch details of a single contract.

Parameters

NameTypeRequiredDescription
symbolstringYesContract code, e.g. "AAPL", "00700"
secTypestringYesSTK / OPT / FUT / WAR / IOPT

Returns

[]model.Contract (common fields below)

FieldTypeDescription
ContractIdint64Contract ID
Symbol / Identifier / NamestringCode / identifier / name
SecType / Market / CurrencystringType / market / currency
PrimaryExchange / ExchangestringPrimary / exchange
Multiplier / LotSizefloat64Contract multiplier / lot size
Tradeable / Marginable / ShortableboolTradable / marginable / shortable
Expiry / Strike / RightstringOption expiry / strike / Call/Put
TickSizes[]TickSizeTick size tiers

Example

cs, err := tc.Contract("AAPL", "STK")
if err != nil {
    log.Fatal(err)
}
if len(cs) > 0 {
    fmt.Printf("%s contractId=%d exchange=%s\n", cs[0].Symbol, cs[0].ContractId, cs[0].PrimaryExchange)
}

Contracts — batch contracts

tc.Contracts(symbols []string, secType string) ([]model.Contract, error)

Description

Batch fetch multiple contracts.

Parameters

NameTypeRequiredDescription
symbols[]stringYesCode list
secTypestringYesContract type

Returns

[]model.Contract (same as Contract)

Example

cs, err := tc.Contracts([]string{"AAPL", "TSLA", "MSFT"}, "STK")

QuoteContract — derivative contracts

tc.QuoteContract(symbol, secType, expiry string) ([]model.Contract, error)

Description

Fetch derivative contracts (options / warrants / callable bull bear). Supports OPT / WAR / IOPT only.

Parameters

NameTypeRequiredDescription
symbolstringYesUnderlying code (e.g. "AAPL", not an option identifier)
secTypestringYesOPT / WAR / IOPT
expirystringYesExpiry date, YYYYMMDD, e.g. "20260619"

Returns

[]model.Contract

Example

cs, err := tc.QuoteContract("AAPL", "OPT", "20260619")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("options=%d\n", len(cs))

Order operations

OrderRequest — order request struct

model.OrderRequest is the request object used by place / preview / modify. Fields have snake_case json tags aligned with the server:

FieldTypeDescription
AccountstringAccount ID (auto-filled by the client)
SymbolstringContract code
SecTypestringSTK / OPT / FUT
ActionstringBUY / SELL
OrderTypestringMKT / LMT / STP / STP_LMT / TRAIL, etc.
TotalQuantityint64Quantity
LimitPricefloat64Limit price (required for LMT / STP_LMT)
AuxPricefloat64Stop / trigger price (required for STP / STP_LMT / TRAIL)
TrailingPercentfloat64Trailing stop percent
TimeInForcestringDAY / GTC / GTD
OutsideRthboolAllow extended hours
Market / CurrencystringMarket / currency
Expiry / Strike / RightstringOption expiry / strike / CALL / PUT
OrderLegs[]OrderLegRequestAttached profit / loss legs
AlgoParams*AlgoParamsRequestAlgo parameters (TWAP / VWAP, etc.)

Convenience constructors

order := model.MarketOrder(account, symbol, secType, action, qty)
order := model.LimitOrder(account, symbol, secType, action, qty, price)
order := model.StopOrder(account, symbol, secType, action, qty, auxPrice)
order := model.StopLimitOrder(account, symbol, secType, action, qty, limit, aux)
order := model.TrailOrder(account, symbol, secType, action, qty, trailPct)

PlaceOrder — place an order

tc.PlaceOrder(order model.OrderRequest) (*model.PlaceOrderResult, error)

Description

Submit an order to the exchange.

Returns

*model.PlaceOrderResult

FieldTypeDescription
IDint64Global order ID (use for Modify / Cancel)
OrderIDint64Account-level order number
SubIDs[]int64Sub-order IDs
Orders[]OrderOrder snapshots

Example

order := model.LimitOrder(cfg.Account, "AAPL", "STK", "BUY", 10, 150.0)
order.Market = "US"
order.Currency = "USD"

placed, err := tc.PlaceOrder(order)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("id=%d orderId=%d\n", placed.ID, placed.OrderID)

PreviewOrder — preview an order

tc.PreviewOrder(order model.OrderRequest) (*model.PreviewResult, error)

Description

Estimate commission and margin impact without actually submitting.

Returns

*model.PreviewResult

FieldTypeDescription
IsPassboolPassed validation
Commissionfloat64Estimated commission
CommissionCurrencystringCommission currency
MarginCurrencystringMargin currency
InitMargin / InitMarginBeforefloat64Initial margin after / before
MaintMargin / MaintMarginBeforefloat64Maintenance margin after / before
EquityWithLoan / EquityWithLoanBeforefloat64Equity after / before
AvailableEEfloat64Available EE
ExcessLiquidityfloat64Excess liquidity
OvernightLiquidationfloat64Overnight liquidation
MessagestringError message when IsPass is false

Example

preview, err := tc.PreviewOrder(order)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("isPass=%v commission=%.2f initMargin=%.2f\n",
    preview.IsPass, preview.Commission, preview.InitMargin)

ModifyOrder — modify an order

tc.ModifyOrder(id int64, order model.OrderRequest) (*model.OrderIDResult, error)

Description

Modify an open order.

Parameters

NameTypeRequiredDescription
idint64YesGlobal order ID (from PlaceOrderResult.ID)
ordermodel.OrderRequestYesOrder object with new parameters

Returns

*model.OrderIDResult (contains ID)

Example

modifyReq := order
modifyReq.LimitPrice = 148.0
mod, err := tc.ModifyOrder(placed.ID, modifyReq)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("modified id=%d\n", mod.ID)

CancelOrder — cancel an order

tc.CancelOrder(id int64) (*model.OrderIDResult, error)

Description

Cancel an open order.

Parameters

NameTypeRequiredDescription
idint64YesGlobal order ID

Returns

*model.OrderIDResult

Example

canc, err := tc.CancelOrder(placed.ID)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("cancelled id=%d\n", canc.ID)

Order queries

Order status enum (v0.3.0, aligned with the Java SDK)

The model package provides an OrderStatus type and 8 constants; call OrderStatus.Code() to get the server-side numeric code. Order.Status is a string — when the server returns an integer it is automatically mapped to the string below during unmarshalling.

ConstantStringCode
OrderStatusInvalid"Invalid"-2
OrderStatusInitial"Initial"-1
OrderStatusPendingCancel"PendingCancel"3
OrderStatusCancelled"Cancelled"4
OrderStatusSubmitted"Submitted"5
OrderStatusFilled"Filled"6
OrderStatusInactive"Inactive"7
OrderStatusPendingSubmit"PendingSubmit"8

Use these string values in OrdersRequest.States (e.g. []string{"Filled", "Submitted"}).


OrdersRequest — orders query request struct

model.OrdersRequest is shared by Orders / ActiveOrders / InactiveOrders / FilledOrders. Every field is optional (leave Account empty to auto-fill the default account).

NameTypeDescription
accountstringAccount ID
sec_typestringSTK / OPT / FUT / CASH, etc.
marketstringMarket, e.g. US / HK
symbolstringContract code
start_dateint64Start time (ms timestamp)
end_dateint64End time (ms timestamp)
limitintMax rows returned
is_briefboolReturn brief fields only
states[]stringOrder status filter; see the enum above
sort_bystringLATEST_CREATED / LATEST_STATUS_UPDATED
seg_typestringSub-account segment (S securities / C commodities, etc.)
langstringLanguage
page_tokenstringPagination token
parent_idint64Parent order ID (used only by ActiveOrders)

Orders — all orders

tc.Orders(req model.OrdersRequest) ([]model.Order, error)

Description

Fetch all historical orders for the current account. Since v0.3.0 the method takes an OrdersRequest, so you can filter by time range, status, contract, etc.

Parameters

See OrdersRequest above.

Returns

[]model.Order (common fields below)

FieldTypeDescription
IDint64Global order ID
OrderIdint64Account-level order number
Symbol / SecType / Market / CurrencystringContract info
Action / OrderType / StatusstringSide / type / status (see enum)
TotalQuantity / FilledQuantityint64Total / filled quantity
LimitPrice / AvgFillPricefloat64Limit / average fill price
TimeInForce / OutsideRthstring/boolTIF / extended hours
Commission / RealizedPnlfloat64Commission / realized P&L
OpenTime / UpdateTime / LatestTimeint64Timestamps (ms)
CanModify / CanCancel / IsOpenboolModifiable / cancelable / open
AlgoStrategystringAlgo strategy

Example

// Minimal call: fetch all orders
orders, err := tc.Orders(model.OrdersRequest{})
if err != nil {
    log.Fatal(err)
}

// Filtered call: latest 100 filled US stock orders
orders, err = tc.Orders(model.OrdersRequest{
    Market:  "US",
    SecType: "STK",
    States:  []string{"Filled"},
    Limit:   100,
    SortBy:  "LATEST_CREATED",
})
for _, o := range orders {
    fmt.Printf("%d %s %s %s qty=%d filled=%d status=%s\n",
        o.ID, o.Symbol, o.Action, o.OrderType, o.TotalQuantity, o.FilledQuantity, o.Status)
}

GetOrder — fetch a single order by ID

tc.GetOrder(req model.GetOrderRequest) (*model.Order, error)

Description

Fetch a single order by ID. At least one of Id (global order ID) or OrderId (account-level order number) is required.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
idint64EitherGlobal order ID
order_idint64EitherAccount-level order number
is_briefboolNoReturn brief fields only
langstringNoLanguage

Returns

*model.Order (same fields as items from Orders)

Example

o, err := tc.GetOrder(model.GetOrderRequest{Id: placed.ID})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%d %s status=%s filled=%d/%d\n",
    o.ID, o.Symbol, o.Status, o.FilledQuantity, o.TotalQuantity)

ActiveOrders — pending orders

tc.ActiveOrders(req model.OrdersRequest) ([]model.Order, error)

Description

Fetch orders currently open (not fully filled). Since v0.3.0 the method accepts an OrdersRequest and supports ParentId for listing children of a given parent order.

Parameters

See OrdersRequest.

Returns

[]model.Order

Example

// Minimal call
activeOrders, err := tc.ActiveOrders(model.OrdersRequest{})

// Children of a specific parent order
activeOrders, err = tc.ActiveOrders(model.OrdersRequest{ParentId: 12345678})

InactiveOrders — cancelled/expired orders

tc.InactiveOrders(req model.OrdersRequest) ([]model.Order, error)

Description

Fetch cancelled or expired orders. Since v0.3.0 the method accepts an OrdersRequest for filtering.

Parameters

See OrdersRequest.

Returns

[]model.Order

Example

// Minimal call
inactive, err := tc.InactiveOrders(model.OrdersRequest{})

// Cancelled only
inactive, err = tc.InactiveOrders(model.OrdersRequest{
    States: []string{"Cancelled"},
    Limit:  50,
})

FilledOrders — filled orders

tc.FilledOrders(req model.OrdersRequest) ([]model.Order, error)

Description

Fetch filled orders. Since v0.3.0 the two positional args (startDateMs, endDateMs int64) are replaced by an OrdersRequest; pass the time window via StartDate / EndDate.

Parameters

See OrdersRequest. StartDate / EndDate are ms timestamps.

Returns

[]model.Order

Example

import "time"

// Minimal call: no time window (server default applies)
filled, err := tc.FilledOrders(model.OrdersRequest{})

// Filtered: last 30 days
now := time.Now().UnixMilli()
filled, err = tc.FilledOrders(model.OrdersRequest{
    StartDate: now - 30*24*3600*1000,
    EndDate:   now,
    Limit:     200,
})

OrderTransactions — order transactions

tc.OrderTransactions(req model.OrderTransactionsRequest) ([]model.Transaction, error)

Description

Fetch fill-by-fill transaction records for an order. Since v0.3.0 the method accepts an OrderTransactionsRequest; you can look up transactions for a specific order via OrderId, or query a batch by time window / contract.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
order_idint64NoOrder ID (for single-order lookup)
symbolstringNoContract code
sec_typestringNoContract type
start_dateint64NoStart time (ms timestamp)
end_dateint64NoEnd time (ms timestamp)
since_datestringNoStart date (yyyyMMdd)
to_datestringNoEnd date (yyyyMMdd)
limitintNoMax rows returned
expiry / strike / rightstring/float64/stringNoOption contract selector
page_tokenstringNoPagination token
langstringNoLanguage

Returns

[]model.Transaction

FieldTypeDescription
IDint64Transaction record ID
OrderIDint64Order ID
AccountIdint64Account ID
Symbol / SecType / Market / CurrencystringContract info
ActionstringSide (BUY/SELL)
FilledQuantityint64Filled quantity
FilledPricefloat64Fill price
FilledAmountfloat64Fill amount
Commissionfloat64Commission
TransactedAtstringFill time string, format "YYYY-MM-DD HH:MM:SS"
TransactionTimeint64Fill time millisecond timestamp

Example

// Minimal call: transactions for a specific order
txs, err := tc.OrderTransactions(model.OrderTransactionsRequest{
    OrderId: placed.ID,
    Symbol:  "AAPL",
    SecType: "STK",
})

// Filtered: all transactions on a contract within a time window
txs, err = tc.OrderTransactions(model.OrderTransactionsRequest{
    Symbol:    "AAPL",
    SecType:   "STK",
    StartDate: now - 7*24*3600*1000,
    EndDate:   now,
    Limit:     100,
})
for _, tx := range txs {
    fmt.Printf("%s %s filledPrice=%.2f qty=%d\n", tx.TransactedAt, tx.Action, tx.FilledPrice, tx.FilledQuantity)
}

Positions and assets

Positions — positions

tc.Positions(req model.PositionsRequest) ([]model.Position, error)

Description

Fetch all positions for the current account. Since v0.3.0 the method accepts a PositionsRequest and supports filtering by Symbol / SecType / Currency / Market / SubAccounts, etc.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
symbolstringNoContract code
sec_typestringNoSTK / OPT / FUT / CASH, etc.
currencystringNoCurrency
marketstringNoMarket
sub_accounts[]stringNoSub-account list
expiry / strike / rightstringNoOption contract selector
asset_quote_typestringNoQuote type
langstringNoLanguage

Returns

[]model.Position

FieldTypeDescription
Account / Symbol / SecType / Market / CurrencystringBasics
Positionint64Position quantity
PositionQty / SalableQtyfloat64Precise quantity / salable quantity
AverageCost / AverageCostByAveragefloat64Amortized cost / average cost
MarketValuefloat64Market value
UnrealizedPnl / UnrealizedPnlPercentfloat64Unrealized P&L / percent
RealizedPnlfloat64Realized P&L
TodayPnl / TodayPnlPercentfloat64Today's P&L / percent
LatestPrice / LastClosePricefloat64Latest / previous close
ContractId / Identifier / Name-Contract identifiers

Example

// Minimal call: all positions
ps, err := tc.Positions(model.PositionsRequest{})

// Filtered: US stocks only
ps, err = tc.Positions(model.PositionsRequest{
    Market:  "US",
    SecType: "STK",
})
for _, p := range ps {
    fmt.Printf("%s qty=%.0f avgCost=%.2f latest=%.2f pnl=%.2f\n",
        p.Symbol, p.PositionQty, p.AverageCost, p.LatestPrice, p.UnrealizedPnl)
}

Assets — account assets

tc.Assets(req model.AssetsRequest) ([]model.Asset, error)

Description

Fetch an overview of account assets (with per-segment breakdown). Since v0.3.0 the method accepts an AssetsRequest.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
segmentboolNoInclude per-segment breakdown
market_valueboolNoInclude market value
sub_accounts[]stringNoSub-account list
base_currencystringNoBase currency
consolidated*boolNoConsolidated aggregation (nil omits the field)
langstringNoLanguage

Returns

[]model.Asset

Each Asset contains account-level aggregates (BuyingPower / CashValue / NetLiquidation / RealizedPnL / UnrealizedPnL / Currency / Capability) plus Segments []AssetSegment.

Each AssetSegment has Category (e.g. "S" for securities, "C" for commodities) / Title / NetLiquidation / CashValue / AvailableFunds / EquityWithLoan / ExcessLiquidity / InitMarginReq / MaintMarginReq / GrossPositionValue / Leverage.

Example

// Minimal call
assets, err := tc.Assets(model.AssetsRequest{})

// Filtered: include segment breakdown
assets, err = tc.Assets(model.AssetsRequest{
    Segment:     true,
    MarketValue: true,
})
for _, a := range assets {
    fmt.Printf("account=%s buyingPower=%.2f netLiq=%.2f segments=%d\n",
        a.Account, a.BuyingPower, a.NetLiquidation, len(a.Segments))
    for _, s := range a.Segments {
        fmt.Printf("  [%s] %s netLiq=%.2f available=%.2f\n",
            s.Category, s.Title, s.NetLiquidation, s.AvailableFunds)
    }
}

PrimeAssets — prime account assets

tc.PrimeAssets(req model.AssetsRequest) (*model.PrimeAsset, error)

Description

Fetch detailed assets for a prime account. Since v0.3.0 the method accepts an AssetsRequest (shared with Assets).

Parameters

See the AssetsRequest in Assets.

Returns

*model.PrimeAsset

FieldTypeDescription
AccountIDstringAccount ID
UpdateTimestampint64Update time (ms)
Segments[]PrimeAssetSegmentSegmented assets

Each PrimeAssetSegment has the full set: Capability / Category / Currency / CashBalance / CashAvailableForTrade / GrossPositionValue / EquityWithLoan / NetLiquidation / InitMargin / MaintainMargin / OvernightMargin / UnrealizedPL / RealizedPL / TotalTodayPL / BuyingPower / LockedFunds / Leverage, plus CurrencyAssets []CurrencyAsset (Currency / CashBalance / CashAvailableForTrade / ForexRate).

Example

// Minimal call
pa, err := tc.PrimeAssets(model.AssetsRequest{})

// Filtered: specify base currency
pa, err = tc.PrimeAssets(model.AssetsRequest{BaseCurrency: "USD"})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("account=%s segments=%d\n", pa.AccountID, len(pa.Segments))
for _, s := range pa.Segments {
    fmt.Printf("  [%s] netLiq=%.2f buyingPower=%.2f\n",
        s.Category, s.NetLiquidation, s.BuyingPower)
    for _, ca := range s.CurrencyAssets {
        fmt.Printf("    %s cash=%.2f fx=%.4f\n", ca.Currency, ca.CashBalance, ca.ForexRate)
    }
}

Account management (new in v0.3.0)

ManagedAccounts — institutional sub-accounts

tc.ManagedAccounts(req model.ManagedAccountsRequest) ([]model.ManagedAccount, error)

Description

List the institutional sub-accounts that the current master account can manage.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
langstringNoLanguage

Returns

[]model.ManagedAccount

FieldTypeDescription
AccountstringSub-account ID
AccountTypestringAccount type
CapabilitystringCapability (cash / margin, etc.)
StatusstringAccount status

Example

subs, err := tc.ManagedAccounts(model.ManagedAccountsRequest{})
if err != nil {
    log.Fatal(err)
}
for _, s := range subs {
    fmt.Printf("%s type=%s capability=%s status=%s\n",
        s.Account, s.AccountType, s.Capability, s.Status)
}

DerivativeContracts — derivative contracts

tc.DerivativeContracts(req model.DerivativeContractsRequest) ([]model.Contract, error)

Description

Batch fetch derivative contracts (options / warrants / callable bull bear) by symbols + type.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
symbols[]stringYesUnderlying code list
sec_typestringYesOPT / WAR / IOPT
expirystringNoExpiry, YYYYMMDD
langstringNoLanguage

Returns

[]model.Contract (see Contract)

Example

cs, err := tc.DerivativeContracts(model.DerivativeContractsRequest{
    Symbols: []string{"AAPL", "TSLA"},
    SecType: "OPT",
    Expiry:  "20260619",
})
fmt.Printf("contracts=%d\n", len(cs))

Asset analytics (new in v0.3.0)

AnalyticsAsset — daily asset analytics

tc.AnalyticsAsset(req model.AnalyticsAssetRequest) ([]model.AnalyticsAsset, error)

Description

Return daily account holdings, cash balance, P&L and net-value index — useful for drawing an account performance curve.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
sub_accountstringNoSub-account ID
seg_typestringNoSub-account segment
currencystringNoCurrency
sub_accounts[]stringNoSub-account list
start_datestringNoStart date (yyyy-MM-dd)
end_datestringNoEnd date (yyyy-MM-dd)
langstringNoLanguage

Returns

[]model.AnalyticsAsset

FieldTypeDescription
DatestringDate (yyyy-MM-dd)
HoldingValuefloat64Holding market value
CashBalancefloat64Cash balance
Pnl / PnlRatefloat64Daily P&L / return rate
NetValueIndexfloat64Net-value index
Currency / SegTypestringCurrency / segment

Example

rows, err := tc.AnalyticsAsset(model.AnalyticsAssetRequest{
    StartDate: "2025-01-01",
    EndDate:   "2025-12-31",
    Currency:  "USD",
})
for _, r := range rows {
    fmt.Printf("%s holding=%.2f cash=%.2f pnl=%.2f nav=%.4f\n",
        r.Date, r.HoldingValue, r.CashBalance, r.Pnl, r.NetValueIndex)
}

AggregateAssets — aggregated account assets

tc.AggregateAssets(req model.AggregateAssetsRequest) (*model.AggregateAssets, error)

Description

Aggregate prime-account assets under a given base_currency view (with per-currency breakdown).

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
seg_typestringNoSegment (S / C, etc.)
base_currencystringNoBase currency for aggregation
langstringNoLanguage

Returns

*model.AggregateAssets

FieldTypeDescription
AccountIDstringAccount ID
NetLiquidationfloat64Total net liquidation
GrossPositionValuefloat64Total position value
CashBalancefloat64Cash balance
BaseCurrencystringBase currency
CurrencyAssets[]CurrencyAssetPer-currency breakdown

Example

agg, err := tc.AggregateAssets(model.AggregateAssetsRequest{BaseCurrency: "USD"})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("netLiq=%.2f gross=%.2f cash=%.2f currencies=%d\n",
    agg.NetLiquidation, agg.GrossPositionValue, agg.CashBalance, len(agg.CurrencyAssets))

EstimateTradableQuantity — estimate tradable quantity

tc.EstimateTradableQuantity(req model.EstimateTradableQuantityRequest) (*model.EstimateTradableQuantity, error)

Description

Estimate order quantity limits (cash buy, margin buy, short sell, sellable, etc.) from the account's available funds, margin and current price.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
symbolstringYesContract code
sec_typestringYesContract type
expiry / strike / rightstringNoOption contract selector
seg_typestringNoSub-account segment
actionstringYesBUY / SELL
order_typestringNoMKT / LMT / STP / STP_LMT
limit_pricefloat64ConditionalRequired for LMT / STP_LMT
stop_pricefloat64ConditionalRequired for STP / STP_LMT
langstringNoLanguage

Returns

*model.EstimateTradableQuantity

FieldTypeDescription
TradableQuantityfloat64Tradable quantity
MaxCashBuyQuantityfloat64Max cash-buy quantity
MaxMarginBuyQuantityfloat64Max margin-buy quantity
MaxShortSellQuantityfloat64Max short-sell quantity
MaxPositionSellQtyfloat64Max sellable from position
CashBuyingPowerfloat64Cash buying power
CurrencystringCurrency

Example

est, err := tc.EstimateTradableQuantity(model.EstimateTradableQuantityRequest{
    Symbol:     "AAPL",
    SecType:    "STK",
    Action:     "BUY",
    OrderType:  "LMT",
    LimitPrice: 150.0,
})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("tradable=%.2f cashBuy=%.2f marginBuy=%.2f\n",
    est.TradableQuantity, est.MaxCashBuyQuantity, est.MaxMarginBuyQuantity)

Fund details & transfers (new in v0.3.0)

FundDetails — fund flow details

tc.FundDetails(req model.FundDetailsRequest) ([]model.FundDetails, error)

Description

Fetch account fund flow entries over a time window (deposits / withdrawals / fees / interest / dividends, etc.).

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
seg_types[]stringNoSegment list
fund_typestringNoFund type
currencystringNoCurrency
start_dateint64NoStart time (ms timestamp)
end_dateint64NoEnd time (ms timestamp)
startintNoPagination offset
limitintNoMax rows returned
langstringNoLanguage

Returns

[]model.FundDetails

FieldTypeDescription
IDint64Entry ID
Account / SegType / FundType / CurrencystringBasics
Amount / Balancefloat64Amount / balance
OccurTimeint64Occurrence time (ms)
RemarkstringRemark
ExternalIDstringExternal ID

Example

now := time.Now().UnixMilli()
rows, err := tc.FundDetails(model.FundDetailsRequest{
    StartDate: now - 30*24*3600*1000,
    EndDate:   now,
    Currency:  "USD",
    Limit:     100,
})
for _, r := range rows {
    fmt.Printf("%d %s amount=%.2f balance=%.2f remark=%s\n",
        r.OccurTime, r.FundType, r.Amount, r.Balance, r.Remark)
}

FundingHistory — funding history

tc.FundingHistory(req model.FundingHistoryRequest) ([]model.FundingHistoryItem, error)

Description

Query deposit / withdrawal transfer records for the account.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
seg_typestringNoSegment
langstringNoLanguage

Returns

[]model.FundingHistoryItem

FieldTypeDescription
IDstringTransfer ID
SegType / Currency / StatusstringSegment / currency / status
Amountfloat64Amount
SubmitTime / UpdateTimeint64Submit / update time (ms)

Example

rows, err := tc.FundingHistory(model.FundingHistoryRequest{})
for _, r := range rows {
    fmt.Printf("%s %s amount=%.2f status=%s\n", r.ID, r.Currency, r.Amount, r.Status)
}

PlaceForexOrder — place a forex order

tc.PlaceForexOrder(req model.ForexOrderRequest) (*model.ForexOrderResult, error)

Description

Submit a forex conversion order (currency-to-currency).

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
seg_typestringNoSub-account segment
source_currencystringYesSource currency
source_amountfloat64YesSource amount
target_currencystringYesTarget currency
external_idstringNoClient-side external ID
time_in_forcestringNoDAY / GTC, etc.
langstringNoLanguage

Returns

*model.ForexOrderResult

FieldTypeDescription
IDstringForex order ID
StatusstringStatus
SourceCurrency / TargetCurrencystringSource / target currency
SourceAmount / TargetAmountfloat64Source / target amount
Ratefloat64FX rate
SubmitTimeint64Submit time (ms)

Example

res, err := tc.PlaceForexOrder(model.ForexOrderRequest{
    SourceCurrency: "USD",
    SourceAmount:   10000,
    TargetCurrency: "HKD",
})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("id=%s rate=%.4f target=%.2f\n", res.ID, res.Rate, res.TargetAmount)

SegmentFundAvailable — available transfer amount

tc.SegmentFundAvailable(req model.SegmentFundRequest) ([]model.SegmentFund, error)

Description

Query the maximum amount that can be transferred between sub-account segments.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
from_segmentstringNoSource segment
to_segmentstringNoTarget segment
currencystringNoCurrency
langstringNoLanguage

Returns

[]model.SegmentFund

FieldTypeDescription
FromSegment / ToSegment / CurrencystringSource / target / currency
AvailableAmtfloat64Available amount

Example

avail, err := tc.SegmentFundAvailable(model.SegmentFundRequest{
    FromSegment: "S",
    ToSegment:   "C",
    Currency:    "USD",
})
for _, a := range avail {
    fmt.Printf("%s->%s %s available=%.2f\n", a.FromSegment, a.ToSegment, a.Currency, a.AvailableAmt)
}

SegmentFundHistory — segment fund history

tc.SegmentFundHistory(req model.SegmentFundRequest) ([]model.SegmentFundHistoryItem, error)

Description

Query the history of sub-account fund transfers.

Parameters

Uses SegmentFundRequest (commonly with Limit to cap result size).

Returns

[]model.SegmentFundHistoryItem

FieldTypeDescription
IDint64Record ID
FromSegment / ToSegment / CurrencystringSource / target / currency
Amountfloat64Amount
StatusstringStatus
SubmitTime / UpdateTimeint64Submit / update time (ms)

Example

history, err := tc.SegmentFundHistory(model.SegmentFundRequest{Limit: 50})
for _, h := range history {
    fmt.Printf("%d %s->%s %s amount=%.2f status=%s\n",
        h.ID, h.FromSegment, h.ToSegment, h.Currency, h.Amount, h.Status)
}

TransferSegmentFund — transfer between segments

tc.TransferSegmentFund(req model.SegmentFundRequest) (*model.SegmentFund, error)

Description

Submit a fund-transfer request between sub-account segments.

Parameters

NameTypeRequiredDescription
accountstringNoAccount ID
from_segmentstringYesSource segment
to_segmentstringYesTarget segment
currencystringYesCurrency
amountfloat64YesAmount
langstringNoLanguage

Returns

*model.SegmentFund (with ID / Status / SubmitTime, etc.)

Example

res, err := tc.TransferSegmentFund(model.SegmentFundRequest{
    FromSegment: "S",
    ToSegment:   "C",
    Currency:    "USD",
    Amount:      1000,
})
fmt.Printf("transferId=%s status=%s\n", res.ID, res.Status)

CancelSegmentFund — cancel a transfer request

tc.CancelSegmentFund(req model.SegmentFundRequest) (*model.SegmentFund, error)

Description

Cancel a pending sub-account fund-transfer request.

Parameters

NameTypeRequiredDescription
idstringYesTransfer request ID (from the ID returned by TransferSegmentFund)
accountstringNoAccount ID
langstringNoLanguage

Returns

*model.SegmentFund

Example

res, err := tc.CancelSegmentFund(model.SegmentFundRequest{ID: "TX123456"})
fmt.Printf("cancelled id=%s status=%s\n", res.ID, res.Status)

Low-level access

For endpoints not yet wrapped by the SDK, call the low-level HttpClient.ExecuteRaw:

package main

import (
	"fmt"
	"log"

	"github.com/tigerfintech/openapi-go-sdk/client"
	"github.com/tigerfintech/openapi-go-sdk/config"
)

func main() {
	cfg, err := config.NewClientConfig()
	if err != nil {
		log.Fatal(err)
	}

	httpClient := client.NewHttpClient(cfg)

	// Pass the API method name and raw JSON parameters
	resp, err := httpClient.ExecuteRaw("market_state", `{"market":"US"}`)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("raw response:", resp)
}