Go

Models

Response data models and streaming message types in Go SDK

All models are Go structs. Import from the relevant package.

Pointer fields (*float64, *int, *string) are nil when the server did not send that value; this is different from a value of 0. Check for nil before reading.

Package Structure

ssi-sdk-go/v3/
├── ssi/          → Auth, Data, Trading, Stream (main import)
├── auth/         → Token, OTPResponse
├── account/      → Account, AccountType
├── market/       → OHLCData, MarketIndexes, MarketIndexSummary, SecuritiesInfo, SecuritiesSummary, MasterData, CorporateAction
├── trading/      → PlaceOrderResponse, ModifyOrderResponse, CancelOrderResponse, MaxBuySellResponse, Batch*, FCOInfo, FCOListResponse, FCOOrder, ...
├── portfolio/    → EquityAccountBalance, DerivativeAccountBalance, EquityPosition, DerivativePosition, Order
├── stream/       → TradeMessage, QuoteMessage, IndexTickMessage, OrderStatusMessage, PortfolioMessage, FCOOrderUpdateMessage, ...
├── tradingws/    → Service (Trading WebSocket), Response, OrderBookQuery
└── (root)        → SSIError, APIError, AuthenticationError, ...

Authentication

Token

FieldTypeDescription
AccessTokenstringAccess token
TokenTypestringToken type (default "Bearer")
ExpiresAtint64Expiration time, Unix epoch seconds
RefreshTokenstringRefresh token
RefreshTokenExpiresAtint64Refresh token expiration, Unix epoch seconds (server key refreshExpiresAt)

Methods: EffectiveExpiresAt(), CanRefresh(). String() / GoString() never print the tokens.

OTPResponse

Returned by RequestOTPTyped().

FieldTypeDescription
MessagestringServer message
TransactionIDstringTransaction id, only for Smart OTP. Pass it to Authenticate / EnsureAuthenticated

Account

Account

FieldTypeDescription
AccountNostringAccount number
AccountType*account.AccountType"Cash", "Margin" or "Derivative". nil when missing; an unknown value is kept as its raw string (see Enums)

Market Data

OHLCData

FieldTypeDescription
SymbolstringStock symbol
TradingDatestringTrading date
OpenPricefloat64Open price
HighPricefloat64High price
LowPricefloat64Low price
ClosePricefloat64Close price
VolumeintVolume
Valuefloat64Trade value

MarketIndexes

FieldTypeDescription
IndexstringIndex code
IndexNamestringIndex name
Board*market.BoardBoard, nil if the value is not a known board
BoardRaw*stringThe board exactly as the server sent it

MarketIndexSummary

FieldTypeDescription
TradingDatestringTrading date
IndexValuefloat64Index value
IndexChangefloat64Change
IndexChangePercentfloat64Change (%)
TotalTradeintTotal trade volume
TotalTradeValuefloat64Total trade value
TotalAdvanceStockintAdvancing stocks
TotalDeclineStockintDeclining stocks
TotalSteadyStockintUnchanged stocks (server key totalNoChangeStock)
TotalMatchintTotal matched volume
TotalMatchValuefloat64Total matched value
TotalDealintTotal deal volume
TotalDealValuefloat64Total deal value
TotalCeilingStockintCeiling stocks
TotalFloorStockintFloor stocks
TotalPropBuyintTotal proprietary buy volume
TotalPropBuyValuefloat64Total proprietary buy value
TotalPropSellintTotal proprietary sell volume
TotalPropSellValuefloat64Total proprietary sell value
TotalBuyForeign / TotalBuyForeignValue*float64Foreign buy volume / value
TotalSellForeign / TotalSellForeignValue*float64Foreign sell volume / value
NetPurchasesForeignVolume / NetPurchasesForeignValue*float64Foreign net purchase volume / value

Note: MarketIndexSummary has no dedicated Index/Board field — use the method's query parameter (GetIndexSummary(index) / GetBoardSummary(board)) to scope the result.

SecuritiesInfo

A missing value is nil, not 0 / empty string.

FieldTypeDescription
SymbolstringStock symbol
Board*market.BoardBoard
IndexstringIndex
SymbolNameVistringVietnamese name
SymbolNameEnstringEnglish name
LotSize*intLot size
ListedShares*intListed shares
ICBCode*stringICB code
ICBName*stringICB name
MaturityDate*stringMaturity date
FirstTradingDate*stringFirst trading date
LastTradingDate*stringLast trading date
CWUnderlyingSymbol*stringCW underlying symbol
CWExercisePrice*float64CW exercise price
CWExecutionRatio*float64CW execution ratio
IIndex*float64I index
INAV*float64iNAV value
OpenInterest*float64Open interest (derivatives)
SettlementPrice*float64Settlement price (derivatives)
StockType*stringStock type

SecuritiesSummary

FieldTypeDescription
SymbolstringStock symbol
TradingDatestringTrading date
PriceChangefloat64Price change
PriceChangePercentfloat64Price change (%)
OpenPricefloat64Open price
HighPricefloat64High price
LowPricefloat64Low price
ClosePricefloat64Close price
AveragePricefloat64Average price
TotalMatchintTotal matched volume
TotalMatchValuefloat64Total matched value
TotalBuyintTotal buy volume
TotalTradeBuyfloat64Total buy value
TotalSellintTotal sell volume
TotalTradeSellfloat64Total sell value
TotalForeignBuy / TotalForeignBuyValueint / float64Foreign buy volume / value
TotalForeignSell / TotalForeignSellValueint / float64Foreign sell volume / value
RemainForeignRoom / TotalForeignRoomintRemaining / total foreign room
TotalDeal / TotalDealValueint / float64Deal volume / value
OpenInterest / SettlementPricefloat64Open interest / settlement price (derivatives)
Ceiling / Floor / RefPrice*float64Always nil here, because this endpoint does not send them. Use GetMasterData

MasterData

Returned by GetMasterData() and GetMasterDataHistorical(from, to).

FieldTypeDescription
Boardmarket.BoardBoard (a raw string for a board the SDK does not know)
SymbolstringSymbol
TradingDatestringTrading date
Ceilingfloat64Ceiling price
Floorfloat64Floor price
RefPricefloat64Reference price

CorporateAction

Returned by GetCorporateActions(opts...) and GetCorporateActionsHistorical(from, to, opts...) (see 3.7. Corporate Actions). Every field is a string exactly as the server sends it; a blank, null or missing field is "".

FieldTypeDescription
SymbolstringSymbol
EventTitlestringEvent title (in the requested language, "vn" or "en")
ExrightDatestringEx-right date, text YYYY/MM/DD
RecordDatestringRecord date, text YYYY/MM/DD
IssueDatestringIssue date, text YYYY/MM/DD
ExchangestringExchange
RatiostringRatio, not parsed (its meaning depends on the event type)

Portfolio

Methods that find nothing return nil (not an empty struct): the balance, PPMMR and derivative-position methods return a nil pointer, and GetEquityPositions returns a nil slice. Check for nil / len(...) == 0.

EquityAccountBalance

FieldTypeDescription
AccountNostringAccount number
AccountBalancefloat64Account balance (available cash)
TotalDebtfloat64Total debt
InterestLoanfloat64Loan interest
OverdueFeeLoanfloat64Overdue fee
Withdrawablefloat64Withdrawable amount
OnHoldCashfloat64On-hold cash
SellUnmatchedfloat64Sell unmatched
SellT0float64Sell T+0
SellT1float64Sell T+1
SellT2float64Sell T+2
BuyUnmatchedfloat64Buy unmatched
BuyT0float64Buy T+0
BuyT1float64Buy T+1
BuyT2float64Buy T+2
AdvanceCashT0float64Advance cash T+0
AdvanceCashT1float64Advance cash T+1
HoldSubscriptionfloat64Hold subscription
Dividendfloat64Dividend

DerivativeAccountBalance

FieldTypeDescription
AccountNostringAccount number
AccountBalancefloat64Account balance
Feefloat64Fee
Commissionfloat64Commission
Interestfloat64Interest
ExtInterestfloat64Extended interest
Loanfloat64Loan
DeliveryAmountfloat64Delivery amount
FloatingPLfloat64Floating P&L
TradingPLfloat64Trading P&L
TotalPLfloat64Total P&L
Withdrawablefloat64Withdrawable amount
CashSSIfloat64Cash at SSI
ValidNonCashSSIfloat64Valid non-cash assets at SSI
WithdrawableSSIfloat64Withdrawable at SSI (was CashWithdrawableSSI before 3.3.0; the old name remains as a deprecated method)
CashVSDCfloat64Cash at VSDC
ValidNonCashVSDCfloat64Valid non-cash assets at VSDC
WithdrawableVSDCfloat64Withdrawable at VSDC (was CashWithdrawableVSDC before 3.3.0; the old name remains as a deprecated method)

EquityPosition

FieldTypeDescription
AccountNostringAccount number
SymbolstringStock symbol
QuantityintTotal quantity
SellableQuantityintSellable quantity
CostPricefloat64Cost price
BuyingQuantityintBuying quantity
SellingQuantityintSelling quantity
MortgageQuantityintMortgage quantity
BlockQuantityintBlocked quantity
DividendQuantityintDividend quantity
BoughtQuantityintBought quantity
SoldQuantityintSold quantity
T1BuyQuantityintT+1 buy quantity
T2BuyQuantityintT+2 buy quantity
T1SellQuantityintT+1 sell quantity
T2SellQuantityintT+2 sell quantity
RestrictedQuantityintRestricted quantity

DerivativePosition

FieldTypeDescription
AccountNostringAccount number
SymbolstringContract symbol
Long / Short / NetintLong / short / net position
BidAvgPrice / AskAvgPricefloat64Avg buy / sell price
FloatingPL / TradingPLfloat64P&L
TradePricefloat64Trade price

Order

FieldTypeDescription
AccountNostringAccount number
ClientRequestIDstringClient request ID
OrderIDstringOrder ID
SymbolstringStock symbol
Sidetrading.OrderSideBuy/Sell
OrderTypetrading.OrderTypeOrder type
Price / AvgPricefloat64Order price / Avg fill price
PriceTextstringPrice as text (for example ATO, ATC)
QuantityintOrder quantity
OSQuantity*intOutstanding quantity. nil for orders from the REST order book (the server does not send it there)
FilledQuantityintFilled quantity
CancelQuantityintCancelled quantity
Statustrading.OrderStatusOrder status
InputTime / ModifyTimestringInput / modify time, format yyyy/MM/dd HH:mm:ss
MessagestringMessage

Trading Responses

PlaceOrderResponse

OrderID, ClientRequestID, Status (trading.OrderStatus)

ModifyOrderResponse

ClientModifyID, OrderID, ClientRequestID, Status

CancelOrderResponse

ClientCancelID, OrderID, ClientRequestID, Status

MaxBuySellResponse

FieldTypeDescription
AccountNostringAccount number
SymbolstringSymbol
MaxBuyQuantityintMaximum buy quantity
MaxSellQuantityintMaximum sell quantity
MarginRatio*stringMargin ratio. nil on derivative accounts
PurchasingPower*intPurchasing power. nil on derivative accounts. The old PurchasePower() method is deprecated and returns a string

Order options

PlaceOrder and the Place*Order helpers take opts ...trading.OrderOption; trading.WithClientRequestID(id) sets your own idempotency key (at most 20 characters). The FCO place and cancel methods take opts ...trading.FCOOption; trading.WithOTPCode(code) supplies the one-time code when the account requires one (optional).

Batch Orders

Types used by PlaceBatchOrders / CancelBatchOrders and by the Trading WebSocket batch methods. Methods, behaviour and examples: Batch Orders.

BatchPlaceOrderItem (one order to place)

The fields mirror the arguments of PlaceOrder.

FieldTypeDescription
AccountNostringAccount number (required)
SymbolstringSymbol (required)
Sidetrading.OrderSidetrading.OrderSideBuy ("B") or trading.OrderSideSell ("S")
QuantityintQuantity, must be greater than 0
Pricefloat64Price (VND). Must be greater than 0 for LO and PLO; other order types are market-priced
OrderTypetrading.OrderTypeATO, ATC, LO, MTL, MP, MOK, MAK, PLO
ClientRequestIDstringIdempotency key of the order, at most 20 characters. If empty, the SDK generates one

BatchCancelOrderItem (one order to cancel)

FieldTypeDescription
AccountNostringAccount number (required)
OrderIDstringOrder ID issued by the server
ClientRequestIDstringThe ClientRequestID you used when placing the order

Each cancel item needs exactly one of OrderID or ClientRequestID. With both, or neither, the SDK returns a *ValidationError.

BatchOrderResponse

FieldTypeDescription
BatchRequestIDstringBatch ID, as returned by the server
Results[]BatchOrderResultOne result per order. The SDK code comment says "in request order"; this is not confirmed by the server, so match results by ClientRequestID / OrderID if you need certainty

If the server sends no results, or results is not a list, Results is an empty slice.

BatchOrderResult

FieldTypeDescription
ClientRequestIDstringIdempotency key of the order
OrderIDstringOrder ID issued by the server
Statustrading.OrderStatusOrder status (an unknown value is kept as a raw string)
Successbooltrue if this order was accepted
ErrorCodestringError code for this order only (when Success == false)
ErrorMessagestringError message for this order only
ClientCancelIDstringCancel ID (clientCancelId) returned by the server, typically seen in CancelBatchOrders results

BatchOrderRequest (wire body)

Built by the SDK; you normally do not create it. BatchRequestID (random string), BatchRequestTime (int64, epoch milliseconds) and Orders. The JSON body is {"batchRequestId", "batchRequestTime", "orders": [...]} and is signed as a whole.

Conditional Orders (FCO)

FCOPlaceResponse

Result of placing a conditional order — FCOID string

FCOCancelResponse

Result of cancelling a conditional order — FCOID string

FCOListResponse

Paginated list of conditional orders.

FieldTypeDescription
PageIndexintCurrent page
PageSizeintPage size
ItemsCountintTotal record count
PagesCountintTotal page count. It can miss the last partial page: page until a page is empty, or compute from ItemsCount
FCOList[]*FCOInfoList of FCO orders

FCOInfo

Detailed information of a single conditional order.

FieldTypeDescription
FCOIDstringFCO order ID
ClientIDstringUsername / client ID
AccountNostringAccount number
QuantityintOrder quantity
PricestringOrder price
PriceSlip*float64Price slip
SymbolstringStock symbol
TypeFCOTypeConditional order type
FromDatestringEffective start date
ToDatestringEffective end date
MatchedQuantityintMatched quantity
IsPlaceOrderboolWhether the underlying order has been placed
StatusFCOStatusFCO order status
DetailstringStatus detail
Params*FCOParamsTrigger parameters. nil when the server sent none
OrderTypeOrderTypeUnderlying order type

FCOParams

Trigger parameters of a conditional order.

FieldTypeDescription
StopPrice*float64Stop / trigger price
SideOrderSideOrder side (Buy/Sell)
ActivePrice*float64Trigger price (Trailing Stop)
TrailingAmount*float64Trailing amount
TPActivePrice*float64Take-profit trigger price
SLActivePrice*float64Stop-loss trigger price
TPPricestringTake-profit price
SLPricestringStop-loss price
TPSlip*float64Take-profit slip
SLSlip*float64Stop-loss slip
OperatorFCOOperatorTrigger comparison operator (the server may send a number 0-4; see ParseFCOOperator)

FCOStatusHistoryItem

Returned by GetFcoStatusHistory(fcoID) as []FCOStatusHistoryItem. An empty history (HTTP 204) gives an empty list.

FieldTypeDescription
StatestringState
TimestringTime of the transition
Code*stringCode, nil if the server sent none
DetailstringDetail

FCOOrderBookResponse

Paginated FCO order book / execution log.

FieldTypeDescription
PageIndexintCurrent page
PageSizeintPage size
ItemsCountintTotal record count
PagesCountintTotal page count
OrderBook[]*FCOOrderList of FCO order book entries

FCOOrder

Execution log entry for an FCO order.

FieldTypeDescription
FCOIDstringParent FCO order ID
AccountNostringAccount number
QuantityintQuantity
PricestringOrder price
SymbolstringStock symbol
SideOrderSideOrder side
OrderTypeOrderTypeUnderlying order type
IsMainOrderboolIs the main order
IsAttachedOrderboolIs an attached order
CreatedTime / UpdatedTimestringCreated / updated time
UniqueIDstringUnique ID
OrderIDstringExchange order ID
MatchedQuantityintMatched quantity
OSQuantityintOutstanding quantity
AvgPricefloat64Average fill price
StatusOrderStatusUnderlying order status
DetailstringDetail
TypeFCOTypeConditional order type

Streaming Messages

Received through SetOnData / SetOnTrading, or through the typed handlers (SetOnOrder, SetOnIndexSummary, ...). See Streaming.

TradeMessage

Type, TradingTime, Symbol, Price, Quantity, Side (string, "U" when the server gave none), TotalVolume, and the pointer fields Open, High, Low, Avg (*float64, nil when not sent).

QuoteMessage

Type, TradingTime, Symbol, BidPrices, BidVolumes, AskPrices, AskVolumes

ForeignRoomMessage

Type, TradingTime, Symbol, TotalRoom, CurrentRoom, BuyQuantity, BuyValue, SellQuantity, SellValue

PutMessage

Type, TradingTime, Symbol, Price (float64), Quantity, TotalQuantity, TotalValue (int)

OddLotMessage

Type, TradingTime, Symbol, Price, Quantity, BidPrices, BidVolumes, AskPrices, AskVolumes

MarketStatusMessage

Market, Status, TradingDate

MarketDataMessage

Reference / ceiling / floor data from a market.<symbol> topic (SubscribeMarket, alias SubscribeMasterData).

Symbol, Board, TradingTime, and the pointer fields Ceiling, Floor, RefPrice (*float64).

OrderStatusMessage

Order status event (order.<account>, eventType orderEvent).

FieldType
Type, AccountNo, ClientRequestID, OrderID, Symbolstring / typed ids
Side, OrderType, Statustyped (trading.OrderSide, OrderType, OrderStatus)
Pricefloat64
PriceText, AvgPriceTextstring
AvgPricefloat64
Quantity, OSQuantity, FilledQuantity, CancelQuantitynumeric
InputTime, ModifiedTime, Messagestring
RejectReason, ErrorCode, ErrorMessagestring
SystemRequestID, NotifyID, ConnectionIDstring

Note the exact names: OSQuantity (not OsQuantity) and ModifiedTime (not ModifyTime).

OrderMatchMessage

Fill event (eventType orderMatchEvent; handler SetOnOrderMatch).

Type, NotifyID, ConnectionID, ClientRequestID, OrderID, Symbol, Side, AccountNo, MatchPrice (float64), MatchPriceText, MatchQty (int), MatchTime

PortfolioMessage

Position update, derivative accounts only (eventType clientPortfolioEvent; handler SetOnPortfolio).

FieldTypeDescription
Type, AccountNo, Symbol, PositionTypestringIdentification
LongQty, ShortQty, Net, BidAvgPrice, AskAvgPrice, TradePrice, MarketPrice, FloatingPL, TradingPL*float64Position values, nil when not sent
TotalAsset, CashBalance, StockValue*float64Always nil: the server never sends them. Do not rely on them

FCOOrderUpdateMessage

Real-time conditional (FCO) order status update, received via SetOnTrading or SetOnOrder when EventType == "fcoEvent".

FieldTypeDescription
FCOIDstringFCO order ID
ProcessStatusFCOStatusFCO processing status (INIT, WAIT, WC, TER, ...)
MatchedQuantityintMatched quantity
IsPlaceOrderboolWhether the underlying order has been placed
SymbolstringStock symbol
QuantityintOrder quantity
PricestringOrder price
AccountNostringAccount number
UpdatedTimestringUpdate time
StatusstringStatus code
MessagestringDetail message
UsernamestringUsername that placed the order
EventTypestringEvent type ("fcoEvent")
Typetrading.FCOTypeConditional order type (GTD, Stop, ...). The field is Type, not FCOType

IntervalMessage

Candle for trade.<symbol>@1m|@5m and trade.index.<code>@1m|@5m.

FieldTypeDescription
Typestream.DataTypetrade
IntervalTimestringStart time of the candle (key st)
TradingTimestringTrading time (key t)
SymbolstringCode
Openfloat64Open price
Highfloat64High price
Lowfloat64Low price
Closefloat64Close price
VolumeintVolume

IndexTickMessage

Tick of the index itself (trade.index.<CODE>, also with the @tick suffix). See index subscriptions.

Not verified. The server sends abbreviated keys only; the meaning of each field was inferred by the SDK from the abbreviation, not confirmed by server documentation. If you need to be sure, read Raw (a copy of the original object).

FieldTypeSource keyNote (inferred)
Typestream.DataType—Always trade
SymbolstringsIndex code
BoardstringbBoard
StatusstringssStatus
TradingTimestringtTrading time
Value*float64vIndex value
Change*float64cChange
ChangePercent*float64crChange in %
Advances / Declines / NoChange*float64adv / dec / ncNumber of symbols up / down / unchanged
Ceilings / Floors*float64ce / flNumber of symbols at ceiling / floor
TotalMatchValue / TotalMatchQuantity*float64tmv / tmqTotal matched value / quantity
TotalPutValue / TotalPutQuantity*float64tvp / tqpTotal put-through value / quantity
TotalQuantity / TotalValue*float64tq / tvTotal quantity / value
Rawmap[string]interface{}—The original object the server sent

IndexSummaryMessage

Index summary (indexsummary.<CODE>; handler SetOnIndexSummary).

Field / methodTypeDescription
IndexstringIndex code, taken from the topic, upper-case
Datamap[string]interface{}The content the server sent, untouched. The public documentation does not list the fields, so the SDK does not guess
Get(keys ...string)interface{}Returns the value of the first key present in Data, or nil

MarketFlagMessage

Session flag (market.flag; handler SetOnMarketFlag).

FieldTypeDescription
BoardstringHOSE, HNX, UPCOM or DER (derivatives), exactly as the server sends it
TradingTimestringTime
FlagstringSession flag (ATO, LO, ATC...)

HeartbeatMessage

Method, Channel, Status, Message

ConnectionEvent

Package transport. Passed to SetOnConnection.

FieldTypeDescription
Statestring"connected", "reconnected", "disconnected" or "failed"
ReconnectCountintHow many times the connection was re-established
ErrerrorReason, when there is one

Trading WebSocket Models

See Trading WebSocket. Order, FCO place and cancel calls reuse the REST types (PlaceOrderResponse, ModifyOrderResponse, CancelOrderResponse, FCOPlaceResponse, FCOCancelResponse, BatchPlaceOrderItem, BatchCancelOrderItem).

tradingws.Response

Returned by the batch, list and query methods.

FieldTypeDescription
IDstringCommand id
MethodstringMethod name, for example query.orderBook
StatusintStatus of the frame
Resultinterface{}Result, usually a map[string]interface{}
RateLimitmap[string]interface{}Quota reported by the server (remaining, resetMs, ...)
ReceivedTimeinterface{}Value of the frame's receivedTime key, if any

tradingws.OrderBookQuery

FieldTypeDescription
AccountNostringAccount number
FromDate / ToDatestringFormat YYYY/MM/DD, ToDate not before FromDate
SymbolstringSymbol
OrderStatustrading.OrderStatusFilter by status
PageIndexintPage, 1-based
PageSizeintPage size

Empty or zero fields are omitted from the request.

Events from the socket arrive at Client().SetOnEvent(...) as map[string]interface{} frames with channel, topic and data (data.eventType: orderEvent, orderMatchEvent, clientPortfolioEvent).

Wrapper Types

AccountBalance

FieldTypeDescription
Equity*EquityAccountBalanceEquity account balance
Derivative*DerivativeAccountBalanceDerivative account balance

Position

FieldTypeDescription
Equity[]EquityPositionEquity positions
Derivative*AllDerivativePositionAll derivative positions

AllDerivativePosition

FieldTypeDescription
OpenPositions[]DerivativePositionOpen positions
ClosedPositions[]DerivativePositionClosed positions
AccountNostringAccount number

PPMMR

FieldTypeDescription
Equity*EquityPPMMREquity PPMMR
Derivative*DerivativePPMMRDerivative PPMMR

On this page