Improved codecov, expanded functionality for BTCMarkets

This commit is contained in:
Ryan O'Hara-Reid
2017-08-24 11:54:57 +10:00
parent c2f12b777c
commit 39fa7f75f9
11 changed files with 618 additions and 303 deletions

View File

@@ -1,25 +0,0 @@
package anx
import (
"testing"
)
func TestStart(t *testing.T) {
}
func TestRun(t *testing.T) {
}
func TestGetTickerPrice(t *testing.T) {
}
func TestGetOrderbookEx(t *testing.T) {
}
func TestGetExchangeAccountInfo(t *testing.T) {
}

View File

@@ -15,37 +15,39 @@ import (
)
const (
BTCC_API_URL = "https://api.btcchina.com/"
BTCC_API_AUTHENTICATED_METHOD = "api_trade_v1.php"
BTCC_API_VER = "2.0.1.3"
BTCC_ORDER_BUY = "buyOrder2"
BTCC_ORDER_SELL = "sellOrder2"
BTCC_ORDER_CANCEL = "cancelOrder"
BTCC_ICEBERG_BUY = "buyIcebergOrder"
BTCC_ICEBERG_SELL = "sellIcebergOrder"
BTCC_ICEBERG_ORDER = "getIcebergOrder"
BTCC_ICEBERG_ORDERS = "getIcebergOrders"
BTCC_ICEBERG_CANCEL = "cancelIcebergOrder"
BTCC_ACCOUNT_INFO = "getAccountInfo"
BTCC_DEPOSITS = "getDeposits"
BTCC_MARKETDEPTH = "getMarketDepth2"
BTCC_ORDER = "getOrder"
BTCC_ORDERS = "getOrders"
BTCC_TRANSACTIONS = "getTransactions"
BTCC_WITHDRAWAL = "getWithdrawal"
BTCC_WITHDRAWALS = "getWithdrawals"
BTCC_WITHDRAWAL_REQUEST = "requestWithdrawal"
BTCC_STOPORDER_BUY = "buyStopOrder"
BTCC_STOPORDER_SELL = "sellStopOrder"
BTCC_STOPORDER_CANCEL = "cancelStopOrder"
BTCC_STOPORDER = "getStopOrder"
BTCC_STOPORDERS = "getStopOrders"
btccAPIUrl = "https://api.btcchina.com/"
btccAPIAuthenticatedMethod = "api_trade_v1.php"
btccAPIVersion = "2.0.1.3"
btccOrderBuy = "buyOrder2"
btccOrderSell = "sellOrder2"
btccOrderCancel = "cancelOrder"
btccIcebergBuy = "buyIcebergOrder"
btccIcebergSell = "sellIcebergOrder"
btccIcebergOrder = "getIcebergOrder"
btccIcebergOrders = "getIcebergOrders"
btccIcebergCancel = "cancelIcebergOrder"
btccAccountInfo = "getAccountInfo"
btccDeposits = "getDeposits"
btccMarketdepth = "getMarketDepth2"
btccOrder = "getOrder"
btccOrders = "getOrders"
btccTransactions = "getTransactions"
btccWithdrawal = "getWithdrawal"
btccWithdrawals = "getWithdrawals"
btccWithdrawalRequest = "requestWithdrawal"
btccStoporderBuy = "buyStopOrder"
btccStoporderSell = "sellStopOrder"
btccStoporderCancel = "cancelStopOrder"
btccStoporder = "getStopOrder"
btccStoporders = "getStopOrders"
)
// BTCC is the main overaching type across the BTCC package
type BTCC struct {
exchange.Base
}
// SetDefaults sets default values for the exchange
func (b *BTCC) SetDefaults() {
b.Name = "BTCC"
b.Enabled = false
@@ -55,7 +57,7 @@ func (b *BTCC) SetDefaults() {
b.RESTPollingDelay = 10
}
//Setup is run on startup to setup exchange with config values
// Setup is run on startup to setup exchange with config values
func (b *BTCC) Setup(exch config.ExchangeConfig) {
if !exch.Enabled {
b.SetEnabled(false)
@@ -72,36 +74,40 @@ func (b *BTCC) Setup(exch config.ExchangeConfig) {
}
}
// GetFee returns the fees associated with transactions
func (b *BTCC) GetFee() float64 {
return b.Fee
}
func (b *BTCC) GetTicker(symbol string) (BTCCTicker, error) {
type Response struct {
Ticker BTCCTicker
}
// GetTicker returns ticker information
// currencyPair - Example "btccny", "ltccny" or "ltcbtc"
func (b *BTCC) GetTicker(currencyPair string) (Ticker, error) {
resp := Response{}
req := fmt.Sprintf("%sdata/ticker?market=%s", BTCC_API_URL, symbol)
err := common.SendHTTPGetRequest(req, true, &resp)
if err != nil {
return BTCCTicker{}, err
}
return resp.Ticker, nil
req := fmt.Sprintf("%sdata/ticker?market=%s", btccAPIUrl, currencyPair)
return resp.Ticker, common.SendHTTPGetRequest(req, true, &resp)
}
func (b *BTCC) GetTradesLast24h(symbol string) bool {
req := fmt.Sprintf("%sdata/trades?market=%s", BTCC_API_URL, symbol)
err := common.SendHTTPGetRequest(req, true, nil)
if err != nil {
log.Println(err)
return false
}
return true
// GetTradesLast24h returns the trades executed on the exchange over the past
// 24 hours by currency pair
// currencyPair - Example "btccny", "ltccny" or "ltcbtc"
func (b *BTCC) GetTradesLast24h(currencyPair string) ([]Trade, error) {
trades := []Trade{}
req := fmt.Sprintf("%sdata/trades?market=%s", btccAPIUrl, currencyPair)
return trades, common.SendHTTPGetRequest(req, true, &trades)
}
func (b *BTCC) GetTradeHistory(symbol string, limit, sinceTid int64, time time.Time) bool {
req := fmt.Sprintf("%sdata/historydata?market=%s", BTCC_API_URL, symbol)
// GetTradeHistory returns trade history data
// currencyPair - Example "btccny", "ltccny" or "ltcbtc"
// limit - limits the returned trades example "10"
// sinceTid - returns trade records starting from id supplied example "5000"
// time - returns trade records starting from unix time 1406794449
func (b *BTCC) GetTradeHistory(currencyPair string, limit, sinceTid int64, time time.Time) ([]Trade, error) {
trades := []Trade{}
req := fmt.Sprintf("%sdata/historydata?market=%s", btccAPIUrl, currencyPair)
v := url.Values{}
if limit > 0 {
@@ -115,37 +121,33 @@ func (b *BTCC) GetTradeHistory(symbol string, limit, sinceTid int64, time time.T
}
req = common.EncodeURLValues(req, v)
err := common.SendHTTPGetRequest(req, true, nil)
if err != nil {
log.Println(err)
return false
}
return true
return trades, common.SendHTTPGetRequest(req, true, &trades)
}
func (b *BTCC) GetOrderBook(symbol string, limit int) (BTCCOrderbook, error) {
result := BTCCOrderbook{}
req := fmt.Sprintf("%sdata/orderbook?market=%s&limit=%d", BTCC_API_URL, symbol, limit)
err := common.SendHTTPGetRequest(req, true, &result)
if err != nil {
return BTCCOrderbook{}, err
// GetOrderBook returns current market order book
// currencyPair - Example "btccny", "ltccny" or "ltcbtc"
// limit - limits the returned trades example "10" if 0 will return full
// orderbook
func (b *BTCC) GetOrderBook(currencyPair string, limit int) (Orderbook, error) {
result := Orderbook{}
req := fmt.Sprintf("%sdata/orderbook?market=%s&limit=%d", btccAPIUrl, currencyPair, limit)
if limit == 0 {
req = fmt.Sprintf("%sdata/orderbook?market=%s", btccAPIUrl, currencyPair)
}
return result, nil
return result, common.SendHTTPGetRequest(req, true, &result)
}
func (b *BTCC) GetAccountInfo(infoType string) {
func (b *BTCC) GetAccountInfo(infoType string) error {
params := make([]interface{}, 0)
if len(infoType) > 0 {
params = append(params, infoType)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ACCOUNT_INFO, params)
if err != nil {
log.Println(err)
}
return b.SendAuthenticatedHTTPRequest(btccAccountInfo, params)
}
func (b *BTCC) PlaceOrder(buyOrder bool, price, amount float64, market string) {
@@ -157,9 +159,9 @@ func (b *BTCC) PlaceOrder(buyOrder bool, price, amount float64, market string) {
params = append(params, market)
}
req := BTCC_ORDER_BUY
req := btccOrderBuy
if !buyOrder {
req = BTCC_ORDER_SELL
req = btccOrderSell
}
err := b.SendAuthenticatedHTTPRequest(req, params)
@@ -177,7 +179,7 @@ func (b *BTCC) CancelOrder(orderID int64, market string) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ORDER_CANCEL, params)
err := b.SendAuthenticatedHTTPRequest(btccOrderCancel, params)
if err != nil {
log.Println(err)
@@ -192,7 +194,7 @@ func (b *BTCC) GetDeposits(currency string, pending bool) {
params = append(params, pending)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_DEPOSITS, params)
err := b.SendAuthenticatedHTTPRequest(btccDeposits, params)
if err != nil {
log.Println(err)
@@ -210,7 +212,7 @@ func (b *BTCC) GetMarketDepth(market string, limit int64) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_MARKETDEPTH, params)
err := b.SendAuthenticatedHTTPRequest(btccMarketdepth, params)
if err != nil {
log.Println(err)
@@ -229,7 +231,7 @@ func (b *BTCC) GetOrder(orderID int64, market string, detailed bool) {
params = append(params, detailed)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ORDER, params)
err := b.SendAuthenticatedHTTPRequest(btccOrder, params)
if err != nil {
log.Println(err)
@@ -263,7 +265,7 @@ func (b *BTCC) GetOrders(openonly bool, market string, limit, offset, since int6
params = append(params, detailed)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ORDERS, params)
err := b.SendAuthenticatedHTTPRequest(btccOrders, params)
if err != nil {
log.Println(err)
@@ -293,7 +295,7 @@ func (b *BTCC) GetTransactions(transType string, limit, offset, since int64, sin
params = append(params, sinceType)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_TRANSACTIONS, params)
err := b.SendAuthenticatedHTTPRequest(btccTransactions, params)
if err != nil {
log.Println(err)
@@ -308,7 +310,7 @@ func (b *BTCC) GetWithdrawal(withdrawalID int64, currency string) {
params = append(params, currency)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_WITHDRAWAL, params)
err := b.SendAuthenticatedHTTPRequest(btccWithdrawal, params)
if err != nil {
log.Println(err)
@@ -323,7 +325,7 @@ func (b *BTCC) GetWithdrawals(currency string, pending bool) {
params = append(params, pending)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_WITHDRAWALS, params)
err := b.SendAuthenticatedHTTPRequest(btccWithdrawals, params)
if err != nil {
log.Println(err)
@@ -335,7 +337,7 @@ func (b *BTCC) RequestWithdrawal(currency string, amount float64) {
params = append(params, currency)
params = append(params, amount)
err := b.SendAuthenticatedHTTPRequest(BTCC_WITHDRAWAL_REQUEST, params)
err := b.SendAuthenticatedHTTPRequest(btccWithdrawalRequest, params)
if err != nil {
log.Println(err)
@@ -353,9 +355,9 @@ func (b *BTCC) IcebergOrder(buyOrder bool, price, amount, discAmount, variance f
params = append(params, market)
}
req := BTCC_ICEBERG_BUY
req := btccIcebergBuy
if !buyOrder {
req = BTCC_ICEBERG_SELL
req = btccIcebergSell
}
err := b.SendAuthenticatedHTTPRequest(req, params)
@@ -373,7 +375,7 @@ func (b *BTCC) GetIcebergOrder(orderID int64, market string) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ICEBERG_ORDER, params)
err := b.SendAuthenticatedHTTPRequest(btccIcebergOrder, params)
if err != nil {
log.Println(err)
@@ -395,7 +397,7 @@ func (b *BTCC) GetIcebergOrders(limit, offset int64, market string) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ICEBERG_ORDERS, params)
err := b.SendAuthenticatedHTTPRequest(btccIcebergOrders, params)
if err != nil {
log.Println(err)
@@ -410,7 +412,7 @@ func (b *BTCC) CancelIcebergOrder(orderID int64, market string) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_ICEBERG_CANCEL, params)
err := b.SendAuthenticatedHTTPRequest(btccIcebergCancel, params)
if err != nil {
log.Println(err)
@@ -439,9 +441,9 @@ func (b *BTCC) PlaceStopOrder(buyOder bool, stopPrice, price, amount, trailingAm
params = append(params, market)
}
req := BTCC_STOPORDER_BUY
req := btccStoporderBuy
if !buyOder {
req = BTCC_STOPORDER_SELL
req = btccStoporderSell
}
err := b.SendAuthenticatedHTTPRequest(req, params)
@@ -459,7 +461,7 @@ func (b *BTCC) GetStopOrder(orderID int64, market string) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_STOPORDER, params)
err := b.SendAuthenticatedHTTPRequest(btccStoporder, params)
if err != nil {
log.Println(err)
@@ -493,7 +495,7 @@ func (b *BTCC) GetStopOrders(status, orderType string, stopPrice float64, limit,
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_STOPORDERS, params)
err := b.SendAuthenticatedHTTPRequest(btccStoporders, params)
if err != nil {
log.Println(err)
@@ -508,7 +510,7 @@ func (b *BTCC) CancelStopOrder(orderID int64, market string) {
params = append(params, market)
}
err := b.SendAuthenticatedHTTPRequest(BTCC_STOPORDER_CANCEL, params)
err := b.SendAuthenticatedHTTPRequest(btccStoporderCancel, params)
if err != nil {
log.Println(err)
@@ -571,7 +573,7 @@ func (b *BTCC) SendAuthenticatedHTTPRequest(method string, params []interface{})
postData["method"] = method
postData["params"] = params
postData["id"] = 1
apiURL := BTCC_API_URL + BTCC_API_AUTHENTICATED_METHOD
apiURL := btccAPIUrl + btccAPIAuthenticatedMethod
data, err := common.JSONEncode(postData)
if err != nil {

View File

@@ -0,0 +1,79 @@
package btcc
import (
"testing"
"time"
"github.com/thrasher-/gocryptotrader/config"
)
// Please supply your own APIkeys here to do better tests
const (
apiKey = ""
apiSecret = ""
)
var b BTCC
func TestSetDefaults(t *testing.T) {
b.SetDefaults()
}
func TestSetup(t *testing.T) {
conf := config.ExchangeConfig{
Enabled: true,
}
b.Setup(conf)
conf = config.ExchangeConfig{
Enabled: false,
APIKey: apiKey,
APISecret: apiSecret,
}
b.Setup(conf)
}
func TestGetFee(t *testing.T) {
if b.GetFee() != 0 {
t.Error("Test failed - GetFee() error")
}
}
func TestGetTicker(t *testing.T) {
_, err := b.GetTicker("ltccny")
if err != nil {
t.Error("Test failed - GetTicker() error", err)
}
}
func TestGetTradesLast24h(t *testing.T) {
_, err := b.GetTradesLast24h("ltccny")
if err != nil {
t.Error("Test failed - GetTradesLast24h() error", err)
}
}
func TestGetTradeHistory(t *testing.T) {
_, err := b.GetTradeHistory("ltccny", 0, 0, time.Time{})
if err != nil {
t.Error("Test failed - GetTradeHistory() error", err)
}
}
func TestGetOrderBook(t *testing.T) {
_, err := b.GetOrderBook("ltccny", 100)
if err != nil {
t.Error("Test failed - GetOrderBook() error", err)
}
_, err = b.GetOrderBook("ltccny", 0)
if err != nil {
t.Error("Test failed - GetOrderBook() error", err)
}
}
func TestGetAccountInfo(t *testing.T) {
err := b.GetAccountInfo("")
if err == nil {
t.Error("Test failed - GetAccountInfo() error", err)
}
}

View File

@@ -1,19 +1,45 @@
package btcc
type BTCCTicker struct {
High float64 `json:",string"`
Low float64 `json:",string"`
Buy float64 `json:",string"`
Sell float64 `json:",string"`
Last float64 `json:",string"`
Vol float64 `json:",string"`
Date int64
Vwap float64 `json:",string"`
Prev_close float64 `json:",string"`
Open float64 `json:",string"`
// Response is the generalized response type
type Response struct {
Ticker Ticker `json:"ticker"`
BtcCny Ticker `json:"ticker_btccny"`
LtcCny Ticker `json:"ticker_ltccny"`
LtcBtc Ticker `json:"ticker_ltcbtc"`
}
type BTCCProfile struct {
// Ticker holds basic ticker information
type Ticker struct {
High float64 `json:"high,string"`
Low float64 `json:"low,string"`
Buy float64 `json:"buy,string"`
Sell float64 `json:"sell,string"`
Last float64 `json:"last,string"`
Vol float64 `json:"vol,string"`
Date int64 `json:"date"`
Vwap float64 `json:"vwap,string"`
PrevClose float64 `json:"prev_close,string"`
Open float64 `json:"open,string"`
}
// Trade holds executed trade data
type Trade struct {
Date int64 `json:"date,string"`
Price float64 `json:"price"`
Amount float64 `json:"amount"`
TID int64 `json:"tid,string"`
Type string `json:"type"`
}
// Orderbook holds orderbook data
type Orderbook struct {
Bids [][]float64 `json:"bids"`
Asks [][]float64 `json:"asks"`
Date int64 `json:"date"`
}
// Profile holds profile information
type Profile struct {
Username string
TradePasswordEnabled bool `json:"trade_password_enabled,bool"`
OTPEnabled bool `json:"otp_enabled,bool"`
@@ -29,13 +55,8 @@ type BTCCProfile struct {
APIKeyPermission int64 `json:"api_key_permission"`
}
type BTCCOrderbook struct {
Bids [][]float64 `json:"bids"`
Asks [][]float64 `json:"asks"`
Date int64 `json:"date"`
}
type BTCCCurrencyGeneric struct {
// CurrencyGeneric holds currency information
type CurrencyGeneric struct {
Currency string
Symbol string
Amount string
@@ -43,7 +64,8 @@ type BTCCCurrencyGeneric struct {
AmountDecimal float64 `json:"amount_decimal"`
}
type BTCCOrder struct {
// Order holds order information
type Order struct {
ID int64
Type string
Price float64
@@ -52,16 +74,18 @@ type BTCCOrder struct {
AmountOrig float64 `json:"amount_original"`
Date int64
Status string
Detail BTCCOrderDetail
Detail OrderDetail
}
type BTCCOrderDetail struct {
// OrderDetail holds order detail information
type OrderDetail struct {
Dateline int64
Price float64
Amount float64
}
type BTCCWithdrawal struct {
// Withdrawal holds withdrawal transaction information
type Withdrawal struct {
ID int64
Address string
Currency string
@@ -71,7 +95,8 @@ type BTCCWithdrawal struct {
Status string
}
type BTCCDeposit struct {
// Deposit holds deposit address information
type Deposit struct {
ID int64
Address string
Currency string
@@ -80,17 +105,20 @@ type BTCCDeposit struct {
Status string
}
type BTCCBidAsk struct {
// BidAsk holds bid and ask information
type BidAsk struct {
Price float64
Amount float64
}
type BTCCDepth struct {
Bid []BTCCBidAsk
Ask []BTCCBidAsk
// Depth holds order book depth
type Depth struct {
Bid []BidAsk
Ask []BidAsk
}
type BTCCTransaction struct {
// Transaction holds transaction information
type Transaction struct {
ID int64
Type string
BTCAmount float64 `json:"btc_amount"`
@@ -99,7 +127,8 @@ type BTCCTransaction struct {
Date int64
}
type BTCCIcebergOrder struct {
// IcebergOrder holds iceberg lettuce
type IcebergOrder struct {
ID int64
Type string
Price float64
@@ -112,7 +141,8 @@ type BTCCIcebergOrder struct {
Status string
}
type BTCCStopOrder struct {
// StopOrder holds stop order information
type StopOrder struct {
ID int64
Type string
StopPrice float64 `json:"stop_price"`
@@ -126,19 +156,22 @@ type BTCCStopOrder struct {
OrderID int64 `json:"order_id"`
}
type BTCCWebsocketOrder struct {
// WebsocketOrder holds websocket order information
type WebsocketOrder struct {
Price float64 `json:"price"`
TotalAmount float64 `json:"totalamount"`
Type string `json:"type"`
}
type BTCCWebsocketGroupOrder struct {
Asks []BTCCWebsocketOrder `json:"ask"`
Bids []BTCCWebsocketOrder `json:"bid"`
Market string `json:"market"`
// WebsocketGroupOrder holds websocket group order book information
type WebsocketGroupOrder struct {
Asks []WebsocketOrder `json:"ask"`
Bids []WebsocketOrder `json:"bid"`
Market string `json:"market"`
}
type BTCCWebsocketTrade struct {
// WebsocketTrade holds websocket trade information
type WebsocketTrade struct {
Amount float64 `json:"amount"`
Date float64 `json:"date"`
Market string `json:"market"`
@@ -147,7 +180,8 @@ type BTCCWebsocketTrade struct {
Type string `json:"type"`
}
type BTCCWebsocketTicker struct {
// WebsocketTicker holds websocket ticker information
type WebsocketTicker struct {
Buy float64 `json:"buy"`
Date float64 `json:"date"`
High float64 `json:"high"`

View File

@@ -56,7 +56,7 @@ func (b *BTCC) OnMessage(message []byte, output chan socketio.Message) {
func (b *BTCC) OnTicker(message []byte, output chan socketio.Message) {
type Response struct {
Ticker BTCCWebsocketTicker `json:"ticker"`
Ticker WebsocketTicker `json:"ticker"`
}
var resp Response
err := common.JSONDecode(message, &resp)
@@ -69,7 +69,7 @@ func (b *BTCC) OnTicker(message []byte, output chan socketio.Message) {
func (b *BTCC) OnGroupOrder(message []byte, output chan socketio.Message) {
type Response struct {
GroupOrder BTCCWebsocketGroupOrder `json:"grouporder"`
GroupOrder WebsocketGroupOrder `json:"grouporder"`
}
var resp Response
err := common.JSONDecode(message, &resp)
@@ -81,7 +81,7 @@ func (b *BTCC) OnGroupOrder(message []byte, output chan socketio.Message) {
}
func (b *BTCC) OnTrade(message []byte, output chan socketio.Message) {
trade := BTCCWebsocketTrade{}
trade := WebsocketTrade{}
err := common.JSONDecode(message, &trade)
if err != nil {

View File

@@ -6,7 +6,7 @@ import (
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/currency/pair"
"github.com/thrasher-/gocryptotrader/exchanges"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
"github.com/thrasher-/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-/gocryptotrader/exchanges/stats"
"github.com/thrasher-/gocryptotrader/exchanges/ticker"

View File

@@ -14,22 +14,36 @@ import (
)
const (
BTCMARKETS_API_URL = "https://api.btcmarkets.net"
BTCMARKETS_API_VERSION = "0"
BTCMARKETS_ACCOUNT_BALANCE = "/account/balance"
BTCMARKETS_ORDER_CREATE = "/order/create"
BTCMARKETS_ORDER_CANCEL = "/order/cancel"
BTCMARKETS_ORDER_HISTORY = "/order/history"
BTCMARKETS_ORDER_OPEN = "/order/open"
BTCMARKETS_ORDER_TRADE_HISTORY = "/order/trade/history"
BTCMARKETS_ORDER_DETAIL = "/order/detail"
btcMarketsAPIURL = "https://api.btcmarkets.net"
btcMarketsAPIVersion = "0"
btcMarketsAccountBalance = "/account/balance"
btcMarketsOrderCreate = "/order/create"
btcMarketsOrderCancel = "/order/cancel"
btcMarketsOrderHistory = "/order/history"
btcMarketsOrderOpen = "/order/open"
btcMarketsOrderTradeHistory = "/order/trade/history"
btcMarketsOrderDetail = "/order/detail"
btcMarketsWithdrawCrypto = "/fundtransfer/withdrawCrypto"
btcMarketsWithdrawAud = "/fundtransfer/withdrawEFT"
//Status Values
orderStatusNew = "New"
orderStatusPlaced = "Placed"
orderStatusFailed = "Failed"
orderStatusError = "Error"
orderStatusCancelled = "Cancelled"
orderStatusPartiallyCancelled = "Partially Cancelled"
orderStatusFullyMatched = "Fully Matched"
orderStatusPartiallyMatched = "Partially Matched"
)
// BTCMarkets is the overarching type across the BTCMarkets package
type BTCMarkets struct {
exchange.Base
Ticker map[string]BTCMarketsTicker
Ticker map[string]Ticker
}
// SetDefaults sets basic defaults
func (b *BTCMarkets) SetDefaults() {
b.Name = "BTC Markets"
b.Enabled = false
@@ -37,9 +51,10 @@ func (b *BTCMarkets) SetDefaults() {
b.Verbose = false
b.Websocket = false
b.RESTPollingDelay = 10
b.Ticker = make(map[string]BTCMarketsTicker)
b.Ticker = make(map[string]Ticker)
}
// Setup takes in an exchange configuration and sets all paramaters
func (b *BTCMarkets) Setup(exch config.ExchangeConfig) {
if !exch.Enabled {
b.SetEnabled(false)
@@ -57,109 +72,90 @@ func (b *BTCMarkets) Setup(exch config.ExchangeConfig) {
}
}
// GetFee returns the BTCMarkets fee on transactions
func (b *BTCMarkets) GetFee() float64 {
return b.Fee
}
func (b *BTCMarkets) GetTicker(symbol string) (BTCMarketsTicker, error) {
ticker := BTCMarketsTicker{}
path := fmt.Sprintf("/market/%s/AUD/tick", symbol)
err := common.SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &ticker)
if err != nil {
return BTCMarketsTicker{}, err
}
return ticker, nil
// GetTicker returns a ticker
// symbol - example "btc" or "ltc"
func (b *BTCMarkets) GetTicker(symbol string) (Ticker, error) {
ticker := Ticker{}
path := fmt.Sprintf("/market/%s/AUD/tick", common.StringToUpper(symbol))
return ticker,
common.SendHTTPGetRequest(btcMarketsAPIURL+path, true, &ticker)
}
func (b *BTCMarkets) GetOrderbook(symbol string) (BTCMarketsOrderbook, error) {
orderbook := BTCMarketsOrderbook{}
path := fmt.Sprintf("/market/%s/AUD/orderbook", symbol)
err := common.SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &orderbook)
if err != nil {
return BTCMarketsOrderbook{}, err
}
return orderbook, nil
// GetOrderbook returns current orderbook
// symbol - example "btc" or "ltc"
func (b *BTCMarkets) GetOrderbook(symbol string) (Orderbook, error) {
orderbook := Orderbook{}
path := fmt.Sprintf("/market/%s/AUD/orderbook", common.StringToUpper(symbol))
return orderbook,
common.SendHTTPGetRequest(btcMarketsAPIURL+path, true, &orderbook)
}
func (b *BTCMarkets) GetTrades(symbol string, values url.Values) ([]BTCMarketsTrade, error) {
trades := []BTCMarketsTrade{}
path := common.EncodeURLValues(fmt.Sprintf("%s/market/%s/AUD/trades", BTCMARKETS_API_URL, symbol), values)
err := common.SendHTTPGetRequest(path, true, &trades)
if err != nil {
return nil, err
}
return trades, nil
// GetTrades returns executed trades on the exchange
// symbol - example "btc" or "ltc"
// values - optional paramater "since" example values.Set(since, "59868345231")
func (b *BTCMarkets) GetTrades(symbol string, values url.Values) ([]Trade, error) {
trades := []Trade{}
path := common.EncodeURLValues(fmt.Sprintf("%s/market/%s/AUD/trades", btcMarketsAPIURL, symbol), values)
return trades, common.SendHTTPGetRequest(path, true, &trades)
}
func (b *BTCMarkets) Order(currency, instrument string, price, amount int64, orderSide, orderType, clientReq string) (int, error) {
type Order struct {
Currency string `json:"currency"`
Instrument string `json:"instrument"`
Price int64 `json:"price"`
Volume int64 `json:"volume"`
OrderSide string `json:"orderSide"`
OrderType string `json:"ordertype"`
ClientRequestId string `json:"clientRequestId"`
// NewOrder requests a new order and returns an ID
// currency - example "AUD"
// instrument - example "BTC"
// price - example 13000000000 (i.e x 100000000)
// amount - example 100000000 (i.e x 100000000)
// orderside - example "Bid" or "Ask"
// orderType - example "limit"
// clientReq - example "abc-cdf-1000"
func (b *BTCMarkets) NewOrder(currency, instrument string, price, amount int64, orderSide, orderType, clientReq string) (int, error) {
order := OrderToGo{
Currency: common.StringToUpper(currency),
Instrument: common.StringToUpper(instrument),
Price: price * common.SatoshisPerBTC,
Volume: amount * common.SatoshisPerBTC,
OrderSide: orderSide,
OrderType: orderType,
ClientRequestID: clientReq,
}
order := Order{}
order.Currency = currency
order.Instrument = instrument
order.Price = price * common.SatoshisPerBTC
order.Volume = amount * common.SatoshisPerBTC
order.OrderSide = orderSide
order.OrderType = orderType
order.ClientRequestId = clientReq
type Response struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
ID int `json:"id"`
ClientRequestID string `json:"clientRequestId"`
}
var resp Response
err := b.SendAuthenticatedRequest("POST", BTCMARKETS_ORDER_CREATE, order, &resp)
resp := Response{}
err := b.SendAuthenticatedRequest("POST", btcMarketsOrderCreate, order, &resp)
if err != nil {
return 0, err
}
if !resp.Success {
return 0, fmt.Errorf("%s Unable to place order. Error message: %s\n", b.GetName(), resp.ErrorMessage)
return 0, fmt.Errorf("%s Unable to place order. Error message: %s", b.GetName(), resp.ErrorMessage)
}
return resp.ID, nil
}
// CancelOrder cancels an order by its ID
// orderID - id for order example "1337"
func (b *BTCMarkets) CancelOrder(orderID []int64) (bool, error) {
resp := Response{}
type CancelOrder struct {
OrderIDs []int64 `json:"orderIds"`
}
orders := CancelOrder{}
orders.OrderIDs = append(orders.OrderIDs, orderID...)
type Response struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
Responses []struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
ID int64 `json:"id"`
}
ClientRequestID string `json:"clientRequestId"`
}
var resp Response
err := b.SendAuthenticatedRequest("POST", BTCMARKETS_ORDER_CANCEL, orders, &resp)
err := b.SendAuthenticatedRequest("POST", btcMarketsOrderCancel, orders, &resp)
if err != nil {
return false, err
}
if !resp.Success {
return false, fmt.Errorf("%s Unable to cancel order. Error message: %s\n", b.GetName(), resp.ErrorMessage)
return false, fmt.Errorf("%s Unable to cancel order. Error message: %s", b.GetName(), resp.ErrorMessage)
}
ordersToBeCancelled := len(orderID)
@@ -169,39 +165,37 @@ func (b *BTCMarkets) CancelOrder(orderID []int64) (bool, error) {
ordersCancelled++
log.Printf("%s Cancelled order %d.\n", b.GetName(), y.ID)
} else {
log.Printf("%s Unable to cancel order %d. Error message: %s\n", b.GetName(), y.ID, y.ErrorMessage)
log.Printf("%s Unable to cancel order %d. Error message: %s", b.GetName(), y.ID, y.ErrorMessage)
}
}
if ordersCancelled == ordersToBeCancelled {
return true, nil
} else {
return false, fmt.Errorf("%s Unable to cancel order(s).", b.GetName())
}
return false, fmt.Errorf("%s Unable to cancel order(s)", b.GetName())
}
func (b *BTCMarkets) GetOrders(currency, instrument string, limit, since int64, historic bool) ([]BTCMarketsOrder, error) {
// GetOrders returns current order information on the exchange
// currency - example "AUD"
// instrument - example "BTC"
// limit - example "10"
// since - since a time example "33434568724"
// historic - if false just normal Orders open
func (b *BTCMarkets) GetOrders(currency, instrument string, limit, since int64, historic bool) ([]Order, error) {
request := make(map[string]interface{})
request["currency"] = currency
request["instrument"] = instrument
request["currency"] = common.StringToUpper(currency)
request["instrument"] = common.StringToUpper(instrument)
request["limit"] = limit
request["since"] = since
path := BTCMARKETS_ORDER_OPEN
path := btcMarketsOrderOpen
if historic {
path = BTCMARKETS_ORDER_HISTORY
path = btcMarketsOrderHistory
}
type response struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
Orders []BTCMarketsOrder `json:"orders"`
}
resp := Response{}
resp := response{}
err := b.SendAuthenticatedRequest("POST", path, request, &resp)
if err != nil {
return nil, err
}
@@ -224,23 +218,18 @@ func (b *BTCMarkets) GetOrders(currency, instrument string, limit, since int64,
return resp.Orders, nil
}
func (b *BTCMarkets) GetOrderDetail(orderID []int64) ([]BTCMarketsOrder, error) {
// GetOrderDetail returns order information an a specific order
// orderID - example "1337"
func (b *BTCMarkets) GetOrderDetail(orderID []int64) ([]Order, error) {
type OrderDetail struct {
OrderIDs []int64 `json:"orderIds"`
}
orders := OrderDetail{}
orders.OrderIDs = append(orders.OrderIDs, orderID...)
type response struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
Orders []BTCMarketsOrder `json:"orders"`
}
resp := response{}
err := b.SendAuthenticatedRequest("POST", BTCMARKETS_ORDER_DETAIL, orders, &resp)
resp := Response{}
err := b.SendAuthenticatedRequest("POST", btcMarketsOrderDetail, orders, &resp)
if err != nil {
return nil, err
}
@@ -263,10 +252,11 @@ func (b *BTCMarkets) GetOrderDetail(orderID []int64) ([]BTCMarketsOrder, error)
return resp.Orders, nil
}
func (b *BTCMarkets) GetAccountBalance() ([]BTCMarketsAccountBalance, error) {
balance := []BTCMarketsAccountBalance{}
err := b.SendAuthenticatedRequest("GET", BTCMARKETS_ACCOUNT_BALANCE, nil, &balance)
// GetAccountBalance returns the full account balance
func (b *BTCMarkets) GetAccountBalance() ([]AccountBalance, error) {
balance := []AccountBalance{}
err := b.SendAuthenticatedRequest("GET", btcMarketsAccountBalance, nil, &balance)
if err != nil {
return nil, err
}
@@ -279,6 +269,53 @@ func (b *BTCMarkets) GetAccountBalance() ([]BTCMarketsAccountBalance, error) {
return balance, nil
}
// WithdrawCrypto withdraws cryptocurrency into a designated address
func (b *BTCMarkets) WithdrawCrypto(amount int64, currency, address string) (string, error) {
req := WithdrawRequestCrypto{
Amount: amount,
Currency: common.StringToUpper(currency),
Address: address,
}
resp := Response{}
err := b.SendAuthenticatedRequest("POST", btcMarketsWithdrawCrypto, req, &resp)
if err != nil {
return "", err
}
if !resp.Success {
return "", errors.New(resp.ErrorMessage)
}
return resp.Status, nil
}
// WithdrawAUD withdraws AUD into a designated bank address
// Does not return a TxID!
func (b *BTCMarkets) WithdrawAUD(accountName, accountNumber, bankName, bsbNumber, currency string, amount int64) (string, error) {
req := WithdrawRequestAUD{
AccountName: accountName,
AccountNumber: accountNumber,
BankName: bankName,
BSBNumber: bsbNumber,
Amount: amount,
Currency: common.StringToUpper(currency),
}
resp := Response{}
err := b.SendAuthenticatedRequest("POST", btcMarketsWithdrawAud, req, &resp)
if err != nil {
return "", err
}
if !resp.Success {
return "", errors.New(resp.ErrorMessage)
}
return resp.Status, nil
}
// SendAuthenticatedRequest sends an authenticated HTTP request
func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interface{}, result interface{}) (err error) {
if !b.AuthenticatedAPISupport {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, b.Name)
@@ -289,7 +326,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa
} else {
b.Nonce.Inc()
}
request := ""
var request string
payload := []byte("")
if data != nil {
@@ -305,7 +342,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa
hmac := common.GetHMAC(common.HashSHA512, []byte(request), []byte(b.APISecret))
if b.Verbose {
log.Printf("Sending %s request to URL %s with params %s\n", reqType, BTCMARKETS_API_URL+path, request)
log.Printf("Sending %s request to URL %s with params %s\n", reqType, btcMarketsAPIURL+path, request)
}
headers := make(map[string]string)
@@ -316,7 +353,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data interfa
headers["timestamp"] = b.Nonce.String()[0:13]
headers["signature"] = common.Base64Encode(hmac)
resp, err := common.SendHTTPRequest(reqType, BTCMARKETS_API_URL+path, headers, bytes.NewBuffer(payload))
resp, err := common.SendHTTPRequest(reqType, btcMarketsAPIURL+path, headers, bytes.NewBuffer(payload))
if err != nil {
return err

View File

@@ -0,0 +1,131 @@
package btcmarkets
import (
"net/url"
"testing"
"github.com/thrasher-/gocryptotrader/config"
)
var bm BTCMarkets
// Please supply your own keys here to do better tests
const (
apiKey = ""
apiSecret = ""
)
func TestSetDefaults(t *testing.T) {
bm.SetDefaults()
}
func TestSetup(t *testing.T) {
conf := config.ExchangeConfig{}
bm.Setup(conf)
conf = config.ExchangeConfig{
APIKey: apiKey,
APISecret: apiSecret,
Enabled: true,
AuthenticatedAPISupport: true,
}
bm.Setup(conf)
}
func TestGetFee(t *testing.T) {
t.Parallel()
if fee := bm.GetFee(); fee == 0 {
t.Error("Test failed - GetFee() error")
}
}
func TestGetTicker(t *testing.T) {
t.Parallel()
_, err := bm.GetTicker("BTC")
if err != nil {
t.Error("Test failed - GetTicker() error", err)
}
}
func TestGetOrderbook(t *testing.T) {
t.Parallel()
_, err := bm.GetOrderbook("BTC")
if err != nil {
t.Error("Test failed - GetOrderbook() error", err)
}
}
func TestGetTrades(t *testing.T) {
t.Parallel()
_, err := bm.GetTrades("BTC", nil)
if err != nil {
t.Error("Test failed - GetTrades() error", err)
}
val := url.Values{}
val.Set("since", "0")
_, err = bm.GetTrades("BTC", val)
if err != nil {
t.Error("Test failed - GetTrades() error", err)
}
}
func TestNewOrder(t *testing.T) {
t.Parallel()
_, err := bm.NewOrder("AUD", "BTC", 0, 0, "Bid", "limit", "testTest")
if err == nil {
t.Error("Test failed - NewOrder() error", err)
}
}
func TestCancelOrder(t *testing.T) {
t.Parallel()
_, err := bm.CancelOrder([]int64{1337})
if err == nil {
t.Error("Test failed - CancelOrder() error", err)
}
}
func TestGetOrders(t *testing.T) {
t.Parallel()
_, err := bm.GetOrders("AUD", "BTC", 10, 0, false)
if err == nil {
t.Error("Test failed - GetOrders() error", err)
}
_, err = bm.GetOrders("AUD", "BTC", 10, 0, true)
if err == nil {
t.Error("Test failed - GetOrders() error", err)
}
}
func TestGetOrderDetail(t *testing.T) {
t.Parallel()
_, err := bm.GetOrderDetail([]int64{1337})
if err == nil {
t.Error("Test failed - GetOrderDetail() error", err)
}
}
func TestGetAccountBalance(t *testing.T) {
t.Parallel()
_, err := bm.GetAccountBalance()
if err == nil {
t.Error("Test failed - GetAccountBalance() error", err)
}
}
func TestWithdrawCrypto(t *testing.T) {
t.Parallel()
_, err := bm.WithdrawCrypto(0, "BTC", "LOLOLOL")
if err == nil {
t.Error("Test failed - WithdrawCrypto() error", err)
}
}
func TestWithdrawAUD(t *testing.T) {
t.Parallel()
_, err := bm.WithdrawAUD("BLA", "1337", "blawest", "1336", "BTC", 10000000)
if err == nil {
t.Error("Test failed - WithdrawAUD() error", err)
}
}

View File

@@ -1,22 +1,35 @@
package btcmarkets
type BTCMarketsTicker struct {
BestBID float64
BestAsk float64
LastPrice float64
Currency string
Instrument string
Timestamp int64
// Response is the genralized response type
type Response struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
ID int `json:"id"`
Responses []struct {
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
ID int64 `json:"id"`
}
ClientRequestID string `json:"clientRequestId"`
Orders []Order `json:"orders"`
Status string `json:"status"`
}
type BTCMarketsTrade struct {
TradeID int64 `json:"tid"`
Amount float64 `json:"amount"`
Price float64 `json:"price"`
Date int64 `json:"date"`
// Ticker holds ticker information
type Ticker struct {
BestBID float64 `json:"bestBid"`
BestAsk float64 `json:"bestAsk"`
LastPrice float64 `json:"lastPrice"`
Currency string `json:"currency"`
Instrument string `json:"instrument"`
Timestamp int64 `json:"timestamp"`
Volume float64 `json:"volume24h"`
}
type BTCMarketsOrderbook struct {
// Orderbook holds current orderbook information returned from the exchange
type Orderbook struct {
Currency string `json:"currency"`
Instrument string `json:"instrument"`
Timestamp int64 `json:"timestamp"`
@@ -24,7 +37,44 @@ type BTCMarketsOrderbook struct {
Bids [][]float64 `json:"bids"`
}
type BTCMarketsTradeResponse struct {
// Trade holds trade information
type Trade struct {
TradeID int64 `json:"tid"`
Amount float64 `json:"amount"`
Price float64 `json:"price"`
Date int64 `json:"date"`
}
// OrderToGo holds order information to be sent to the exchange
type OrderToGo struct {
Currency string `json:"currency"`
Instrument string `json:"instrument"`
Price int64 `json:"price"`
Volume int64 `json:"volume"`
OrderSide string `json:"orderSide"`
OrderType string `json:"ordertype"`
ClientRequestID string `json:"clientRequestId"`
}
// Order holds order information
type Order struct {
ID int64 `json:"id"`
Currency string `json:"currency"`
Instrument string `json:"instrument"`
OrderSide string `json:"orderSide"`
OrderType string `json:"ordertype"`
CreationTime float64 `json:"creationTime"`
Status string `json:"status"`
ErrorMessage string `json:"errorMessage"`
Price float64 `json:"price"`
Volume float64 `json:"volume"`
OpenVolume float64 `json:"openVolume"`
ClientRequestID string `json:"clientRequestId"`
Trades []TradeResponse `json:"trades"`
}
// TradeResponse holds trade information
type TradeResponse struct {
ID int64 `json:"id"`
CreationTime float64 `json:"creationTime"`
Description string `json:"description"`
@@ -33,24 +83,26 @@ type BTCMarketsTradeResponse struct {
Fee float64 `json:"fee"`
}
type BTCMarketsOrder struct {
ID int64 `json:"id"`
Currency string `json:"currency"`
Instrument string `json:"instrument"`
OrderSide string `json:"orderSide"`
OrderType string `json:"ordertype"`
CreationTime float64 `json:"creationTime"`
Status string `json:"status"`
ErrorMessage string `json:"errorMessage"`
Price float64 `json:"price"`
Volume float64 `json:"volume"`
OpenVolume float64 `json:"openVolume"`
ClientRequestId string `json:"clientRequestId"`
Trades []BTCMarketsTradeResponse `json:"trades"`
}
type BTCMarketsAccountBalance struct {
// AccountBalance holds account balance details
type AccountBalance struct {
Balance float64 `json:"balance"`
PendingFunds float64 `json:"pendingFunds"`
Currency string `json:"currency"`
}
// WithdrawRequestCrypto is a generalized withdraw request type
type WithdrawRequestCrypto struct {
Amount int64 `json:"amount"`
Currency string `json:"currency"`
Address string `json:"address"`
}
// WithdrawRequestAUD is a generalized withdraw request type
type WithdrawRequestAUD struct {
Amount int64 `json:"amount"`
Currency string `json:"currency"`
AccountName string `json:"accountName"`
AccountNumber string `json:"accountNumber"`
BankName string `json:"bankName"`
BSBNumber string `json:"bsbNumber"`
}

View File

@@ -12,10 +12,12 @@ import (
"github.com/thrasher-/gocryptotrader/exchanges/ticker"
)
// Start runs ticker monitor in a new routine
func (b *BTCMarkets) Start() {
go b.Run()
}
// Run starts a go routine to monitor ticker price
func (b *BTCMarkets) Run() {
if b.Verbose {
log.Printf("%s polling delay: %ds.\n", b.GetName(), b.RESTPollingDelay)
@@ -42,6 +44,7 @@ func (b *BTCMarkets) Run() {
}
}
// GetTickerPrice returns ticker information
func (b *BTCMarkets) GetTickerPrice(p pair.CurrencyPair) (ticker.TickerPrice, error) {
tickerNew, err := ticker.GetTicker(b.GetName(), p)
if err == nil {
@@ -61,6 +64,7 @@ func (b *BTCMarkets) GetTickerPrice(p pair.CurrencyPair) (ticker.TickerPrice, er
return tickerPrice, nil
}
// GetOrderbookEx returns orderbook base on the currency pair
func (b *BTCMarkets) GetOrderbookEx(p pair.CurrencyPair) (orderbook.OrderbookBase, error) {
ob, err := orderbook.GetOrderbook(b.GetName(), p)
if err == nil {
@@ -88,11 +92,12 @@ func (b *BTCMarkets) GetOrderbookEx(p pair.CurrencyPair) (orderbook.OrderbookBas
return orderBook, nil
}
//GetExchangeAccountInfo : Retrieves balances for all enabled currencies for the BTCMarkets exchange
func (e *BTCMarkets) GetExchangeAccountInfo() (exchange.AccountInfo, error) {
// GetExchangeAccountInfo retrieves balances for all enabled currencies for the
// BTCMarkets exchange
func (b *BTCMarkets) GetExchangeAccountInfo() (exchange.AccountInfo, error) {
var response exchange.AccountInfo
response.ExchangeName = e.GetName()
accountBalance, err := e.GetAccountBalance()
response.ExchangeName = b.GetName()
accountBalance, err := b.GetAccountBalance()
if err != nil {
return response, err
}