Python

Models

Data models and constants in Python SDK 3.3.2

This page lists the SDK's data models (the page name utilities is a legacy name; the content is Models). All models are imported from ssi_sdk.models:

from ssi_sdk.models import Account, OHLCData, PlaceOrderResponse, TradeMessage

Every model is a dataclass. A field typed X | str | None means the SDK returns the enum member when it recognises the value, the raw string when the value is unknown, and None when the server did not send it. For the enums see Enums.

Authentication

Token

FieldTypeDescription
access_tokenstrAccess token (hidden from repr; do not print/log)
token_typestrToken type (default "Bearer")
expires_atintExpiration time, epoch seconds (0 = unknown / treated as expired)
refresh_tokenstrRefresh token (hidden from repr)
refresh_token_expires_atintRefresh token expiration

Properties: effective_expires_at (the effective expiry time) and can_refresh (whether a refresh is possible).

OTPResponse

Result of auth.request_otp_typed().

FieldTypeDescription
messagestrMessage from the server
transaction_idstr | NoneOnly present for Smart OTP; pass it to ensure_authenticated(transaction_id=...). See Smart OTP

Account

Account

FieldTypeDescription
account_nostrAccount number
account_typeAccountType | str | NoneAccount type; the raw string for an unknown type, None when the server did not send it (no longer defaults to Cash)

Market Data

OHLCData

FieldTypeDescription
symbolstrStock symbol
trading_datestrTrading date
open_pricefloat | intOpen price
high_pricefloat | intHigh price
low_pricefloat | intLow price
close_pricefloat | intClose price
volumeintVolume
valuefloat | intTrade value

MarketIndexes

FieldTypeDescription
indexstrIndex code
index_namestrIndex name
boardBoard | str | NoneBoard
board_rawstr | NoneRaw board code as the server sent it

MarketIndexSummary

MarketIndexSummary has no index or board field; the index code is the argument you pass when calling.

FieldTypeDescription
trading_datestrTrading date
index_valuefloatIndex value
index_changefloatChange
index_change_percentfloatChange (%)
total_tradeintTotal trade volume
total_trade_valuefloatTotal trade value
total_advance_stockintAdvancing stocks
total_decline_stockintDeclining stocks
total_steady_stockintUnchanged stocks
total_matchintTotal matched volume
total_match_valuefloatTotal matched value
total_dealintTotal negotiated (put-through) volume
total_deal_valuefloatTotal negotiated value
total_ceiling_stockintStocks at ceiling
total_floor_stockintStocks at floor
total_prop_buyintProprietary buy volume
total_prop_buy_valuefloatProprietary buy value
total_prop_sellintProprietary sell volume
total_prop_sell_valuefloatProprietary sell value
total_buy_foreign / total_buy_foreign_valueoptionalForeign buy volume / value
total_sell_foreign / total_sell_foreign_valueoptionalForeign sell volume / value
net_purchases_foreign_volume / net_purchases_foreign_valueoptionalForeign net buy volume / value

The foreign fields are optional (None when the server did not send them).

SecuritiesInfo

A numeric field the server omits is None (not 0); an empty date is None.

FieldTypeDescription
symbolstrStock symbol
boardBoard | str | NoneBoard
indexstr | NoneIndex
symbol_name_vistr | NoneVietnamese name
symbol_name_enstr | NoneEnglish name
lot_sizeint | NoneLot size
listed_sharesint | NoneListed shares
icb_codestr | NoneICB industry code
icb_namestr | NoneICB industry name
maturity_datestr | NoneMaturity date
first_trading_datestr | NoneFirst trading date
last_trading_datestr | NoneLast trading date
cw_underlying_symbolstr | NoneCW underlying symbol
cw_exercise_pricefloat | NoneCW exercise price
cw_execution_ratiofloat | NoneCW execution ratio
i_indexfloat | NoneI-index
i_navfloat | NoneiNAV value
open_interestint | NoneOpen interest (derivatives)
settlement_pricefloat | NoneSettlement price (derivatives)
stock_typestr | NoneSecurity type

MasterData

Ceiling / floor / reference price of a symbol (from get_master_data()).

FieldTypeDescription
boardBoard | str | NoneBoard
symbolstrStock symbol
trading_datestrTrading date
ceilingfloat | NoneCeiling price
floorfloat | NoneFloor price
ref_pricefloat | NoneReference price

CorporateAction

One corporate action (dividend, bonus shares, rights issue, ...) of a symbol (from get_corporate_actions() and get_corporate_actions_historical()). Every field is a str exactly as the server sends it: dates stay YYYY/MM/DD text and ratio is not parsed, because its meaning depends on the event type. A field the server leaves blank (a newly announced event has no ex-right date or ratio yet) is "".

FieldTypeDescription
symbolstrStock symbol
event_titlestrEvent name
exright_datestrEx-right date
record_datestrRecord date
issue_datestrIssue date
exchangestrExchange code, for example "HOSE"
ratiostrEvent ratio as text, for example "0.9388"

SecuritiesSummary

FieldTypeDescription
symbolstrStock symbol
trading_datestrTrading date
price_changefloatPrice change
price_change_percentfloatPrice change (%)
open_pricefloatOpen price
high_pricefloatHigh price
low_pricefloatLow price
close_pricefloatClose price
average_pricefloatAverage price
total_matchintTotal matched volume
total_match_valuefloatTotal matched value
total_buyintTotal buy volume
total_trade_buyfloatTotal buy value
total_sellintTotal sell volume
total_trade_sellfloatTotal sell value
total_foreign_buy / total_foreign_buy_valueoptionalForeign buy volume / value
total_foreign_sell / total_foreign_sell_valueoptionalForeign sell volume / value
remain_foreign_room / total_foreign_roomoptionalRemaining foreign room / total foreign room
total_deal / total_deal_valueoptionalNegotiated volume / value
open_interest / settlement_priceoptionalOpen interest / settlement price (derivatives)
ceiling / floor / ref_priceNoneNot sent by this endpoint; use get_master_data()

DownloadData and DownloadDataRequest are deprecated; do not use them.

Portfolio

Balances (EquityAccountBalance, DerivativeAccountBalance) and positions (Position) can be None when the account has no data yet, so check for None before using them.

EquityAccountBalance

FieldTypeDescription
account_nostrAccount number
account_balancefloatAccount balance
total_debtfloatTotal debt
interest_loanfloatLoan interest
overdue_fee_loanfloatOverdue loan fee
withdrawablefloatWithdrawable cash
on_hold_cashfloatCash on hold
sell_unmatchedfloatUnmatched sell proceeds
sell_t0floatSell proceeds T0
sell_t1floatSell proceeds T1
sell_t2floatSell proceeds T2
buy_unmatchedfloatUnmatched buy amount
buy_t0floatBuy amount T0
buy_t1floatBuy amount T1
buy_t2floatBuy amount T2
advance_cash_t0floatCash advance T0
advance_cash_t1floatCash advance T1
hold_subscriptionfloatCash held for subscription
dividendfloatDividend

DerivativeAccountBalance

FieldTypeDescription
account_nostrAccount number
account_balancefloatAccount balance
feefloatFee
commissionfloatCommission
interestfloatInterest
ext_interestfloatExternal interest
loanfloatLoan
delivery_amountfloatDelivery amount
floating_plfloatUnrealized P/L
trading_plfloatTrading P/L
total_plfloatTotal P/L
withdrawablefloatWithdrawable cash
cash_ssifloatSSI cash
valid_non_cash_ssifloatValid non-cash assets, SSI
withdrawable_ssifloatWithdrawable, SSI
cash_vsdcfloatVSDC cash
valid_non_cash_vsdcfloatValid non-cash assets, VSDC
withdrawable_vsdcfloatWithdrawable, VSDC

cash_withdrawable_ssi and cash_withdrawable_vsdc are old aliases of withdrawable_ssi / withdrawable_vsdc; they still read but emit a DeprecationWarning.

EquityPosition

FieldTypeDescription
account_nostrAccount number
symbolstrStock symbol
quantityintTotal quantity
sellable_quantityintSellable quantity
cost_pricefloatCost price
buying_quantityintQuantity being bought
selling_quantityintQuantity being sold
mortgage_quantityintMortgaged quantity
block_quantityintBlocked quantity
dividend_quantityintDividend quantity
bought_quantityintBought quantity
sold_quantityintSold quantity
t1_buy_quantityintT1 buy quantity
t2_buy_quantityintT2 buy quantity
t1_sell_quantityintT1 sell quantity
t2_sell_quantityintT2 sell quantity
restricted_quantityintRestricted quantity

DerivativePosition

FieldTypeDescription
account_nostrAccount number
symbolstrContract symbol
long / short / netintLong / short / net position
bid_avg_price / ask_avg_pricefloatAverage buy / sell price
floating_pl / trading_plfloatP/L
trade_pricefloatTrade price

AllDerivativePosition

FieldTypeDescription
open_positionslist[DerivativePosition]Open positions
closed_positionslist[DerivativePosition]Closed positions
account_nostrAccount number

Order

FieldTypeDescription
account_nostrAccount number
client_request_idstrClient request ID
order_idstrOrder ID
symbolstrStock symbol
sideOrderSide | str | NoneBuy/Sell
order_typeOrderType | str | NoneOrder type
priceint | float | OrderType | strOrder price (can be an order type such as ATO, ATC)
avg_pricefloatAverage matched price
quantityintOrder quantity
os_quantityint | NoneOutstanding quantity
filled_quantityintFilled quantity
cancel_quantityintCancelled quantity
statusOrderStatus | str | NoneOrder status
input_time / modify_timestrInput / modify time
messagestrMessage

Trading Responses

PlaceOrderResponse

order_id, client_request_id, status (OrderStatus | str)

ModifyOrderResponse

client_modify_id, order_id, client_request_id, status (OrderStatus | str)

CancelOrderResponse

client_cancel_id, order_id, client_request_id, status (OrderStatus | str)

MaxBuySellResponse

account_no, symbol, max_buy_quantity, max_sell_quantity, margin_ratio (str | None), purchasing_power (int | None)

Conditional Orders (FCO)

FCOPlaceResponse

Result of placing a conditional order — fco_id

FCOCancelResponse

Result of cancelling a conditional order — fco_id

FCOListResponse

Paginated list of conditional orders.

FieldTypeDescription
page_indexintCurrent page
page_sizeintPage size
items_countintTotal records
pages_countintTotal pages
fco_listlist[FCOInfo]FCO order list

FCOInfo

Details of one conditional order.

FieldTypeDescription
fco_idstrFCO order ID
client_idstrUsername / Client ID
account_nostrAccount number
quantityintOrder quantity
pricestrOrder price
price_slipfloat | NonePrice slippage
order_typeOrderType | str | NoneOrder type placed when triggered
symbolstrStock symbol
typeFCOType | str | NoneConditional order type
from_datestrEffective from
to_datestrEffective to
matched_quantityintMatched quantity
is_place_orderboolWhether the order has been placed on the book
statusFCOStatus | str | NoneFCO order status
detailstrStatus detail
paramsFCOParams | NoneTrigger parameters of the FCO order

FCOParams

Trigger parameters of a conditional order.

FieldTypeDescription
stop_pricefloat | NoneStop / trigger price
sideOrderSide | NoneOrder side (Buy/Sell)
active_pricefloat | NoneActivation price (Trailing Stop)
trailing_amountfloat | NoneTrailing amount
tp_active_pricefloat | NoneTake Profit activation price
sl_active_pricefloat | NoneStop Loss activation price
tp_pricestr | NoneTake Profit price
sl_pricestr | NoneStop Loss price
tp_slipfloat | NoneTake Profit slippage
sl_slipfloat | NoneStop Loss slippage
operatorFCOOperator | str | NoneTrigger comparison operator

The request parameter classes used when placing orders (GTDParams, StopParams, TrailingStopParams, OCOParams, BullBearParams) also have an optional code field (OTP code, default None).

FCOStatusHistoryItem

One row of the status-change history of a conditional order (from get_fco_status_history).

FieldTypeDescription
statestrState (see FCOStatus in Enums)
timestrWhen the state changed
codestr | NoneStatus code, if any
detailstrDetail

FCOOrderBookResponse

FCO matching log (paginated).

FieldTypeDescription
page_indexintCurrent page
page_sizeintPage size
items_countintTotal records
pages_countintTotal pages
order_booklist[FCOOrder]FCO order log

FCOOrder

Trade / execution log of an FCO order.

FieldTypeDescription
fco_idstrParent FCO order ID
account_nostrAccount number
quantityintQuantity
pricestrOrder price
symbolstrStock symbol
typeFCOType | str | NoneConditional order type
sideOrderSide | str | NoneOrder side
order_typeOrderType | str | NoneChild order type
is_main_orderboolIs the main order
is_attached_orderboolIs an attached order
created_time / updated_timestrCreated / updated time
unique_idstrUnique ID
order_idstrExchange order ID
matched_quantityintMatched quantity
os_quantityintOutstanding quantity
avg_pricefloatAverage matched price
statusOrderStatus | str | NoneChild order status
detailstrDetail

Batch Order

Models for batch orders (place / cancel several orders in one request). Usage, examples and limits: Services, section 5.4.

The two TypedDicts below describe each element you pass to place_batch_orders / cancel_batch_orders:

TypeRequired fieldsOptional fields
BatchPlaceOrderItemaccount_no, symbol, side, quantity, price, order_typeclient_request_id
BatchCancelOrderItemaccount_noorder_id, client_request_id

BatchOrderRequest

FieldTypeDescription
batch_request_idstrID of the whole batch (reusing an id is an HTTP 409)
batch_request_timeintTime the batch is sent, epoch milliseconds
orderslist[dict]The orders

It has to_dict() (camelCase payload) and to_str() (the JSON string that is signed and sent).

BatchOrderResult

Outcome of one order in the batch.

FieldTypeDescription
client_request_idstrClient request ID of the order
order_idstrOrder ID
statusOrderStatus | strStatus
successboolWhether this order succeeded (default False)
error_codestrServer error code when the order was rejected
error_messagestrServer error text when the order was rejected
client_cancel_idstrID of the cancel request (generated by the SDK, only for batch cancel)

BatchOrderResponse

FieldTypeDescription
batch_request_idstrID of the whole batch
resultslist[BatchOrderResult]One result per order

Note: the SDK's per-batch maximum is MAX_BATCH_ORDERS = 20 (override with Config.max_batch_orders), while the API reference says 50; the limit the server actually applies has not been confirmed. See Configuration and Services, section 5.4.

Streaming Messages

These messages arrive through the callbacks of stream.streaming, see Services, section 6.

TradeMessage

type, trading_time, symbol, price, quantity, side, total_volume, plus the optional open, high, low, avg (None when the server did not send them).

IntervalMessage

FieldTypeDescription
typeDataTypeData type
interval_timestrInterval time
trading_timestrTrading time
symbolstrStock symbol
openfloat | intOpen
highfloat | intHigh
lowfloat | intLow
closefloat | intClose
volumeintVolume

IndexTickMessage

Real-time index tick (see Services, section 6.7).

FieldServer keyDescription
typeData type
symbolsIndex code
boardbBoard
statusssStatus
trading_timetTime
valuevIndex value
changecChange
change_percentcrChange (%)
advancesadvAdvancing stocks
declinesdecDeclining stocks
no_changencUnchanged stocks
ceilingsceStocks at ceiling
floorsflStocks at floor
total_match_valuetmvTotal matched value
total_match_quantitytmqTotal matched quantity
total_put_valuetvpTotal negotiated value
total_put_quantitytqpTotal negotiated quantity
total_quantitytqTotal quantity
total_valuetvTotal value
rawThe whole data object the server sent

Not confirmed: the attribute names are inferred from the server's abbreviations and have not been checked against a real frame. When you need to be sure, read msg.raw.

IndexSummaryMessage

FieldTypeDescription
indexstrIndex code taken from the topic, upper-case (for example "VN30")
datadictThe server's payload, untouched

The fields inside data are not publicly documented, so the SDK does not guess them; read them with msg.get("key1", "key2", default=None) (returns the value of the first key present).

MarketFlagMessage

FieldTypeDescription
boardstrBoard code as the server sends it: HOSE, HNX, UPCOM or DER (derivatives; not the enum Board's DERIVATIVES)
trading_timestrTime
flagstrSession flag (for example "ATO", "LO", "ATC"), kept as the raw string

MarketDataMessage

symbol, board, trading_time, ceiling, floor, ref_price

QuoteMessage

type, trading_time, symbol, bid_prices, bid_volumes, ask_prices, ask_volumes

ForeignRoomMessage

type, trading_time, symbol, total_room, current_room, buy_quantity, buy_value, sell_quantity, sell_value

PutMessage

type, trading_time, symbol, price, quantity, total_quantity, total_value

OddLotMessage

type, trading_time, symbol, price, quantity, bid_prices, bid_volumes, ask_prices, ask_volumes

MarketStatusMessage

market, status, trading_date

OrderStatusMessage

type, account_no, client_request_id, order_id, symbol, side, order_type, price, quantity, os_quantity, filled_quantity, cancel_quantity, status, input_time, modified_time, message, plus avg_price, reject_reason, system_request_id, error_code, error_message, notify_id, connection_id.

modify_time is a deprecated alias of modified_time. os_quantity is None when the order comes from the REST order book. An order the server rejects reports status RJ with error_code.

OrderMatchMessage

type, notify_id, connection_id, client_request_id, order_id, symbol, side, account_no, match_price, match_qty, match_time

PortfolioMessage

type, account_no, symbol, long_qty, short_qty, net, bid_avg_price, ask_avg_price, trade_price, market_price, floating_pl, trading_pl, position_type

total_asset, cash_balance and stock_value are deprecated and always None.

FCOOrderUpdateMessage

FCO conditional-order status update (streaming, received via on_trading when event_type == "fcoEvent").

FieldTypeDescription
fco_idstrFCO order ID
process_statusFCOStatus | NoneFCO processing status (INIT, WAIT, WC, TER, ...)
matched_quantityintMatched quantity
is_place_orderboolWhether the order has been placed on the book
symbolstrStock symbol
quantityintOrder quantity
pricestrOrder price
account_nostrAccount number
updated_timestrUpdate time (YYYY/MM/DD HH:MM:SS)
statusstrStatus code
messagestrDetail message / trigger or disconnect reason
usernamestrUsername that placed the order
event_typestrEvent type ("fcoEvent")
typeFCOType | NoneConditional order type (GTD, STOP, ...)

HeartbeatMessage

method, channel, status, message

ConnectionEvent

Connection-state event of the stream, received via on_connection. It is a frozen dataclass and is not exported at top level: from ssi_sdk.transport.reconnect import ConnectionEvent.

FieldTypeDescription
statestrconnected, reconnected, disconnected or failed
reconnect_countintNumber of reconnects so far (default 0)
errorException | NoneThe error that caused the event (default None)

Details: Services, section 6.9.

Trading WebSocket

Import from ssi_sdk (these were in ssi_sdk.experimental in 3.3.1 and earlier; that module was removed in 3.3.2). Full usage: Services, section 7; how to create the service: Client Classes.

TradingWSResponse

Result of a command sent over the Trading WebSocket.

FieldTypeDescription
idstrRequest ID
methodstrMethod that was called
statusintStatus code (default 200)
resultAnyReturned data
rate_limitdictRate-limit information the server sends back
received_timeint | NoneTime the response was received

TradingWSError

Extends WebSocketError; raised when the server rejects a command or refuses the connection. Constructor TradingWSError(status, code, message); attributes .status, .error_code and .server_message. See Exceptions.

Wrapper Types

AccountBalance

FieldTypeDescription
equityEquityAccountBalance | NoneEquity balance
derivativeDerivativeAccountBalance | NoneDerivative balance

Position

FieldTypeDescription
equitylist[EquityPosition] | NoneEquity positions
derivativeAllDerivativePosition | NoneDerivative positions

PPMMR

FieldTypeDescription
equityEquityPPMMR | NoneEquity PPMMR
derivativeDerivativePPMMR | NoneDerivative PPMMR

OrderBook

FieldTypeDescription
orderslist[Order]Order list
total_ordersintTotal orders

Constants

The SDK's limit constants (module ssi_sdk.constant). The values are SDK defaults only; the ones that relate to the server may differ in practice.

ConstantValueMeaning
MAX_CLIENT_REQUEST_ID_LENGTH20Maximum length of client_request_id
MAX_BATCH_ORDERS20Maximum orders per batch (SDK default; override with Config.max_batch_orders)
DEFAULT_SIZE / DEFAULT_PAGE1000 / 1Default page size / page number for pagination
CORPORATE_ACTIONS_MAX_DAYS5Longest date range of one corporate actions request (days)
CORPORATE_ACTIONS_LANGUAGES("vn", "en")Allowed language values for corporate actions
TOPIC_MARKET_FLAG"market.flag"Session flag topic
TOKEN_EXPIRY_SKEW_MS30000A token counts as expired 30 seconds early
WS_RECONNECT_MAX_DELAY_MS60000Maximum stream reconnect delay
WS_RATE_LIMIT_BACKOFF_MS30000Wait time when rate limited on the WebSocket
WS_TOKEN_REFRESH_LEAD_MS60000How long before expiry the token is refreshed
WS_SERVER_MAX_CONNECTIONS10Maximum WebSocket connections on the server side
WS_MAX_FRAME_BYTES4000Maximum frame size the SDK sends (server limit is 4096)

Time constants carry the _ms suffix (milliseconds). For the matching configuration options see Configuration.

On this page