allyinvest/client.go

87 lines
2.0 KiB
Go
Raw Normal View History

package main
import (
"encoding/xml"
"fmt"
"github.com/joho/godotenv"
"github.com/mrjones/oauth"
"io/ioutil"
2019-11-26 20:35:50 +00:00
"log"
"net/http"
"os"
)
/* The trading endpoint for Ally */
const endpoint string = "https://api.tradeking.com/v1/"
type AllyApi struct {
consumer *oauth.Consumer
Client *http.Client
}
func (c *AllyApi) Initialize() {
err := godotenv.Load()
if err != nil {
panic(err)
}
// Set up our new oauth consumer
c.consumer = oauth.NewConsumer(
os.Getenv("CONSUMER_KEY"),
os.Getenv("CONSUMER_SECRET"),
oauth.ServiceProvider{
RequestTokenUrl: "https://developers.tradeking.com/oauth/request_token",
AuthorizeTokenUrl: "https://developers.tradeking.com/oauth/authorize",
AccessTokenUrl: "https://developers.tradeking.com/oauth/access_token",
},
)
c.Client, err = c.consumer.MakeHttpClient(
&oauth.AccessToken{Token: os.Getenv("ACCESS_TOKEN"), Secret: os.Getenv("ACCESS_SECRET")})
if err != nil {
panic(err)
}
}
func (c *AllyApi) get(path string) (resp *http.Response, err error) {
resp, err = c.Client.Get(fmt.Sprintf("%s\\%s", endpoint, path))
2019-11-27 13:29:14 +00:00
return resp, err
}
2019-11-27 13:29:14 +00:00
//GetAndMarshal call GET on the path, and marshal the resopnse to interface
// type
func (c *AllyApi) getAndRead(path string) []byte {
resp, err := c.get(path)
if err != nil {
2019-11-27 13:29:14 +00:00
log.Fatal("Could not make request")
}
2019-11-27 13:29:14 +00:00
defer resp.Body.Close()
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
2019-11-27 13:29:14 +00:00
log.Fatal("Could not read body!")
return nil
}
2019-11-27 13:29:14 +00:00
return raw
}
2019-11-27 13:29:14 +00:00
/* The /accounts endpoint of Ally */
func (c *AllyApi) Accounts() []AccountSummary {
var resp AccountResponse
2019-11-27 13:29:14 +00:00
_ = xml.Unmarshal(c.getAndRead("accounts"), &resp)
return resp.Accounts.Accountsummary
}
2019-11-26 20:35:50 +00:00
func (c *AllyApi) AccountBalances() (balances []AccountBalance) {
var resp AccountBalanceResponse
2019-11-27 13:29:14 +00:00
_ = xml.Unmarshal(c.getAndRead("accounts/balances"), &resp)
return resp.AccountBalances
}
2019-11-26 20:35:50 +00:00
2019-11-27 13:29:14 +00:00
func (c *AllyApi) AccountDetail(accountId int) AccountDetailResponse {
var resp AccountDetailResponse
_ = xml.Unmarshal(c.getAndRead(fmt.Sprintf("accounts/%d", accountId)), &resp)
return resp
2019-11-26 20:35:50 +00:00
}