Documentation ¶
Overview ¶
Package longbridge implements the long bridge trading and quote API. It provides two clients, TradeClient and QuoteClient, to access trading service and quote service respectively. The API implementation strictly follows the document at https://open.longbridgeapp.com/docs. For each exported API, we have related short test examples. To run the examples, set the environment variables for LB_APP_KEY, LB_APP_SECRET, and LB_ACCESS_TOKEN obtained from long bridge developer center page.
For debugging, set -logtostderr and -v=<log level> to print out the internal protocol flow to console. In the implementation, glog is used to print different level of logging information. The log level rule is:
Without V(n), show the log that are essential to be known by caller. V(2) for normal verbose notification for error cases. V(3) for deubgging information and consists detailed variable information. V(4) for high frequency repeated debugging information.
Index ¶
- Constants
- Variables
- type AccessTokenInfo
- type AdjustType
- type AssetType
- type Balance
- type Broker
- type BrokerInfo
- type BrokerQueue
- type CapDistribution
- type CapFlowDistribution
- type Cash
- type Cashflow
- type CashflowDirection
- type CashflowReq
- type Config
- type FinanceIndex
- type FundPosition
- type GetHistoryOrderFillsReq
- type GetHistoryOrdersReq
- type GetTodayOrderFillsReq
- type GetTodyOrdersReq
- type IntradayCapFlow
- type IntradayLine
- type Issuer
- type KLine
- type KLineType
- type Language
- type MarginRatio
- type Market
- type MarketSession
- type MarketTradePeriod
- type ModifyOrderReq
- type OptionExtend
- type Order
- type OrderBook
- type OrderBookList
- type OrderFill
- type OrderStatus
- type OrderTag
- type OrderType
- type OutsideRTH
- type PlaceOrderReq
- type PostMarketQuote
- type PreMarketQuote
- type PushBrokers
- type PushOrderBook
- type PushQuote
- type PushTickers
- type QotSubscription
- type QuoteClient
- func (c *QuoteClient) Close()
- func (c QuoteClient) GetBrokerInfo() ([]*BrokerInfo, error)
- func (c QuoteClient) GetBrokerQueue(symbol Symbol) (*BrokerQueue, error)
- func (c QuoteClient) GetFinanceIndices(symbols []Symbol, indices []FinanceIndex) ([]*SecurityFinanceIndex, error)
- func (c QuoteClient) GetIntradayCapFlowDistribution(symbol Symbol) (*CapFlowDistribution, error)
- func (c QuoteClient) GetIntradayCapFlows(symbol Symbol) ([]*IntradayCapFlow, error)
- func (c QuoteClient) GetIntradayLines(symbol Symbol) ([]*IntradayLine, error)
- func (c QuoteClient) GetKLines(symbol Symbol, klType KLineType, count int32, adj AdjustType) ([]*KLine, error)
- func (c QuoteClient) GetMarketTradePeriods() ([]*MarketTradePeriod, error)
- func (c QuoteClient) GetOptionExpiryDates(symbol Symbol) ([]string, error)
- func (c QuoteClient) GetOptionStrikePrices(symbol Symbol, expiry string) ([]*StrikePriceInfo, error)
- func (c QuoteClient) GetOrderBookList(symbol Symbol) (*OrderBookList, error)
- func (c QuoteClient) GetRealtimeOptionQuote(symbols []Symbol) ([]*RealtimeOptionQuote, error)
- func (c QuoteClient) GetRealtimeQuote(symbols []Symbol) ([]*RealTimeQuote, error)
- func (c QuoteClient) GetRealtimeWarrantQuote(symbols []Symbol) ([]*RealtimeWarrantQuote, error)
- func (c QuoteClient) GetStaticInfo(symbols []Symbol) ([]*StaticInfo, error)
- func (c QuoteClient) GetSubscriptions() ([]*QotSubscription, error)
- func (c QuoteClient) GetTickers(symbol Symbol, count int) ([]*Ticker, error)
- func (c QuoteClient) GetTradeDates(market Market, begin string, end string) ([]TradeDate, error)
- func (c QuoteClient) GetWarrantIssuers() ([]*Issuer, error)
- func (c *QuoteClient) GetWatchedGroups() ([]*WatchedGroup, error)
- func (c QuoteClient) RefreshAccessToken(expire time.Time) (*AccessTokenInfo, error)
- func (c QuoteClient) SearchWarrants(cond *WarrantFilter) ([]*Warrant, error)
- func (c QuoteClient) SubscribePush(symbols []Symbol, subTypes []SubscriptionType, needFirstPush bool) ([]*QotSubscription, error)
- func (c QuoteClient) UnsubscribePush(symbols []Symbol, subTypes []SubscriptionType, all bool) error
- type RealTimeQuote
- type RealtimeOptionQuote
- type RealtimeWarrantQuote
- type Request
- type RiskLevel
- type SecurityFinanceIndex
- type StaticInfo
- type StockPosition
- type StrikePriceInfo
- type SubscriptionType
- type Symbol
- type Ticker
- type TimeInForce
- type TradeClient
- func (c *TradeClient) CancelOrder(orderID string) error
- func (c *TradeClient) Close()
- func (c TradeClient) Enable(enable bool)
- func (c *TradeClient) GetAccountBalances() ([]*Balance, error)
- func (c *TradeClient) GetCashflows(r *CashflowReq) ([]*Cashflow, error)
- func (c *TradeClient) GetFundPositions(fundSymbols ...Symbol) ([]*FundPosition, error)
- func (c *TradeClient) GetHistoryOrderFills(r *GetHistoryOrderFillsReq) ([]*OrderFill, error)
- func (c *TradeClient) GetHistoryOrders(r *GetHistoryOrdersReq) ([]*Order, error)
- func (c *TradeClient) GetMarginRatio(symbol Symbol) (*MarginRatio, error)
- func (c *TradeClient) GetStockPositions(symbols ...Symbol) ([]*StockPosition, error)
- func (c *TradeClient) GetTodayOrderFills(r *GetTodayOrderFillsReq) ([]*OrderFill, error)
- func (c *TradeClient) GetTodayOrders(r *GetTodyOrdersReq) ([]*Order, error)
- func (c *TradeClient) ModifyOrder(r *ModifyOrderReq) error
- func (c *TradeClient) PlaceOrder(r *PlaceOrderReq) (string, error)
- func (c TradeClient) RefreshAccessToken(expire time.Time) (*AccessTokenInfo, error)
- func (c TradeClient) Subscribe(topics []string) error
- func (c TradeClient) Unsubscribe(topics []string) error
- type TradeDate
- type TradeDir
- type TradeSessionType
- type TradeStatus
- type TrdSide
- type TriggerStatus
- type Warrant
- type WarrantExtended
- type WarrantFilter
- type WatchedGroup
- type WatchedSecurity
Examples ¶
- QuoteClient.GetBrokerInfo
- QuoteClient.GetBrokerQueue
- QuoteClient.GetFinanceIndices
- QuoteClient.GetIntradayCapFlowDistribution
- QuoteClient.GetIntradayCapFlows
- QuoteClient.GetIntradayLines
- QuoteClient.GetKLines
- QuoteClient.GetMarketTradePeriods
- QuoteClient.GetOptionExpiryDates
- QuoteClient.GetOptionStrikePrices
- QuoteClient.GetOrderBookList
- QuoteClient.GetRealtimeOptionQuote
- QuoteClient.GetRealtimeQuote
- QuoteClient.GetRealtimeWarrantQuote
- QuoteClient.GetStaticInfo
- QuoteClient.GetSubscriptions
- QuoteClient.GetTickers
- QuoteClient.GetTradeDates
- QuoteClient.GetWarrantIssuers
- QuoteClient.GetWatchedGroups
- QuoteClient.SearchWarrants
- QuoteClient.SubscribePush
- TradeClient.CancelOrder
- TradeClient.Enable
- TradeClient.GetAccountBalances
- TradeClient.GetCashflows
- TradeClient.GetFundPositions
- TradeClient.GetHistoryOrderFills
- TradeClient.GetHistoryOrders
- TradeClient.GetMarginRatio
- TradeClient.GetStockPositions
- TradeClient.GetTodayOrderFills
- TradeClient.GetTodayOrders
- TradeClient.ModifyOrder
- TradeClient.PlaceOrder
Constants ¶
const ( LimitOrder OrderType = "LO" EnhancedLimitOrder OrderType = "ELO" MarketOrder OrderType = "MO" AtAuctionMarketOrder OrderType = "AO" AtAuctionLimitOrder OrderType = "ALO" OddLotsOrder OrderType = "ODD" // 碎股單掛單 LimitIfTouched OrderType = "LIT" // 觸價限價單 MarketIfTouched OrderType = "MIT" // 觸價市價單 TSLPAMT OrderType = "TSLPAMT" // Trailing Limit If Touched (Trailing Amount) 跟蹤止損限價單 (跟蹤金额) TSLPPCT OrderType = "TSLPPCT" // Trailing Limit If Touched (Trailing Percent) 跟蹤止損限價單 (跟蹤漲跌幅) TSMAMT OrderType = "TSMAMT" // Trailing Market If Touched (Trailing Amount) 跟蹤止損市價單 (跟蹤金额) TSMPCT OrderType = "TSMPCT" // Trailing Market If Touched (Trailing Percent) 跟蹤止損市價單 (跟蹤漲跌幅) Buy TrdSide = "Buy" Sell TrdSide = "Sell" DayOrder TimeInForce = "Day" // 當日有效 GoodTilCancel TimeInForce = "GTC" // 撤單前有效 GoodTilDate TimeInForce = "GTD" // 到期前有效 RTHOnly OutsideRTH = "RTH_ONLY" // Regular trading hour only AnyTime OutsideRTH = "ANY_TIME" NotReported OrderStatus = "NotReported" // 待提交 ReplacedNotReported OrderStatus = "ReplacedNotReported" // 待提交 (改單成功) ProtectedNotReported OrderStatus = "ProtectedNotReported" // 待提交 (保價訂單) VarietiesNotReported OrderStatus = "VarietiesNotReported" // 待提交 (條件單) FilledStatus OrderStatus = "FilledStatus" // 已成交 WaitToNew OrderStatus = "WaitToNew" // 已提待報 NewStatus OrderStatus = "NewStatus" // 已委托 WaitToReplace OrderStatus = "WaitToReplace" // 修改待報 PendingReplaceStatus OrderStatus = "PendingReplaceStatus" // 待修改 ReplacedStatus OrderStatus = "ReplacedStatus" // 已修改 PartialFilledStatus OrderStatus = "PartialFilledStatus" // 部分成交 WaitToCancel OrderStatus = "WaitToCancel" // 撤銷待報 PendingCancelStatus OrderStatus = "PendingCancelStatus" // 待撤回 RejectedStatus OrderStatus = "RejectedStatus" // 已拒絕 CanceledStatus OrderStatus = "CanceledStatus" // 已撤單 ExpiredStatus OrderStatus = "ExpiredStatus" // 已過期 PartialWithdrawal OrderStatus = "PartialWithdrawal" // 部分撤單 NormalOrder OrderTag = "Normal" // Normal order GTCOrder OrderTag = "GTC" // Long term order GreyOrder OrderTag = "Grey" // Grey order 暗盤單 NotUsed TriggerStatus = "NOT_USED" // 未激活 Deactive TriggerStatus = "DEACTIVE" Active TriggerStatus = "ACTIVE" Released TriggerStatus = "RELEASED" // 已觸發 )
const ( TradeStatusNormal = TradeStatus(quote.TradeStatus_NORMAL) TradeStatusHalted = TradeStatus(quote.TradeStatus_HALTED) TradeStatusDelisted = TradeStatus(quote.TradeStatus_DELISTED) TradeStatusFuse = TradeStatus(quote.TradeStatus_FUSE) TradeStatusPrepareList = TradeStatus(quote.TradeStatus_PREPARE_LIST) TradeStatusCodeMoved = TradeStatus(quote.TradeStatus_CODE_MOVED) TradeStatusToBeOpened = TradeStatus(quote.TradeStatus_TO_BE_OPENED) TradeStatusSlitStockHalts = TradeStatus(quote.TradeStatus_SPLIT_STOCK_HALTS) TradeStatusExpired = TradeStatus(quote.TradeStatus_EXPIRED) TradeStatusWarrantPrepareList = TradeStatus(quote.TradeStatus_WARRANT_PREPARE_LIST) TradeStatusSuspendTrade = TradeStatus(quote.TradeStatus_SUSPEND_TRADE) )
const ( DirNeutral = TradeDir(0) DirDown = TradeDir(1) DirUp = TradeDir(2) )
const ( NormalTradingSession = TradeSessionType(quote.TradeSession_NORMAL_TRADE) PreTradingSession = TradeSessionType(quote.TradeSession_PRE_TRADE) PostTradingSession = TradeSessionType(quote.TradeSession_POST_TRADE) )
const ( KLine1M = KLineType(quote.Period_ONE_MINUTE) KLine5M = KLineType(quote.Period_FIVE_MINUTE) KLine15M = KLineType(quote.Period_FIFTEEN_MINUTE) KLine30M = KLineType(quote.Period_THIRTY_MINUTE) KLine60M = KLineType(quote.Period_SIXTY_MINUTE) KLineDay = KLineType(quote.Period_DAY) KLineWeek = KLineType(quote.Period_WEEK) KLineMonth = KLineType(quote.Period_MONTH) KLineYear = KLineType(quote.Period_YEAR) )
const ( AdjustNone = AdjustType(quote.AdjustType_NO_ADJUST) AdjustFwd = AdjustType(quote.AdjustType_FORWARD_ADJUST) )
const ( SubscriptionRealtimeQuote = SubscriptionType(quote.SubType_QUOTE) SubscriptionOrderBook = SubscriptionType(quote.SubType_DEPTH) SubscriptionBrokerQueue = SubscriptionType(quote.SubType_BROKERS) SubscriptionTicker = SubscriptionType(quote.SubType_TRADE) )
Variables ¶
var ( // OrderTypes includes all order types in predefined order. OrderTypes = []OrderType{ MarketOrder, LimitOrder, EnhancedLimitOrder, AtAuctionMarketOrder, AtAuctionLimitOrder, OddLotsOrder, LimitIfTouched, MarketIfTouched, TSLPAMT, TSLPPCT, TSMAMT, TSMPCT, } )
Functions ¶
This section is empty.
Types ¶
type AccessTokenInfo ¶
type AccessTokenInfo struct { Code int `json:"code"` Message string `json:"message"` Data struct { Token string `json:"token"` ExpiredAt time.Time `json:"expired_at"` IssuedAt time.Time `json:"issued_at"` AccountInfo struct { MemberID string `json:"member_id"` Aaid string `json:"aaid"` AccountChannel string `json:"account_channel"` } `json:"account_info"` } `json:"data"` }
type AdjustType ¶
type AdjustType int32
type BrokerInfo ¶
type BrokerQueue ¶
type CapDistribution ¶
type CapFlowDistribution ¶
type CapFlowDistribution struct { Symbol Symbol Timestamp int64 InFlow CapDistribution OutFlow CapDistribution }
type CashflowDirection ¶
type CashflowDirection int
const ( Outflow CashflowDirection = iota + 1 Inflow )
type CashflowReq ¶
type CashflowReq struct { StartTimestamp int64 EndTimestamp int64 BusinessType AssetType Symbol Symbol // Page is start page (>= 1), default is 1. Page uint64 // Size is page size (1 ~ 10000), default is 50. Size uint64 // IsAll indicates if get all cash flows. Default is get cash flows in current page. IsAll bool }
CashflowReq is the request to get cash flows. Only field StartTimestamp and EndTimestamp are required.
type Config ¶
type Config struct { AccessToken string // Required AppKey string // Required AppSecret string // Required BaseURL string // Optional, if not set, use default base URL https://openapi.longbridgeapp.com TradeEndpoint string // Optional, if not set, use wss://openapi-trade.longbridgeapp.com QuoteEndpoint string // Optional, if not set, use wss://openapi-quote.longbridgeapp.com ReconnectInterval int // Optional, if not set, use default 3 seconds for reconnecting to the above endpoints }
Config contains the network address and the necessary credential information for accessing long bridge service.
type FinanceIndex ¶
const ( IndexUnknown FinanceIndex = quote.CalcIndex_CALCINDEX_UNKNOWN IndexLastDone FinanceIndex = quote.CalcIndex_CALCINDEX_LAST_DONE IndexChangeVal FinanceIndex = quote.CalcIndex_CALCINDEX_CHANGE_VAL IndexChangeRate FinanceIndex = quote.CalcIndex_CALCINDEX_CHANGE_RATE IndexVolume FinanceIndex = quote.CalcIndex_CALCINDEX_VOLUME IndexTurnover FinanceIndex = quote.CalcIndex_CALCINDEX_TURNOVER IndexYtdChange_RATE FinanceIndex = quote.CalcIndex_CALCINDEX_YTD_CHANGE_RATE IndexTurnoverRate FinanceIndex = quote.CalcIndex_CALCINDEX_TURNOVER_RATE IndexTotalMarket_VALUE FinanceIndex = quote.CalcIndex_CALCINDEX_TOTAL_MARKET_VALUE IndexCapitalFlow FinanceIndex = quote.CalcIndex_CALCINDEX_CAPITAL_FLOW IndexAmplitude FinanceIndex = quote.CalcIndex_CALCINDEX_AMPLITUDE IndexVolumeRatio FinanceIndex = quote.CalcIndex_CALCINDEX_VOLUME_RATIO IndexPeTtm_RATIO FinanceIndex = quote.CalcIndex_CALCINDEX_PE_TTM_RATIO IndexPbRatio FinanceIndex = quote.CalcIndex_CALCINDEX_PB_RATIO IndexDividendRatio_TTM FinanceIndex = quote.CalcIndex_CALCINDEX_DIVIDEND_RATIO_TTM IndexFiveDay_CHANGE_RATE FinanceIndex = quote.CalcIndex_CALCINDEX_FIVE_DAY_CHANGE_RATE IndexTenDay_CHANGE_RATE FinanceIndex = quote.CalcIndex_CALCINDEX_TEN_DAY_CHANGE_RATE IndexHalfYear_CHANGE_RATE FinanceIndex = quote.CalcIndex_CALCINDEX_HALF_YEAR_CHANGE_RATE IndexFiveMinutes_CHANGE_RATE FinanceIndex = quote.CalcIndex_CALCINDEX_FIVE_MINUTES_CHANGE_RATE IndexExpiryDate FinanceIndex = quote.CalcIndex_CALCINDEX_EXPIRY_DATE IndexStrikePrice FinanceIndex = quote.CalcIndex_CALCINDEX_STRIKE_PRICE IndexUpperStrike_PRICE FinanceIndex = quote.CalcIndex_CALCINDEX_UPPER_STRIKE_PRICE IndexLowerStrike_PRICE FinanceIndex = quote.CalcIndex_CALCINDEX_LOWER_STRIKE_PRICE IndexOutstandingQty FinanceIndex = quote.CalcIndex_CALCINDEX_OUTSTANDING_QTY IndexOutstandingRatio FinanceIndex = quote.CalcIndex_CALCINDEX_OUTSTANDING_RATIO IndexPremium FinanceIndex = quote.CalcIndex_CALCINDEX_PREMIUM IndexItmOtm FinanceIndex = quote.CalcIndex_CALCINDEX_ITM_OTM IndexImpliedVolatility FinanceIndex = quote.CalcIndex_CALCINDEX_IMPLIED_VOLATILITY IndexWarrantDelta FinanceIndex = quote.CalcIndex_CALCINDEX_WARRANT_DELTA IndexCallPrice FinanceIndex = quote.CalcIndex_CALCINDEX_CALL_PRICE IndexToCall_PRICE FinanceIndex = quote.CalcIndex_CALCINDEX_TO_CALL_PRICE IndexEffectiveLeverage FinanceIndex = quote.CalcIndex_CALCINDEX_EFFECTIVE_LEVERAGE IndexLeverageRatio FinanceIndex = quote.CalcIndex_CALCINDEX_LEVERAGE_RATIO IndexConversionRatio FinanceIndex = quote.CalcIndex_CALCINDEX_CONVERSION_RATIO IndexBalancePoint FinanceIndex = quote.CalcIndex_CALCINDEX_BALANCE_POINT IndexOpenInterest FinanceIndex = quote.CalcIndex_CALCINDEX_OPEN_INTEREST IndexDelta FinanceIndex = quote.CalcIndex_CALCINDEX_DELTA IndexGamma FinanceIndex = quote.CalcIndex_CALCINDEX_GAMMA IndexTheta FinanceIndex = quote.CalcIndex_CALCINDEX_THETA IndexVega FinanceIndex = quote.CalcIndex_CALCINDEX_VEGA IndexRho FinanceIndex = quote.CalcIndex_CALCINDEX_RHO )
type FundPosition ¶
type GetHistoryOrderFillsReq ¶
GetHistoryOrderFillsReq is a request to get history order fills (executions).
type GetHistoryOrdersReq ¶
type GetHistoryOrdersReq struct { Symbol Symbol Status []OrderStatus Side TrdSide Market Market StartTimestamp int64 EndTimestamp int64 }
GetHistoryOrdersReq is the request to get history orders. All fields are optional.
type GetTodayOrderFillsReq ¶
GetTodayOrderFillsReq is a request to get today's order fills (executions). All fields are optional filters.
type GetTodyOrdersReq ¶
type GetTodyOrdersReq struct { Symbol Symbol Status []OrderStatus Side TrdSide Market Market OrderID uint64 }
GetTodyOrdersReq is the request to get today orders. All fields are optional.
type IntradayCapFlow ¶
type IntradayLine ¶
type MarginRatio ¶
type MarketSession ¶
type MarketSession struct { SessionType TradeSessionType BeginTime int32 // The time is encoded with int as HHMM, e.g., 930 means 9:30am, and it is in the corresponding market timezone. EndTime int32 }
type MarketTradePeriod ¶
type MarketTradePeriod struct { Market Market TradeSessions []*MarketSession }
type ModifyOrderReq ¶
type ModifyOrderReq struct { OrderID string // Required Quantity uint64 // Required // Price is optional, required for order of type LO/ELO/ALO/ODD/LIT Price float64 TriggerPrice float64 LimitOffset float64 TrailingAmount float64 TrailingPercent float64 Remark string // Max 64 characters }
ModifyOrderReq is a request to modify order.
type OptionExtend ¶
type Order ¶
type Order struct { Currency string // Required ExecutedPrice float64 ExecutedQuantity uint64 ExpireDate string // In format of 'YYYY-MM-DD' if provided LastDone string LimitOffset float64 Msg string OrderID uint64 // Required OrderType OrderType // Required OutsideRTH OutsideRTH Price float64 Quantity uint64 // Required Side TrdSide // Required Status OrderStatus // Required StockName string // Required SubmittedTimestamp int64 // Required Symbol Symbol // Required Tag OrderTag // Required TimeInForce TimeInForce // Required TrailingAmount float64 TrailingPercent float64 TriggerTimestamp int64 TriggerPrice float64 TriggerStatus TriggerStatus UpdatedTimestamp int64 }
type OrderBookList ¶
type OrderStatus ¶
type OrderStatus string
type OutsideRTH ¶
type OutsideRTH string // Outside regular trading hours
type PlaceOrderReq ¶
type PlaceOrderReq struct { // Stock symbol: Required, use ticker.region format, example: AAPL.US Symbol Symbol // Order type: Required OrderType OrderType Price float64 // For limit order (LO, ELO, ALO) // Quantity: Required Quantity uint64 TriggerPrice float64 LimitOffset float64 TrailingAmount float64 TrailingPercent float64 // Expire date (in timezone HKT or EDT) for long term order ExpireDate time.Time // Trade side: Required Side TrdSide OutsideRTH OutsideRTH // Time in force: Required TimeInForce TimeInForce Remark string // Max 64 characters }
PlaceOrderReq is a request to place order. Fields are optional unless marked as 'Required'.
type PostMarketQuote ¶
type PreMarketQuote ¶
type PushBrokers ¶
type PushOrderBook ¶
type PushTickers ¶
type QotSubscription ¶
type QotSubscription struct { Symbol Symbol Subscriptions []SubscriptionType }
type QuoteClient ¶
type QuoteClient struct {
// contains filtered or unexported fields
}
func NewQuoteClient ¶
func NewQuoteClient(conf *Config) (*QuoteClient, error)
func (*QuoteClient) Close ¶
func (c *QuoteClient) Close()
func (QuoteClient) GetBrokerInfo ¶
func (c QuoteClient) GetBrokerInfo() ([]*BrokerInfo, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() bs, err := c.GetBrokerInfo() if err != nil { log.Fatalf("Error getting broker queue for: %v", err) } for _, b := range bs { log.Printf("%#v", b) }
Output:
func (QuoteClient) GetBrokerQueue ¶
func (c QuoteClient) GetBrokerQueue(symbol Symbol) (*BrokerQueue, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() bq, err := c.GetBrokerQueue("5.HK") if err != nil { log.Fatalf("Error getting broker queue for: %v", err) } log.Printf("%s\n", bq.Symbol) for _, bid := range bq.Bid { log.Printf("%#v\n", bid) } for _, ask := range bq.Ask { log.Printf("%#v\n", ask) }
Output:
func (QuoteClient) GetFinanceIndices ¶
func (c QuoteClient) GetFinanceIndices(symbols []Symbol, indices []FinanceIndex) ([]*SecurityFinanceIndex, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() fs, err := c.GetFinanceIndices([]longbridge.Symbol{"700.HK", "5.HK"}, []longbridge.FinanceIndex{longbridge.IndexLastDone, longbridge.IndexBalancePoint, longbridge.IndexCapitalFlow, longbridge.IndexExpiryDate}) if err != nil { log.Fatalf("Error getting intraday capital flow distribution: %v", err) } for _, f := range fs { log.Printf("%+v", f) }
Output:
func (QuoteClient) GetIntradayCapFlowDistribution ¶
func (c QuoteClient) GetIntradayCapFlowDistribution(symbol Symbol) (*CapFlowDistribution, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() cd, err := c.GetIntradayCapFlowDistribution("700.HK") if err != nil { log.Fatalf("Error getting intraday capital flow distribution: %v", err) } log.Printf("%+v", cd)
Output:
func (QuoteClient) GetIntradayCapFlows ¶
func (c QuoteClient) GetIntradayCapFlows(symbol Symbol) ([]*IntradayCapFlow, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() fs, err := c.GetIntradayCapFlows("700.HK") if err != nil { log.Fatalf("Error getting intraday capital flow: %v", err) } for _, f := range fs { log.Printf("%+v", f) }
Output:
func (QuoteClient) GetIntradayLines ¶
func (c QuoteClient) GetIntradayLines(symbol Symbol) ([]*IntradayLine, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ls, err := c.GetIntradayLines("AAPL.US") if err != nil { log.Fatalf("Error getting tickers for: %v", err) } for _, l := range ls { log.Printf("%#v", l) }
Output:
func (QuoteClient) GetKLines ¶
func (c QuoteClient) GetKLines(symbol Symbol, klType KLineType, count int32, adj AdjustType) ([]*KLine, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ks, err := c.GetKLines("AAPL.US", longbridge.KLine1M, 10, longbridge.AdjustNone) if err != nil { log.Fatalf("Error getting klines: %v", err) } for _, k := range ks { log.Printf("%#v", k) }
Output:
func (QuoteClient) GetMarketTradePeriods ¶
func (c QuoteClient) GetMarketTradePeriods() ([]*MarketTradePeriod, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ms, err := c.GetMarketTradePeriods() if err != nil { log.Fatalf("Error getting market periods: %v", err) } for _, m := range ms { log.Printf("%#v", m.Market) for _, s := range m.TradeSessions { log.Printf("%#v", s) } }
Output:
func (QuoteClient) GetOptionExpiryDates ¶
GetOptionExpiryDates returns the expiry dates for a stock. The dates are encoded as YYMMDD, with timezone related to its corresponding market.
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ks, err := c.GetOptionExpiryDates("AAPL.US") if err != nil { log.Fatalf("Error getting option chain expiry dates: %v", err) } for _, k := range ks { log.Printf("%#v", k) }
Output:
func (QuoteClient) GetOptionStrikePrices ¶
func (c QuoteClient) GetOptionStrikePrices(symbol Symbol, expiry string) ([]*StrikePriceInfo, error)
GetOptionStrikePrices returns the strike price list for a stock's option chain on given expiry date (in YYYYMMDD format).
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ks, err := c.GetOptionStrikePrices("AAPL.US", "20230120") if err != nil { log.Fatalf("Error getting option chain strike price: %v", err) } for _, k := range ks { log.Printf("%#v", k) }
Output:
func (QuoteClient) GetOrderBookList ¶
func (c QuoteClient) GetOrderBookList(symbol Symbol) (*OrderBookList, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ol, err := c.GetOrderBookList("5.HK") if err != nil { log.Fatalf("Error getting order book for: %v", err) } log.Printf("%s\n", ol.Symbol) for _, bid := range ol.Bid { log.Printf("%#v\n", bid) } for _, ask := range ol.Ask { log.Printf("%#v\n", ask) }
Output:
func (QuoteClient) GetRealtimeOptionQuote ¶
func (c QuoteClient) GetRealtimeOptionQuote(symbols []Symbol) ([]*RealtimeOptionQuote, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() qs, err := c.GetRealtimeOptionQuote([]longbridge.Symbol{"AAPL230317P160000.US"}) if err != nil { log.Fatalf("Error getting real time option quote: %v", err) } for _, q := range qs { log.Printf("%#v\n", q) }
Output:
func (QuoteClient) GetRealtimeQuote ¶
func (c QuoteClient) GetRealtimeQuote(symbols []Symbol) ([]*RealTimeQuote, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() qs, err := c.GetRealtimeQuote([]longbridge.Symbol{"5.HK", "MSFT.US"}) if err != nil { log.Fatalf("Error getting real time quote: %v", err) } for _, q := range qs { log.Printf("%#v\n", q) }
Output:
func (QuoteClient) GetRealtimeWarrantQuote ¶
func (c QuoteClient) GetRealtimeWarrantQuote(symbols []Symbol) ([]*RealtimeWarrantQuote, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() qs, err := c.GetRealtimeWarrantQuote([]longbridge.Symbol{"21125.HK"}) if err != nil { log.Fatalf("Error getting real time warrant quote: %v", err) } for _, q := range qs { log.Printf("%#v\n", q) }
Output:
func (QuoteClient) GetStaticInfo ¶
func (c QuoteClient) GetStaticInfo(symbols []Symbol) ([]*StaticInfo, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ss, err := c.GetStaticInfo([]longbridge.Symbol{"700.HK", "AAPL.US"}) if err != nil { log.Fatalf("Error getting static info: %v", err) } for _, s := range ss { log.Printf("%#v\n", s) }
Output:
func (QuoteClient) GetSubscriptions ¶
func (c QuoteClient) GetSubscriptions() ([]*QotSubscription, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ss, err := c.GetSubscriptions() if err != nil { log.Fatalf("Error getting subscription list: %v", err) } for _, s := range ss { log.Printf("%#v", s) }
Output:
func (QuoteClient) GetTickers ¶
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ts, err := c.GetTickers("AAPL.US", 10) if err != nil { log.Fatalf("Error getting tickers for: %v", err) } for _, t := range ts { log.Printf("%#v", t) }
Output:
func (QuoteClient) GetTradeDates ¶
GetTradeDates returns the trading days in given time range for the market. The begin and end are encoded as "20060102" format. The trading days are sorted in ascending time order. Note: The interval cannot be greater than one month. Only supports query data of the most recent year
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ds, err := c.GetTradeDates("HK", "20220530", "20220630") if err != nil { log.Fatalf("Error getting trade date list: %v", err) } for _, d := range ds { log.Printf("%#v", d) }
Output:
func (QuoteClient) GetWarrantIssuers ¶
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() is, err := c.GetWarrantIssuers() if err != nil { log.Fatalf("Error getting warrant issuer list: %v", err) } for _, i := range is { log.Printf("%#v", i) }
Output:
func (*QuoteClient) GetWatchedGroups ¶
func (c *QuoteClient) GetWatchedGroups() ([]*WatchedGroup, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() groups, err := c.GetWatchedGroups() if err != nil { log.Fatalf("Error getting watched groups: %v", err) } for _, g := range groups { log.Printf("%v %v: %v", g.ID, g.Name, g.Securities) }
Output:
func (QuoteClient) RefreshAccessToken ¶
func (c QuoteClient) RefreshAccessToken(expire time.Time) (*AccessTokenInfo, error)
func (QuoteClient) SearchWarrants ¶
func (c QuoteClient) SearchWarrants(cond *WarrantFilter) ([]*Warrant, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() ws, err := c.SearchWarrants(&longbridge.WarrantFilter{ Symbol: "700.HK", Language: longbridge.SimplifiedChinese, SortBy: 0, SortOrder: 1, SortOffset: 1, PageSize: 10, }) if err != nil { log.Fatalf("Error searching warrants: %v", err) } for _, w := range ws { log.Printf("%#v", w) }
Output:
func (QuoteClient) SubscribePush ¶
func (c QuoteClient) SubscribePush(symbols []Symbol, subTypes []SubscriptionType, needFirstPush bool) ([]*QotSubscription, error)
Example ¶
c, err := longbridge.NewQuoteClient(&longbridge.Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() c.OnPushTickers = func(t *longbridge.PushTickers) { log.Printf("Got tickers for %s, seq=%d", t.Symbol, t.Sequence) for _, ticker := range t.Tickers { log.Printf("Ticker: %#v", ticker) } } c.OnPushQuote = func(q *longbridge.PushQuote) { log.Printf("Got realtime quote: %#v", q) } c.OnPushBrokers = func(b *longbridge.PushBrokers) { log.Printf("Got broker list for %s, seq=%d", b.Symbol, b.Sequence) for _, bid := range b.Bid { log.Printf("%#v", bid) } for _, ask := range b.Ask { log.Printf("%#v", ask) } } c.OnPushOrderBook = func(b *longbridge.PushOrderBook) { log.Printf("Got order books for %s, seq=%d", b.Symbol, b.Sequence) for _, bid := range b.Bid { log.Printf("%#v", bid) } for _, ask := range b.Ask { log.Printf("%#v", ask) } } ss, err := c.SubscribePush([]longbridge.Symbol{"AAPL.US"}, []longbridge.SubscriptionType{longbridge.SubscriptionTicker, longbridge.SubscriptionRealtimeQuote, longbridge.SubscriptionOrderBook, longbridge.SubscriptionBrokerQueue}, true) if err != nil { log.Fatalf("Error subscribe quote push: %v", err) } for _, s := range ss { log.Printf("%#v", s) } time.Sleep(30 * time.Second) if err := c.UnsubscribePush(nil, []longbridge.SubscriptionType{longbridge.SubscriptionTicker, longbridge.SubscriptionRealtimeQuote, longbridge.SubscriptionOrderBook, longbridge.SubscriptionBrokerQueue}, true); err != nil { log.Fatalf("Error unsubscribing all symbols' quote push: %v", err) }
Output:
func (QuoteClient) UnsubscribePush ¶
func (c QuoteClient) UnsubscribePush(symbols []Symbol, subTypes []SubscriptionType, all bool) error
Unsubscribe clears the subscription given by symbols. If symbols is empty and all is true, it will clear the requested subscriptions for all subscribed symbols.
type RealTimeQuote ¶
type RealtimeOptionQuote ¶
type RealtimeWarrantQuote ¶
type SecurityFinanceIndex ¶
type SecurityFinanceIndex struct { Symbol Symbol LastDone float64 ChangeVal float64 ChangeRate float64 Volume int64 Turnover float64 YtdChangeRate float64 TurnoverRate float64 TotalMarketValue float64 CapitalFlow float64 Amplitude float64 VolumeRatio float64 PeTtmRatio float64 PbRatio float64 DividendRatioTtm float64 FiveDayChangeRate float64 TenDayChangeRate float64 HalfYearChangeRate float64 FiveMinutesChangeRate float64 ExpiryDate string StrikePrice float64 UpperStrikePrice float64 LowerStrikePrice float64 OutstandingQty int64 OutstandingRatio float64 Premium float64 ItmOtm float64 ImpliedVolatility float64 WarrantDelta float64 CallPrice float64 ToCallPrice float64 EffectiveLeverage float64 LeverageRatio float64 ConversionRatio float64 BalancePoint float64 OpenInterest int64 Delta float64 Gamma float64 Theta float64 Vega float64 Rho float64 }
type StaticInfo ¶
type StockPosition ¶
type StrikePriceInfo ¶
type SubscriptionType ¶
type Symbol ¶
type Symbol string
Symbol is a stock symbol (of format <StockCode>.<Market>) or fund symbol (ISIN format)
func MakeSymbol ¶
MakeSymbol creates a stock symbol from stock code and market.
type TimeInForce ¶
type TimeInForce string
type TradeClient ¶
type TradeClient struct {
// contains filtered or unexported fields
}
func NewTradeClient ¶
func NewTradeClient(conf *Config) (*TradeClient, error)
func (*TradeClient) CancelOrder ¶
func (c *TradeClient) CancelOrder(orderID string) error
CancelOrder cancels an open order.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() orderID, err := c.PlaceOrder(&longbridge.PlaceOrderReq{ Symbol: "AMD.US", OrderType: longbridge.LimitOrder, Price: 180, Quantity: 1, ExpireDate: time.Now().AddDate(0, 1, 0), Side: longbridge.Sell, OutsideRTH: longbridge.AnyTime, TimeInForce: longbridge.GoodTilCancel, Remark: "钓鱼单", }) if err != nil { log.Fatalf("Error placing order: %v", err) } time.Sleep(time.Second) if err := c.CancelOrder(orderID); err != nil { log.Fatalf("Error cancelling submitted order (id: %v): %v", orderID, err) } log.Printf("Order cancelled successfully, ID: %v", orderID)
Output:
func (*TradeClient) Close ¶
func (c *TradeClient) Close()
func (TradeClient) Enable ¶
func (c TradeClient) Enable(enable bool)
Example ¶
// Before running the example, set the access key, app key and app secret in the env. i.e., // export LB_ACCESS_TOKEN="<your access token>" // export LB_APP_KEY="<your app key>" // export LB_APP_SECRET="<your app secret>" // Then run with command to see the detailed log. // go test -v -run ExampleTradeClient_Enable -args -logtostderr -v=4 c, err := NewTradeClient(&Config{ AccessToken: os.Getenv("LB_ACCESS_TOKEN"), AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } c.OnOrderChange = func(order *Order) { log.Printf("Got order: %#v\n", order) } c.Enable(true) time.Sleep(11 * time.Second) log.Println("Start to close subscription") c.Enable(false) time.Sleep(10 * time.Second) log.Println("Start to re-enable subscription") c.Enable(true) time.Sleep(15 * time.Second) log.Println("Closing") c.Close()
Output:
func (*TradeClient) GetAccountBalances ¶
func (c *TradeClient) GetAccountBalances() ([]*Balance, error)
GetAccountBalances get account balances.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() balances, err := c.GetAccountBalances() if err != nil { log.Fatalf("Error getting account balance: %v", err) } for _, b := range balances { log.Printf("%+v", b) }
Output:
func (*TradeClient) GetCashflows ¶
func (c *TradeClient) GetCashflows(r *CashflowReq) ([]*Cashflow, error)
GetCashflows get cash flows of an account.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() cs, err := c.GetCashflows(&longbridge.CashflowReq{ StartTimestamp: time.Now().AddDate(-1, 0, 0).Unix(), EndTimestamp: time.Now().Unix()}) if err != nil { log.Fatalf("Error getting account cash flow: %v", err) } for _, c := range cs { log.Printf("%+v\n", c) }
Output:
func (*TradeClient) GetFundPositions ¶
func (c *TradeClient) GetFundPositions(fundSymbols ...Symbol) ([]*FundPosition, error)
GetFundPositions gets fund positions. Fund symbols are optional.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() positions, err := c.GetFundPositions() if err != nil { log.Fatalf("Error getting fund positions: %v", err) } for _, position := range positions { log.Printf("%+v", position) }
Output:
func (*TradeClient) GetHistoryOrderFills ¶
func (c *TradeClient) GetHistoryOrderFills(r *GetHistoryOrderFillsReq) ([]*OrderFill, error)
GetHistoryOrderFills gets history order fills in ascending trade completion time.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() os, err := c.GetHistoryOrderFills(&longbridge.GetHistoryOrderFillsReq{ Symbol: "", StartTimestamp: time.Now().AddDate(-1, 0, 0).Unix(), EndTimestamp: time.Now().Unix(), }) if err != nil { log.Fatalf("Error getting history order fills: %v", err) } for _, o := range os { log.Printf("%+v\n", o) }
Output:
func (*TradeClient) GetHistoryOrders ¶
func (c *TradeClient) GetHistoryOrders(r *GetHistoryOrdersReq) ([]*Order, error)
GetHistoryOrders get history orders in ascending update time order.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() os, err := c.GetHistoryOrders(&longbridge.GetHistoryOrdersReq{ Symbol: "", Status: nil, Side: "", Market: longbridge.HK, StartTimestamp: time.Now().AddDate(-1, 0, 0).Unix(), EndTimestamp: time.Now().Unix(), }) if err != nil { log.Fatalf("Error getting history orders: %v", err) } for _, o := range os { log.Printf("%+v\n", o) }
Output:
func (*TradeClient) GetMarginRatio ¶
func (c *TradeClient) GetMarginRatio(symbol Symbol) (*MarginRatio, error)
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() mr, err := c.GetMarginRatio("700.HK") if err != nil { log.Fatalf("Error getting margin ratio: %v", err) } log.Printf("%#v", mr)
Output:
func (*TradeClient) GetStockPositions ¶
func (c *TradeClient) GetStockPositions(symbols ...Symbol) ([]*StockPosition, error)
GetStockPositions gets stock positions. If stock symbols are provided, only the positions matching the symbols will be returned. If stocks symbols are left empty, all account positions will be returned.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() positions, err := c.GetStockPositions() if err != nil { log.Fatalf("Error getting stock positions: %v", err) } for _, position := range positions { log.Printf("%+v", position) }
Output:
func (*TradeClient) GetTodayOrderFills ¶
func (c *TradeClient) GetTodayOrderFills(r *GetTodayOrderFillsReq) ([]*OrderFill, error)
GetTodayOrderFills get today order fills in ascending trade done time.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() os, err := c.GetTodayOrderFills(&longbridge.GetTodayOrderFillsReq{ Symbol: "", OrderID: 0, }) if err != nil { log.Fatalf("Error getting today's order fills: %v", err) } for _, o := range os { log.Printf("%+v\n", o) }
Output:
func (*TradeClient) GetTodayOrders ¶
func (c *TradeClient) GetTodayOrders(r *GetTodyOrdersReq) ([]*Order, error)
GetTodayOrders get today orders in ascending update time order.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() os, err := c.GetTodayOrders(&longbridge.GetTodyOrdersReq{ Symbol: "", Status: nil, Side: "", Market: longbridge.US, OrderID: 0, }) if err != nil { log.Fatalf("Error getting today's orders: %v", err) } for _, o := range os { log.Printf("%+v\n", o) }
Output:
func (*TradeClient) ModifyOrder ¶
func (c *TradeClient) ModifyOrder(r *ModifyOrderReq) error
ModifyOrder modifies an order. Order ID and quantity are required.
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() orderID, err := c.PlaceOrder(&longbridge.PlaceOrderReq{ Symbol: "AMD.US", OrderType: longbridge.LimitOrder, Price: 180, Quantity: 1, ExpireDate: time.Now().AddDate(0, 1, 0), Side: longbridge.Sell, OutsideRTH: longbridge.AnyTime, TimeInForce: longbridge.GoodTilCancel, Remark: "钓鱼单", }) if err != nil { log.Fatalf("Error placing order: %v", err) } time.Sleep(time.Second) if err := c.ModifyOrder(&longbridge.ModifyOrderReq{ OrderID: orderID, Quantity: 1, Price: 200, TriggerPrice: 200, }); err != nil { log.Fatalf("Error modifying submitted order (id: %v): %v", orderID, err) } log.Printf("Order modified successfully, ID: %v", orderID)
Output:
func (*TradeClient) PlaceOrder ¶
func (c *TradeClient) PlaceOrder(r *PlaceOrderReq) (string, error)
PlaceOrder places an order. It returns order ID and error (if any).
Example ¶
c, err := longbridge.NewTradeClient(&longbridge.Config{ BaseURL: "https://openapi.longbridgeapp.com", AccessToken: os.Getenv("LB_ACCESS_TOKEN"), QuoteEndpoint: "tcp://openapi-quote.longbridgeapp.com:2020", AppKey: os.Getenv("LB_APP_KEY"), AppSecret: os.Getenv("LB_APP_SECRET"), }) if err != nil { log.Fatalf("Error creating longbridge client: %v", err) } defer c.Close() orderID, err := c.PlaceOrder(&longbridge.PlaceOrderReq{ Symbol: "AMD.US", OrderType: longbridge.LimitOrder, Price: 180, Quantity: 1, ExpireDate: time.Now().AddDate(0, 1, 0), Side: longbridge.Sell, OutsideRTH: longbridge.AnyTime, TimeInForce: longbridge.GoodTilCancel, Remark: "钓鱼单", }) if err != nil { log.Fatalf("Error placing order: %v", err) } log.Printf("Order submitted successfully, ID: %v", orderID)
Output:
func (TradeClient) RefreshAccessToken ¶
func (c TradeClient) RefreshAccessToken(expire time.Time) (*AccessTokenInfo, error)
func (TradeClient) Subscribe ¶
Subscribe subscribes the topic for push notification. Currently for trade API only "private" has effect.
func (TradeClient) Unsubscribe ¶
type TradeSessionType ¶
type TradeSessionType = quote.TradeSession
type TradeStatus ¶
type TradeStatus = quote.TradeStatus
type TriggerStatus ¶
type TriggerStatus string
type Warrant ¶
type Warrant struct { Symbol Symbol Name string LastDone float64 ChangeRate float64 ChangeVal float64 Turnover float64 ExpiryDate string // YYYYMMDD StrikePrice float64 UpperStrikePrice float64 LowerStrikePrice float64 OutstandingQty float64 OutstandingRatio float64 Premium float64 ItmOtm float64 ImpliedVolatility float64 Delta float64 CallPrice float64 EffectiveLeverage float64 LeverageRatio float64 ConversionRatio float64 BalancePoint float64 State string }
type WarrantExtended ¶
type WarrantFilter ¶
type WarrantFilter struct { Symbol Symbol Language Language SortBy int32 SortOrder int32 // 0 Ascending 1 Desending SortOffset int32 PageSize int32 // Up to 500 Type []int32 // optional values: 0 - Call 1 - Put 2 - Bull 3 - Bear 4 - Inline IssuerIDs []int32 // ExpiryDateType can have the following values. // 1 - Less than 3 months // 2 - 3 - 6 months // 3 - 6 - 12 months // 4 - greater than 12 months ExpiryDateType []int32 // Optional values for PriceType // 1 - In bounds // 2 - Out bounds PriceType []int32 // Optional values for Status: // 2 - Suspend trading // 3 - Papare List // 4 - Normal Status []int32 }
WarrantFilter includes the search conditions for warrants. The field defintion can refer to https://open.longbridgeapp.com/en/docs/quote/pull/warrant-filter
type WatchedGroup ¶
type WatchedGroup struct { ID string Name string Securities []*WatchedSecurity }
type WatchedSecurity ¶
func (*WatchedSecurity) String ¶
func (wg *WatchedSecurity) String() string