├── .gitignore ├── .travis.yml ├── LICENSE ├── README.adoc ├── _config.yml └── bittrex ├── common.go ├── common_test.go ├── public.go ├── public_test.go ├── requests.go └── responses.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | golang-bittrex-api 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 15 | .glide/ 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.8 5 | 6 | before_install: go get ./... 7 | go_import_path: github.com/saniales/golang-bittrex-api -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = THIS PROJECT IS NOW ARCHIVED 2 | 3 | You can use link:https://github.com/toorop/go-bittrex[toorop/go-bittrex library] to connect to Bittrex API. 4 | 5 | = golang-bittrex-api 6 | The Bot Guy 7 | 8 | image:https://travis-ci.org/thebotguys/golang-bittrex-api.svg?branch=master["Build Status", link="https://travis-ci.org/thebotguys/golang-bittrex-api"] 9 | 10 | This wrapper will allow to connect to Bittrex API (version 2.0) 11 | 12 | == Getting the package 13 | 14 | [source, bash] 15 | ---- 16 | $ go get github.com/thebotguys/golang-bittrex-api/bittrex 17 | ---- 18 | 19 | == Calling the API functions 20 | For *Public API* is simple: 21 | [source, go] 22 | ---- 23 | result, err := bittrex.APIFuncDesired(parameters) 24 | if err != nil { 25 | // Handle error 26 | } 27 | // For example 28 | marketSummaries, err := bittrex.GetMarketSummary("BTC-ETH") 29 | if err != nil { 30 | fmt.Println("ERROR OCCURRED: ", err) 31 | } 32 | ---- 33 | For *Private API* is almost equally simple, you have to provide an auth struct with your keys: 34 | [source, go] 35 | ---- 36 | auth := bittrex.Auth{ 37 | PublicKey: "YOUR-PUBLIC-KEY", 38 | SecretKey: "YOUR-SECRET-KEY", 39 | } 40 | result, err := bittrex.PrivateAPIFuncDesired(auth, parameters) 41 | if err != nil { 42 | // Handle error 43 | } 44 | // For example 45 | balances, err := bittrex.GetBalance(auth, "BTC") 46 | if err != nil { 47 | fmt.Println("ERROR OCCURRED: ", err) 48 | } 49 | ---- 50 | 51 | You are *strongly* advised to check if the API is online at the start of your program, with the following code: 52 | [source, go] 53 | ---- 54 | err := bittrex.IsAPIAlive() 55 | if err != nil { 56 | fmt.Println("CANNOT REACH BITTREX API SERVERS: ", err) 57 | } 58 | ---- 59 | 60 | If you are *VERY HARDCORE* you can use an `Options` struct to handle all connections parameters, like `Connection Timeout`: 61 | [source, go] 62 | ---- 63 | // Currently this feature is not implemented 64 | marketSummaries, err := bittrex.GetMarketSummariesWithOpts(&bittrex.Options{ 65 | ConnTimeout: time.Second * 30, 66 | }) 67 | if err != nil { 68 | fmt.Println("ERROR OCCURRED: ", err) 69 | } 70 | ---- 71 | Check out the tests (like link:https://github.com/thebotguys/golang-bittrex-api/blob/master/bittrex/public_test.go[this] one) for an example of usage, but _most of the times_ it will be as simple as the code above. 72 | 73 | == API Limits 74 | The API limits are unknown at the moment but there is an important note, came from resolving a test error: 75 | 76 | Due to the Bittrex anti DDoS System (Cloudflare) it's not possible to perform more than one request per second (otherwise it will be cached, resulting in error like the one described in link:https://github.com/thebotguys/golang-bittrex-api/issues/18[`Issue #18`]) 77 | 78 | I publicly thank link:https://github.com/mastrolinux[*@mastrolinux*], which helped me in the discovery process of this _(let's call it) bug_. 79 | 80 | == Socket API 81 | *Work in progress* 82 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker -------------------------------------------------------------------------------- /bittrex/common.go: -------------------------------------------------------------------------------- 1 | package bittrex 2 | 3 | import ( 4 | "encoding/json" 5 | 6 | "github.com/juju/errors" 7 | 8 | "fmt" 9 | "io/ioutil" 10 | "net/http" 11 | "time" 12 | ) 13 | 14 | // BaseURL represents the base URL for all requests 15 | const ( 16 | BaseURL = "https://bittrex.com/api" 17 | Private = "auth" 18 | Public = "pub" 19 | APIVersion = "2.0" 20 | ) 21 | 22 | // Auth represents the auth credentials to authenticate to the Bittrex API: 23 | // 24 | // It consists of a set of a private and a public key. 25 | type Auth struct { 26 | PublicKey string // The public key to connect to bittrex API. 27 | PrivateKey string // The private key to connect to bittrex API. 28 | } 29 | 30 | var ( 31 | // defaultClient represents the default configuration for HTTP requests to the API. 32 | defaultClient = http.Client{ 33 | Timeout: time.Second * 30, 34 | } 35 | // client represents the actual configuration for HTTP requests to the API. 36 | client = defaultClient 37 | ) 38 | 39 | // SetCustomHTTPClient sets a custom client for requests. 40 | func SetCustomHTTPClient(value http.Client) { 41 | client = value 42 | } 43 | 44 | // apiCall performs a generic API call. 45 | func apiCall(Version, Visibility, Entity, Feature string, GetParameters *publicParams, PostParameters *privateParams) (*json.RawMessage, error) { 46 | URL := fmt.Sprintf("%s/v%s/%s/%s/%s", BaseURL, Version, Visibility, Entity, Feature) 47 | req, err := http.NewRequest("GET", URL, nil) 48 | if err != nil { 49 | return nil, errors.Annotatef(err, "%s - URL: %s", Feature, URL) 50 | } 51 | 52 | req.Header.Set("Accept", "application/json") 53 | req.Header.Set("Cache-Control", "no-cache") 54 | req.Header.Add("Cache-Control", "no-store") 55 | req.Header.Add("Cache-Control", "must-revalidate") 56 | 57 | if Visibility == Public && GetParameters != nil { // Add them to query string 58 | queryString := req.URL.Query() 59 | GetParameters.AddToQueryString(&queryString) 60 | req.URL.RawQuery = queryString.Encode() 61 | } else if Visibility == Private { 62 | addSecurityHeaders(req.Header) 63 | if PostParameters != nil { 64 | PostParameters.AddToPostForm(&req.PostForm) 65 | } 66 | } 67 | 68 | resp, err := client.Do(req) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | if resp.StatusCode != 200 { 74 | return nil, fmt.Errorf("Status Code: %d", resp.StatusCode) 75 | } 76 | defer resp.Body.Close() 77 | 78 | content, err := ioutil.ReadAll(resp.Body) 79 | if err != nil { 80 | return nil, err 81 | } 82 | 83 | var ret response 84 | err = json.Unmarshal(content, &ret) 85 | if err != nil { 86 | return nil, err 87 | } 88 | 89 | if ret.Success == false { 90 | return nil, fmt.Errorf("Error Response: %s", ret.Message) 91 | } 92 | 93 | return ret.Result, nil 94 | } 95 | 96 | // publicCall performs a call to the public bittrex API. 97 | // 98 | // It does not need API Keys. 99 | func publicCall(Entity, Feature string, GetParameters *publicParams) (*json.RawMessage, error) { 100 | return apiCall(APIVersion, Public, Entity, Feature, GetParameters, nil) 101 | } 102 | 103 | // authCall performs a call to the private bittrex API. 104 | // 105 | // It needs an Auth struct to be passed with valid Keys. 106 | func authCall(Entity, Feature string, PostParams *privateParams, auth Auth) (*json.RawMessage, error) { 107 | if auth.PublicKey == "" || auth.PrivateKey == "" { 108 | return nil, errors.New("Cannot perform private api request without authentication keys") 109 | } 110 | //createHMAC signature 111 | return apiCall(APIVersion, Private, Entity, Feature, nil, PostParams) 112 | } 113 | 114 | // addSecurityHeaders adds security headers, required for bittrex private API calls. 115 | // 116 | // Example of this headers which need to be added are HMAC signature. 117 | func addSecurityHeaders(header http.Header) { 118 | 119 | } 120 | -------------------------------------------------------------------------------- /bittrex/common_test.go: -------------------------------------------------------------------------------- 1 | package bittrex_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/thebotguys/golang-bittrex-api/bittrex" 7 | ) 8 | 9 | func testIsAPIAlive(t *testing.T) bool { 10 | err := bittrex.IsAPIAlive() 11 | if err != nil { 12 | t.Log("API is not reachable, test is invalid") 13 | } 14 | return err == nil 15 | } 16 | -------------------------------------------------------------------------------- /bittrex/public.go: -------------------------------------------------------------------------------- 1 | package bittrex 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | "sort" 10 | "time" 11 | ) 12 | 13 | // IsAPIAlive returns true if the bittrex api is reachable with the current network connection. 14 | func IsAPIAlive() error { 15 | var pingResponse pingResponse 16 | timestamp := time.Now().UTC().Unix() 17 | URL := fmt.Sprintf("https://socket.bittrex.com/signalr/ping?_=%d", timestamp) 18 | response, err := http.Get(URL) 19 | if err != nil { 20 | return err 21 | } 22 | defer response.Body.Close() 23 | 24 | if response.StatusCode != 200 { 25 | return fmt.Errorf("Status Code: %d", response.StatusCode) 26 | } 27 | 28 | body, err := ioutil.ReadAll(response.Body) 29 | if err != nil { 30 | return err 31 | } 32 | 33 | err = json.Unmarshal(body, &pingResponse) 34 | if err != nil { 35 | return err 36 | } 37 | if pingResponse.Response == "pong" { 38 | return nil 39 | } 40 | return errors.New("API is not live") 41 | } 42 | 43 | // GetBTCPrice returns the current BTC Price. 44 | func GetBTCPrice() (*BTCPrice, error) { 45 | result, err := publicCall("currencies", "GetBTCPrice", nil) 46 | if err != nil { 47 | return nil, err 48 | } 49 | 50 | var btcPrice BTCPrice 51 | 52 | err = json.Unmarshal(*result, &btcPrice) 53 | if err != nil { 54 | return nil, err 55 | } 56 | return &btcPrice, nil 57 | } 58 | 59 | // GetLatestTick returns the latest tick of the 60 | // specified market's candlestick chart, 61 | // following the specified tick interval. 62 | func GetLatestTick(marketName, tickInterval string) (*CandleStick, error) { 63 | ticks, err := tickFunc(marketName, tickInterval, "GetLatestTick") 64 | if err != nil { 65 | return nil, err 66 | } 67 | return &ticks[0], nil 68 | } 69 | 70 | // GetTicks returns the ticks of the 71 | // specified market's candlestick chart, 72 | // following the specified tick interval. 73 | func GetTicks(marketName, tickInterval string) (CandleSticks, error) { 74 | return tickFunc(marketName, tickInterval, "GetTicks") 75 | } 76 | 77 | // GetMarketSummaries gets the summary of all markets. 78 | func GetMarketSummaries() (MarketSummaries, error) { 79 | now := time.Now().Unix() 80 | GetParameters := publicParams{ 81 | Timestamp: &now, 82 | } 83 | result, err := publicCall("markets", "GetMarketSummaries", &GetParameters) 84 | if err != nil { 85 | return nil, err 86 | } 87 | var resp MarketSummariesResult 88 | err = json.Unmarshal(*result, &resp) 89 | if err != nil { 90 | return nil, err 91 | } 92 | 93 | return resp.Summaries(), nil 94 | } 95 | 96 | // GetMarketSummary gets the summary of a single market. 97 | func GetMarketSummary(marketName string) (*MarketSummary, error) { 98 | now := time.Now().UnixNano() 99 | GetParameters := publicParams{ 100 | MarketName: &marketName, 101 | Timestamp: &now, 102 | } 103 | 104 | result, err := publicCall("market", "GetMarketSummary", &GetParameters) 105 | if err != nil { 106 | return nil, err 107 | } 108 | 109 | var ret MarketSummary 110 | err = json.Unmarshal(*result, &ret) 111 | if err != nil { 112 | return nil, err 113 | } 114 | return &ret, nil 115 | } 116 | 117 | // tickFunc is a common pattern for GetTicks and GetLatestTick functions. 118 | // candles are sorted by timestamp from the oldest to the most recent: 119 | // 120 | // oldest = index -> 0 121 | // newest = index -> len(candlestick_array) - 1 122 | func tickFunc(marketName, tickInterval, tickFeature string) (CandleSticks, error) { 123 | now := time.Now().Unix() 124 | GetParameters := publicParams{ 125 | MarketName: &marketName, 126 | TickInterval: &tickInterval, 127 | Timestamp: &now, 128 | } 129 | result, err := publicCall("market", tickFeature, &GetParameters) 130 | if err != nil { 131 | return nil, err 132 | } 133 | var ret CandleSticks 134 | err = json.Unmarshal(*result, &ret) 135 | if err != nil { 136 | return nil, err 137 | } 138 | sort.Sort(csByTimestamp{ret}) // sort from most recent 139 | return ret, nil 140 | } 141 | 142 | // GetOrderBook gets the current order book, made up by currently open orders. 143 | func GetOrderBook(marketName string) (OrderBook, error) { 144 | return nil, nil 145 | } 146 | 147 | //GetMarkets gets all markets data. 148 | func GetMarkets() (Markets, error) { 149 | now := time.Now().Unix() 150 | GetParameters := publicParams{ 151 | Timestamp: &now, 152 | } 153 | 154 | // GetMarkets uses GetMarketsSummaries now to gather its data. 155 | // This is due to a 404 on GetMarkets endpoint. See Issue #28. 156 | result, err := publicCall("markets", "GetMarketSummaries", &GetParameters) 157 | if err != nil { 158 | return nil, err 159 | } 160 | 161 | var resp MarketSummariesResult 162 | err = json.Unmarshal(*result, &resp) 163 | if err != nil { 164 | return nil, err 165 | } 166 | 167 | return resp.Markets(), nil 168 | } 169 | -------------------------------------------------------------------------------- /bittrex/public_test.go: -------------------------------------------------------------------------------- 1 | package bittrex_test 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | 8 | "github.com/thebotguys/golang-bittrex-api/bittrex" 9 | ) 10 | 11 | func TestGetBTCPrice(t *testing.T) { 12 | if testIsAPIAlive(t) { 13 | _, err := bittrex.GetBTCPrice() 14 | if err != nil { 15 | t.Fatal(err) 16 | } 17 | } 18 | } 19 | 20 | func TestGetTicks(t *testing.T) { 21 | if testIsAPIAlive(t) { 22 | time.Sleep(time.Second * 2) 23 | _, err := bittrex.GetTicks("BTC-ETH", "thirtyMin") 24 | if err != nil { 25 | t.Fatal(err) 26 | } 27 | time.Sleep(time.Second * 2) 28 | val, err := bittrex.GetTicks("INVALID-MARKET-HAHA", "thirtyMin") 29 | if err == nil { 30 | t.Fatal("Error expected, but function did " + 31 | "not fail (GetTicks(\"INVALID-MARKET-HAHA\", " + 32 | "\"thirtyMin\"))\n Value Returned : " + 33 | fmt.Sprint(val)) 34 | } 35 | time.Sleep(time.Second * 2) 36 | val, err = bittrex.GetTicks("", "thirtyMin") 37 | if err == nil { 38 | t.Fatal("Error expected, but function did " + 39 | "not fail (GetTicks(\"\", \"thirtyMin\"))\n" + 40 | "Value Returned : " + fmt.Sprint(val)) 41 | } 42 | time.Sleep(time.Second * 2) 43 | val, err = bittrex.GetTicks("BTC-LTC", "INVALID-INTERVAL-HAHA") 44 | if err == nil { 45 | t.Fatal("Error expected, but function did " + 46 | "not fail (GetTicks(\"BTC-LTC\", \"INVALID-INTERVAL-HAHA\"))\n" + 47 | "Value Returned : " + fmt.Sprint(val)) 48 | } 49 | time.Sleep(time.Second * 2) 50 | val, err = bittrex.GetTicks("BTC-LTC", "") 51 | if err == nil { 52 | t.Fatal("Error expected, but function did " + 53 | "not fail (GetTicks(\"BTC-LTC\", \"\"))\n" + 54 | "Value Returned : " + fmt.Sprint(val)) 55 | } 56 | } 57 | } 58 | 59 | func TestGetLatestTick(t *testing.T) { 60 | if testIsAPIAlive(t) { 61 | time.Sleep(time.Second * 2) 62 | _, err := bittrex.GetLatestTick("BTC-ETH", "thirtyMin") 63 | if err != nil { 64 | t.Fatal(err) 65 | } 66 | time.Sleep(time.Second * 2) 67 | val, err := bittrex.GetLatestTick("INVALID-MARKET-HAHA", "thirtyMin") 68 | if err == nil { 69 | t.Fatal("Error expected, but function did " + 70 | "not fail (GetLatestTick(\"INVALID-MARKET-HAHA\", " + 71 | "\"thirtyMin\"))\n Value Returned : " + 72 | fmt.Sprint(val)) 73 | } 74 | time.Sleep(time.Second * 2) 75 | val, err = bittrex.GetLatestTick("", "thirtyMin") 76 | if err == nil { 77 | t.Fatal("Error expected, but function did " + 78 | "not fail (GetLatestTick(\"\", \"thirtyMin\"))\n" + 79 | "Value Returned : " + fmt.Sprint(val)) 80 | } 81 | time.Sleep(time.Second * 2) 82 | val, err = bittrex.GetLatestTick("BTC-LTC", "INVALID-INTERVAL-HAHA") 83 | if err == nil { 84 | t.Fatal("Error expected, but function did " + 85 | "not fail (GetLatestTick(\"BTC-LTC\", \"INVALID-INTERVAL-HAHA\"))\n" + 86 | "Value Returned : " + fmt.Sprint(val)) 87 | } 88 | time.Sleep(time.Second * 2) 89 | val, err = bittrex.GetLatestTick("BTC-LTC", "") 90 | if err == nil { 91 | t.Fatal("Error expected, but function did " + 92 | "not fail (GetLatestTick(\"BTC-LTC\", \"\"))\n" + 93 | "Value Returned : " + fmt.Sprint(val)) 94 | } 95 | } 96 | } 97 | 98 | func TestGetMarketSummaries(t *testing.T) { 99 | if testIsAPIAlive(t) { 100 | _, err := bittrex.GetMarketSummaries() 101 | if err != nil { 102 | t.Fatal(err) 103 | } 104 | } 105 | } 106 | 107 | func TestGetMarketSummary(t *testing.T) { 108 | if testIsAPIAlive(t) { 109 | var err error 110 | time.Sleep(time.Second * 2) 111 | _, err = bittrex.GetMarketSummary("BTC-ETH") // no error expected 112 | if err != nil { 113 | t.Fatal(err) 114 | } 115 | time.Sleep(time.Second * 2) 116 | val, err := bittrex.GetMarketSummary("INVALID-MARKET-HAHA") // error expected 117 | if err == nil { 118 | t.Fatal("Error expected, but function did not fail (GetMarketSummary(\"INVALID-MARKET-HAHA\"))\n Value Returned : " + fmt.Sprint(val)) 119 | } 120 | time.Sleep(time.Second * 2) 121 | val, err = bittrex.GetMarketSummary("") // error expected 122 | if err == nil { 123 | t.Fatal("Error expected, but function did not fail (GetMarketSummary(\"\"))\n Value Returned : " + fmt.Sprint(val)) 124 | } 125 | } 126 | } 127 | 128 | func TestGetMarkets(t *testing.T) { 129 | if testIsAPIAlive(t) { 130 | _, err := bittrex.GetMarkets() // no error expected 131 | if err != nil { 132 | t.Fatal(err) 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /bittrex/requests.go: -------------------------------------------------------------------------------- 1 | package bittrex 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | ) 7 | 8 | // publicParams represents the possible public parameters that can 9 | // be passed for public Api calls. 10 | type publicParams struct { 11 | MarketName *string 12 | TickInterval *string 13 | Timestamp *int64 14 | } 15 | 16 | // AddToQueryString adds the non empty fields of the publicParams struct 17 | // to the specified query string. 18 | func (pp *publicParams) AddToQueryString(queryString *url.Values) { 19 | if queryString != nil { 20 | if pp.MarketName != nil { 21 | queryString.Set("marketName", *pp.MarketName) 22 | } 23 | if pp.TickInterval != nil { 24 | queryString.Set("tickInterval", *pp.TickInterval) 25 | } 26 | queryString.Set("_", fmt.Sprint(*pp.Timestamp)) 27 | } 28 | } 29 | 30 | // privateParams represents the possible private parameters that can 31 | // be passed for auth API calls. 32 | type privateParams struct { 33 | } 34 | 35 | // AddToPostForm adds the non empty fields of the publicParams struct 36 | // to the specified post form. 37 | func (pp privateParams) AddToPostForm(postForm *url.Values) { 38 | if postForm != nil { 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /bittrex/responses.go: -------------------------------------------------------------------------------- 1 | package bittrex 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/shopspring/decimal" 9 | ) 10 | 11 | type response struct { 12 | Success bool `json:"success,required"` 13 | Message string `json:"message,omitempty"` 14 | Result *json.RawMessage `json:"result,required"` 15 | } 16 | 17 | type pingResponse struct { 18 | Response string `json:"response,required"` 19 | } 20 | 21 | type versionResponse struct { 22 | Version json.Number `json:"version,required,Number"` 23 | } 24 | 25 | // MarketSummary is the summary data of a market (usually 24h summary). 26 | type MarketSummary struct { 27 | MarketName string `json:"MarketName,required"` //The name of the market (e.g. BTC-ETH). 28 | High decimal.Decimal `json:"High,required"` // The 24h high for the market. 29 | Low decimal.Decimal `json:"Low,required"` // The 24h low for the market. 30 | Last decimal.Decimal `json:"Last,required"` // The value of the last trade for the market (in base currency). 31 | Bid decimal.Decimal `json:"Bid,required"` // The current highest bid value for the market. 32 | Ask decimal.Decimal `json:"Ask,required"` // The current lowest ask value for the market. 33 | Volume decimal.Decimal `json:"Volume,required"` // The 24h volume of the market, in market currency. 34 | BaseVolume decimal.Decimal `json:"BaseVolume,required"` // The 24h volume for the market, in base currency. 35 | Timestamp string `json:"Timestamp,required"` // The timestamp of the request. 36 | OpenBuyOrders uint64 `json:"OpenBuyOrders,required"` // The number of currently open buy orders. 37 | OpenSellOrders uint64 `json:"OpenSellOrders,required"` // The number of currently open sell orders. 38 | PrevDay decimal.Decimal `json:"PrevDay,required"` // The closing price 24h before. 39 | Created string `json:"Created,required"` // The timestamp of the creation of the market. 40 | } 41 | 42 | // MarketSummaries is a set of MarketSummary objects. 43 | type MarketSummaries []MarketSummary 44 | 45 | // MarketSummaryResult is a single unit of a MarketSummariesResult response and 46 | // represents a single couple (Market Data, Market Summary) value. 47 | type MarketSummaryResult struct { 48 | IsVerified bool `json:"IsVerified"` 49 | Market Market `json:"Market,required"` 50 | Summary MarketSummary `json:"Summary,required"` 51 | } 52 | 53 | // MarketSummariesResult is the response from a GetSummaries call. 54 | type MarketSummariesResult []MarketSummaryResult 55 | 56 | // Markets returns only the markets. 57 | func (msr MarketSummariesResult) Markets() Markets { 58 | ret := make(Markets, len(msr)) 59 | 60 | for i, result := range msr { 61 | ret[i] = result.Market 62 | } 63 | 64 | return ret 65 | } 66 | 67 | // Summaries returns only the market summaries. 68 | func (msr MarketSummariesResult) Summaries() MarketSummaries { 69 | ret := make(MarketSummaries, len(msr)) 70 | 71 | for i, result := range msr { 72 | ret[i] = result.Summary 73 | } 74 | 75 | return ret 76 | } 77 | 78 | // OpenOrder represents a currently open order. 79 | type OpenOrder struct { 80 | } 81 | 82 | // OrderBook represents a set of public open Orders, which compose the OrderBook. 83 | type OrderBook []OpenOrder 84 | 85 | // Market represents a market metadata (name, base currency, trade currency) 86 | // and so forth. 87 | type Market struct { 88 | BaseCurrency string `json:"BaseCurrency,required"` 89 | BaseCurrencyLong string `json:"BaseCurrencyLong,required"` 90 | MarketCurrency string `json:"MarketCurrency,required"` 91 | MarketCurrencyLong string `json:"MarketCurrencyLong,required"` 92 | MarketName string `json:"MarketName,required"` 93 | MinTradeSize decimal.Decimal `json:"MinTradeSize,required"` 94 | IsActive bool `json:"IsActive,required"` 95 | Created string `json:"Created,required"` 96 | Notice string `json:"Notice,required"` 97 | IsSponsored bool `json:"IsSponsored,required"` 98 | LogoURL string `json:"LogoUrl,required"` 99 | } 100 | 101 | // Markets is a set of markets. 102 | type Markets []Market 103 | 104 | type btcPriceResult struct { 105 | Bpi struct { 106 | USD struct { 107 | Code string `json:"code,required"` 108 | Description string `json:"description,required"` 109 | Rate string `json:"rate,required"` 110 | RateFloat json.Number `json:"rate_float,required"` 111 | } `json:"USD,required"` 112 | Disclaimer string `json:"disclaimer,required"` 113 | } `json:"bpi,required"` 114 | Time struct { 115 | Updated string `json:"updated,required"` 116 | UpdatedISO string `json:"updatedISO,omitempty"` 117 | UpdatedUK string `json:"updateduk,omitempty"` 118 | } `json:"time,required"` 119 | } 120 | 121 | // CandleStick represents a single candlestick in a chart. 122 | type CandleStick struct { 123 | High decimal.Decimal `json:"H,required"` 124 | Open decimal.Decimal `json:"O,required"` 125 | Close decimal.Decimal `json:"C,required"` 126 | Low decimal.Decimal `json:"L,required"` 127 | Volume decimal.Decimal `json:"V,required"` 128 | BaseVolume decimal.Decimal `json:"BV,required"` 129 | Timestamp candleTime `json:"T,required"` 130 | } 131 | 132 | // CandleSticks is an array of CandleStick objects. It is a result from GetTicks 133 | // and GetLatestTick calls too. 134 | type CandleSticks []CandleStick 135 | type csByTimestamp struct { 136 | CandleSticks 137 | } 138 | 139 | func (csbt csByTimestamp) Less(i, j int) bool { 140 | return time.Time(csbt.CandleSticks[i].Timestamp).Before(time.Time(csbt.CandleSticks[j].Timestamp)) 141 | } 142 | 143 | func (csbt csByTimestamp) Len() int { 144 | return len(csbt.CandleSticks) 145 | } 146 | 147 | func (csbt csByTimestamp) Swap(i, j int) { 148 | csbt.CandleSticks[i], csbt.CandleSticks[j] = csbt.CandleSticks[j], csbt.CandleSticks[i] 149 | } 150 | 151 | // CandleIntervals represent all valid intervals supported 152 | // by the GetTicks and GetLatestTick calls. 153 | var CandleIntervals = map[string]bool{ 154 | "oneMin": true, 155 | "fiveMin": true, 156 | "thirtyMin": true, 157 | "hour": true, 158 | "day": true, 159 | } 160 | 161 | type candleTime time.Time 162 | 163 | func (t *candleTime) UnmarshalJSON(b []byte) error { 164 | if len(b) < 2 { 165 | return fmt.Errorf("could not parse time %s", string(b)) 166 | } 167 | // trim enclosing "" 168 | result, err := time.Parse("2006-01-02T15:04:05", string(b[1:len(b)-1])) 169 | if err != nil { 170 | return fmt.Errorf("could not parse time: %v", err) 171 | } 172 | *t = candleTime(result) 173 | return nil 174 | } 175 | 176 | func (t candleTime) MarshalJSON() ([]byte, error) { 177 | stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02T15:04:05")) 178 | return []byte(stamp), nil 179 | } 180 | 181 | func (result btcPriceResult) Compress() BTCPrice { 182 | value, _ := result.Bpi.USD.RateFloat.Float64() 183 | ts, _ := time.Parse(time.RFC3339, result.Time.UpdatedISO) 184 | return BTCPrice{ 185 | USDValue: decimal.NewFromFloat(value), 186 | Timestamp: ts, 187 | } 188 | } 189 | 190 | // BTCPrice represents the BTC price at the specified timestamp. 191 | type BTCPrice struct { 192 | USDValue decimal.Decimal 193 | Timestamp time.Time 194 | } 195 | --------------------------------------------------------------------------------