github.com/vmpartner/bitmex@v1.1.0/swagger/api_client.go (about)

     1  /* 
     2   * BitMEX API
     3   *
     4   * ## REST API for the BitMEX Trading Platform  [View Changelog](/app/apiChangelog)    #### Getting Started   ##### Fetching Data  All REST endpoints are documented below. You can try out any query right from this interface.  Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first.  Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI).  *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits.  ##### Return Types  By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data.  ##### Trade Data Queries  *This is only a small subset of what is available, to get you started.*  Fill in the parameters and click the `Try it out!` button to try any of these queries.  * [Pricing Data](#!/Quote/Quote_get)  * [Trade Data](#!/Trade/Trade_get)  * [OrderBook Data](#!/OrderBook/OrderBook_getL2)  * [Settlement Data](#!/Settlement/Settlement_get)  * [Exchange Statistics](#!/Stats/Stats_history)  Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available.  ##### Swagger Specification  [⇩ Download Swagger JSON](swagger.json)    ## All API Endpoints  Click to expand a section. 
     5   *
     6   * OpenAPI spec version: 1.2.0
     7   * Contact: support@bitmex.com
     8   * Generated by: https://github.com/swagger-api/swagger-codegen.git
     9   */
    10  
    11  package swagger
    12  
    13  import (
    14  	"bytes"
    15  	"encoding/json"
    16  	"encoding/xml"
    17  	"fmt"
    18  	"errors"
    19  	"io"
    20  	"mime/multipart"
    21  	"golang.org/x/oauth2"
    22  	"golang.org/x/net/context"
    23  	"net/http"
    24  	"net/url"
    25  	"time"
    26  	"os"
    27  	"path/filepath"
    28  	"reflect"
    29  	"regexp"
    30  	"strings"
    31  	"unicode/utf8"
    32  	"strconv"
    33  )
    34  
    35  var (
    36  	jsonCheck = regexp.MustCompile("(?i:[application|text]/json)")
    37  	xmlCheck  = regexp.MustCompile("(?i:[application|text]/xml)")
    38  )
    39  
    40  // APIClient manages communication with the BitMEX API API v1.2.0
    41  // In most cases there should be only one, shared, APIClient.
    42  type APIClient struct {
    43  	cfg    *Configuration
    44  	common service // Reuse a single struct instead of allocating one for each service on the heap.
    45  
    46  	// API Services
    47  	APIKeyApi       *APIKeyApiService
    48  	AnnouncementApi *AnnouncementApiService
    49  	ChatApi         *ChatApiService
    50  	ExecutionApi    *ExecutionApiService
    51  	FundingApi      *FundingApiService
    52  	InstrumentApi   *InstrumentApiService
    53  	InsuranceApi    *InsuranceApiService
    54  	LeaderboardApi  *LeaderboardApiService
    55  	LiquidationApi  *LiquidationApiService
    56  	NotificationApi *NotificationApiService
    57  	OrderApi        *OrderApiService
    58  	OrderBookApi    *OrderBookApiService
    59  	PositionApi     *PositionApiService
    60  	QuoteApi        *QuoteApiService
    61  	SchemaApi       *SchemaApiService
    62  	SettlementApi   *SettlementApiService
    63  	StatsApi        *StatsApiService
    64  	TradeApi        *TradeApiService
    65  	UserApi         *UserApiService
    66  }
    67  
    68  type service struct {
    69  	client *APIClient
    70  }
    71  
    72  // NewAPIClient creates a new API client. Requires a userAgent string describing your application.
    73  // optionally a custom http.Client to allow for advanced features such as caching.
    74  func NewAPIClient(cfg *Configuration) *APIClient {
    75  	if cfg.HTTPClient == nil {
    76  		cfg.HTTPClient = http.DefaultClient
    77  	}
    78  
    79  	c := &APIClient{}
    80  	c.cfg = cfg
    81  	c.common.client = c
    82  
    83  	// API Services
    84  	c.APIKeyApi = (*APIKeyApiService)(&c.common)
    85  	c.AnnouncementApi = (*AnnouncementApiService)(&c.common)
    86  	c.ChatApi = (*ChatApiService)(&c.common)
    87  	c.ExecutionApi = (*ExecutionApiService)(&c.common)
    88  	c.FundingApi = (*FundingApiService)(&c.common)
    89  	c.InstrumentApi = (*InstrumentApiService)(&c.common)
    90  	c.InsuranceApi = (*InsuranceApiService)(&c.common)
    91  	c.LeaderboardApi = (*LeaderboardApiService)(&c.common)
    92  	c.LiquidationApi = (*LiquidationApiService)(&c.common)
    93  	c.NotificationApi = (*NotificationApiService)(&c.common)
    94  	c.OrderApi = (*OrderApiService)(&c.common)
    95  	c.OrderBookApi = (*OrderBookApiService)(&c.common)
    96  	c.PositionApi = (*PositionApiService)(&c.common)
    97  	c.QuoteApi = (*QuoteApiService)(&c.common)
    98  	c.SchemaApi = (*SchemaApiService)(&c.common)
    99  	c.SettlementApi = (*SettlementApiService)(&c.common)
   100  	c.StatsApi = (*StatsApiService)(&c.common)
   101  	c.TradeApi = (*TradeApiService)(&c.common)
   102  	c.UserApi = (*UserApiService)(&c.common)
   103  
   104  	return c
   105  }
   106  
   107  func atoi(in string) (int, error) {
   108  	return strconv.Atoi(in)
   109  }
   110  
   111  // selectHeaderContentType select a content type from the available list.
   112  func selectHeaderContentType(contentTypes []string) string {
   113  	if len(contentTypes) == 0 {
   114  		return ""
   115  	}
   116  	if contains(contentTypes, "application/json") {
   117  		return "application/json"
   118  	}
   119  	return contentTypes[0] // use the first content type specified in 'consumes'
   120  }
   121  
   122  // selectHeaderAccept join all accept types and return
   123  func selectHeaderAccept(accepts []string) string {
   124  	if len(accepts) == 0 {
   125  		return ""
   126  	}
   127  
   128  	if contains(accepts, "application/json") {
   129  		return "application/json"
   130  	}
   131  
   132  	return strings.Join(accepts, ",")
   133  }
   134  
   135  // contains is a case insenstive match, finding needle in a haystack
   136  func contains(haystack []string, needle string) bool {
   137  	for _, a := range haystack {
   138  		if strings.ToLower(a) == strings.ToLower(needle) {
   139  			return true
   140  		}
   141  	}
   142  	return false
   143  }
   144  
   145  // Verify optional parameters are of the correct type.
   146  func typeCheckParameter(obj interface{}, expected string, name string) error {
   147  	// Make sure there is an object.
   148  	if obj == nil {
   149  		return nil
   150  	}
   151  
   152  	// Check the type is as expected.
   153  	if reflect.TypeOf(obj).String() != expected {
   154  		return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
   155  	}
   156  	return nil
   157  }
   158  
   159  // parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
   160  func parameterToString(obj interface{}, collectionFormat string) string {
   161  	var delimiter string
   162  
   163  	switch collectionFormat {
   164  	case "pipes":
   165  		delimiter = "|"
   166  	case "ssv":
   167  		delimiter = " "
   168  	case "tsv":
   169  		delimiter = "\t"
   170  	case "csv":
   171  		delimiter = ","
   172  	}
   173  
   174  	if reflect.TypeOf(obj).Kind() == reflect.Slice {
   175  		return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
   176  	}
   177  
   178  	return fmt.Sprintf("%v", obj)
   179  }
   180  
   181  // callAPI do the request. 
   182  func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
   183  	return c.cfg.HTTPClient.Do(request)
   184  }
   185  
   186  // Change base path to allow switching to mocks
   187  func (c *APIClient) ChangeBasePath(path string) {
   188  	c.cfg.BasePath = path
   189  }
   190  
   191  // prepareRequest build the request
   192  func (c *APIClient) prepareRequest(
   193  	ctx context.Context,
   194  	path string, method string,
   195  	postBody interface{},
   196  	headerParams map[string]string,
   197  	queryParams url.Values,
   198  	formParams url.Values,
   199  	fileName string,
   200  	fileBytes []byte) (localVarRequest *http.Request, err error) {
   201  
   202  	var body *bytes.Buffer
   203  
   204  	if len(formParams) > 0 {
   205  		tmpBody := make(map[string]string)
   206  		for k, v := range formParams {
   207  			tmpBody[k] = v[0]
   208  		}
   209  		bodyBytes, err := json.Marshal(tmpBody)
   210  		if err != nil {
   211  			return nil, err
   212  		}
   213  		postBody = string(bodyBytes)
   214  		formParams = url.Values{}
   215  	}
   216  
   217  	// Detect postBody type and post.
   218  	if postBody != nil {
   219  		contentType := headerParams["Content-Type"]
   220  		if contentType == "" {
   221  			contentType = detectContentType(postBody)
   222  			headerParams["Content-Type"] = contentType
   223  		}
   224  
   225  		body, err = setBody(postBody, contentType)
   226  		if err != nil {
   227  			return nil, err
   228  		}
   229  	}
   230  
   231  	// add form paramters and file if available.
   232  	if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
   233  		if body != nil {
   234  			return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
   235  		}
   236  		body = &bytes.Buffer{}
   237  		w := multipart.NewWriter(body)
   238  
   239  		for k, v := range formParams {
   240  			for _, iv := range v {
   241  				if strings.HasPrefix(k, "@") { // file
   242  					err = addFile(w, k[1:], iv)
   243  					if err != nil {
   244  						return nil, err
   245  					}
   246  				} else { // form value
   247  					w.WriteField(k, iv)
   248  				}
   249  			}
   250  		}
   251  		if len(fileBytes) > 0 && fileName != "" {
   252  			w.Boundary()
   253  			//_, fileNm := filepath.Split(fileName)
   254  			part, err := w.CreateFormFile("file", filepath.Base(fileName))
   255  			if err != nil {
   256  				return nil, err
   257  			}
   258  			_, err = part.Write(fileBytes)
   259  			if err != nil {
   260  				return nil, err
   261  			}
   262  			// Set the Boundary in the Content-Type
   263  			headerParams["Content-Type"] = w.FormDataContentType()
   264  		}
   265  
   266  		// Set Content-Length
   267  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   268  		w.Close()
   269  	}
   270  
   271  	// Setup path and query paramters
   272  	url, err := url.Parse(path)
   273  	if err != nil {
   274  		return nil, err
   275  	}
   276  
   277  	// Adding Query Param
   278  	query := url.Query()
   279  	for k, v := range queryParams {
   280  		for _, iv := range v {
   281  			query.Add(k, iv)
   282  		}
   283  	}
   284  
   285  	// Encode the parameters.
   286  	url.RawQuery = query.Encode()
   287  
   288  	// Generate a new request
   289  	if body != nil {
   290  		localVarRequest, err = http.NewRequest(method, url.String(), body)
   291  	} else {
   292  		localVarRequest, err = http.NewRequest(method, url.String(), nil)
   293  	}
   294  	if err != nil {
   295  		return nil, err
   296  	}
   297  
   298  	// add header parameters, if any
   299  	if len(headerParams) > 0 {
   300  		headers := http.Header{}
   301  		for h, v := range headerParams {
   302  			headers.Set(h, v)
   303  		}
   304  		localVarRequest.Header = headers
   305  	}
   306  
   307  	// Override request host, if applicable
   308  	if c.cfg.Host != "" {
   309  		localVarRequest.Host = c.cfg.Host
   310  	}
   311  
   312  	// Add the user agent to the request.
   313  	localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)
   314  
   315  	// Walk through any authentication.
   316  	if ctx != nil {
   317  		// OAuth2 authentication
   318  		if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
   319  			// We were able to grab an oauth2 token from the context
   320  			var latestToken *oauth2.Token
   321  			if latestToken, err = tok.Token(); err != nil {
   322  				return nil, err
   323  			}
   324  
   325  			latestToken.SetAuthHeader(localVarRequest)
   326  		}
   327  
   328  		// Basic HTTP Authentication
   329  		if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
   330  			localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
   331  		}
   332  
   333  		// AccessToken Authentication
   334  		if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
   335  			localVarRequest.Header.Add("Authorization", "Bearer "+auth)
   336  		}
   337  
   338  		// before setting auth header, remove Api-Nonce, Api-Key, Api-Signature
   339  		localVarRequest.Header.Del("Api-Nonce")
   340  		localVarRequest.Header.Del("Api-Key")
   341  		localVarRequest.Header.Del("Api-Signature")
   342  
   343  		// APIKey Authentication
   344  		if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {
   345  			if postBody != nil {
   346  				SetAuthHeader(localVarRequest, auth, c.cfg, method, path, postBody.(string), queryParams)
   347  			} else {
   348  				SetAuthHeader(localVarRequest, auth, c.cfg, method, path, "", queryParams)
   349  			}
   350  		}
   351  	}
   352  
   353  	for header, value := range c.cfg.DefaultHeader {
   354  		localVarRequest.Header.Add(header, value)
   355  	}
   356  
   357  	return localVarRequest, nil
   358  }
   359  
   360  // Add a file to the multipart request
   361  func addFile(w *multipart.Writer, fieldName, path string) error {
   362  	file, err := os.Open(path)
   363  	if err != nil {
   364  		return err
   365  	}
   366  	defer file.Close()
   367  
   368  	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
   369  	if err != nil {
   370  		return err
   371  	}
   372  	_, err = io.Copy(part, file)
   373  
   374  	return err
   375  }
   376  
   377  // Prevent trying to import "fmt"
   378  func reportError(format string, a ...interface{}) (error) {
   379  	return fmt.Errorf(format, a...)
   380  }
   381  
   382  // Set request body from an interface{}
   383  func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
   384  	if bodyBuf == nil {
   385  		bodyBuf = &bytes.Buffer{}
   386  	}
   387  
   388  	if reader, ok := body.(io.Reader); ok {
   389  		_, err = bodyBuf.ReadFrom(reader)
   390  	} else if b, ok := body.([]byte); ok {
   391  		_, err = bodyBuf.Write(b)
   392  	} else if s, ok := body.(string); ok {
   393  		_, err = bodyBuf.WriteString(s)
   394  	} else if jsonCheck.MatchString(contentType) {
   395  		err = json.NewEncoder(bodyBuf).Encode(body)
   396  	} else if xmlCheck.MatchString(contentType) {
   397  		xml.NewEncoder(bodyBuf).Encode(body)
   398  	}
   399  
   400  	if err != nil {
   401  		return nil, err
   402  	}
   403  
   404  	if bodyBuf.Len() == 0 {
   405  		err = fmt.Errorf("Invalid body type %s\n", contentType)
   406  		return nil, err
   407  	}
   408  	return bodyBuf, nil
   409  }
   410  
   411  // detectContentType method is used to figure out `Request.Body` content type for request header
   412  func detectContentType(body interface{}) string {
   413  	contentType := "text/plain; charset=utf-8"
   414  	kind := reflect.TypeOf(body).Kind()
   415  
   416  	switch kind {
   417  	case reflect.Struct, reflect.Map, reflect.Ptr:
   418  		contentType = "application/json; charset=utf-8"
   419  	case reflect.String:
   420  		contentType = "text/plain; charset=utf-8"
   421  	default:
   422  		if b, ok := body.([]byte); ok {
   423  			contentType = http.DetectContentType(b)
   424  		} else if kind == reflect.Slice {
   425  			contentType = "application/json; charset=utf-8"
   426  		}
   427  	}
   428  
   429  	return contentType
   430  }
   431  
   432  // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
   433  type cacheControl map[string]string
   434  
   435  func parseCacheControl(headers http.Header) cacheControl {
   436  	cc := cacheControl{}
   437  	ccHeader := headers.Get("Cache-Control")
   438  	for _, part := range strings.Split(ccHeader, ",") {
   439  		part = strings.Trim(part, " ")
   440  		if part == "" {
   441  			continue
   442  		}
   443  		if strings.ContainsRune(part, '=') {
   444  			keyval := strings.Split(part, "=")
   445  			cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
   446  		} else {
   447  			cc[part] = ""
   448  		}
   449  	}
   450  	return cc
   451  }
   452  
   453  // CacheExpires helper function to determine remaining time before repeating a request.
   454  func CacheExpires(r *http.Response) (time.Time) {
   455  	// Figure out when the cache expires.
   456  	var expires time.Time
   457  	now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
   458  	if err != nil {
   459  		return time.Now()
   460  	}
   461  	respCacheControl := parseCacheControl(r.Header)
   462  
   463  	if maxAge, ok := respCacheControl["max-age"]; ok {
   464  		lifetime, err := time.ParseDuration(maxAge + "s")
   465  		if err != nil {
   466  			expires = now
   467  		}
   468  		expires = now.Add(lifetime)
   469  	} else {
   470  		expiresHeader := r.Header.Get("Expires")
   471  		if expiresHeader != "" {
   472  			expires, err = time.Parse(time.RFC1123, expiresHeader)
   473  			if err != nil {
   474  				expires = now
   475  			}
   476  		}
   477  	}
   478  	return expires
   479  }
   480  
   481  func strlen(s string) (int) {
   482  	return utf8.RuneCountInString(s)
   483  }