Files
gocryptotrader/cmd/exchange_template/wrapper_file.tmpl
Ryan O'Hara-Reid 7b718700f7 orderbook: Implement initial linked list (#643)
* Exchanges: Initial implementation after rebase of depth (WIP)

* orderbook/buffer: convert and couple orderbook interaction functionality from buffer to orderbook linked list - Use single point reference for orderbook depth

* buffer/orderbook: conversion continued (WIP)

* exchange: buffer/linkedlist handover (WIP)

* Added some tests for yesterday

* linkedList: added more testing and trying to figure out broken things

* Started tying everything in

* continuous integration and testing

* orderbook: expanded tests

* go mod tidy

* Add in different synchornisation levels for protocols
Add in timer for the streaming system to reduce updates to datahandler
Add in more test code as I integrate more exchanges

* Depth: Add tests, add length check to call linked list updating, add in constructor.
Linked List: Improve tests, add in checks for zero liquidity on books.
Node: Added in cleaner POC, add in contructor.
Buffer: Fixed tests, checked benchmarks.

* orderbook: reinstate dispatch calls

* Addr glorious & madcozbad nits

* fix functionality and add tests

* Address linterinos

* remove label

* expanded comment

* fix races and and bitmex test

* reinstate go routine for alerting changes

* rm line :D

* fix more tests

* Addr glorious nits

* rm glorious field

* depth: defer unlock to stop deadlock

* orderbook: remove unused vars

* buffer: fix test to what it should be

* nits: madcosbad addr

* nits: glorious nits

* linkedlist: remove unused params

* orderbook: shift time call to outside of push to inline, add in case for update inster price for zero liquidity, nits

* orderbook: nits addressed

* engine: change stream -> websocket convention and remove unused function

* nits: glorious nits

* Websocket Buffer: Add verbosity switch

* linked list: Add comment

* linked list: fix spelling

* nits: glorious nits

* orderbook: Adds in test and explicit time type with constructor, fix nits

* linter

* spelling: removed the dere fence

* depth: Update alerting mechanism to a more battle tested state

* depth: spelling

* nits: glorious nits

* linked list: match cases

* buffer: fix linter issue

* golangci: increase timeout by 30 seconds

* nodes: update atomic checks

* spelling: fix

* node: add in commentary

* exchanges/syncer: add function to switch over to REST when websocket functionality is not available for a specific asset type

* linter: exchange linter issues

* syncer: Add in warning

* nits: glorious nits

* AssetWebsocketSupport: unexport map

* Nits: Adrr

* rm letter

* exchanges: Orderbook verification change for naming, deprecate checksum bypass as it has the potential to obfuscate errors that are at the tail end of the book, add in verification for websocket stream updates

* general: fix spelling remove breakpoint

* nits: fix more glorious nits until more are found

* orderbook: fix tests

* orderbook: fix wait tests and add in more checks

* nits: addr

* orderbook: remove dispatch reference

* linkedlist: consolidate bid/ask functions

* linked lisdt: remove words

* fix spelling
2021-04-23 15:16:01 +10: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{
Exchange: {{.Variable}}.Name,
Pair: p,
Asset: assetType,
VerifyOrderbook: {{.Variable}}.CanVerifyOrderbook,
}
// 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}}