Files
gocryptotrader/cmd/exchange_template/wrapper_file.tmpl
Adam 504c2fad6d Feature: Implement funding rates, futures and coin margin (exchange API coverage) (#530)
* ALMOST THERE

* more api wips

* more api thingz

* testing n more api wipz

* more apiz

* more wips

* what is goin on

* more wips

* whip n testing

* testing

* testing

no keys

* remove log

* kraken is broken

ugh

* still broken

* fixing auth funcs + usdtm api docs

* wip

* api stuffs

* whip

* more wips

* whip

* more wip

* api wip n testing

* wip

* wip

* unsaved

* wip n testing

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* whip

* wrapper authenticated functions

* adding asset type and fixing dependencies

* wip

* binance auth wrapper start

* wrapper functionality

* wip

* wip

* wip

* wrapper cancel functions

* order submission for wrappers

* wip

* more error fixing and nits

* websocket beginning n error fix

* wip

* WOW

* glorious n shazzy nits

* useless nits

* wip

* fixing things

* merge stuffs

* crapveyor

* crapveyor rebuild

* probably broke more things than he fixed

* rm lns n other thangs

* hope

* please

* stop it

* done

* ofcourse

* rm vb

* fix lbank

* appveyor please

* float lev

* DONT ASK RYAN FOR HELP EVER

* wip

* wip

* endpoint upgrades continued

* path upgrade

* NeeeNeeeNeeeNeeeNING

* fix stuffs

* fixing time issue

* fixing broken funcs

* glorious nits

* shaz changes

* fixing errors for fundmon

* more error fixing for fundmon

* test running past 30s

* basic changes

* THX AGAIN SHAZBERT

* path system upgrade

* config upgrade

* unsaved stuffs

* broken wip config upgrade

* path system upgrade contd.

* path system upgrade contd

* path upgrade ready for review

* testing verbose removed

* linter stuffs

* appveyor stuffs

* appveyor stuff

* fixed?

* bugfix

* wip

* broken stuff

* fix test

* wierd hack fix

* appveyor pls stop

* error found

* more useless nits

* bitmex err

* broken wip

* broken wip path upgrade change to uint32

* changed url lookups to uint

* WOW

* ready4review

* config fixed HOPEFULLY

* config fix and glorious changes

* efficient way of getting orders and open orders

* binance wrapper logic fixing

* testing, adding tests and fixing lot of errrrrs

* merge master

* appveyor stuffs

* appveyor stuffs

* fmt

* test

* octalLiteral issue fix?

* octalLiteral fix?

* rm vb

* prnt ln to restart

* adding testz

* test fixzzz

* READY FOR REVIEW

* Actually ready now

* FORMATTING

* addressing shazzy n glorious nits

* crapveyor

* rm vb

* small change

* fixing err

* shazbert nits

* review changes

* requested changes

* more requested changes

* noo

* last nit fixes

* restart appveyor

* improving test cov

* Update .golangci.yml

* shazbert changes

* moving pair formatting

* format pair update wip

* path upgrade complete

* error fix

* appveyor linters

* more linters

* remove testexch

* more formatting changes

* changes

* shazbert changes

* checking older requested changes to ensure completion

* wip

* fixing broken code

* error fix

* all fixed

* additional changes

* more changes

* remove commented code

* ftx margin api

* appveyor fixes

* more appveyor issues + test addition

* more appveyor issues + test addition

* remove unnecessary

* testing

* testing, fixing okex api, error fix

* git merge fix

* go sum

* glorious changes and error fix

* rm vb

* more glorious changes and go mod tidy

* fixed now

* okex testing upgrade

* old config migration and batch fetching fix

* added test

* glorious requested changes WIP

* tested and fixed

* go fmted

* go fmt and test fix

* additional funcs and tests for fundingRates

* OKEX tested and fixed

* appveyor fixes

* ineff assign

* 1 glorious change

* error fix

* typo

* shazbert changes

* glorious code changes and path fixing huobi WIP

* adding assetType to accountinfo functions

* fixing panic

* panic fix and updating account info wrappers WIP

* updateaccountinfo updated

* testing WIP binance USDT n Coin Margined and Kraken Futures

* auth functions tested and fixed

* added test

* config reverted

* shazbert and glorious changes

* shazbert and glorious changes

* latest changes and portfolio update

* go fmt change:

* remove commented codes

* improved error checking

* index out of range fix

* rm ln

* critical nit

* glorious latest changes

* appveyor changes

* shazbert change

* easier readability

* latest glorious changes

* shadow dec

* assetstore updated

* last change

* another last change

* merge changes

* go mod tidy

* thrasher requested changes wip

* improving struct layouts

* appveyor go fmt

* remove unnecessary code

* shazbert changes

* small change

* oopsie

* tidy

* configtest reverted

* error fix

* oopsie

* for what

* test patch fix

* insecurities

* fixing tests

* fix config
2021-02-12 16:19:18 +11:00

468 lines
16 KiB
Cheetah

{{define "wrapper"}}
package {{.Name}}
import (
"sync"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/config"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/account"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/protocol"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
)
// GetDefaultConfig returns a default exchange config
func ({{.Variable}} *{{.CapitalName}}) GetDefaultConfig() (*config.ExchangeConfig, error) {
{{.Variable}}.SetDefaults()
exchCfg := new(config.ExchangeConfig)
exchCfg.Name = {{.Variable}}.Name
exchCfg.HTTPTimeout = exchange.DefaultHTTPTimeout
exchCfg.BaseCurrencies = {{.Variable}}.BaseCurrencies
{{.Variable}}.SetupDefaults(exchCfg)
if {{.Variable}}.Features.Supports.RESTCapabilities.AutoPairUpdates {
err := {{.Variable}}.UpdateTradablePairs(true)
if err != nil {
return nil, err
}
}
return exchCfg, nil
}
// SetDefaults sets the basic defaults for {{.CapitalName}}
func ({{.Variable}} *{{.CapitalName}}) SetDefaults() {
{{.Variable}}.Name = "{{.CapitalName}}"
{{.Variable}}.Enabled = true
{{.Variable}}.Verbose = true
{{.Variable}}.API.CredentialsValidator.RequiresKey = true
{{.Variable}}.API.CredentialsValidator.RequiresSecret = true
// If using only one pair format for request and configuration, across all
// supported asset types either SPOT and FUTURES etc. You can use the
// example below:
// Request format denotes what the pair as a string will be, when you send
// a request to an exchange.
requestFmt := &currency.PairFormat{/*Set pair request formatting details here for e.g.*/ Uppercase: true, Delimiter: ":"}
// Config format denotes what the pair as a string will be, when saved to
// the config.json file.
configFmt := &currency.PairFormat{/*Set pair request formatting details here*/}
err := {{.Variable}}.SetGlobalPairsManager(requestFmt, configFmt, /*multiple assets can be set here using the asset package ie asset.Spot*/)
if err != nil {
log.Errorln(log.ExchangeSys, err)
}
// If assets require multiple differences in formating for request and
// configuration, another exchange method can be be used e.g. futures
// contracts require a dash as a delimiter rather than an underscore. You
// can use this example below:
fmt1 := currency.PairStore{
RequestFormat: &currency.PairFormat{Uppercase: true},
ConfigFormat: &currency.PairFormat{Uppercase: true},
}
fmt2 := currency.PairStore{
RequestFormat: &currency.PairFormat{Uppercase: true},
ConfigFormat: &currency.PairFormat{Uppercase: true, Delimiter: ":"},
}
err = {{.Variable}}.StoreAssetPairFormat(asset.Spot, fmt1)
if err != nil {
log.Errorln(log.ExchangeSys, err)
}
err = {{.Variable}}.StoreAssetPairFormat(asset.Margin, fmt2)
if err != nil {
log.Errorln(log.ExchangeSys, err)
}
// Fill out the capabilities/features that the exchange supports
{{.Variable}}.Features = exchange.Features{
Supports: exchange.FeaturesSupported{
{{ if .REST }} REST: true, {{ end }}
{{ if .WS }} Websocket: true, {{ end }}
RESTCapabilities: protocol.Features{
TickerFetching: true,
OrderbookFetching: true,
},
WebsocketCapabilities: protocol.Features{
TickerFetching: true,
OrderbookFetching: true,
},
WithdrawPermissions: exchange.AutoWithdrawCrypto |
exchange.AutoWithdrawFiat,
},
Enabled: exchange.FeaturesEnabled{
AutoPairUpdates: true,
},
}
// NOTE: SET THE EXCHANGES RATE LIMIT HERE
{{.Variable}}.Requester = request.New({{.Variable}}.Name,
common.NewHTTPClientWithTimeout(exchange.DefaultHTTPTimeout))
// NOTE: SET THE URLs HERE
{{.Variable}}.API.Endpoints = {{.Variable}}.NewEndpoints()
{{.Variable}}.API.Endpoints.SetDefaultEndpoints(map[exchange.URL]string{
exchange.RestSpot: {{.Name}}APIURL,
// exchange.WebsocketSpot: {{.Name}}WSAPIURL,
})
{{.Variable}}.Websocket = stream.New()
{{.Variable}}.WebsocketResponseMaxLimit = exchange.DefaultWebsocketResponseMaxLimit
{{.Variable}}.WebsocketResponseCheckTimeout = exchange.DefaultWebsocketResponseCheckTimeout
{{.Variable}}.WebsocketOrderbookBufferLimit = exchange.DefaultWebsocketOrderbookBufferLimit
}
// Setup takes in the supplied exchange configuration details and sets params
func ({{.Variable}} *{{.CapitalName}}) Setup(exch *config.ExchangeConfig) error {
if !exch.Enabled {
{{.Variable}}.SetEnabled(false)
return nil
}
{{.Variable}}.SetupDefaults(exch)
/*
wsRunningEndpoint, err := {{.Variable}}.API.Endpoints.GetURL(exchange.WebsocketSpot)
if err != nil {
return err
}
// If websocket is supported, please fill out the following
err = {{.Variable}}.Websocket.Setup(
&stream.WebsocketSetup{
Enabled: exch.Features.Enabled.Websocket,
Verbose: exch.Verbose,
AuthenticatedWebsocketAPISupport: exch.API.AuthenticatedWebsocketSupport,
WebsocketTimeout: exch.WebsocketTrafficTimeout,
DefaultURL: {{.Name}}WSAPIURL,
ExchangeName: exch.Name,
RunningURL: wsRunningEndpoint,
Connector: {{.Variable}}.WsConnect,
Subscriber: {{.Variable}}.Subscribe,
UnSubscriber: {{.Variable}}.Unsubscribe,
Features: &{{.Variable}}.Features.Supports.WebsocketCapabilities,
})
if err != nil {
return err
}
{{.Variable}}.WebsocketConn = &stream.WebsocketConnection{
ExchangeName: {{.Variable}}.Name,
URL: {{.Variable}}.Websocket.GetWebsocketURL(),
ProxyURL: {{.Variable}}.Websocket.GetProxyAddress(),
Verbose: {{.Variable}}.Verbose,
ResponseCheckTimeout: exch.WebsocketResponseCheckTimeout,
ResponseMaxLimit: exch.WebsocketResponseMaxLimit,
}
// NOTE: PLEASE ENSURE YOU SET THE ORDERBOOK BUFFER SETTINGS CORRECTLY
{{.Variable}}.Websocket.Orderbook.Setup(
exch.OrderbookConfig.WebsocketBufferLimit,
true,
true,
false,
false,
exch.Name)
*/
return nil
}
// Start starts the {{.CapitalName}} go routine
func ({{.Variable}} *{{.CapitalName}}) Start(wg *sync.WaitGroup) {
wg.Add(1)
go func() {
{{.Variable}}.Run()
wg.Done()
}()
}
// Run implements the {{.CapitalName}} wrapper
func ({{.Variable}} *{{.CapitalName}}) Run() {
if {{.Variable}}.Verbose {
{{ if .WS }} log.Debugf(log.ExchangeSys,
"%s Websocket: %s.",
{{.Variable}}.Name,
common.IsEnabled({{.Variable}}.Websocket.IsEnabled())) {{ end }}
{{.Variable}}.PrintEnabledPairs()
}
if !{{.Variable}}.GetEnabledFeatures().AutoPairUpdates {
return
}
err := {{.Variable}}.UpdateTradablePairs(false)
if err != nil {
log.Errorf(log.ExchangeSys,
"%s failed to update tradable pairs. Err: %s",
{{.Variable}}.Name,
err)
}
}
// FetchTradablePairs returns a list of the exchanges tradable pairs
func ({{.Variable}} *{{.CapitalName}}) FetchTradablePairs(asset asset.Item) ([]string, error) {
// Implement fetching the exchange available pairs if supported
return nil, nil
}
// UpdateTradablePairs updates the exchanges available pairs and stores
// them in the exchanges config
func ({{.Variable}} *{{.CapitalName}}) UpdateTradablePairs(forceUpdate bool) error {
pairs, err := {{.Variable}}.FetchTradablePairs(asset.Spot)
if err != nil {
return err
}
p, err := currency.NewPairsFromStrings(pairs)
if err != nil {
return err
}
return {{.Variable}}.UpdatePairs(p, asset.Spot, false, forceUpdate)
}
// UpdateTicker updates and returns the ticker for a currency pair
func ({{.Variable}} *{{.CapitalName}}) UpdateTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error) {
// NOTE: EXAMPLE FOR GETTING TICKER PRICE
/*
tickerPrice := new(ticker.Price)
tick, err := {{.Variable}}.GetTicker(p.String())
if err != nil {
return tickerPrice, err
}
tickerPrice = &ticker.Price{
High: tick.High,
Low: tick.Low,
Bid: tick.Bid,
Ask: tick.Ask,
Open: tick.Open,
Close: tick.Close,
Pair: p,
}
err = ticker.ProcessTicker({{.Variable}}.Name, tickerPrice, assetType)
if err != nil {
return tickerPrice, err
}
*/
return ticker.GetTicker({{.Variable}}.Name, p, assetType)
}
// FetchTicker returns the ticker for a currency pair
func ({{.Variable}} *{{.CapitalName}}) FetchTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error) {
tickerNew, err := ticker.GetTicker({{.Variable}}.Name, p, assetType)
if err != nil {
return {{.Variable}}.UpdateTicker(p, assetType)
}
return tickerNew, nil
}
// FetchOrderbook returns orderbook base on the currency pair
func ({{.Variable}} *{{.CapitalName}}) FetchOrderbook(currency currency.Pair, assetType asset.Item) (*orderbook.Base, error) {
ob, err := orderbook.Get({{.Variable}}.Name, currency, assetType)
if err != nil {
return {{.Variable}}.UpdateOrderbook(currency, assetType)
}
return ob, nil
}
// UpdateOrderbook updates and returns the orderbook for a currency pair
func ({{.Variable}} *{{.CapitalName}}) UpdateOrderbook(p currency.Pair, assetType asset.Item) (*orderbook.Base, error) {
book := &orderbook.Base{
ExchangeName: {{.Variable}}.Name,
Pair: p,
AssetType: assetType,
VerificationBypass: {{.Variable}}.OrderbookVerificationBypass,
}
// NOTE: UPDATE ORDERBOOK EXAMPLE
/*
orderbookNew, err := {{.Variable}}.GetOrderBook(exchange.FormatExchangeCurrency({{.Variable}}.Name, p).String(), 1000)
if err != nil {
return book, err
}
for x := range orderbookNew.Bids {
book.Bids = append(book.Bids, orderbook.Item{
Amount: orderbookNew.Bids[x].Quantity,
Price: orderbookNew.Bids[x].Price,
})
}
for x := range orderbookNew.Asks {
book.Asks = append(book.Asks, orderbook.Item{
Amount: orderBookNew.Asks[x].Quantity,
Price: orderBookNew.Asks[x].Price,
})
}
*/
err := book.Process()
if err != nil {
return book, err
}
return orderbook.Get({{.Variable}}.Name, p, assetType)
}
// UpdateAccountInfo retrieves balances for all enabled currencies
func ({{.Variable}} *{{.CapitalName}}) UpdateAccountInfo(assetType asset.Item) (account.Holdings, error) {
return account.Holdings{}, common.ErrNotYetImplemented
}
// FetchAccountInfo retrieves balances for all enabled currencies
func ({{.Variable}} *{{.CapitalName}}) FetchAccountInfo(assetType asset.Item) (account.Holdings, error) {
return account.Holdings{}, common.ErrNotYetImplemented
}
// GetFundingHistory returns funding history, deposits and
// withdrawals
func ({{.Variable}} *{{.CapitalName}}) GetFundingHistory() ([]exchange.FundHistory, error) {
return nil, common.ErrNotYetImplemented
}
// GetWithdrawalsHistory returns previous withdrawals data
func ({{.Variable}} *{{.CapitalName}}) GetWithdrawalsHistory(c currency.Code) (resp []exchange.WithdrawalHistory, err error) {
return nil, common.ErrNotYetImplemented
}
// GetRecentTrades returns the most recent trades for a currency and asset
func ({{.Variable}} *{{.CapitalName}}) GetRecentTrades(p currency.Pair, assetType asset.Item) ([]trade.Data, error) {
return nil, common.ErrNotYetImplemented
}
// GetHistoricTrades returns historic trade data within the timeframe provided
func ({{.Variable}} *{{.CapitalName}}) GetHistoricTrades (p currency.Pair, assetType asset.Item, timestampStart, timestampEnd time.Time) ([]trade.Data, error) {
return nil, common.ErrNotYetImplemented
}
// SubmitOrder submits a new order
func ({{.Variable}} *{{.CapitalName}}) SubmitOrder(s *order.Submit) (order.SubmitResponse, error) {
var submitOrderResponse order.SubmitResponse
if err := s.Validate(); err != nil {
return submitOrderResponse, err
}
return submitOrderResponse, common.ErrNotYetImplemented
}
// ModifyOrder will allow of changing orderbook placement and limit to
// market conversion
func ({{.Variable}} *{{.CapitalName}}) ModifyOrder(action *order.Modify) (string, error) {
// if err := action.Validate(); err != nil {
// return "", err
// }
return "", common.ErrNotYetImplemented
}
// CancelOrder cancels an order by its corresponding ID number
func ({{.Variable}} *{{.CapitalName}}) CancelOrder(ord *order.Cancel) error {
// if err := ord.Validate(ord.StandardCancel()); err != nil {
// return err
// }
return common.ErrNotYetImplemented
}
// CancelBatchOrders cancels orders by their corresponding ID numbers
func ({{.Variable}} *{{.CapitalName}}) CancelBatchOrders(orders []order.Cancel) (order.CancelBatchResponse, error) {
return order.CancelBatchResponse{}, common.ErrNotYetImplemented
}
// CancelAllOrders cancels all orders associated with a currency pair
func ({{.Variable}} *{{.CapitalName}}) CancelAllOrders(orderCancellation *order.Cancel) (order.CancelAllResponse, error) {
// if err := orderCancellation.Validate(); err != nil {
// return err
// }
return order.CancelAllResponse{}, common.ErrNotYetImplemented
}
// GetOrderInfo returns order information based on order ID
func ({{.Variable}} *{{.CapitalName}}) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
return order.Detail{}, common.ErrNotYetImplemented
}
// GetDepositAddress returns a deposit address for a specified currency
func ({{.Variable}} *{{.CapitalName}}) GetDepositAddress(cryptocurrency currency.Code, accountID string) (string, error) {
return "", common.ErrNotYetImplemented
}
// WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is
// submitted
func ({{.Variable}} *{{.CapitalName}}) WithdrawCryptocurrencyFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error) {
// if err := withdrawRequest.Validate(); err != nil {
// return nil, err
// }
return nil, common.ErrNotYetImplemented
}
// WithdrawFiatFunds returns a withdrawal ID when a withdrawal is
// submitted
func ({{.Variable}} *{{.CapitalName}}) WithdrawFiatFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error) {
// if err := withdrawRequest.Validate(); err != nil {
// return nil, err
// }
return nil, common.ErrNotYetImplemented
}
// WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a withdrawal is
// submitted
func ({{.Variable}} *{{.CapitalName}}) WithdrawFiatFundsToInternationalBank(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error) {
// if err := withdrawRequest.Validate(); err != nil {
// return nil, err
// }
return nil, common.ErrNotYetImplemented
}
// GetActiveOrders retrieves any orders that are active/open
func ({{.Variable}} *{{.CapitalName}}) GetActiveOrders(getOrdersRequest *order.GetOrdersRequest) ([]order.Detail, error) {
// if err := getOrdersRequest.Validate(); err != nil {
// return nil, err
// }
return nil, common.ErrNotYetImplemented
}
// GetOrderHistory retrieves account order information
// Can Limit response to specific order status
func ({{.Variable}} *{{.CapitalName}}) GetOrderHistory(getOrdersRequest *order.GetOrdersRequest) ([]order.Detail, error) {
// if err := getOrdersRequest.Validate(); err != nil {
// return nil, err
// }
return nil, common.ErrNotYetImplemented
}
// GetFeeByType returns an estimate of fee based on the type of transaction
func ({{.Variable}} *{{.CapitalName}}) GetFeeByType(feeBuilder *exchange.FeeBuilder) (float64, error) {
return 0, common.ErrNotYetImplemented
}
// ValidateCredentials validates current credentials used for wrapper
func ({{.Variable}} *{{.CapitalName}}) ValidateCredentials(assetType asset.Item) error {
_, err := {{.Variable}}.UpdateAccountInfo(assetType)
return {{.Variable}}.CheckTransientError(err)
}
// GetHistoricCandles returns candles between a time period for a set time interval
func ({{.Variable}} *{{.CapitalName}}) GetHistoricCandles(pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) {
return kline.Item{}, common.ErrNotYetImplemented
}
// GetHistoricCandlesExtended returns candles between a time period for a set time interval
func ({{.Variable}} *{{.CapitalName}}) GetHistoricCandlesExtended(pair currency.Pair, a asset.Item, start, end time.Time, interval kline.Interval) (kline.Item, error) {
return kline.Item{}, common.ErrNotYetImplemented
}
{{end}}