github.com/polygon-io/client-go@v1.16.4/README.md (about) 1 # Polygon Go Client 2  3 4 <!-- todo: add a codecov badge --> 5 <!-- todo: figure out a way to show all build statuses --> 6 <!-- todo: consider moving some stuff into separate readmes --> 7 8 [![docs][doc-img]][doc] [![Build][build-img]][build] [![Go Report Card][report-card-img]][report-card] 9 10 The official Go client library for the [Polygon](https://polygon.io/) REST and WebSocket API. This client makes use of Go generics and thus requires Go 1.18. See the [docs](https://polygon.io/docs/stocks/getting-started) for more details on our API. 11 12 ## Getting Started 13 14 This section guides you through setting up a simple project with polygon-io/client-go. 15 16 First, make a new directory for your project and navigate into it: 17 ```bash 18 mkdir myproject && cd myproject 19 ``` 20 21 Next, initialize a new module for dependency management. This creates a `go.mod` file to track your dependencies: 22 ```bash 23 go mod init example 24 ``` 25 26 Then, create a `main.go` file. For quick start, you can find over 100+ [example code snippets](https://github.com/polygon-io/client-go/tree/master/rest/example) that demonstrate connecting to both the REST and WebSocket APIs. Here's an example that fetches the last trade for `AAPL`. 27 28 ```bash 29 cat > main.go <<EOF 30 // Stocks - Last Trade 31 // https://polygon.io/docs/stocks/get_v2_last_trade__stocksticker 32 // https://github.com/polygon-io/client-go/blob/master/rest/trades.go 33 package main 34 35 import ( 36 "context" 37 "log" 38 "os" 39 40 polygon "github.com/polygon-io/client-go/rest" 41 "github.com/polygon-io/client-go/rest/models" 42 ) 43 44 func main() { 45 46 // init client 47 c := polygon.New(os.Getenv("POLYGON_API_KEY")) 48 49 // set params 50 params := &models.GetLastTradeParams{ 51 Ticker: "AAPL", 52 } 53 54 // make request 55 res, err := c.GetLastTrade(context.Background(), params) 56 if err != nil { 57 log.Fatal(err) 58 } 59 60 // do something with the result 61 log.Print(res) 62 63 } 64 EOF 65 ``` 66 67 Please remember to set your Polygon API key, which you can find on the polygon.io dashboard, in the environment variable `POLYGON_API_KEY`. Or, as a less secure option, by hardcoding it in your code. But please note that hardcoding the API key can be risky if your code is shared or exposed. You can configure the environment variable by running: 68 69 ``` 70 export POLYGON_API_KEY="<your_api_key>" <- mac/linux 71 xset POLYGON_API_KEY "<your_api_key>" <- windows 72 ``` 73 74 Then, run `go mod tidy` to automatically download and install the necessary dependencies. This command ensures your `go.mod` file reflects all dependencies used in your project: 75 ```bash 76 go mod tidy 77 ``` 78 79 Finally, execute your application: 80 ```bash 81 go run main.go 82 ``` 83 84 ## REST API Client 85 86 [![rest-docs][rest-doc-img]][rest-doc] 87 88 To get started, you'll need to import two main packages. 89 90 ```golang 91 import ( 92 polygon "github.com/polygon-io/client-go/rest" 93 "github.com/polygon-io/client-go/rest/models" 94 ) 95 ``` 96 97 Next, create a new client with your [API key](https://polygon.io/dashboard/signup). 98 99 ```golang 100 c := polygon.New("YOUR_API_KEY") 101 ``` 102 103 Or create a client with a custom HTTP client implementation. 104 105 ```golang 106 hc := http.Client{} // some custom HTTP client 107 c := polygon.NewWithClient("YOUR_API_KEY", hc) 108 ``` 109 110 ### Using the client 111 112 After creating the client, making calls to the Polygon API is simple. 113 114 ```golang 115 params := models.GetTickerDetailsParams{ 116 Ticker: "AAPL", 117 }.WithDate(models.Date(time.Date(2021, 7, 22, 0, 0, 0, 0, time.Local))) 118 119 res, err := c.GetTickerDetails(context.Background(), params) 120 if err != nil { 121 log.Fatal(err) 122 } 123 log.Print(res) // do something with the result 124 ``` 125 126 ### Pagination 127 128 Our list methods return iterators that handle pagination for you. 129 130 ```golang 131 // create a new iterator 132 params := models.ListTradesParams{Ticker: "AAPL"}. 133 WithTimestamp(models.GTE, models.Nanos(time.Date(2021, 7, 22, 0, 0, 0, 0, time.UTC))). 134 WithOrder(models.Asc) 135 iter := c.ListTrades(context.Background(), params) 136 137 // iter.Next() advances the iterator to the next value in the list 138 for iter.Next() { 139 log.Print(iter.Item()) // do something with the current value 140 } 141 142 // if the loop breaks, it has either reached the end of the list or an error has occurred 143 // you can check if something went wrong with iter.Err() 144 if iter.Err() != nil { 145 log.Fatal(iter.Err()) 146 } 147 ``` 148 149 We also provide a builder method to make it easier to retrieve all trades and quotes for a specific day. 150 151 ```golang 152 params := models.ListQuotesParams{Ticker: "AAPL"}. 153 WithDay(2021, 7, 22). // get all quotes for July 22, 2021 154 WithOrder(models.Asc) 155 iter := c.ListQuotes(context.Background(), params) 156 157 for iter.Next() { 158 log.Print(iter.Item()) 159 } 160 if iter.Err() != nil { 161 log.Fatal(iter.Err()) 162 } 163 ``` 164 165 ### Request options 166 167 Advanced users may want to add additional headers or query params to a given request. 168 169 ```golang 170 params := &models.GetGroupedDailyAggsParams{ 171 Locale: models.US, 172 MarketType: models.Stocks, 173 Date: models.Date(time.Date(2021, 7, 22, 0, 0, 0, 0, time.Local)), 174 } 175 176 res, err := c.GetGroupedDailyAggs(context.Background(), params, 177 models.APIKey("YOUR_OTHER_API_KEY"), 178 models.Header("X-CUSTOM-HEADER", "VALUE"), 179 models.QueryParam("adjusted", strconv.FormatBool(true))) 180 if err != nil { 181 log.Fatal(err) 182 } 183 log.Print(res) // do something with the result 184 ``` 185 186 #### Launchpad Usage 187 188 Users of the Launchpad product will need to pass in certain headers in order to make API requests. 189 Example can be found [here](./rest/example/launchpad). 190 191 ### Debugging 192 193 Sometimes you may find it useful to see the actual request and response details while working with the API. The client allows for this through its `models.WithTrace(true)` option. 194 195 #### How to Enable Debug Mode 196 197 You can activate the debug mode per request as follows by adding `models.WithTrace(true)` after the `params`: 198 199 ```go 200 iter := c.ListAggs(context.Background(), params, models.WithTrace(true)) 201 ``` 202 203 #### What Does Debug Mode Do? 204 205 When debug mode is enabled, the client will print out useful debugging information for each API request. This includes: the request URL, the headers sent in the request, and the headers received in the response. 206 207 #### Example Output 208 209 For instance, if you made a request for `TSLA` data for the date `2023-08-01`, you would see debug output similar to the following: 210 211 ``` 212 Request URL: /v2/aggs/ticker/AAPL/range/1/day/1672531200000/1678320000000?adjusted=true&limit=50000&sort=desc 213 Request Headers: map[Accept-Encoding:[gzip] Authorization:[REDACTED] User-Agent:[Polygon.io GoClient/v1.14.1]] 214 Response Headers: map[Content-Encoding:[gzip] Content-Length:[1639] Content-Type:[application/json] Date:[Tue, 05 Sep 2023 23:25:00 GMT] Server:[nginx/1.19.2] Strict-Transport-Security:[max-age=15724800; includeSubDomains] Vary:[Accept-Encoding] X-Request-Id:[ba3d3e9f42622bd16d05dafe01200f72]] 215 ``` 216 217 This can be an invaluable tool for debugging issues or understanding how the client interacts with the API. 218 219 ## WebSocket Client 220 221 [![ws-docs][ws-doc-img]][ws-doc] 222 223 Import the WebSocket client and models packages to get started. 224 225 ```golang 226 import ( 227 polygonws "github.com/polygon-io/client-go/websocket" 228 "github.com/polygon-io/client-go/websocket/models" 229 ) 230 ``` 231 232 Next, create a new client with your API key and a couple other config options. 233 234 ```golang 235 // create a new client 236 c, err := polygonws.New(polygonws.Config{ 237 APIKey: "YOUR_API_KEY", 238 Feed: polygonws.RealTime, 239 Market: polygonws.Stocks, 240 }) 241 if err != nil { 242 log.Fatal(err) 243 } 244 defer c.Close() // the user of this client must close it 245 246 // connect to the server 247 if err := c.Connect(); err != nil { 248 log.Error(err) 249 return 250 } 251 ``` 252 253 The client automatically reconnects to the server when the connection is dropped. By default, it will attempt to reconnect indefinitely but the number of retries is configurable. When the client successfully reconnects, it automatically resubscribes to any topics that were set before the disconnect. 254 255 ### Using the client 256 257 After creating a client, subscribe to one or more topics and start accessing data. Currently, all of the data is pushed to a single output channel. 258 259 ```golang 260 // passing a topic by itself will subscribe to all tickers 261 if err := c.Subscribe(polygonws.StocksSecAggs); err != nil { 262 log.Fatal(err) 263 } 264 if err := c.Subscribe(polygonws.StocksTrades, "TSLA", "GME"); err != nil { 265 log.Fatal(err) 266 } 267 268 for { 269 select { 270 case err := <-c.Error(): // check for any fatal errors (e.g. auth failed) 271 log.Fatal(err) 272 case out, more := <-c.Output(): // read the next data message 273 if !more { 274 return 275 } 276 277 switch out.(type) { 278 case models.EquityAgg: 279 log.Print(out) // do something with the agg 280 case models.EquityTrade: 281 log.Print(out) // do something with the trade 282 } 283 } 284 } 285 ``` 286 287 See the [full example](./websocket/example/main.go) for more details on how to use this client effectively. 288 289 ## Release planning 290 291 This client will attempt to follow the release cadence of our API. When endpoints are deprecated and newer versions are added, the client will maintain two methods in a backwards compatible way (e.g. `ListTrades` and `ListTradesV4(...)`). When deprecated endpoints are removed from the API, we'll rename the versioned method (e.g. `ListTradesV4(...)` -> `ListTrades(...)`), remove the old method, and release a new major version of the client. The goal is to give users ample time to upgrade to newer versions of our API _before_ we bump the major version of the client, and in general, we'll try to bundle breaking changes like this to avoid frequent major version bumps. 292 293 There are a couple exceptions to this. When we find small breaking issues with this client library (e.g. incorrect response types), we may decide to release them under the same major version. These changes will be clearly outlined in the release notes. Also, methods that fall under the VX client are considered experimental and may be modified or deprecated as needed. We'll call out any breaking changes to VX endpoints in our release notes to make using them easier. 294 295 ## Contributing 296 297 If you found a bug or have an idea for a new feature, please first discuss it with us by [submitting a new issue](https://github.com/polygon-io/client-go/issues/new/choose). We will respond to issues within at most 3 weeks. We're also open to volunteers if you want to submit a PR for any open issues but please discuss it with us beforehand. PRs that aren't linked to an existing issue or discussed with us ahead of time will generally be declined. If you have more general feedback or want to discuss using this client with other users, feel free to reach out on our [Slack channel](https://polygon-io.slack.com/archives/C03FCSBSAFL). 298 299 ------------------------------------------------------------------------------- 300 301 [doc-img]: https://pkg.go.dev/badge/github.com/polygon-io/client-go 302 [doc]: https://pkg.go.dev/github.com/polygon-io/client-go 303 [rest-doc-img]: https://pkg.go.dev/badge/github.com/polygon-io/client-go/rest 304 [rest-doc]: https://pkg.go.dev/github.com/polygon-io/client-go/rest 305 [ws-doc-img]: https://pkg.go.dev/badge/github.com/polygon-io/client-go/websocket 306 [ws-doc]: https://pkg.go.dev/github.com/polygon-io/client-go/websocket 307 [build-img]: https://github.com/polygon-io/client-go/actions/workflows/test.yml/badge.svg 308 [build]: https://github.com/polygon-io/client-go/actions 309 [report-card-img]: https://goreportcard.com/badge/github.com/polygon-io/client-go 310 [report-card]: https://goreportcard.com/report/github.com/polygon-io/client-go