initial commit
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-11-12 12:04:22 -07:00
parent 0444f8ecf8
commit 22aac4adbd
16 changed files with 850 additions and 0 deletions

114
questrade/account.go Normal file
View File

@ -0,0 +1,114 @@
package questrade
import (
"fmt"
"net/url"
"strconv"
)
// 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 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"`
}
// Balance belonging to an Account
//
// Ref: http://www.questrade.com/api/documentation/rest-operations/account-calls/accounts-id-balances
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"`
}
// 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 AccountBalances struct {
PerCurrencyBalances []Balance `json:"perCurrencyBalances"`
CombinedBalances []Balance `json:"combinedBalances"`
SODPerCurrencyBalances []Balance `json:"sodPerCurrencyBalances"`
SODCombinedBalances []Balance `json:"sodCombinedBalances"`
}
// GetAccounts returns the logged-in User ID, and a list of accounts
// belonging to that user.
func (c *Client) GetAccounts() (int, []Account, error) {
list := struct {
UserID int `json:"userId"`
Accounts []Account `json:"accounts"`
}{}
err := c.get("v1/accounts", &list, url.Values{})
if err != nil {
return 0, []Account{}, err
}
return list.UserID, list.Accounts, nil
}
// GetBalances returns the balances for the account with the specified account number
func (c *Client) GetBalances(number string) (AccountBalances, error) {
bal := AccountBalances{}
err := c.get("v1/accounts/"+number+"/balances", &bal, url.Values{})
if err != nil {
return AccountBalances{}, err
}
return bal, nil
}
func (c *Client) GetQuestradeAccountBalance(accountID int) (int, error) {
balances, err := c.GetBalances(strconv.Itoa(accountID))
if err != nil {
return 0, fmt.Errorf("failed to get balances for account ID '%d': %v", accountID, err)
}
for _, balance := range balances.CombinedBalances {
if balance.Currency != "CAD" {
continue
}
return int(balance.TotalEquity) * 1000, nil
}
return 0, fmt.Errorf("could not find a CAD balance for this account in questade response")
}

137
questrade/client.go Normal file
View File

@ -0,0 +1,137 @@
package questrade
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
)
const loginServerURL = "https://login.questrade.com/oauth2/"
type LoginCredentials struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
ApiServer string `json:"api_server"`
}
// 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.
type Client struct {
Credentials LoginCredentials
SessionTimer *time.Timer
RateLimitRemaining int
RateLimitReset time.Time
httpClient *http.Client
transport *http.Transport
}
// authHeader is a shortcut that returns a string to be placed
// in the authorization header of API calls
func (l LoginCredentials) authHeader() string {
return l.TokenType + " " + l.AccessToken
}
// Send an HTTP GET request, and return the processed response
func (c *Client) get(endpoint string, out interface{}, query url.Values) error {
req, err := http.NewRequest("GET", c.Credentials.ApiServer+endpoint+query.Encode(), nil)
if err != nil {
return err
}
req.Header.Add("Authorization", c.Credentials.authHeader())
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http get request failed: %v", err)
}
err = c.processResponse(res, out)
if err != nil {
return err
}
return nil
}
// processResponse takes the body of an HTTP response, and either returns
// the error code, or unmarshalls the JSON response, extracts
// rate limit info, and places it into the object
// output parameter. This function closes the response body after reading it.
func (c *Client) processResponse(res *http.Response, out interface{}) error {
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return err
}
if res.StatusCode != 200 {
return newQuestradeError(res, body)
}
err = json.Unmarshal(body, out)
if err != nil {
return err
}
reset, _ := strconv.Atoi(res.Header.Get("X-RateLimit-Reset"))
c.RateLimitReset = time.Unix(int64(reset), 0)
c.RateLimitRemaining, _ = strconv.Atoi(res.Header.Get("X-RateLimit-Remaining"))
return nil
}
// 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.
// TODO - Return a proper error when login fails with HTTP 400 - Bad Request
func (c *Client) Login() error {
login := loginServerURL
vars := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {c.Credentials.RefreshToken}}
res, err := c.httpClient.PostForm(login+"token", vars)
if err != nil {
return err
}
err = c.processResponse(res, &c.Credentials)
if err != nil {
return err
}
c.SessionTimer = time.NewTimer(time.Duration(c.Credentials.ExpiresIn) * time.Second)
return nil
}
// NewClient is the factory function for clients - takes a refresh token and logs in
func NewClient(refreshToken string) (*Client, error) {
transport := &http.Transport{
ResponseHeaderTimeout: 5 * time.Second,
}
client := &http.Client{
Transport: transport,
}
// Create a new client
c := &Client{
Credentials: LoginCredentials{
RefreshToken: refreshToken,
},
httpClient: client,
transport: transport,
}
err := c.Login()
if err != nil {
return nil, err
}
return c, nil
}

41
questrade/errors.go Normal file
View File

@ -0,0 +1,41 @@
package questrade
import (
"encoding/json"
"fmt"
"net/http"
)
type QuestradeError struct {
Code int `json:"code"`
StatusCode int
Message string `json:"message"`
Endpoint string
}
func newQuestradeError(res *http.Response, body []byte) QuestradeError {
// Unmarshall the error text
var e QuestradeError
err := json.Unmarshal(body, &e)
if err != nil {
e.Code = -999
e.Message = string(body)
}
e.StatusCode = res.StatusCode
e.Endpoint = res.Request.URL.String()
return e
}
func (q QuestradeError) Error() string {
return fmt.Sprintf("\nQuestradeError:\n"+
"\tStatus code: HTTP %d\n"+
"\tEndpoint: %s\n"+
"\tError code: %d\n"+
"\tMessage: %s\n",
q.StatusCode,
q.Endpoint,
q.Code,
q.Message)
}

3
questrade/go.mod Normal file
View File

@ -0,0 +1,3 @@
module deadbeef.codes/steven/ynab-portfolio-monitor/questrade
go 1.21.1