GithubHelp home page GithubHelp logo

alpacahq / alpaca-trade-api-go Goto Github PK

View Code? Open in Web Editor NEW
314.0 36.0 85.0 685 KB

Go client for Alpaca's trade API

License: Apache License 2.0

Go 99.99% Makefile 0.01%
hacktoberfest trading golang go

alpaca-trade-api-go's Introduction

alpaca-trade-api-go

GitHub Status Go Report Card

alpaca-trade-api-go is a Go library for the Alpaca trade and marketdata API. It allows rapid trading algo development easily, with support for the both REST and streaming interfaces. For details of each API behavior, please see the online API document.

Installation

go get -u github.com/alpacahq/alpaca-trade-api-go/v3/alpaca

Examples

In order to call Alpaca's trade API, you need to obtain an API key pair from the web console.

Trading REST example

package main

import (
	"fmt"

	"github.com/alpacahq/alpaca-trade-api-go/v3/alpaca"
)

func main() {
	client := alpaca.NewClient(alpaca.ClientOpts{
		// Alternatively you can set your key and secret using the
		// APCA_API_KEY_ID and APCA_API_SECRET_KEY environment variables
		APIKey:    "YOUR_API_KEY",
		APISecret: "YOUR_API_SECRET",
		BaseURL:   "https://paper-api.alpaca.markets",
	})
	acct, err := client.GetAccount()
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", *acct)
}

Trade updates stream example

The following example shows how you can stream your own trade updates. First we register a handler function that simply prints the received trade updates, then we submit a single AAPL buy order. You should see two updates, a "new" event as soon as you submit the order, and a "fill" event soon after that, provided that the market is open.

// Listen to trade updates in the background (with unlimited reconnect)
alpaca.StreamTradeUpdatesInBackground(context.TODO(), func(tu alpaca.TradeUpdate) {
	log.Printf("TRADE UPDATE: %+v\n", tu)
})

// Send a single AAPL order
qty := decimal.NewFromInt(1)
if _, err := alpaca.PlaceOrder(alpaca.PlaceOrderRequest{
	Symbol:      "AAPL",
	Qty:         &qty,
	Side:        "buy",
	Type:        "market",
	TimeInForce: "day",
}); err != nil {
	log.Fatalf("failed place order: %v", err)
}
log.Println("order sent")

select {}

Further examples

See the examples directory for further examples:

  • algo-trading examples
    • long-short
    • martingale
    • mean-reversion
  • marketdata examples
    • crypto-stream
    • data-stream
    • marketdata

API Document

The HTTP API document is located here.

Authentication

The Alpaca API requires API key ID and secret key, which you can obtain from the web console after you sign in. This key pair can then be applied to the SDK either by setting environment variables (APCA_API_KEY_ID=<key_id> and APCA_API_SECRET_KEY=<secret_key>), or hardcoding them into the Go code directly as shown in the examples above.

export APCA_API_KEY_ID=xxxxx
export APCA_API_SECRET_KEY=yyyyy

Endpoint

For paper trading, set the environment variable APCA_API_BASE_URL or set the BaseURL option when constructing the client.

export APCA_API_BASE_URL=https://paper-api.alpaca.markets

Documentation

For a more in-depth look at the SDK, see the package documentation.

alpaca-trade-api-go's People

Contributors

117 avatar alexandroskyriakakis avatar andrewkim316 avatar bensie avatar ccnlui avatar cksidharthan avatar coopernurse avatar drew887 avatar ducille avatar gjtorikian avatar gliptak avatar gnvk avatar itsankoff avatar jeefy avatar jrenk avatar kalmant avatar leki75 avatar matteosantama avatar neal avatar noramehesz avatar notargets avatar r4stl1n avatar rafaeelaudibert avatar rocketbitz avatar rumsrami avatar sai-g avatar shlomiku avatar timwatson avatar ttt733 avatar umitanuki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alpaca-trade-api-go's Issues

Not possible to list non-trade Account activities

This struct in entities.go defines the Date field as time.Time, but the value (from Alpaca) is of the form 'YYYY-MM-dd' for non-trade activities so it always fails to unmarshall the data from Alpaca. For example I have a 'SPIN' activity from a spin off.

type AccountActivity struct {
	ID              string          `json:"id"`
	ActivityType    string          `json:"activity_type"`
	TransactionTime time.Time       `json:"transaction_time"`
	Type            string          `json:"type"`
	Price           decimal.Decimal `json:"price"`
	Qty             decimal.Decimal `json:"qty"`
	Side            string          `json:"side"`
	Symbol          string          `json:"symbol"`
	LeavesQty       decimal.Decimal `json:"leaves_qty"`
	CumQty          decimal.Decimal `json:"cum_qty"`
	Date            time.Time       `json:"date"`
	NetAmount       decimal.Decimal `json:"net_amount"`
	Description     string          `json:"description"`
	PerShareAmount  decimal.Decimal `json:"per_share_amount"`
}

Add the ability to update the Data Url

Similar to how thebase url can be updated using SetBaseUrl, it would be nice to be able to update the data url as well.

My use case for this is I would like to proxy my requests through nginx first to do some additional configurations on the request before sending the response back to the client, but I can only do the for the base url currently.

Asset.Class returns empty string

I believe the Asset entity uses the wrong json tag when fetching assets with ListAssets. The JSON from alpaca has a class key while the Asset entity uses "asset_class".

alpaca.auth() (stream.go) depends on common.Credentials()

One should not expose secrets in environment variables as they are easily hackable in shared environments, I would like to instead, load credentials from a custom secure location at runtime even for streaming, but the fact that stream.go hardcodes the credentials source from common.Credentials() makes this an impossible task.

authRequest := ClientMsg{
Action: "authenticate",
Data: map[string]interface{}{
"key_id": common.Credentials().ID,
"secret_key": common.Credentials().Secret,
},
}

A pattern for stream.Register(...) like alpaca.NewClient(...) should be supported.

	client := alpaca.NewClient(&common.APIKey{
		ID: "XXX",
		PolygonKeyID: "XXX",
		Secret: "YYY",
	})

I'll be happy to try to implement it.

Update: It seems like @istrau2 made progress some time ago, this could be used as a starting point #79

Data Proxy Setup Error

When I attempted to use the data proxy with:

DATA_PROXY_WS=ws://127.0.0.1:8765

I get a TLS error as this line:

if ub.Scheme == "http" {
only changes to ws scheme if http is detected.

I am able to resolve by doing one of the following:

  1. Set data proxy scheme to http, eg: DATA_PROXY_WS=http://127.0.0.1:8765 (currently what I am doing)
  2. Adjust the linked line to look for ws or http and set the scheme appropriately

If there is a preferred approach, I am happy to open a PR for this

Add example for Authentication.

The issue here is that I am looking to use the Go library for my implementation but I need a little more info on how to get get streaming the KYC flow working with the go library. Let me know if there's anything I can do to help.

Fix or remove Quote functionality

None of ListQuotes or GetQuote works. Please either make it work or remove those calls.

Doesn't seem like an API issue but more like lacking support in the endpoint.

Running this program:

package main

import (
        "fmt"

        "github.com/alpacahq/alpaca-trade-api-go/alpaca"
)

func main() {
        _, err := alpaca.ListQuotes([]string{"AAPL"})

        if err != nil {
                fmt.Println("Error:", err.Error())
        }

        _, err = alpaca.GetQuote("AAPL")

        if err != nil {
                fmt.Println("Error:", err.Error())
        }
}

Obtaining this output:

Error: endpoint not found
Error: invalid character 'N' looking for beginning of value

Add missing params to ListOrders

ListOrders currently supports a subset of the available params. Missing params:

  • after
  • direction
  • symbols

I'd suggest we add a new method that accepts a request struct that includes all supported params. I'm open to naming suggestions. We could deprecate the old method. The result would be something like:

func (c *Client) ListOrders(status *string, until *time.Time, limit *int, nested *bool) ([]Order, error) {
	req := ListOrdersRequest{
		Status: status,
		Until:  until,
		Limit:  limit,
		Nested: nested,
	}
	return c.ListOrders2(req)
}

func (c *Client) ListOrders2(req ListOrdersRequest) ([]Order, error) {
// code here
}

GetSymbolBars with StartDt not working

I was writing a back-testing framework, and I tried to get SymbolBar with old date:

const (
    TimeParseLayout = "2006-01-02 15:04:05"
)
startDate, _ := time.Parse(TimeParseLayout, "2008-03-10 10:00:00")
bars, _ := client.GetSymbolBars("AAPL", alpaca.ListBarParams{Timeframe: "minute", EndDt: &startDate})
fmt.Printf("%v", print(bars[0].GetTime())

And for some reason I was getting the current date as a result.

I Intercept the requests and found out that the request format was wrong than the documentation.

The request:

GET /v1/bars/minute?end_dt=2008-03-10T10%3A03%3A00Z&symbols=AAPL HTTP/1.1
Host: data.alpaca.markets
User-Agent: Go-http-client/1.1
Apca-Api-Key-Id: XXXXXXXXXXXXXXX
Apca-Api-Secret-Key: XXXXXXXXXXXXXXXXXXXXX
Accept-Encoding: gzip, deflate
Connection: close

The end_dt param should be end, and the date format should be with the format of 2017-04-15T09:31:00-04:00.
That way the request works.

GET /v1/bars/minute?end=2017-04-15T09:31:00-04:00&symbols=AAPL HTTP/1.1
Host: data.alpaca.markets
User-Agent: Go-http-client/1.1
Apca-Api-Key-Id: XXXXXXXXXXXXXXXX
Apca-Api-Secret-Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Accept-Encoding: gzip, deflate
Connection: close

Account Updates not working on wss://paper-api.alpaca.markets/stream

Hello,

Subscriptions to account updates on wss://paper-api.alpaca.markets/stream are confirmed with {listening map[streams:[account_updates]]} however we do not receive any account updates after seeing this message.

I initially encountered this issue while writing a custom API however I have chosen to reproduce it using this repo.

Steps for reproduction:

git clone https://github.com/Connah-rs/alpaca-trade-api-go.git
cd alpaca-trade-api-go/examples/long-short
replace YOUR_API_KEY_HERE, YOUR_API_SECRET_HERE in long-short.go with your paper keys
go run long-short.go (to create some account activity)

in another terminal:
cd alpaca-trade-api-go/issue
replace YOUR_API_KEY_HERE, YOUR_API_SECRET_HERE in main.go with your paper keys
go run main.go

You can uncomment the lines:

	// if err := stream.Register(alpaca.TradeUpdates, tradeHandler); err != nil {
	// 	panic(err)
	// }

To check trade updates are working

I have added a type to alpaca/entities.go and added the appropriate switch statements in alpaca/stream.go. Just in case any of that was wrong, msg is logged after ReadJSON (shows sub confirmation and nothing after)

I also changed the wss in alpaca/stream.go so that it is always wss://paper-api.alpaca.markets/stream. We have had confirmation from alpaca that this is the correct wss for streaming account activity on paper accounts

Any help on this would be greatly appreciated!

Go package installation doesn't work

Hello, I've tried installing package from the terminal with this command
go get github.com/alpacahq/alpaca-trade-api-go.

Unfortunately, I'm getting an error saying
can't load package: package github.com/alpacahq/alpaca-trade-api-go: no Go files in /Users/tulga/go/src/github.com/alpacahq/alpaca-trade-api-go.

go get results in error

go get github.com/alpacahq/alpaca-trade-api-go
package github.com/alpacahq/alpaca-trade-api-go: no Go files in /c/Code/go/src/github.com/alpacahq/alpaca-trade-api-go

Is this expected? Technically the error seems correct are no go files in the root directory.

I'm specifically using Windows Subsystem for Linux, but haven't really had issues with go.

Issues pulling Intraday historical data

Hey Alpaci,

I'm trying to pull intraday historical data via GetBars and I'm getting inconsistent results...

TLDR; my goal is to create a script that allows me to fetch all of the 1 minute intraday data as far back as possible

Doesn't return data unless the date range is large enough?

If I try to fetch data between 2020-12-25 13:00:00 and 2020-12-30 13:00:00 then I get no results... but If I fetch data between 2020-12-24 13:00:00 and 2020-12-30 13:00:00 I get 1990 items.

Is there is a reason that the first one would fail and the second one would success right after?

Missing minutes sometimes hours

Most of the calls succeed and data is returned - however upon some manual inspection I noticed some missing minutes (I assumed this was minutes without any transactions) but theres many minutes missing in a row and it doesnt seem likely that there was no transaction for up to 55 mins

Open High Low Close Vol Time
219.3 219.3 219.2 219.2 129 2021-03-04T04:05:00-05:00
219.31 219.31 219.31 219.31 100 2021-03-04T04:02:00-05:00
219.2 219.2 219.2 219.2 20 2021-03-04T04:01:00-05:00
219.05 219.11 219.05 219.11 450 2021-03-04T04:00:00-05:00
219.3 219.3 219.3 219.3 420 2021-03-04T03:05:00-05:00
219.14 219.14 219.14 219.14 2 2021-03-04T03:04:00-05:00
219.11 219.11 219.11 219.11 100 2021-03-04T02:45:00-05:00

Notice the gap between 2021-03-04T04:00:00-05:00 and 2021-03-04T03:05:00-05:00. That's :55 minutes between 3:05 and 4:00....

Is there any reason large chunks of data are missing?

The script in question

package main

import (
	"fmt"
	"github.com/davecgh/go-spew/spew"
	"github.com/fatih/structs"
	"os"
	"reflect"
	"sort"
	"time"

	"github.com/alpacahq/alpaca-trade-api-go/alpaca"
	"github.com/alpacahq/alpaca-trade-api-go/common"
	v2 "github.com/alpacahq/alpaca-trade-api-go/v2"
)

func init() {
	os.Setenv(common.EnvApiKeyID, "XXXX")
	os.Setenv(common.EnvApiSecretKey, "XXXX")
	fmt.Printf("Running w/ credentials [%v %v]\n", common.Credentials().ID, common.Credentials().Secret)
}

func main() {
	alpacaClient := alpaca.NewClient(common.Credentials())

	end := time.Now().AddDate(0, 0, -1) // yesterday
	start := end.AddDate(0, 0, -5)      // Subtract N Day

	// holder for all data
	mybars := []v2.Bar{}
	counter := 0
	for {

		if counter > 100 {
			break
		}

		bars := alpacaClient.GetBars(
			"IWM",
			v2.Min,
			v2.Raw,
			start,
			end,
			10000,
		)

		innerBars := []v2.Bar{}
		// iterate over channel
		for msg := range bars {
			innerBars = append(innerBars, msg.Bar)
		}

		// first and last
		startBar := innerBars[0]
		fmt.Printf("(%d)\t\t(%d)\t(%d)\t(%.2f)\t%s - %s\n", len(mybars), counter, len(innerBars), start.Sub(end).Hours()/24, start, end)
		if len(innerBars) < 2 {
			// increment fail counter
			counter += 1
			// push start day back one day
			start = start.AddDate(0, 0, -1)
		} else {
			end = startBar.Timestamp
			start = end.AddDate(0, 0, -5) // Subtract N Day
			mybars = append(mybars, innerBars...)

		}
		// short sleep
		time.Sleep(time.Millisecond * 100)
	}

	// sort them so the dates are in order
	sort.SliceStable(mybars, func(i, j int) bool {
		return mybars[i].Timestamp.After(mybars[j].Timestamp)
	})

	// write all data to file
	WriteBars(mybars, "intra.csv")
}

func WriteBars(bars []v2.Bar, name string) {

	//init the loc
	loc, _ := time.LoadLocation("America/New_York")

	file, fileErr := os.Create(name)
	if fileErr != nil {
		spew.Dump(fileErr)
	}
	names := structs.Names(bars[0])
	for i := 0; i < len(names); i++ {
		// values[i] = v.Field(i).Interface()
		fmt.Fprintf(file, "%s", names[i])
		if i < (len(names) - 1) {
			fmt.Fprintf(file, ",")
		}
	}
	fmt.Fprintf(file, "\n")

	for i := range bars {
		k := bars[i]
		v := reflect.ValueOf(k)

		// write each value type accordingly
		for i := 0; i < v.NumField(); i++ {
			if i < 4 {
				// these are all floats
				fmt.Fprintf(file, "%.2f", v.Field(i).Interface())
			} else if i == 4 {
				// this is a usize
				j := int(v.Field(i).Interface().(uint64))
				fmt.Fprintf(file, "%d", j)
			} else {
				// this is a UTC time.Time
				t := v.Field(i).Interface().(time.Time)
				fmt.Fprintf(file, "%s", t.In(loc).Format(time.RFC3339))
			}

			// if its not the last column add a comma
			if i < (v.NumField() - 1) {
				fmt.Fprintf(file, ",")
			}
		}
		fmt.Fprintf(file, "\n")
	}
}

UPDATE:

Heres a link to the csv file the above produced: https://docs.google.com/spreadsheets/d/1nVsGPuTGg_XTQZDx8aBawNBsgAvroijWM55hsfAo7Ug/edit?usp=sharing

Take Profit Price on Market Order Not Working

Hello,

I am making a place order request in the follow format. Assume all inputs are correctly formatted. In addition, assume the takeProfitPrice is greater than the current market value for the AssetKey. Knowing the above. I make an order and submit. However the order gets processed successfully, but the LimitPrice for TP is not propagating for some reason. It just is not there. Is there a reason for this? I read the docs and I don't see that I am doing anything wrong. I can place the same exact in that format on alpaca website, so unsure what the issue is.

placeOrderRequest = alpaca.PlaceOrderRequest{
	AssetKey: &ticker,
	Qty:      &qty,
	TakeProfit: &alpaca.TakeProfit{
		LimitPrice: &takeProfitPrice,
	},
	Type:        alpaca.Market,
	TimeInForce: alpaca.Day,
	Side:        side,
}

Failed to get reader: WebSocket closed

FYI, just testing the new News endpoint, I'm getting disconnects one per about two hours, sometimes sooner, please see the screenshot.

2022-02-02_20-05

Otw, I'm subscriber to marketdata.
PS: great new News API, the right way to go, thank you so much.

panic: nats: Authorization Violation

panic: nats: Authorization Violation

note:

  1. common not import
  2. json not import
  3. key and id had modify to mine

src:
import (
"os"
"fmt"

"github.com/alpacahq/alpaca-trade-api-go/alpaca"
"github.com/alpacahq/alpaca-trade-api-go/polygon"
"github.com/alpacahq/alpaca-trade-api-go/stream"
nats "github.com/nats-io/go-nats"

)

func main() {
os.Setenv(common.EnvApiKeyID, "<key_id>")
os.Setenv(common.EnvApiSecretKey, "<secret_key>")

if err := stream.Register(alpaca.TradeUpdates, tradeHandler); err != nil {
    panic(err)
}

if err := stream.Register("Q.AAPL", quoteHandler); err != nil {
    panic(err)
}

select{}

}

func tradeHandler(msg interface{}) {
fmt.Println(msg)
}

func quoteHandler(msg interface{}) {
quote := polygon.StreamQuote{}

if err := json.Unmarshal(msg.(*nats.Msg).Data, &quote); err != nil {
    panic(err)
}

fmt.Println(quote.Symbol, quote.BidPrice, quote.BidSize, quote.AskPrice, quote.AskSize)

}

Return order for ClosePosition()

The ClosePosition method create a market sell order for the symbol. Currently it only return err, is it ok to also return the sell order as well?

Reconnect fail on nil interface

Lines 188-203 when given an unexpected EOF exception continues on to the reconnect function. The reconnect function assumes that the interface will not be nil (the value becomes nil by some other part of the code) throws a unneeded panic which kills the entire program.

https://github.com/alpacahq/alpaca-trade-api-go/blob/master/alpaca/stream.go#L200

else {
			if websocket.IsCloseError(err) {
				// if this was a graceful closure, don't reconnect
				if s.closed.Load().(bool) {
					return
				}
			} else {
				log.Printf("alpaca stream read error (%v)", err)
			}

			err := s.reconnect()
			if err != nil {
				panic(err)
			}
		}
	}

Stack Trace:
Screen Shot 2021-02-08 at 2 23 42 PM

Resolution:

It would be nice to either nil check the interface before converting to a string. Or returned an error message instead of a panic so the program isn't killed.

Spelling error in AccountActivity type

AccountActivity type is spelled "AccountActvity" in several places.

  1. alpaca/entities.go @222
    type AccountActvity struct {
  2. alpaca/rest.go @150
    func (c *Client) GetAccountActivities(activityType *string, opts *AccountActivitiesRequest) ([]AccountActvity, error) {
  3. alpaca/rest.go @191
    activities := []AccountActvity{}
  4. alpaca/rest.go @716
    func GetAccountActivities(activityType *string, opts *AccountActivitiesRequest) ([]AccountActvity, error) {

[Feature] : Add GitHub Issue Forms

Summary

As we can see the repository has no predefined Issue template, because of which there is non uniformity in the issues section.

GitHub has recently rolled out a public beta for their issue forms feature. This would allow you to create interactive issue templates and validate them ๐Ÿคฏ.

forbidden error marketdata.GetTrades

I'm trying to run a very simple test of the alpaca-trade-api-go:

package main

import (
	"fmt"
	"time"

	"github.com/alpacahq/alpaca-trade-api-go/v2/marketdata"
)

func main() {
	trades, err := marketdata.GetTrades("INTC", marketdata.GetTradesParams{
		Start:      time.Date(2022, 3, 17, 4, 0, 0, 0, time.UTC),
		TotalLimit: 1,
	})

	if err != nil {
		panic(err)
	}

	for _, trade := range trades {
		fmt.Printf("%+v\n", trade)
	}
}

Unfortunately, this always generates this unclear error:

$ go run main.go 
panic: forbidden.

goroutine 1 [running]:
main.main()
        /workspaces/go-alpaca/main.go:28 +0x205
exit status 2

I have tried it in a container running golang 1.18 and on WSL running golang 1.13.8 - identical results in both.

What might I be doing wrong?

panic: access key verification failed : access key not found (Code = 40110000)

Unable to continue with golang. The code below fails with the error panic: access key verification failed : access key not found (Code = 40110000).

The same key and secret work direct from Postman and Python. Have regenerated the key/secret multiple times but issue persists.


package main

import (
	"fmt"
	"os"
	
	"github.com/alpacahq/alpaca-trade-api-go/alpaca"
	"github.com/alpacahq/alpaca-trade-api-go/common"
	
)

func init() {

	API_KEY := "XXXXXXXXXXXXXXXXXXXXXX"
	API_SECRET := "XXXXXXXXXXXXXXXXXXXXXX"
	BASE_URL := "https://paper-api.alpaca.markets"

	// Check for environment variables
	if common.Credentials().ID == "" {
		os.Setenv(common.EnvApiKeyID, API_KEY)
	}
	if common.Credentials().Secret == "" {
		os.Setenv(common.EnvApiSecretKey, API_SECRET)
	}
	alpaca.SetBaseUrl(BASE_URL)
	

	fmt.Printf("Running w/ credentials [%v %v]\n", common.Credentials().ID, common.Credentials().Secret)
}

func main() {
	// Get our account information.
	account, err := alpaca.GetAccount()
	if err != nil {
		panic(err)
	}

	// Check if our account is restricted from trading.
	if account.TradingBlocked {
		fmt.Println("Account is currently restricted from trading.")
	}

	// Check how much money we can use to open new positions.
	fmt.Printf("%v is available as buying power.\n", account.BuyingPower)
}

Time frames not working

start := time.Now().Add(time.Minute * time.Duration(30))
end := time.Now()
bars, err := client.GetSymbolBars("GOOG", alpaca.ListBarParams {
 TimeFrame: "minute",
 StartDt: &start,
 EndDt: &end,
})
fmt.Println(len(bars))

I would expect this to return 30 bars, but instead, it returns the default 100 bars no matter what times I set.

Add a newer version tag to the repository

When using go mod, it by defaults downloads v1.0.0 of alpaca-trade-api-go, which is very old (from December) and which is out-of-sync with the API documentation.

Manually changing the version from v1.0.0 to master helps.

Here's a sample session:

$ cat <<EOF > main.go
package main

import (
        "github.com/alpacahq/alpaca-trade-api-go/alpaca"
)

func main() {
        alpaca.SetBaseUrl("https://api.alpaca.markets")
}
EOF
$ go mod init
go: creating new go.mod: module github.com/pyohannes/gotrade/example
$ go mod download
$ go build
go: finding github.com/alpacahq/alpaca-trade-api-go/alpaca latest
# github.com/pyohannes/gotrade/example
./main.go:8:2: undefined: alpaca.SetBaseUrl
$ sed -i s/v1.0.0/master/ go.mod
$ go build
go: finding github.com/alpacahq/alpaca-trade-api-go master
$

Please add a new version tag which is in sync with the published API documentation.

Better handling for stream errors?

Today I received the following error while reading streams:

polygon stream read error (websocket: close 1006 (abnormal closure): unexpected EOF)

Although the library does attempt to reconnect with s.conn = openSocket(), this does not set any of the channels (as Subscribe) does, so nothing actually happens.

Since this is just a printed message, and not, for example, a returned err value, I can't act on it. I would prefer to reconnect to my established channels on an error like this. Do you have any suggestions on how this can be done? I am not certain the current code will allow for it.

Documented example is broken

After registering an OAuth program and running the documented example using my Client ID and Client Secret, I get the following error:

panic: access key verification failed : access key not found (Code = 40110000)

Steps to Reproduce:

  1. Register an OAuth App
  2. Copy example code from documentation (v1.5.0)
  3. Set environment values:
os.Setenv(common.EnvApiKeyID, "f9a...c52")
os.Setenv(common.EnvApiSecretKey, "5c6...4bd")
  1. Run application

Expected:
The alpacaClient.GetAccount() func to return an account and nil error

Actual:

go run main.go
Running w/ credentials [f9a...c52 5c6...4bd]
panic: access key verification failed : access key not found (Code = 40110000)

goroutine 1 [running]:
main.main()
        C:/.../main.go:25 +0x115
exit status 2

int32 is insufficient for some volume

Please consider updating the type for volume fields in entities.go from int32 to int64. int32 has a max value of 2.1 billion, and as we've seen this week, even daily volume can blow past that

Issue with Data Proxy Setup

When I attempted to use the data proxy with:

DATA_PROXY_WS=ws://127.0.0.1:8765

I get a TLS error as this line:

if ub.Scheme == "http" {
only changes to ws scheme if http is detected.

I am able to resolve by doing one of the following:

  1. Set data proxy scheme to http, eg: DATA_PROXY_WS=http://127.0.0.1:8765 (currently what I am doing)
  2. Adjust the linked line to look for ws or http and set the scheme appropriately

If there is a preferred approach, I am happy to open a PR for this

WARN datav2stream: got error from server: slow client

I have a subscription and streaming all tickers ("*") for trades, quotes and bars based on the data-stream example Every now and then I get this error where I also observe drop in Network History:

WARN datav2stream: got error from server: slow client

I use 8 goroutines stream.WithProcessors(8) on Intel-i9 comp and my network's bandwidth is 300Mb, should not be a problem. How can I resolve this isssue? Thank you.

Json unmarshaling error at marketdata.go GetBars

I tried both GetBarsAsync and GetBars and they return this puzzling error:
json unmarshal error: invalid character 'N' looking for beginning of value
This seems to be a reference to the "N" field of TimeFrame, though I cannot determine where in the call this error would originate.

Below is the code that calls it.

mktClient := marketdata.NewClient(marketdata.ClientOpts{
  ApiKey:    key,
  ApiSecret: secret,
  BaseURL:   "https://data.alpaca.markets/v2",
})

bars, err := mktClient.GetBars("AAPL", marketdata.GetBarsParams{
  Start:      time.Now().AddDate(0,0,-15),
  End:        time.Now().AddDate(0,0,-5),
  Feed:       "sip",
  TimeFrame:  marketdata.OneMin,
  Adjustment: marketdata.Raw,
})

Please advise! Thanks.

alpaca/rest.go compilation error

I'm getting this error compiling the tree:

$ go test ./...
# github.com/alpacahq/alpaca-trade-api-go/alpaca
alpaca/rest.go:180:23: conversion from int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)
FAIL	github.com/alpacahq/alpaca-trade-api-go/alpaca [build failed]

I can open a PR to fix that.. I'm using Go v1.15.2.

paper bars endpoint not found

Initially reported by @ezuhl in the Alpaca-API repository:

I am using the paper endpoint via your go-lang api.

Request:
limit := 5
param := alpaca.BarListParams{}
param.Timeframe = "day"
//param.StartDt = &start
//param.EndDt = &end
param.Limit = &limit

barList ,err  := alpacaClient.ListBarLists([]string{"MMM", "ABT", "ABBV", "ACN"},param)

//https://paper-api.alpaca.markets/v1/bars?limit=5&symbols=MMM%2CABT%2CABBV%2CACN

Response:
{"code":40410000,"message":"endpoint not found"}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.