Documentation
¶
Overview ¶
Package qapi is a light wrapper for the Questrade REST API, written in Go.
Please note this is not an official API wrapper, and is not endorsed by Questrade. Please see http://www.questrade.com/api/home for official documentation.
Index ¶
- type Account
- type AccountBalances
- type Balance
- type Candlestick
- type ChainPerRoot
- type ChainPerStrikePrice
- type Client
- func (c *Client) DeleteOrder(acctNum string, orderID int) error
- func (c *Client) GetAccounts() (int, []Account, error)
- func (c *Client) GetBalances(number string) (AccountBalances, error)
- func (c *Client) GetCandles(id int, start time.Time, end time.Time, interval string) ([]Candlestick, error)
- func (c *Client) GetExecutions(number string, start time.Time, end time.Time) ([]Execution, error)
- func (c *Client) GetMarkets() ([]Market, error)
- func (c *Client) GetOptionChain(id int) ([]OptionChain, error)
- func (c *Client) GetOrderImpact(req OrderRequest) (OrderImpact, error)
- func (c *Client) GetOrders(number string, start time.Time, end time.Time, state string) ([]Order, error)
- func (c *Client) GetOrdersByID(number string, orderIds ...int) ([]Order, error)
- func (c *Client) GetQuote(id int) (Quote, error)
- func (c *Client) GetQuotes(ids ...int) ([]Quote, error)
- func (c *Client) GetServerTime() (time.Time, error)
- func (c *Client) GetSymbols(ids ...int) ([]Symbol, error)
- func (c *Client) Login(practice bool) error
- func (c *Client) PlaceOrder(req OrderRequest) ([]Order, error)
- func (c *Client) RevokeAuth() error
- func (c *Client) SearchSymbols(prefix string, offset int) ([]SymbolSearchResult, error)
- type Execution
- type LoginCredentials
- type Market
- type MinTickData
- type OptionChain
- type OptionContractDeliverables
- type Order
- type OrderImpact
- type OrderLeg
- type OrderRequest
- type Position
- type QuestradeError
- type Quote
- type Symbol
- type SymbolSearchResult
- type UnderlyingMultiplierPair
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Account ¶
type Account struct { // Type of the account (e.g., "Cash", "Margin"). Type string `json:"type"` // Eight-digit account number (e.g., "26598145") // Stored as a string, it's used for making account-related API calls Number string `json:"number"` // Status of the account (e.g., Active). Status string `json:"status"` // Whether this is a primary account for the holder. IsPrimary bool `json:"isPrimary"` // Whether this account is one that gets billed for various expenses such as inactivity fees, market data, etc. IsBilling bool `json:"isBilling"` // Type of client holding the account (e.g., "Individual"). ClientAccountType string `json:"clientAccountType"` }
Account represents an account associated with the user on behalf of which the API client is authorized.
Ref: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts
type AccountBalances ¶
type AccountBalances struct { PerCurrencyBalances []Balance `json:"perCurrencyBalances"` CombinedBalances []Balance `json:"combinedBalances"` SODPerCurrencyBalances []Balance `json:"sodPerCurrencyBalances"` SODCombinedBalances []Balance `json:"sodCombinedBalances"` }
AccountBalances represents per-currency and combined balances for a specified account.
Ref: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts-id-balances
type Balance ¶
type Balance struct { // Currency of the balance figure(e.g., "USD" or "CAD"). Currency string `json:"currency"` // Balance amount. Cash float32 `json:"cash"` // Market value of all securities in the account in a given currency. MarketValue float32 `json:"marketValue"` // Equity as a difference between cash and marketValue properties. TotalEquity float32 `json:"totalEquity"` // Buying power for that particular currency side of the account. BuyingPower float32 `json:"buyingPower"` // Maintenance excess for that particular side of the account. MaintenanceExcess float32 `json:"maintenanceExcess"` // Whether real-time data was used to calculate the above values. IsRealTime bool `json:"isRealTime"` }
Balance belonging to an Account
Ref: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts-id-balances
type Candlestick ¶
type Candlestick struct { // Candlestick start timestamp Start time.Time `json:"start"` // Candlestick end timestamp End time.Time `json:"end"` // Opening price. Open float32 `json:"open"` // High price. High float32 `json:"high"` // Low price. Low float32 `json:"low"` // Closing price. Close float32 `json:"close"` // Trading volume. Volume int `json:"volume"` }
Candlestick represents historical market data in the form of OHLC candlesticks for a specified symbol.
type ChainPerRoot ¶
type ChainPerRoot struct { // Option root symbol. Root string `json:"root"` // Slice of ChainPerStrikePrice elements. ChainPerStrikePrice []ChainPerStrikePrice `json:"chainPerStrikePrice"` // NOTE - This value appears in example API response, but is not documented Multiplier int `json:"multiplier"` }
type ChainPerStrikePrice ¶
type Client ¶
type Client struct { Credentials LoginCredentials SessionTimer *time.Timer RateLimitRemaining int RateLimitReset time.Time // contains filtered or unexported fields }
A client is the structure that will be used to consume the API endpoints. It holds the login credentials, http client/transport, rate limit information, and the login session timer.
func NewClient ¶
NewClient is the factory function for clients - takes a refresh token and logs into either the practice or live server.
func (*Client) DeleteOrder ¶
DeleteOrder - Sends a delete request for the specified order See: http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders-orderid
func (*Client) GetAccounts ¶
GetAccounts returns the logged-in User ID, and a list of accounts belonging to that user.
func (*Client) GetBalances ¶
func (c *Client) GetBalances(number string) (AccountBalances, error)
GetBalances returns the balances for the account with the specified account number
func (*Client) GetCandles ¶
func (c *Client) GetCandles(id int, start time.Time, end time.Time, interval string) ([]Candlestick, error)
GetCandles retrieves historical market data between the start and end dates, in the given data granularity. See: http://www.questrade.com/api/documentation/rest-operations/market-calls/markets-candles-id
func (*Client) GetExecutions ¶
GetExecutions returns the number of executions for a given account between the start and end times If the times are zero-value, then the API will default the start and end times to the beginning and end of the current day.
func (*Client) GetMarkets ¶
GetMarkets retrieves information about supported markets
func (*Client) GetOptionChain ¶
func (c *Client) GetOptionChain(id int) ([]OptionChain, error)
GetOptionChain Retrieves an option chain for a particular underlying symbol. TODO - More comprehensive tests - perhaps I should learn what an option chain is?
func (*Client) GetOrderImpact ¶
func (c *Client) GetOrderImpact(req OrderRequest) (OrderImpact, error)
GetOrderImpact calculates the impact that a given order will have on an account without placing it. See: http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders-impact
func (*Client) GetOrders ¶
func (c *Client) GetOrders(number string, start time.Time, end time.Time, state string) ([]Order, error)
GetOrders returns orders for a specified account. Will return results based on the start and end times, and the order state. Use GetOrdersByID() to retrieve individual order details. If the times are zero-value, then the API will default the start and end times to the beginning and end of the current day. TODO - Verify order state enumeration in accordance with API docs See: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts-id-orders
func (*Client) GetOrdersByID ¶
GetOrdersByID returns the orders specified by the list of OrderID's
func (*Client) GetQuote ¶
GetQuote retrieves a single Level 1 market data quote for a single symbol TODO - Test
func (*Client) GetQuotes ¶
GetQuotes retrieves a single Level 1 market data quote for many symbols TODO - Test
func (*Client) GetServerTime ¶
GetServerTime retrieves the current time on Questrade's server
func (*Client) GetSymbols ¶
GetSymbols returns detailed symbol information for the given symbol ID's
func (*Client) Login ¶
Login takes the refresh token from the client login credentials and exchanges it for an access token. Returns a timer that expires when the login session is over. If the practice flag is true, then the client will log into the practice server. TODO - Return a proper error when login fails with HTTP 400 - Bad Request
func (*Client) PlaceOrder ¶
func (c *Client) PlaceOrder(req OrderRequest) ([]Order, error)
PlaceOrder submits an order request, or an update to an existing order to Questrade See: http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders
func (*Client) RevokeAuth ¶
RevokeAuth revokes authorization of the refresh token NOTE - You will have to create another manual authorization on the Questrade website to use an application again.
func (*Client) SearchSymbols ¶
func (c *Client) SearchSymbols(prefix string, offset int) ([]SymbolSearchResult, error)
SearchSymbols returns symbol search matches for a symbol prefix, at a given offset from the beginning of the search results.
type Execution ¶
type Execution struct { // Execution symbol. Symbol string `json:"symbol"` // Internal symbol identifier SymbolID int `json:"symbolId"` // Execution quantity. Quantity int `json:"quantity"` // Client side of the order to which execution belongs. Side string `json:"side"` // Execution price. Price float32 `json:"price"` // Internal identifier of the execution. ID int `json:"id"` // Internal identifier of the order to which the execution belongs. OrderID int `json:"orderId"` // Internal identifier of the order chain to which the execution belongs. OrderChainID int `json:"orderChainId"` // Identifier of the execution at the market where it originated. ExchangeExecID string `json:"exchangeExecId"` // Execution timestamp. Timestamp time.Time `json:"timestamp"` // Manual notes that may have been entered by Trade Desk staff Notes string `json:"notes"` // Trading venue where execution originated. Venue string `json:"venue"` // Execution cost (price x quantity). TotalCost float32 `json:"totalCost"` // Questrade commission for orders placed with Trade Desk. OrderPlacementCommission float32 `json:"orderPlacementCommission"` // Questrade commission. Commission float32 `json:"commission"` // Liquidity fee charged by execution venue. ExecutionFee float32 `json:"executionFee"` // SEC fee charged on all sales of US securities. SecFee float32 `json:"secFee"` // Additional execution fee charged by TSX (if applicable). CanadianExecutionFee int `json:"canadianExecutionFee"` // Internal identifierof the parent order. ParentID int `json:"parentId"` }
Execution belonging to an Account
Ref: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts-id-executions
type LoginCredentials ¶
type Market ¶
type Market struct { // Market name. Name string `json:"name"` // List of trading venue codes. TradingVenues []string `json:"tradingVenues"` // Default trading venue code. DefaultTradingVenue string `json:"defaultTradingVenue"` // List of primary order route codes. PrimaryOrderRoutes []string `json:"primaryOrderRoutes"` // List of secondary order route codes. SecondaryOrderRoutes []string `json:"secondaryOrderRoutes"` // List of level 1 market data feed codes. Level1Feeds []string `json:"level1Feeds"` // List of level 2 market data feed codes. Level2Feeds []string `json:"level2Feeds"` // Pre-market opening time for current trading date. ExtendedStartTime time.Time `json:"extendedStartTime"` // Regular market opening time for current trading date. StartTime time.Time `json:"startTime"` // Regular market closing time for current trading date. EndTime time.Time `json:"endTime"` // Extended market closing time for current trading date. ExtendedEndTime time.Time `json:"extendedEndTime"` // Currency code (ISO format). Currency string `json:"currency"` // Number of snap quotes that the user can retrieve from a market. SnapQuotesLimit int `json:"snapQuotesLimit"` }
Market represents information about supported markets
type MinTickData ¶
type OptionChain ¶
type OptionChain struct { // Option expiry date. ExpiryDate time.Time `json:"expiryDate"` // Description of the underlying option. Description string `json:"description"` // Primary listing exchange. ListingExchange string `json:"listingExchange"` // Option exercise style (e.g., "American"). OptionExerciseType string `json:"optionExerciseType"` // Slice of ChainPerRoot elements ChainPerRoot []ChainPerRoot `json:"chainPerRoot"` }
Option Chain Ref: www.questrade.com/api/documentation/rest-operations/market-calls/symbols-id-options
type OptionContractDeliverables ¶
type OptionContractDeliverables struct { Underlyings []UnderlyingMultiplierPair `json:"underlyings"` CashInLieu float32 `json:"cashInLieu"` }
type Order ¶
type Order struct { // Internal order identifier. ID int `json:"id"` // Symbol that follows Questrade symbology (e.g., "TD.TO"). Symbol string `json:"symbol"` // Internal symbol identifier. SymbolID int `json:"symbolId"` // Total quantity of the order. TotalQuantity int `json:"totalQuantity"` // Unfilled portion of the order quantity. OpenQuantity int `json:"openQuantity"` // Filled portion of the order quantity. FilledQuantity int `json:"filledQuantity"` // Unfilled portion of the order quantity after cancellation. CanceledQuantity int `json:"canceledQuantity"` // Client view of the order side (e.g., "Buy-To-Open"). Side string `json:"side"` // Order price type (e.g., "Market"). OrderType string `json:"orderType"` // Limit price. LimitPrice float32 `json:"limitPrice"` // Stop price. StopPrice float32 `json:"stopPrice"` // Specifies all-or-none special instruction. IsAllOrNone bool `json:"isAllOrNone"` // Specifies Anonymous special instruction. IsAnonymous bool `json:"isAnonymous"` // Specifies Iceberg special instruction. IcebergQuantity int `json:"icebergQuantity"` // Specifies Minimum special instruction. MinQuantity int `json:"minQuantity"` // Average price of all executions received for this order. AvgExecPrice float32 `json:"avgExecPrice"` // Price of the last execution received for the order in question. LastExecPrice float32 `json:"lastExecPrice"` // See enumerations for all allowed values Source string `json:"source"` // See Order Time In Force section for all allowed values. TimeInForce string `json:"timeInForce"` // Good-Till-Date marker and date parameter GtdDate *time.Time `json:"gtdDate",string` // See Order State section for all allowed values. State string `json:"state"` // Human readable order rejection reason message. ClientReasonStr string `json:"clientReasonStr"` // Internal identifier of a chain to which the order belongs. ChainID int `json:"chainId"` // Order creation time. CreationTime *time.Time `json:"creationTime",string` // Time of the last update. UpdateTime *time.Time `json:"updateTime",string` // Notes that may have been manually added by Questrade staff. Notes string `json:"notes"` // See enumerations for all allowed values PrimaryRoute string `json:"primaryRoute"` // See enumerations for all allowed values SecondaryRoute string `json:"secondaryRoute"` // Order route name. OrderRoute string `json:"orderRoute"` // Venue where non-marketable portion of the order was booked. VenueHoldingOrder string `json:"venueHoldingOrder"` // Total commission amount charged for this order. CommissionCharged float32 `json:"commissionCharged"` // Identifier assigned to this order by exchange where it was routed. ExchangeOrderID string `json:"exchangeOrderId"` IsSignificantShareholder bool `json:"isSignificantShareholder"` // Whether user that placed the order is an insider. IsInsider bool `json:"isInsider"` // Whether limit offset is specified in dollars (vs. percent). IsLimitOffsetInDollar bool `json:"isLimitOffsetInDollar"` // Internal identifier of user that placed the order. UserID int `json:"userId"` // Commission for placing the order via the Trade Desk over the phone. PlacementCommission float32 `json:"placementCommission"` // List of OrderLeg elements. Legs []OrderLeg `json:"legs"` // Multi-leg strategy to which the order belongs. StrategyType string `json:"strategyType"` // Stop price at which order was triggered. TriggerStopPrice float32 `json:"triggerStopPrice"` // Internal identifier of the order group. OrderGroupID int `json:"orderGroupId"` // Bracket Order class. Primary, Profit or Loss. OrderClass string `json:"orderClass"` }
Ref: http://www.questrade.com/api/documentSymation/rest-operations/account-calls/accounts-id-orders
type OrderImpact ¶
type OrderImpact struct { // Estimate of commissions to be charged on the order. EstimatedCommissions float32 `json:"estimatedCommissions"` // Estimate of change in buying power from the order. BuyingPowerEffect float32 `json:"buyingPowerEffect"` // Estimate of buying power in which order will result. BuyingPowerResult float32 `json:"buyingPowerResult"` // Estimate of change in maintenance excess from the order. MaintExcessEffect float32 `json:"maintExcessEffect"` // Estimate of maintenance excess in which the order will result. MaintExcessResult float32 `json:"maintExcessResult"` // Client view of the order side (e.g., "Buy-To-Open"). Side string `json:"side"` // Estimate of the order execution value. TradeValueCalculation string `json:"tradeValueCalculation"` // Estimated average fill price. Price float32 `json:"price"` }
Ref: http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders-impact
type OrderRequest ¶
type OrderRequest struct { // Account number against which order is being submitted. AccountID string `json:"accountNumber"` // Optional – order id of the order to be replaced. OrderID int `json:"orderId,omitempty"` // Internal symbol identifier. SymbolID int `json:"symbolId"` // Order quantity. Quantity int `json:"quantity"` // Iceberg instruction quantity. IcebergQuantity int `json:"icebergQuantity,omitempty"` // Limit price. LimitPrice float32 `json:"limitPrice,omitempty"` // Stop price. StopPrice float32 `json:"stopPrice,omitempty"` TimeInForce string `json:"timeInForce"` // Identifies whether the all-or-none instruction is enabled. IsAllOrNone bool `json:"isAllOrNone"` // Identifies whether the anonymous instruction is enabled. IsAnonymous bool `json:"isAnonymous"` IsLimitOffsetInDollar bool `json:"isLimitOffsetInDollar"` // Order type (e.g., "Market"). OrderType string `json:"orderType"` // Order side (e.g., "Buy"). Action string `json:"action"` // Secondary order route (e.g., "NYSE"). SecondaryRoute string `json:"secondaryRoute"` // Primary order route (e.g., "AUTO"). PrimaryRoute string `json:"primaryRoute"` }
Ref: http://www.questrade.com/api/documentation/rest-operations/order-calls/accounts-id-orders
type Position ¶
type Position struct { // Position symbol. Symbol string `json:"symbol"` // Internal symbol identifier SymbolID int `json:"symbolId"` // Position quantity remaining open. OpenQuantity float32 `json:"openQuantity"` // Portion of the position that was closed today. ClosedQuantity float32 `json:"closedQuantity"` // Market value of the position (quantity x price). CurrentMarketValue float32 `json:"currentMarketValue"` // Current price of the position symbol. CurrentPrice float32 `json:"currentPrice"` // Average price paid for all executions constituting the position. AverageEntryPrice float32 `json:"averageEntryPrice"` // Realized profit/loss on this position. ClosedPnL float32 `json:"closedPnL"` // Unrealized profit/loss on this position. OpenPnL float32 `json:"openPnL"` // Total cost of the position. TotalCost float32 `json:"totalCost"` // Designates whether real-time quote was used to compute PnL. IsRealTime bool `json:"isRealTime"` // Designates whether a symbol is currently undergoing a reorg. IsUnderReorg bool `json:"isUnderReorg"` }
Position belonging to an account
Ref: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts-id-positions
type QuestradeError ¶
type QuestradeError struct { Code int `json:"code",string` StatusCode int Message string `json:"message"` Endpoint string OrderId int `json:"orderId,omitempty"` Orders []Order `json:"orders,omitempty"` }
func (QuestradeError) Error ¶
func (q QuestradeError) Error() string
type Quote ¶
type Quote struct { // Symbol name following Questrade’s symbology. Symbol string `json:"symbol"` // Internal symbol identifier. SymbolID int `json:"symbolId"` // Market tier. Tier string `json:"tier"` // Bid price. BidPrice float32 `json:"bidPrice"` // Bid quantity. BidSize int `json:"bidSize"` // Ask price. AskPrice float32 `json:"askPrice"` // Ask quantity. AskSize int `json:"askSize"` // Price of the last trade during regular trade hours. LastTradeTrHrs float32 `json:"lastTradeTrHrs"` // Price of the last trade. LastTradePrice float32 `json:"lastTradePrice"` // Quantity of the last trade. LastTradeSize int `json:"lastTradeSize"` // Trade direction. LastTradeTick string `json:"lastTradeTick"` // Timestamp LastTtradeTime string `json:"lastTradeTime"` // Volume. Volume int `json:"volume"` // Opening trade price. OpenPrice float32 `json:"openPrice"` // Daily high price. HighPrice float32 `json:"highPrice"` // Daily low price. LowPrice float32 `json:"lowPrice"` // Whether a quote is delayed (true) or real-time. Delay int `json:"delay"` // Whether trading in the symbol is currently halted. IsHalted bool `json:"isHalted"` }
Quote represents a Lvl 1 market data quote for a particular symbol
type Symbol ¶
type Symbol struct { // Symbol that follows Questrade symbology (e.g., "TD.TO"). Symbol string `json:"symbol"` // Symbol identifier SymbolID int `json:"symbolId"` // Closing trade price from the previous trading day. PrevDayClosePrice float32 `json:"prevDayClosePrice"` // 52-week high price. HighPrice52 float32 `json:"highPrice52"` // 52-week low price. LowPrice52 float32 `json:"lowPrice52"` // Average trading volume over trailing 3 months. AverageVol3Months int `json:"averageVol3Months"` // Average trading volume over trailing 20 days. AverageVol20Days int `json:"averageVol20Days"` OutstandingShares int `json:"outstandingShares"` // Trailing 12-month earnings per share. EPS float32 `json:"eps"` // Trailing 12-month price to earnings ratio. PE float32 `json:"pe"` // Dividend amount per share. Dividend float32 `json:"dividend"` // Dividend yield (dividend / prevDayClosePrice). Yield float32 `json:"yield"` // Dividend ex-date. ExDate *time.Time `json:"exDate"` // Market capitalization (outstandingShares * prevDayClosePrice). MarketCap float32 `json:"marketCap"` // Option type (e.g., "Call"). OptionType string `json:"optionType"` // Option duration type (e.g., "Weekly"). OptionDurationType string `json:"optionDurationType"` // Option root symbol (e.g., "MSFT"). OptionRoot string `json:"optionRoot"` // Option contract deliverables. OptionContractDeliverables OptionContractDeliverables `json:"optionContractDeliverables"` // Option exercise style (e.g., "American"). OptionExerciseType string `json:"optionExerciseType"` // Primary listing exchange. ListingExchange string `json:"listingExchange"` // Symbol description (e.g., "Microsoft Corp."). Description string `json:"description"` // Security type (e.g., "Stock"). SecurityType string `json:"securityType"` // Option expiry date. OptionExpiryDate *time.Time `json:"optionExpiryDate"` // Dividend declaration date. DividendDate *time.Time `json:"dividendDate"` // Option strike price. OptionStrikePrice float32 `json:"optionStrikePrice"` // Indicates whether the symbol is actively listed. IsQuotable bool `json:"isQuotable"` // Indicates whether the symbol is an underlying option. HasOptions bool `json:"hasOptions"` // String Currency code (follows ISO format). Currency string `json:"currency"` // List of MinTickData records. MinTicks []MinTickData `json:"minTicks"` }
Detailed information about a symbol Ref: http://www.questrade.com/api/documentation/rest-operations/market-calls/symbols-id
type SymbolSearchResult ¶
type SymbolSearchResult struct { Symbol string `json:"symbol"` SymbolID int `json:"symbolId"` Description string `json:"description"` SecurityType string `json:"securityType"` ListingExchange string `json:"listingExchange"` IsQuotable bool `json:"isQuotable"` IsTradable bool `json:"isTradable"` Currency string `json:"currency"` }
Symbol information retreived from search results Ref: http://www.questrade.com/api/documentation/rest-operations/market-calls/symbols-search