Rename BTC-e to WEX and reinstate exchange

This commit is contained in:
Adrian Gallagher
2017-09-16 13:03:00 +10:00
parent 9114de8a06
commit 542828e957
8 changed files with 556 additions and 543 deletions

393
exchanges/wex/wex.go Normal file
View File

@@ -0,0 +1,393 @@
package wex
import (
"errors"
"fmt"
"log"
"net/url"
"strconv"
"strings"
"time"
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/config"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
"github.com/thrasher-/gocryptotrader/exchanges/ticker"
)
const (
wexAPIPublicURL = "https://wex.nz/api"
wexAPIPrivateURL = "https://wex.nz/tapi"
wexAPIPublicVersion = "3"
wexAPIPrivateVersion = "1"
wexInfo = "info"
wexTicker = "ticker"
wexDepth = "depth"
wexTrades = "trades"
wexAccountInfo = "getInfo"
wexTrade = "Trade"
wexActiveOrders = "ActiveOrders"
wexOrderInfo = "OrderInfo"
wexCancelOrder = "CancelOrder"
wexTradeHistory = "TradeHistory"
wexTransactionHistory = "TransHistory"
wexWithdrawCoin = "WithdrawCoin"
wexCoinDepositAddress = "CoinDepositAddress"
wexCreateCoupon = "CreateCoupon"
wexRedeemCoupon = "RedeemCoupon"
)
// WEX is the overarching type across the wex package
type WEX struct {
exchange.Base
Ticker map[string]Ticker
}
// SetDefaults sets current default value for WEX
func (w *WEX) SetDefaults() {
w.Name = "WEX"
w.Enabled = false
w.Fee = 0.2
w.Verbose = false
w.Websocket = false
w.RESTPollingDelay = 10
w.Ticker = make(map[string]Ticker)
w.RequestCurrencyPairFormat.Delimiter = "_"
w.RequestCurrencyPairFormat.Uppercase = false
w.RequestCurrencyPairFormat.Separator = "-"
w.ConfigCurrencyPairFormat.Delimiter = ""
w.ConfigCurrencyPairFormat.Uppercase = true
w.AssetTypes = []string{ticker.Spot}
}
// Setup sets exchange configuration parameters for WEX
func (w *WEX) Setup(exch config.ExchangeConfig) {
if !exch.Enabled {
w.SetEnabled(false)
} else {
w.Enabled = true
w.AuthenticatedAPISupport = exch.AuthenticatedAPISupport
w.SetAPIKeys(exch.APIKey, exch.APISecret, "", false)
w.RESTPollingDelay = exch.RESTPollingDelay
w.Verbose = exch.Verbose
w.Websocket = exch.Websocket
w.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",")
w.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",")
w.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",")
err := w.SetCurrencyPairFormat()
if err != nil {
log.Fatal(err)
}
err = w.SetAssetTypes()
if err != nil {
log.Fatal(err)
}
}
}
// GetFee returns the exchange fee
func (w *WEX) GetFee() float64 {
return w.Fee
}
// GetInfo returns the WEX info
func (w *WEX) GetInfo() (Info, error) {
req := fmt.Sprintf("%s/%s/%s/", wexAPIPublicURL, wexAPIPublicVersion, wexInfo)
resp := Info{}
err := common.SendHTTPGetRequest(req, true, &resp)
if err != nil {
return resp, err
}
return resp, nil
}
// GetTicker returns a ticker for a specific currency
func (w *WEX) GetTicker(symbol string) (map[string]Ticker, error) {
type Response struct {
Data map[string]Ticker
}
response := Response{}
req := fmt.Sprintf("%s/%s/%s/%s", wexAPIPublicURL, wexAPIPublicVersion, wexTicker, symbol)
err := common.SendHTTPGetRequest(req, true, &response.Data)
if err != nil {
return nil, err
}
return response.Data, nil
}
// GetDepth returns the depth for a specific currency
func (w *WEX) GetDepth(symbol string) (Orderbook, error) {
type Response struct {
Data map[string]Orderbook
}
response := Response{}
req := fmt.Sprintf("%s/%s/%s/%s", wexAPIPublicURL, wexAPIPublicVersion, wexDepth, symbol)
err := common.SendHTTPGetRequest(req, true, &response.Data)
if err != nil {
return Orderbook{}, err
}
depth := response.Data[symbol]
return depth, nil
}
// GetTrades returns the trades for a specific currency
func (w *WEX) GetTrades(symbol string) ([]Trades, error) {
type Response struct {
Data map[string][]Trades
}
response := Response{}
req := fmt.Sprintf("%s/%s/%s/%s", wexAPIPublicURL, wexAPIPublicVersion, wexTrades, symbol)
err := common.SendHTTPGetRequest(req, true, &response.Data)
if err != nil {
return nil, err
}
trades := response.Data[symbol]
return trades, nil
}
// GetAccountInfo returns a users account info
func (w *WEX) GetAccountInfo() (AccountInfo, error) {
var result AccountInfo
err := w.SendAuthenticatedHTTPRequest(wexAccountInfo, url.Values{}, &result)
if err != nil {
return result, err
}
return result, nil
}
// GetActiveOrders returns the active orders for a specific currency
func (w *WEX) GetActiveOrders(pair string) (map[string]ActiveOrders, error) {
req := url.Values{}
req.Add("pair", pair)
var result map[string]ActiveOrders
err := w.SendAuthenticatedHTTPRequest(wexActiveOrders, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// GetOrderInfo returns the order info for a specific order ID
func (w *WEX) GetOrderInfo(OrderID int64) (map[string]OrderInfo, error) {
req := url.Values{}
req.Add("order_id", strconv.FormatInt(OrderID, 10))
var result map[string]OrderInfo
err := w.SendAuthenticatedHTTPRequest(wexOrderInfo, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// CancelOrder cancels an order for a specific order ID
func (w *WEX) CancelOrder(OrderID int64) (bool, error) {
req := url.Values{}
req.Add("order_id", strconv.FormatInt(OrderID, 10))
var result CancelOrder
err := w.SendAuthenticatedHTTPRequest(wexCancelOrder, req, &result)
if err != nil {
return false, err
}
return true, nil
}
// Trade places an order and returns the order ID if successful or an error
func (w *WEX) Trade(pair, orderType string, amount, price float64) (int64, error) {
req := url.Values{}
req.Add("pair", pair)
req.Add("type", orderType)
req.Add("amount", strconv.FormatFloat(amount, 'f', -1, 64))
req.Add("rate", strconv.FormatFloat(price, 'f', -1, 64))
var result Trade
err := w.SendAuthenticatedHTTPRequest(wexTrade, req, &result)
if err != nil {
return 0, err
}
return int64(result.OrderID), nil
}
// GetTransactionHistory returns the transaction history
func (w *WEX) GetTransactionHistory(TIDFrom, Count, TIDEnd int64, order, since, end string) (map[string]TransHistory, error) {
req := url.Values{}
req.Add("from", strconv.FormatInt(TIDFrom, 10))
req.Add("count", strconv.FormatInt(Count, 10))
req.Add("from_id", strconv.FormatInt(TIDFrom, 10))
req.Add("end_id", strconv.FormatInt(TIDEnd, 10))
req.Add("order", order)
req.Add("since", since)
req.Add("end", end)
var result map[string]TransHistory
err := w.SendAuthenticatedHTTPRequest(wexTransactionHistory, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// GetTradeHistory returns the trade history
func (w *WEX) GetTradeHistory(TIDFrom, Count, TIDEnd int64, order, since, end, pair string) (map[string]TradeHistory, error) {
req := url.Values{}
req.Add("from", strconv.FormatInt(TIDFrom, 10))
req.Add("count", strconv.FormatInt(Count, 10))
req.Add("from_id", strconv.FormatInt(TIDFrom, 10))
req.Add("end_id", strconv.FormatInt(TIDEnd, 10))
req.Add("order", order)
req.Add("since", since)
req.Add("end", end)
req.Add("pair", pair)
var result map[string]TradeHistory
err := w.SendAuthenticatedHTTPRequest(wexTradeHistory, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// WithdrawCoins withdraws coins for a specific coin
func (w *WEX) WithdrawCoins(coin string, amount float64, address string) (WithdrawCoins, error) {
req := url.Values{}
req.Add("coinName", coin)
req.Add("amount", strconv.FormatFloat(amount, 'f', -1, 64))
req.Add("address", address)
var result WithdrawCoins
err := w.SendAuthenticatedHTTPRequest(wexWithdrawCoin, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// CoinDepositAddress returns the deposit address for a specific currency
func (w *WEX) CoinDepositAddress(coin string) (string, error) {
req := url.Values{}
req.Add("coinName", coin)
var result CoinDepositAddress
err := w.SendAuthenticatedHTTPRequest(wexCoinDepositAddress, req, &result)
if err != nil {
return "", nil
}
return result.Address, nil
}
// CreateCoupon creates an exchange coupon for a sepcific currency
func (w *WEX) CreateCoupon(currency string, amount float64) (CreateCoupon, error) {
req := url.Values{}
req.Add("currency", currency)
req.Add("amount", strconv.FormatFloat(amount, 'f', -1, 64))
var result CreateCoupon
err := w.SendAuthenticatedHTTPRequest(wexCreateCoupon, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// RedeemCoupon redeems an exchange coupon
func (w *WEX) RedeemCoupon(coupon string) (RedeemCoupon, error) {
req := url.Values{}
req.Add("coupon", coupon)
var result RedeemCoupon
err := w.SendAuthenticatedHTTPRequest(wexRedeemCoupon, req, &result)
if err != nil {
return result, err
}
return result, nil
}
// SendAuthenticatedHTTPRequest sends an authenticated HTTP request to WEX
func (w *WEX) SendAuthenticatedHTTPRequest(method string, values url.Values, result interface{}) (err error) {
if !w.AuthenticatedAPISupport {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, w.Name)
}
if w.Nonce.Get() == 0 {
w.Nonce.Set(time.Now().Unix())
} else {
w.Nonce.Inc()
}
values.Set("nonce", w.Nonce.String())
values.Set("method", method)
encoded := values.Encode()
hmac := common.GetHMAC(common.HashSHA512, []byte(encoded), []byte(w.APISecret))
if w.Verbose {
log.Printf("Sending POST request to %s calling method %s with params %s\n", wexAPIPrivateURL, method, encoded)
}
headers := make(map[string]string)
headers["Key"] = w.APIKey
headers["Sign"] = common.HexEncodeToString(hmac)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := common.SendHTTPRequest("POST", wexAPIPrivateURL, headers, strings.NewReader(encoded))
if err != nil {
return err
}
response := Response{}
err = common.JSONDecode([]byte(resp), &response)
if err != nil {
return err
}
if response.Success != 1 {
return errors.New(response.Error)
}
JSONEncoded, err := common.JSONEncode(response.Return)
if err != nil {
return err
}
err = common.JSONDecode(JSONEncoded, &result)
if err != nil {
return err
}
return nil
}

130
exchanges/wex/wex_types.go Normal file
View File

@@ -0,0 +1,130 @@
package wex
type Ticker struct {
High float64
Low float64
Avg float64
Vol float64
Vol_cur float64
Last float64
Buy float64
Sell float64
Updated int64
}
type Orderbook struct {
Asks [][]float64 `json:"asks"`
Bids [][]float64 `json:"bids"`
}
type Trades struct {
Type string `json:"type"`
Price float64 `json:"bid"`
Amount float64 `json:"amount"`
TID int64 `json:"tid"`
Timestamp int64 `json:"timestamp"`
}
type Response struct {
Return interface{} `json:"return"`
Success int `json:"success"`
Error string `json:"error"`
}
type Pair struct {
DecimalPlaces int `json:"decimal_places"`
MinPrice float64 `json:"min_price"`
MaxPrice float64 `json:"max_price"`
MinAmount float64 `json:"min_amount"`
Hidden int `json:"hidden"`
Fee float64 `json:"fee"`
}
type Info struct {
ServerTime int64 `json:"server_time"`
Pairs map[string]Pair `json:"pairs"`
}
type AccountInfo struct {
Funds map[string]float64 `json:"funds"`
OpenOrders int `json:"open_orders"`
Rights struct {
Info int `json:"info"`
Trade int `json:"trade"`
Withdraw int `json:"withdraw"`
} `json:"rights"`
ServerTime float64 `json:"server_time"`
TransactionCount int `json:"transaction_count"`
}
type ActiveOrders struct {
Pair string `json:"pair"`
Type string `json:"sell"`
Amount float64 `json:"amount"`
Rate float64 `json:"rate"`
TimestampCreated float64 `json:"time_created"`
Status int `json:"status"`
}
type OrderInfo struct {
Pair string `json:"pair"`
Type string `json:"sell"`
StartAmount float64 `json:"start_amount"`
Amount float64 `json:"amount"`
Rate float64 `json:"rate"`
TimestampCreated float64 `json:"time_created"`
Status int `json:"status"`
}
type CancelOrder struct {
OrderID float64 `json:"order_id"`
Funds map[string]float64 `json:"funds"`
}
type Trade struct {
Received float64 `json:"received"`
Remains float64 `json:"remains"`
OrderID float64 `json:"order_id"`
Funds map[string]float64 `json:"funds"`
}
type TransHistory struct {
Type int `json:"type"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
Description string `json:"desc"`
Status int `json:"status"`
Timestamp float64 `json:"timestamp"`
}
type TradeHistory struct {
Pair string `json:"pair"`
Type string `json:"type"`
Amount float64 `json:"amount"`
Rate float64 `json:"rate"`
OrderID float64 `json:"order_id"`
MyOrder int `json:"is_your_order"`
Timestamp float64 `json:"timestamp"`
}
type CoinDepositAddress struct {
Address string `json:"address"`
}
type WithdrawCoins struct {
TID int64 `json:"tId"`
AmountSent float64 `json:"amountSent"`
Funds map[string]float64 `json:"funds"`
}
type CreateCoupon struct {
Coupon string `json:"coupon"`
TransID int64 `json:"transID"`
Funds map[string]float64 `json:"funds"`
}
type RedeemCoupon struct {
CouponAmount float64 `json:"couponAmount,string"`
CouponCurrency string `json:"couponCurrency"`
TransID int64 `json:"transID"`
}

View File

@@ -0,0 +1,114 @@
package wex
import (
"log"
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/currency/pair"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
"github.com/thrasher-/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-/gocryptotrader/exchanges/ticker"
)
// Start starts the BTCE go routine
func (w *WEX) Start() {
go w.Run()
}
// Run implements the BTCE wrapper
func (w *WEX) Run() {
if w.Verbose {
log.Printf("%s Websocket: %s.", w.GetName(), common.IsEnabled(w.Websocket))
log.Printf("%s polling delay: %ds.\n", w.GetName(), w.RESTPollingDelay)
log.Printf("%s %d currencies enabled: %s.\n", w.GetName(), len(w.EnabledPairs), w.EnabledPairs)
}
}
// UpdateTicker updates and returns the ticker for a currency pair
func (w *WEX) UpdateTicker(p pair.CurrencyPair, assetType string) (ticker.Price, error) {
var tickerPrice ticker.Price
pairsCollated, err := exchange.GetAndFormatExchangeCurrencies(w.Name, w.GetEnabledCurrencies())
if err != nil {
return tickerPrice, err
}
result, err := w.GetTicker(pairsCollated.String())
if err != nil {
return tickerPrice, err
}
for _, x := range w.GetEnabledCurrencies() {
currency := exchange.FormatExchangeCurrency(w.Name, x).Lower().String()
var tp ticker.Price
tp.Pair = x
tp.Last = result[currency].Last
tp.Ask = result[currency].Sell
tp.Bid = result[currency].Buy
tp.Last = result[currency].Last
tp.Low = result[currency].Low
tp.Volume = result[currency].Vol_cur
ticker.ProcessTicker(w.Name, x, tp, assetType)
}
return ticker.GetTicker(w.Name, p, assetType)
}
// GetTickerPrice returns the ticker for a currency pair
func (w *WEX) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Price, error) {
tick, err := ticker.GetTicker(w.GetName(), p, assetType)
if err != nil {
return w.UpdateTicker(p, assetType)
}
return tick, nil
}
// GetOrderbookEx returns the orderbook for a currency pair
func (w *WEX) GetOrderbookEx(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
ob, err := orderbook.GetOrderbook(w.GetName(), p, assetType)
if err == nil {
return w.UpdateOrderbook(p, assetType)
}
return ob, nil
}
// UpdateOrderbook updates and returns the orderbook for a currency pair
func (w *WEX) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
var orderBook orderbook.Base
orderbookNew, err := w.GetDepth(exchange.FormatExchangeCurrency(w.Name, p).String())
if err != nil {
return orderBook, err
}
for x := range orderbookNew.Bids {
data := orderbookNew.Bids[x]
orderBook.Bids = append(orderBook.Bids, orderbook.Item{Price: data[0], Amount: data[1]})
}
for x := range orderbookNew.Asks {
data := orderbookNew.Asks[x]
orderBook.Asks = append(orderBook.Asks, orderbook.Item{Price: data[0], Amount: data[1]})
}
orderbook.ProcessOrderbook(w.GetName(), p, orderBook, assetType)
return orderbook.GetOrderbook(w.Name, p, assetType)
}
// GetExchangeAccountInfo retrieves balances for all enabled currencies for the
// BTCE exchange
func (w *WEX) GetExchangeAccountInfo() (exchange.AccountInfo, error) {
var response exchange.AccountInfo
response.ExchangeName = w.GetName()
accountBalance, err := w.GetAccountInfo()
if err != nil {
return response, err
}
for x, y := range accountBalance.Funds {
var exchangeCurrency exchange.AccountCurrencyInfo
exchangeCurrency.CurrencyName = common.StringToUpper(x)
exchangeCurrency.TotalValue = y
exchangeCurrency.Hold = 0
response.Currencies = append(response.Currencies, exchangeCurrency)
}
return response, nil
}