mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-17 23:16:52 +00:00
* initial update of currency system * WIP progress * Finish initial currency string error returns * fix whoopsie testing for non https insecureinos * Current WIP for getEnabledPairs check and error return * WIP continued * When getting enabled pairs throw error when item is not contained in available pairs list * More updates -WIP * Wip continued including potential interface * Current WIP * pairs manager pass * drop asset string and just use the map key, plus return some errors and create more work for myself. * clean and fixed a bug in currency.json, will not populate correctly without coinmarketcap api keys set. * purge logger references after merge * go mod tidy after merge * Pointer change WIP * fix some issues and added error returns to a few items (WIP) * WIP * Clean * Fix some linter issues * Fix more linter issues * even more linters * xtda nits * revert pointer change and rm field * Addr madcozbadd nits * fix linter issues: shadow declarations * Fix linter issues: gocritic huge things * linter issue fix * Addr nits * flush go mod files * after merge woops * fix shadow dec * Addr thrasher nits * addr nits * fix some issues * more fixes * RM println * Addr glorious nits * Add helper method for setting assets * add missing format directive * Addr nits * Actually process new futures contracts -_- derp * WIP for GRPC upgrade for pair management * update config pairs * finished disabling and enabling asset * linked update of tradable pairs to cli * fix oopsies * defer writing to file on program termination for currency storage system * update template * don't add disabled asset items to initial sync * Fix enable disabling a list of pairs and added in a slice error type so we can add whats allowable without throwing an error and return a report, also addressed some other nits * WIP on getting a channel to unsub * Wip track down unsubscribe bug and start creating streaming interface * purge websocket orderbook object and centralised updating routine for orderbook * general clean before interface implementation * stage one connection interface WIP * WIP * repackage wshandler WIP * find difference of subs and change signature of subscriber functions so we can batch subscriptions and unsubscription in exchanges that support it * design change on mange subscription routine WIP * integrated ZB with the new webosocket updates * WIP - okex conversion * integrate websocket upgrades for lakebtc, kraken, huobi, hitbtc, gateio, and WIP for coinbene * integrate another range of exchanges for websocket update * Added subscriber and unsubscriber methods to websocket functionality * fixed tests WIP * amalgamate cache setup with main websocket setup * reinstate exported fields traffic alert and shutdownC to accommodate gemini and lakebtc implementations * added in colon * Updated websocket auth handling as they werent getting passed through. Added a setter method for websocket URL due to the Binance generated auth key/listenKey. Fixed bug which stopped reconnection. * Fix subscribe candle bug Fix time conversion in candle Fix inititial candle history to datahandler Include funding to orderbook handling Include funding to trades Reduce code duplication in sub and unsub functions Added the ability to include funding currency websocket subscriptions validated all channels and added more items todo list (Auth items) * RM line * bitstamp pass * btcmarkets pass - still needs to implement unsubscriber functionality and pairs change test. * Batch outgoing subscriptions and fix unsubscribe bug * BTSE - bumped time to minute to reduce pinger calling by 75 calls per day. Fix authentication bug and add authentication pass into to-do. Batch outgoing subscription calls * fix type field and batch outgoing subs and unsubs for coinbasepro * Batch outgoing subs and unsubs * Fixes bug when matching return from authentication * Fix bug where params where being sent out of order due to map ,where depth items werent being subscribed too, where trying to subscribe to too many kline items caused error, where trying to get a nano secocond ID conflicted due to speed of generation. * Add websocket capability for currency pair change by utilizing full channel subscription list in subscribe function. * Add error handling * Fix public: time conversions, subscription list, stopped pushing heartbeat to data handler, aggregated list of connections. * hitBTC pass * returned nil instead of error due to period null bids and asks updates coming through. * Fix auth ping capture and reply. Added in interval handling for kline data. Added correct full trade data handling. Fix subscribe and unsubscribe. * Fix when websocket auth conn and token generation fail we don't try and auth sub. Fix bug between auth and normal connection id generation and matching. Batch outgoing payloads to increase efficiency. Updated matching functions to utilise channels instead of waitgroups and go routines. * RM debug output * rm func to get shutdown channel * Add unsubscriber functionality, added wsTicker type, removed return as this will impede data flow and cause reconnection when handling and processing data * okgroup WIP * *Added missing fields for websocket trades *Fix bug processing kline interval *Added fields for websocket ticker struct *Fix auth bug -Updated request and response matching param to interface so we can custom signature match. Stops auth subscribing before a reply is issued. -Updated channel inclusion of pair fo auth subs as this was missing. *Assortment of perfomance improvements * poloniex pass * send all trades to data handler, validated enabled and disable pairs * initial clean * centralised request matching mechanism * websocket main improvements WIP * WIP * Websocket management via gctcli WIP * GRPC expansion * Updated GCTCLI with websocket url and proxy setting functionality which flushes connection * Fix continuous spawning of routines bug on error with reconnection * Addr linter issues * fix subscription bug that I caused when I changed to a switch case * fix linter issue * fix woopsie * End of day WIP * Fix order submission REST, time conversion, order type conversion, orderID bugs * fix gateio test and unsubscribe bug * revert comment out code * websocketAPI changed to to true in configtest.json * fix race in gateio test * End of day WIP for websocket tests. * BugFix for binance when book isn't seeded. Updated websocket tests. Deprecated subscription manager. RM wrapper funcs. * Added string title to exchange name as they are saved as lower case in type, reinstated verbose check in websocket.go * Added verbosity check for setting websocket URL * fix bug where the asset had a mind of its own * purge dodgy coding * Fix tests, drop blocking chan in websocket Dial function * few more changes * race condition fix for websocket tests. * fix intermittent test failure due to underlying hash table storage * Address madcuzbad nit * RM superfluous printlines * Add quick top example with paramater fields * First pass Glorious nits * As per madcozbad suggestion return error when enabled pair not found in full return map. Add test. * addr madcozbadd nits * as per glorious suggestion rm'd loadedJSON field * adjusted ticker, added test and RM'd code that can never be executed * Addr nits and add in crypto rand genration for ID's * remove global channel declaration and rescoped as this was causing a lock * as per glorious suggestion restructured return error for websocket * addr glorious suggestions * fix linter issues * purge non-existent pair from testdata * add side field to struct and parse * addr glorious nits * Add verbosity to error returns and logs and fix string parsing in GCTRPC * fix speeling mistwake * Adds websocket functionality check before flushing websocket connection * Addr kraken panic and setting/flush websocket url stage one. * added websocket url check before setting with tests * Added in edge case test if by the time we call contains on available pairs it has been changed * remove error return for func * Continuation of tests * continuation of tests * Stop potential panic within pair creation function * Implement changes to upstream * rm sup comment * fix bug when subscribing and unsubscribing. Also add in boolean to determine there are currencies that need to be flushed via set pairs via gctcli * fix test * Fix linter issues * Fix tests * turn websocket off in config example * Fix issue where you cannot enable websocket when config is set to false, also added config websocket enable state saving * Introduced err var for same error returns * Add err var exchange base not found * restructure function * drop gctscript from generic response name * drop managesub delay const as its not being used * correctly implement websocket rate limiting for coinut * remove quotations * drop pair management check * fix spelling * return error in function to not update currency with unset role * amalagamted enable/disable into set function and added in pairstore fetch function * update error description * rm function * moved test function to sharedtestvals and move type to types.go * append delimiter onto currency delimiter strings * add test coverage * rm functions as they are set as methods in base * remove superfluous methods * Fix issue that would occur when a subscription errored and not appending successful subs * fix after rebase woopsie * fix linter issues * fix bug streamline code * fix linter issues * fix linter issues * fix case where it should not change ID if set but append new * fix whoopsie * fix websocket tests * fix readme, fix wrapper issues reporting template, go mod tidy * add test coverage * add test coverage and verified futures pariing * add in futures bypass as its not currently supported on BTSE until API update and implementation * removed downside/upside profit contract type as its no longer supported. Added in check in set config pairs to warn user of potential conflict and to manually remove or update. * If asset enabled add pair and increase code coverage * remove strings.title, set and fetch with strings.Lower but keep struct field exchangename unchanged. Streamline ticker and orderbook code. * Add code coverage * log error if setting default currency fails, add code coverage * address glorious nits * Addr xtda nits * fix linter issues * addr glorious nits * xtda nits * Addr glorious nits * add subscription protection and removed a superfluous wait call * fix test * fix whoopsie * addr xtda nits * addr glorious nits * Added asset types to subscriptions structs, also added in error handling for resubscription errors * consolidated rpc returned type and added in sucessful strings * dropped stream timing down to 100ms * DOC changes * proxy and url usage string additions * WIP * go mod tidy rides again * Addr nits * Addr nits, fix tests * fix wording * add in test case for currency matching * Add byte length check on outbound websocket payload subscriptions * addr thrasher nits * Addr madcozbadd nits * addr linter issues * Addr glorious nits by amalgamating function into one mega amazing function. * fix futures account subscription bug * addr glorious nits and reinstated wg.Wait() checks * changed string to currency delimiter string and setconnected by function
437 lines
13 KiB
Go
437 lines
13 KiB
Go
package zb
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/thrasher-corp/gocryptotrader/common/convert"
|
|
"github.com/thrasher-corp/gocryptotrader/common/crypto"
|
|
"github.com/thrasher-corp/gocryptotrader/currency"
|
|
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
|
|
)
|
|
|
|
const (
|
|
zbTradeURL = "http://api.zb.live/data"
|
|
zbMarketURL = "https://trade.zb.live/api"
|
|
zbAPIVersion = "v1"
|
|
|
|
zbAccountInfo = "getAccountInfo"
|
|
zbMarkets = "markets"
|
|
zbKline = "kline"
|
|
zbOrder = "order"
|
|
zbCancelOrder = "cancelOrder"
|
|
zbTicker = "ticker"
|
|
zbTickers = "allTicker"
|
|
zbDepth = "depth"
|
|
zbUnfinishedOrdersIgnoreTradeType = "getUnfinishedOrdersIgnoreTradeType"
|
|
zbGetOrdersGet = "getOrders"
|
|
zbWithdraw = "withdraw"
|
|
zbDepositAddress = "getUserAddress"
|
|
)
|
|
|
|
// ZB is the overarching type across this package
|
|
// 47.91.169.147 api.zb.com
|
|
// 47.52.55.212 trade.zb.com
|
|
type ZB struct {
|
|
exchange.Base
|
|
}
|
|
|
|
// SpotNewOrder submits an order to ZB
|
|
func (z *ZB) SpotNewOrder(arg SpotNewOrderRequestParams) (int64, error) {
|
|
var result SpotNewOrderResponse
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", "order")
|
|
vals.Set("amount", strconv.FormatFloat(arg.Amount, 'f', -1, 64))
|
|
vals.Set("currency", arg.Symbol)
|
|
vals.Set("price", strconv.FormatFloat(arg.Price, 'f', -1, 64))
|
|
vals.Set("tradeType", string(arg.Type))
|
|
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if result.Code != 1000 {
|
|
return 0, fmt.Errorf("unsuccessful new order, message: %s code: %d", result.Message, result.Code)
|
|
}
|
|
newOrderID, err := strconv.ParseInt(result.ID, 10, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return newOrderID, nil
|
|
}
|
|
|
|
// CancelExistingOrder cancels an order
|
|
func (z *ZB) CancelExistingOrder(orderID int64, symbol string) error {
|
|
type response struct {
|
|
Code int `json:"code"` // Result code
|
|
Message string `json:"message"` // Result Message
|
|
}
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", "cancelOrder")
|
|
vals.Set("id", strconv.FormatInt(orderID, 10))
|
|
vals.Set("currency", symbol)
|
|
|
|
var result response
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if result.Code != 1000 {
|
|
return errors.New(result.Message)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetAccountInformation returns account information including coin information
|
|
// and pricing
|
|
func (z *ZB) GetAccountInformation() (AccountsResponse, error) {
|
|
var result AccountsResponse
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", "getAccountInfo")
|
|
|
|
return result, z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
}
|
|
|
|
// GetUnfinishedOrdersIgnoreTradeType returns unfinished orders
|
|
func (z *ZB) GetUnfinishedOrdersIgnoreTradeType(currency string, pageindex, pagesize int64) ([]Order, error) {
|
|
var result []Order
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", zbUnfinishedOrdersIgnoreTradeType)
|
|
vals.Set("currency", currency)
|
|
vals.Set("pageIndex", strconv.FormatInt(pageindex, 10))
|
|
vals.Set("pageSize", strconv.FormatInt(pagesize, 10))
|
|
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
return result, err
|
|
}
|
|
|
|
// GetOrders returns finished orders
|
|
func (z *ZB) GetOrders(currency string, pageindex, side int64) ([]Order, error) {
|
|
var response []Order
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", zbGetOrdersGet)
|
|
vals.Set("currency", currency)
|
|
vals.Set("pageIndex", strconv.FormatInt(pageindex, 10))
|
|
vals.Set("tradeType", strconv.FormatInt(side, 10))
|
|
return response, z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &response, request.Auth)
|
|
}
|
|
|
|
// GetMarkets returns market information including pricing, symbols and
|
|
// each symbols decimal precision
|
|
func (z *ZB) GetMarkets() (map[string]MarketResponseItem, error) {
|
|
endpoint := fmt.Sprintf("%s/%s/%s", z.API.Endpoints.URL, zbAPIVersion, zbMarkets)
|
|
|
|
var res map[string]MarketResponseItem
|
|
err := z.SendHTTPRequest(endpoint, &res, request.UnAuth)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
// GetLatestSpotPrice returns latest spot price of symbol
|
|
//
|
|
// symbol: string of currency pair
|
|
// 获取最新价格
|
|
func (z *ZB) GetLatestSpotPrice(symbol string) (float64, error) {
|
|
res, err := z.GetTicker(symbol)
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return res.Ticker.Last, nil
|
|
}
|
|
|
|
// GetTicker returns a ticker for a given symbol
|
|
func (z *ZB) GetTicker(symbol string) (TickerResponse, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s?market=%s", z.API.Endpoints.URL, zbAPIVersion, zbTicker, symbol)
|
|
var res TickerResponse
|
|
err := z.SendHTTPRequest(urlPath, &res, request.UnAuth)
|
|
return res, err
|
|
}
|
|
|
|
// GetTickers returns ticker data for all supported symbols
|
|
func (z *ZB) GetTickers() (map[string]TickerChildResponse, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s", z.API.Endpoints.URL, zbAPIVersion, zbTickers)
|
|
resp := make(map[string]TickerChildResponse)
|
|
err := z.SendHTTPRequest(urlPath, &resp, request.UnAuth)
|
|
return resp, err
|
|
}
|
|
|
|
// GetOrderbook returns the orderbook for a given symbol
|
|
func (z *ZB) GetOrderbook(symbol string) (OrderbookResponse, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s?market=%s", z.API.Endpoints.URL, zbAPIVersion, zbDepth, symbol)
|
|
var res OrderbookResponse
|
|
|
|
err := z.SendHTTPRequest(urlPath, &res, request.UnAuth)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
|
|
if len(res.Asks) == 0 {
|
|
return res, fmt.Errorf("ZB GetOrderbook asks is empty")
|
|
}
|
|
|
|
if len(res.Bids) == 0 {
|
|
return res, fmt.Errorf("ZB GetOrderbook bids is empty")
|
|
}
|
|
|
|
// reverse asks data
|
|
var data [][]float64
|
|
for x := len(res.Asks); x > 0; x-- {
|
|
data = append(data, res.Asks[x-1])
|
|
}
|
|
|
|
res.Asks = data
|
|
return res, nil
|
|
}
|
|
|
|
// GetSpotKline returns Kline data
|
|
func (z *ZB) GetSpotKline(arg KlinesRequestParams) (KLineResponse, error) {
|
|
vals := url.Values{}
|
|
vals.Set("type", arg.Type)
|
|
vals.Set("market", arg.Symbol)
|
|
if arg.Since > 0 {
|
|
vals.Set("since", strconv.FormatInt(arg.Since, 10))
|
|
}
|
|
if arg.Size != 0 {
|
|
vals.Set("size", fmt.Sprintf("%d", arg.Size))
|
|
}
|
|
|
|
urlPath := fmt.Sprintf("%s/%s/%s?%s", z.API.Endpoints.URL, zbAPIVersion, zbKline, vals.Encode())
|
|
|
|
var res KLineResponse
|
|
var rawKlines map[string]interface{}
|
|
err := z.SendHTTPRequest(urlPath, &rawKlines, klineFunc)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
if rawKlines == nil || rawKlines["symbol"] == nil {
|
|
return res, errors.New("zb GetSpotKline rawKlines is nil")
|
|
}
|
|
|
|
res.Symbol = rawKlines["symbol"].(string)
|
|
res.MoneyType = rawKlines["moneyType"].(string)
|
|
|
|
rawKlineDatasString, _ := json.Marshal(rawKlines["data"].([]interface{}))
|
|
var rawKlineDatas [][]interface{}
|
|
if err := json.Unmarshal(rawKlineDatasString, &rawKlineDatas); err != nil {
|
|
return res, errors.New("zb rawKlines unmarshal failed")
|
|
}
|
|
for _, k := range rawKlineDatas {
|
|
ot, err := convert.TimeFromUnixTimestampFloat(k[0])
|
|
if err != nil {
|
|
return res, errors.New("zb cannot parse Kline.OpenTime")
|
|
}
|
|
res.Data = append(res.Data, &KLineResponseData{
|
|
ID: k[0].(float64),
|
|
KlineTime: ot,
|
|
Open: k[1].(float64),
|
|
High: k[2].(float64),
|
|
Low: k[3].(float64),
|
|
Close: k[4].(float64),
|
|
Volume: k[5].(float64),
|
|
})
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
// GetCryptoAddress fetches and returns the deposit address
|
|
// NOTE - PLEASE BE AWARE THAT YOU NEED TO GENERATE A DEPOSIT ADDRESS VIA
|
|
// LOGGING IN AND NOT BY USING THIS ENDPOINT OTHERWISE THIS WILL GIVE YOU A
|
|
// GENERAL ERROR RESPONSE.
|
|
func (z *ZB) GetCryptoAddress(currency currency.Code) (UserAddress, error) {
|
|
var resp UserAddress
|
|
|
|
vals := url.Values{}
|
|
vals.Set("method", zbDepositAddress)
|
|
vals.Set("currency", currency.Lower().String())
|
|
|
|
return resp,
|
|
z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &resp, request.Auth)
|
|
}
|
|
|
|
// SendHTTPRequest sends an unauthenticated HTTP request
|
|
func (z *ZB) SendHTTPRequest(path string, result interface{}, f request.EndpointLimit) error {
|
|
return z.SendPayload(context.Background(), &request.Item{
|
|
Method: http.MethodGet,
|
|
Path: path,
|
|
Result: result,
|
|
Verbose: z.Verbose,
|
|
HTTPDebugging: z.HTTPDebugging,
|
|
HTTPRecording: z.HTTPRecording,
|
|
Endpoint: f,
|
|
})
|
|
}
|
|
|
|
// SendAuthenticatedHTTPRequest sends authenticated requests to the zb API
|
|
func (z *ZB) SendAuthenticatedHTTPRequest(httpMethod string, params url.Values, result interface{}, f request.EndpointLimit) error {
|
|
if !z.AllowAuthenticatedRequest() {
|
|
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, z.Name)
|
|
}
|
|
|
|
params.Set("accesskey", z.API.Credentials.Key)
|
|
|
|
hmac := crypto.GetHMAC(crypto.HashMD5,
|
|
[]byte(params.Encode()),
|
|
[]byte(crypto.Sha1ToHex(z.API.Credentials.Secret)))
|
|
|
|
now := time.Now()
|
|
params.Set("reqTime", fmt.Sprintf("%d", convert.UnixMillis(now)))
|
|
params.Set("sign", fmt.Sprintf("%x", hmac))
|
|
|
|
urlPath := fmt.Sprintf("%s/%s?%s",
|
|
z.API.Endpoints.URLSecondary,
|
|
params.Get("method"),
|
|
params.Encode())
|
|
|
|
var intermediary json.RawMessage
|
|
|
|
errCap := struct {
|
|
Code int64 `json:"code"`
|
|
Message string `json:"message"`
|
|
}{}
|
|
|
|
// Expiry of timestamp doesn't appear to be documented, so making a reasonable assumption
|
|
ctx, cancel := context.WithDeadline(context.Background(), now.Add(15*time.Second))
|
|
defer cancel()
|
|
err := z.SendPayload(ctx, &request.Item{
|
|
Method: httpMethod,
|
|
Path: urlPath,
|
|
Body: strings.NewReader(""),
|
|
Result: &intermediary,
|
|
AuthRequest: true,
|
|
Verbose: z.Verbose,
|
|
HTTPDebugging: z.HTTPDebugging,
|
|
HTTPRecording: z.HTTPRecording,
|
|
Endpoint: f,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = json.Unmarshal(intermediary, &errCap)
|
|
if err == nil {
|
|
if errCap.Code > 1000 {
|
|
return fmt.Errorf("sendAuthenticatedHTTPRequest error code: %d message %s",
|
|
errCap.Code,
|
|
errorCode[errCap.Code])
|
|
}
|
|
}
|
|
|
|
return json.Unmarshal(intermediary, result)
|
|
}
|
|
|
|
// GetFee returns an estimate of fee based on type of transaction
|
|
func (z *ZB) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
|
|
var fee float64
|
|
switch feeBuilder.FeeType {
|
|
case exchange.CryptocurrencyTradeFee:
|
|
fee = calculateTradingFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
|
|
case exchange.CryptocurrencyWithdrawalFee:
|
|
fee = getWithdrawalFee(feeBuilder.Pair.Base)
|
|
case exchange.OfflineTradeFee:
|
|
fee = getOfflineTradeFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
|
|
}
|
|
if fee < 0 {
|
|
fee = 0
|
|
}
|
|
|
|
return fee, nil
|
|
}
|
|
|
|
// getOfflineTradeFee calculates the worst case-scenario trading fee
|
|
func getOfflineTradeFee(price, amount float64) float64 {
|
|
return 0.002 * price * amount
|
|
}
|
|
|
|
func calculateTradingFee(purchasePrice, amount float64) (fee float64) {
|
|
fee = 0.002
|
|
return fee * amount * purchasePrice
|
|
}
|
|
|
|
func getWithdrawalFee(c currency.Code) float64 {
|
|
return WithdrawalFees[c]
|
|
}
|
|
|
|
var errorCode = map[int64]string{
|
|
1000: "Successful call",
|
|
1001: "General error message",
|
|
1002: "internal error",
|
|
1003: "Verification failed",
|
|
1004: "Financial security password lock",
|
|
1005: "The fund security password is incorrect. Please confirm and re-enter.",
|
|
1006: "Real-name certification is awaiting review or review",
|
|
1009: "This interface is being maintained",
|
|
1010: "Not open yet",
|
|
1012: "Insufficient permissions",
|
|
1013: "Can not trade, if you have any questions, please contact online customer service",
|
|
1014: "Cannot be sold during the pre-sale period",
|
|
2002: "Insufficient balance in Bitcoin account",
|
|
2003: "Insufficient balance of Litecoin account",
|
|
2005: "Insufficient balance in Ethereum account",
|
|
2006: "Insufficient balance in ETC currency account",
|
|
2007: "Insufficient balance of BTS currency account",
|
|
2009: "Insufficient account balance",
|
|
3001: "Pending order not found",
|
|
3002: "Invalid amount",
|
|
3003: "Invalid quantity",
|
|
3004: "User does not exist",
|
|
3005: "Invalid parameter",
|
|
3006: "Invalid IP or inconsistent with the bound IP",
|
|
3007: "Request time has expired",
|
|
3008: "Transaction history not found",
|
|
4001: "API interface is locked",
|
|
4002: "Request too frequently",
|
|
}
|
|
|
|
// Withdraw transfers funds
|
|
func (z *ZB) Withdraw(currency, address, safepassword string, amount, fees float64, itransfer bool) (string, error) {
|
|
type response struct {
|
|
Code int `json:"code"` // Result code
|
|
Message string `json:"message"` // Result Message
|
|
ID string `json:"id"` // Withdrawal ID
|
|
}
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
vals.Set("currency", currency)
|
|
vals.Set("fees", strconv.FormatFloat(fees, 'f', -1, 64))
|
|
vals.Set("itransfer", strconv.FormatBool(itransfer))
|
|
vals.Set("method", "withdraw")
|
|
vals.Set("recieveAddr", address)
|
|
vals.Set("safePwd", safepassword)
|
|
|
|
var resp response
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &resp, request.Auth)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if resp.Code != 1000 {
|
|
return "", errors.New(resp.Message)
|
|
}
|
|
|
|
return resp.ID, nil
|
|
}
|