From 4c9b19eb876be6f07df756030074803b95a16c7f Mon Sep 17 00:00:00 2001 From: eric Date: Mon, 6 Jan 2020 09:49:21 +0800 Subject: [PATCH 01/27] [fmex] update fmex ws endpoint --- fmex/fmex_ws.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fmex/fmex_ws.go b/fmex/fmex_ws.go index 38dfeb36..d3b0a123 100644 --- a/fmex/fmex_ws.go +++ b/fmex/fmex_ws.go @@ -72,7 +72,7 @@ func NewFMexWs(client *http.Client) *FMexWs { fmWs := &FMexWs{} fmWs.clientId = getRandomString(8) fmWs.WsBuilder = NewWsBuilder(). - WsUrl("wss://api.testnet.fmex.com/v2/ws"). + WsUrl("wss://api.fmex.com/v2/ws"). AutoReconnect(). Heartbeat(func() []byte { ts := time.Now().Unix()*1000 + fmWs.timeoffset*1000 From b417a4fa56db9dfd9ea36c7e87948b2604eb21f3 Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 9 Jan 2020 23:51:00 +0800 Subject: [PATCH 02/27] [fcoin] depth UTime unit is millisecond in websocket --- fcoin/fcoin.go | 2 +- fcoin/fcoin_test.go | 2 +- fcoin/fcoin_ws.go | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/fcoin/fcoin.go b/fcoin/fcoin.go index 9f66efef..5be43fbc 100644 --- a/fcoin/fcoin.go +++ b/fcoin/fcoin.go @@ -90,7 +90,7 @@ func NewWithConfig(c *APIConfig) *FCoin { var err error fc.tradeSymbols, err = fc.GetTradeSymbols() if len(fc.tradeSymbols) == 0 || err != nil { - panic("trade symbol is empty, pls check connection...") + panic("[fcoin] trade symbol is empty, pls check connection...") } return fc diff --git a/fcoin/fcoin_test.go b/fcoin/fcoin_test.go index 26b02479..7525a713 100644 --- a/fcoin/fcoin_test.go +++ b/fcoin/fcoin_test.go @@ -13,7 +13,7 @@ var ft = NewFCoin(&http.Client{ Transport: &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse("socks5://127.0.0.1:1080") - return nil, nil + //return nil, nil }, Dial: (&net.Dialer{ Timeout: 10 * time.Second, diff --git a/fcoin/fcoin_ws.go b/fcoin/fcoin_ws.go index 034bfe16..4df158d2 100644 --- a/fcoin/fcoin_ws.go +++ b/fcoin/fcoin_ws.go @@ -82,14 +82,14 @@ func NewFCoinWs(client *http.Client) *FCoinWs { "cmd": "ping", "id": fcWs.clientId, "args": args} - data , _ := json.Marshal(heartbeatData) + data, _ := json.Marshal(heartbeatData) return data }, 25*time.Second). ProtoHandleFunc(fcWs.handle) fc := NewFCoin(client, "", "") fcWs.tradeSymbols = fc.tradeSymbols if len(fcWs.tradeSymbols) == 0 { - panic("trade symbol is empty, pls check connection...") + panic("[fcoin] trade symbol is empty, pls check connection...") } return fcWs } @@ -256,7 +256,7 @@ func (fcWs *FCoinWs) handle(msg []byte) error { case "depth": dep := fcWs.parseDepthData(datamap["bids"].([]interface{}), datamap["asks"].([]interface{})) stime := int64(ToInt(datamap["ts"])) - dep.UTime = time.Unix(stime/1000, 0) + dep.UTime = time.Unix(0, stime*1000*1000) pair, err := fcWs.getPairFromType(resp[2]) if err != nil { panic(err) From 11c173303003a081590c4ec42e23cc2d1a8e04ab Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 9 Jan 2020 23:51:50 +0800 Subject: [PATCH 03/27] [fmex] depth UTime unit is millisecond in websocket --- fmex/fmex_swap.go | 11 ++++------- fmex/fmex_ws.go | 2 +- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/fmex/fmex_swap.go b/fmex/fmex_swap.go index f46131c1..2db5b94e 100644 --- a/fmex/fmex_swap.go +++ b/fmex/fmex_swap.go @@ -22,12 +22,6 @@ const ( baseUrl = "https://api.fmex.com" ) -type FMexTicker struct { - Ticker - SellAmount, - BuyAmount float64 -} - type FMexSwap struct { httpClient *http.Client baseUrl, @@ -426,7 +420,10 @@ func (fm *FMexSwap) PlaceFutureOrder2(ord *OrderParam) (string, error) { if err != nil { return "", err } - data := r.(map[string]interface{}) + data, isOk := r.(map[string]interface{}) + if !isOk { + return "", errors.New(fmt.Sprintf("PlaceFutureOrder2 UNKNOW:%v", r)) + } return fmt.Sprintf("%d", int64(data["id"].(float64))), nil } diff --git a/fmex/fmex_ws.go b/fmex/fmex_ws.go index d3b0a123..3a1fd43d 100644 --- a/fmex/fmex_ws.go +++ b/fmex/fmex_ws.go @@ -252,7 +252,7 @@ func (fmWs *FMexWs) handle(msg []byte) error { case "depth": dep := fmWs.parseDepthData(datamap["bids"].([]interface{}), datamap["asks"].([]interface{})) stime := int64(ToInt(datamap["ts"])) - dep.UTime = time.Unix(stime/1000, 0) + dep.UTime = time.Unix(0, stime*1000000) pair, err := getPairFromType(resp[2]) if err != nil { panic(err) From 306a2194eba49c9b5dbab3ab82b0b131f7d428d0 Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 9 Jan 2020 23:53:09 +0800 Subject: [PATCH 04/27] [fcoin margin] enable Loan for margin account --- fcoin/fcoin_margin.go | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/fcoin/fcoin_margin.go b/fcoin/fcoin_margin.go index 6a1d2560..e8866e81 100644 --- a/fcoin/fcoin_margin.go +++ b/fcoin/fcoin_margin.go @@ -115,12 +115,9 @@ func (fm *FCoinMargin) GetMarginAccount(currency CurrencyPair) (*MarginAccount, if !isOk || ok != "ok" { return nil, errors.New("response status error") } - //fmt.Println(r) acc := MarginAccount{} acc.Sub = make(map[Currency]MarginSubAccount, 2) - // "open": true, #是否已经开通该类型杠杆账户. true:已开通;false:未开通 - // "leveraged_account_type": "btcusdt", #杠杆账户类型 - // "state": "open" #账户状态. close 已关闭;open 已开通-未发生借贷;normal 已借贷-风险率正常;blow_up 已爆仓;overrun 已穿仓", allowableValues = "close,open,normal,blow_up,overrun") + response, isOk := r["data"].(map[string]interface{}) if !isOk { return nil, errors.New("response data error") @@ -136,7 +133,7 @@ func (fm *FCoinMargin) GetMarginAccount(currency CurrencyPair) (*MarginAccount, Frozen: ToFloat64(response["frozen_base_currency_amount"]), Available: ToFloat64(response["available_base_currency_amount"]), CanWithdraw: ToFloat64(response["available_base_currency_loan_amount"]), - //Loan: ToFloat64(response["borrowed"]), + Loan: ToFloat64(response["base_currency_unpaid_amount"]), //LendingFee: ToFloat64(response["lending_fee"]), } @@ -146,7 +143,7 @@ func (fm *FCoinMargin) GetMarginAccount(currency CurrencyPair) (*MarginAccount, Frozen: ToFloat64(response["frozen_quote_currency_amount"]), Available: ToFloat64(response["available_quote_currency_amount"]), CanWithdraw: ToFloat64(response["available_quote_currency_loan_amount"]), - //Loan: ToFloat64(response["borrowed"]), + Loan: ToFloat64(response["quote_currency_unpaid_amount"]), //LendingFee: ToFloat64(response["lending_fee"]), } From 2ef5a26fbbd20020ee29c00a1ba42fba3ce938ea Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 14 May 2020 12:10:21 +0800 Subject: [PATCH 05/27] [OKEX SWAP] Fix bug in swap position json tag --- okex/SwapResponse.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/okex/SwapResponse.go b/okex/SwapResponse.go index 08b9c036..fbbf3704 100644 --- a/okex/SwapResponse.go +++ b/okex/SwapResponse.go @@ -11,7 +11,7 @@ type SwapPositionHolding struct { LiquidationPrice float64 `json:"liquidation_price , string"` Position float64 `json:"position,string"` AvailPosition float64 `json:"avail_position,string"` - AvgCost float64 `json:"avg_cost , string"` + AvgCost float64 `json:"avg_cost,string"` SettlementPrice float64 `json:"settlement_price,string"` InstrumentId string `json:"instrument_id"` Leverage string `json:"leverage"` @@ -169,7 +169,8 @@ type BaseTickerInfo struct { Volume24h float64 `json:"volume_24h,string"` Low24h float64 `json:"low_24h,string"` BestBid float64 `json:"best_bid,string"` - BestAsk float64 `json:"best_ask,string"`} + BestAsk float64 `json:"best_ask,string"` +} type SwapTickerList []BaseTickerInfo From 4db73101afa715e861315d4cf1c6515cf8688092 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Thu, 14 May 2020 16:50:35 +0800 Subject: [PATCH 06/27] ws api interface --- WsApi.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 WsApi.go diff --git a/WsApi.go b/WsApi.go new file mode 100644 index 00000000..425d96e2 --- /dev/null +++ b/WsApi.go @@ -0,0 +1,35 @@ +package goex + +type FuturesWsApi interface { + DepthCallback(func(depth *Depth)) + TickerCallback(func(ticker *FutureTicker)) + TradeCallback(func(trade *Trade, contract string)) + //OrderCallback(func(order *FutureOrder)) + //PositionCallback(func(position *FuturePosition)) + //AccountCallback(func(account *FutureAccount)) + + SubscribeDepth(pair CurrencyPair, contractType string) error + SubscribeTicker(pair CurrencyPair, contractType string) error + SubscribeTrade(pair CurrencyPair, contractType string) error + + //Login() error + //SubscribeOrder(pair CurrencyPair, contractType string) error + //SubscribePosition(pair CurrencyPair, contractType string) error + //SubscribeAccount(pair CurrencyPair) error +} + +type SpotWsApi interface { + DepthCallback(func(depth *Depth)) + TickerCallback(func(ticker *Ticker)) + TradeCallback(func(trade *Trade)) + //OrderCallback(func(order *Order)) + //AccountCallback(func(account *Account)) + + SubscribeDepth(pair CurrencyPair) error + SubscribeTicker(pair CurrencyPair) error + SubscribeTrade(pair CurrencyPair) error + + //Login() error + //SubscribeOrder(pair CurrencyPair) error + //SubscribeAccount(pair CurrencyPair) error +} From 7f8e29daca7a4d72fb6a675188409f371064b703 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Thu, 14 May 2020 18:41:15 +0800 Subject: [PATCH 07/27] [okex] futures and spot ws --- builder/APIBuilder.go | 20 ++++++++++++++++++++ builder/APIBuilder_test.go | 27 +++++++++++++++++++++++++++ okex/OKExFuture.go | 2 +- okex/OKExFuturesWs.go | 22 +++++++--------------- okex/OKExFuturesWs_test.go | 2 +- okex/OKExSpotWs.go | 18 +++++++----------- 6 files changed, 63 insertions(+), 28 deletions(-) diff --git a/builder/APIBuilder.go b/builder/APIBuilder.go index 122fe6e7..bbec074b 100644 --- a/builder/APIBuilder.go +++ b/builder/APIBuilder.go @@ -2,6 +2,7 @@ package builder import ( "context" + "errors" "fmt" . "github.com/nntaoli-project/goex" @@ -311,3 +312,22 @@ func (builder *APIBuilder) BuildFuture(exName string) (api FutureRestAPI) { return nil } } + +func (builder *APIBuilder) BuildFuturesWs(exName string) (FuturesWsApi, error) { + switch exName { + case OKEX_V3, OKEX, OKEX_FUTURE: + return okex.NewOKExV3FuturesWs(okex.NewOKEx(&APIConfig{ + HttpClient: builder.client, + Endpoint: builder.futuresEndPoint, + })), nil + } + return nil, errors.New("not support the exchange " + exName) +} + +func (builder *APIBuilder) BuildSpotWs(exName string) (SpotWsApi, error) { + switch exName { + case OKEX_V3, OKEX: + return okex.NewOKExSpotV3Ws(nil), nil + } + return nil, errors.New("not support the exchange " + exName) +} diff --git a/builder/APIBuilder_test.go b/builder/APIBuilder_test.go index d8463ffe..0c6d987f 100644 --- a/builder/APIBuilder_test.go +++ b/builder/APIBuilder_test.go @@ -2,12 +2,19 @@ package builder import ( "github.com/nntaoli-project/goex" + "github.com/nntaoli-project/goex/internal/logger" "github.com/stretchr/testify/assert" + "log" "testing" + "time" ) var builder = NewAPIBuilder() +func init() { + logger.SetLevel(logger.INFO) +} + func TestAPIBuilder_Build(t *testing.T) { assert.Equal(t, builder.APIKey("").APISecretkey("").Build(goex.OKCOIN_COM).GetExchangeName(), goex.OKCOIN_COM) assert.Equal(t, builder.APIKey("").APISecretkey("").Build(goex.HUOBI_PRO).GetExchangeName(), goex.HUOBI_PRO) @@ -19,3 +26,23 @@ func TestAPIBuilder_Build(t *testing.T) { assert.Equal(t, builder.APIKey("").APISecretkey("").Build(goex.FCOIN_MARGIN).GetExchangeName(), goex.FCOIN_MARGIN) assert.Equal(t, builder.APIKey("").APISecretkey("").BuildFuture(goex.HBDM).GetExchangeName(), goex.HBDM) } + +func TestAPIBuilder_BuildSpotWs(t *testing.T) { + //os.Setenv("HTTPS_PROXY" , "socks5://127.0.0.1:1080") + wsApi , _ := builder.BuildSpotWs(goex.OKEX_V3) + wsApi.DepthCallback(func(depth *goex.Depth) { + log.Println(depth) + }) + wsApi.SubscribeDepth(goex.BTC_USDT) + time.Sleep(time.Minute) +} + +func TestAPIBuilder_BuildFuturesWs(t *testing.T) { + //os.Setenv("HTTPS_PROXY" , "socks5://127.0.0.1:1080") + wsApi , _ := builder.BuildFuturesWs(goex.OKEX_V3) + wsApi.DepthCallback(func(depth *goex.Depth) { + log.Println(depth) + }) + wsApi.SubscribeDepth(goex.BTC_USD , goex.QUARTER_CONTRACT) + time.Sleep(time.Minute) +} diff --git a/okex/OKExFuture.go b/okex/OKExFuture.go index 2faaf389..b4303cff 100644 --- a/okex/OKExFuture.go +++ b/okex/OKExFuture.go @@ -113,7 +113,7 @@ func (ok *OKExFuture) GetFutureContractId(pair CurrencyPair, contractAlias strin time.Sleep(120 * time.Millisecond) //retry contractInfo, err = ok.GetAllFutureContractInfo() if err != nil { - logger.Warnf(fmt.Sprintf("Get Futures Contract Alias Error [%s] ???", err.Error())) + logger.Errorf(fmt.Sprintf("Get Futures Contract Id Error [%s] ???", err.Error())) } } } diff --git a/okex/OKExFuturesWs.go b/okex/OKExFuturesWs.go index db3defa9..dc7bf684 100644 --- a/okex/OKExFuturesWs.go +++ b/okex/OKExFuturesWs.go @@ -30,29 +30,24 @@ func NewOKExV3FuturesWs(base *OKEx) *OKExV3FuturesWs { return okV3Ws } -func (okV3Ws *OKExV3FuturesWs) TickerCallback(tickerCallback func(*FutureTicker)) *OKExV3FuturesWs { +func (okV3Ws *OKExV3FuturesWs) TickerCallback(tickerCallback func(*FutureTicker)) { okV3Ws.tickerCallback = tickerCallback - return okV3Ws } -func (okV3Ws *OKExV3FuturesWs) DepthCallback(depthCallback func(*Depth)) *OKExV3FuturesWs { +func (okV3Ws *OKExV3FuturesWs) DepthCallback(depthCallback func(*Depth)) { okV3Ws.depthCallback = depthCallback - return okV3Ws } -func (okV3Ws *OKExV3FuturesWs) TradeCallback(tradeCallback func(*Trade, string)) *OKExV3FuturesWs { +func (okV3Ws *OKExV3FuturesWs) TradeCallback(tradeCallback func(*Trade, string)) { okV3Ws.tradeCallback = tradeCallback - return okV3Ws } -func (okV3Ws *OKExV3FuturesWs) OrderCallback(orderCallback func(*FutureOrder, string)) *OKExV3FuturesWs { +func (okV3Ws *OKExV3FuturesWs) OrderCallback(orderCallback func(*FutureOrder, string)) { okV3Ws.orderCallback = orderCallback - return okV3Ws } -func (okV3Ws *OKExV3FuturesWs) KlineCallback(klineCallback func(*FutureKline, int)) *OKExV3FuturesWs { +func (okV3Ws *OKExV3FuturesWs) KlineCallback(klineCallback func(*FutureKline, int)) { okV3Ws.klineCallback = klineCallback - return okV3Ws } func (okV3Ws *OKExV3FuturesWs) SetCallbacks(tickerCallback func(*FutureTicker), @@ -80,6 +75,7 @@ func (okV3Ws *OKExV3FuturesWs) getChannelName(currencyPair CurrencyPair, contrac } else { prefix = "futures" contractId = okV3Ws.base.OKExFuture.GetFutureContractId(currencyPair, contractType) + logger.Info("contractid=",contractId) } channelName = prefix + "/%s:" + contractId @@ -87,11 +83,7 @@ func (okV3Ws *OKExV3FuturesWs) getChannelName(currencyPair CurrencyPair, contrac return channelName } -func (okV3Ws *OKExV3FuturesWs) SubscribeDepth(currencyPair CurrencyPair, contractType string, size int) error { - if (size > 0) && (size != 5) { - return errors.New("only support depth 5") - } - +func (okV3Ws *OKExV3FuturesWs) SubscribeDepth(currencyPair CurrencyPair, contractType string) error { if okV3Ws.depthCallback == nil { return errors.New("please set depth callback func") } diff --git a/okex/OKExFuturesWs_test.go b/okex/OKExFuturesWs_test.go index 81ea6b50..7eb04680 100644 --- a/okex/OKExFuturesWs_test.go +++ b/okex/OKExFuturesWs_test.go @@ -49,7 +49,7 @@ func TestNewOKExV3FuturesWs(t *testing.T) { t.Log(s, order) }) //ok.OKExV3FutureWs.SubscribeTicker(goex.EOS_USD, goex.QUARTER_CONTRACT) - ok.OKExV3FutureWs.SubscribeDepth(goex.EOS_USDT, goex.QUARTER_CONTRACT, 5) + ok.OKExV3FutureWs.SubscribeDepth(goex.EOS_USDT, goex.QUARTER_CONTRACT) //ok.OKExV3FutureWs.SubscribeTrade(goex.EOS_USD, goex.QUARTER_CONTRACT) //ok.OKExV3FutureWs.SubscribeOrder(goex.BSV_USD, goex.NEXT_WEEK_CONTRACT) time.Sleep(1 * time.Minute) diff --git a/okex/OKExSpotWs.go b/okex/OKExSpotWs.go index f2e304fc..6d08bd34 100644 --- a/okex/OKExSpotWs.go +++ b/okex/OKExSpotWs.go @@ -30,28 +30,24 @@ func NewOKExSpotV3Ws(base *OKEx) *OKExV3SpotWs { return okV3Ws } -func (okV3Ws *OKExV3SpotWs) TickerCallback(tickerCallback func(*Ticker)) *OKExV3SpotWs { +func (okV3Ws *OKExV3SpotWs) TickerCallback(tickerCallback func(*Ticker)) { okV3Ws.tickerCallback = tickerCallback - return okV3Ws } -func (okV3Ws *OKExV3SpotWs) DepthCallback(depthCallback func(*Depth)) *OKExV3SpotWs { +func (okV3Ws *OKExV3SpotWs) DepthCallback(depthCallback func(*Depth)) { okV3Ws.depthCallback = depthCallback - return okV3Ws } -func (okV3Ws *OKExV3SpotWs) TradeCallback(tradeCallback func(*Trade)) *OKExV3SpotWs { +func (okV3Ws *OKExV3SpotWs) TradeCallback(tradeCallback func(*Trade)) { okV3Ws.tradeCallback = tradeCallback - return okV3Ws } -func (okV3Ws *OKExV3SpotWs) KLineCallback(klineCallback func(kline *Kline, period KlinePeriod)) *OKExV3SpotWs { + +func (okV3Ws *OKExV3SpotWs) KLineCallback(klineCallback func(kline *Kline, period KlinePeriod)) { okV3Ws.klineCallback = klineCallback - return okV3Ws } -func (okV3Ws *OKExV3SpotWs) OrderCallback(orderCallback func(*Order)) *OKExV3SpotWs { +func (okV3Ws *OKExV3SpotWs) OrderCallback(orderCallback func(*Order)) { okV3Ws.orderCallback = orderCallback - return okV3Ws } func (okV3Ws *OKExV3SpotWs) SetCallbacks(tickerCallback func(*Ticker), @@ -66,7 +62,7 @@ func (okV3Ws *OKExV3SpotWs) SetCallbacks(tickerCallback func(*Ticker), okV3Ws.orderCallback = orderCallback } -func (okV3Ws *OKExV3SpotWs) SubscribeDepth(currencyPair CurrencyPair, size int) error { +func (okV3Ws *OKExV3SpotWs) SubscribeDepth(currencyPair CurrencyPair) error { if okV3Ws.depthCallback == nil { return errors.New("please set depth callback func") } From e53b87e1ee2ed7a6731bf109f861f5bbeae10a85 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 15 May 2020 19:34:54 +0800 Subject: [PATCH 08/27] [HBDM] fix bug for ticker --- huobi/Hbdm.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/huobi/Hbdm.go b/huobi/Hbdm.go index 83133261..5b9f57f1 100644 --- a/huobi/Hbdm.go +++ b/huobi/Hbdm.go @@ -340,15 +340,20 @@ func (dm *Hbdm) GetFutureTicker(currencyPair CurrencyPair, contractType string) return nil, errors.New(ret["err_msg"].(string)) } - tick := ret["tick"].(map[string]interface{}) + tick, ok1 := ret["tick"].(map[string]interface{}) + ask, ok2 := tick["ask"].([]interface{}) + bid, ok3 := tick["bid"].([]interface{}) + if !ok1 || !ok2 || !ok3 { + return nil, errors.New("no tick data") + } return &Ticker{ Pair: currencyPair, Last: ToFloat64(tick["close"]), Vol: ToFloat64(tick["amount"]), Low: ToFloat64(tick["low"]), High: ToFloat64(tick["high"]), - Sell: ToFloat64(tick["ask"].([]interface{})[0]), - Buy: ToFloat64(tick["bid"].([]interface{})[0]), + Sell: ToFloat64(ask[0]), + Buy: ToFloat64(bid[0]), Date: ToUint64(ret["ts"])}, nil } From 7911814b313e529cd1e37d2a660bd88dc5356646 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Sat, 16 May 2020 15:34:15 +0800 Subject: [PATCH 09/27] [delete] cryptopia exchange --- cryptopia/Cryptopia.go | 402 ------------------------------------ cryptopia/Cryptopia_test.go | 22 -- cryptopia/README.md | 2 - 3 files changed, 426 deletions(-) delete mode 100644 cryptopia/Cryptopia.go delete mode 100644 cryptopia/Cryptopia_test.go delete mode 100644 cryptopia/README.md diff --git a/cryptopia/Cryptopia.go b/cryptopia/Cryptopia.go deleted file mode 100644 index c645d021..00000000 --- a/cryptopia/Cryptopia.go +++ /dev/null @@ -1,402 +0,0 @@ -package cryptopia - -import ( - "crypto/hmac" - "crypto/md5" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "log" - "strconv" - "strings" - - . "github.com/nntaoli-project/goex" - - "net/http" - "net/http/httputil" - "net/url" - "time" -) - -const ( - API_BASE_URL = "https://www.cryptopia.co.nz/api/" - - TICKERS_URI = "GetMarkets" - TICKER_URI = "GetMarket/" - DEPTH_URI = "GetMarketOrders" - CANCEL_URI = "CancelTrade" - SUBMIT_ORDER_URI = "SubmitTrade" - DEFAULT_HTTPCLIENT_TIMEOUT = 30 // HTTP client timeout -) - -type Cryptopia struct { - accessKey, - secretKey string - httpClient *http.Client - debug bool -} -type jsonResponse struct { - Success bool `json:"success"` - Error string `json:"error"` - Message string `json:"message"` - Result json.RawMessage `json:"data"` -} - -type placedOrderResponse struct { - OrderId int `json:"OrderId"` -} - -type cancelOrderPayload struct { - OrderId int `json:"OrderId"` - TradePairId int `json:"TradePairId"` - Type string -} - -func New(client *http.Client, accessKey, secretKey string) *Cryptopia { - debug := false - return &Cryptopia{accessKey, secretKey, client, debug} -} - -func (cta *Cryptopia) GetExchangeName() string { - return CRYPTOPIA -} - -func (cta *Cryptopia) GetTickers(currency CurrencyPair) (*Ticker, error) { - return cta.GetTicker(currency) - - //tickerUri := API_BASE_URL + TICKERS_URI - ////log.Println("tickerUrl:", tickerUri) - //bodyDataMap, err := HttpGet(cta.httpClient, tickerUri) - ////log.Println("Cryptopia bodyDataMap:", tickerUri, bodyDataMap) - // - //if err != nil { - // log.Println(err) - // return nil, err - //} - // - //if result, isok := bodyDataMap["success"].(bool); isok == true && result != true { - // log.Println("bodyDataMap[\"success\"]", isok, result) - // return nil, errors.New("err") - //} - ////timestamp := time.Now().Unix() - // - //panic("not implement") - //return nil, nil -} - -func (cta *Cryptopia) GetTicker(currency CurrencyPair) (*Ticker, error) { - currency = cta.adaptCurrencyPair(currency) - - tickerUri := API_BASE_URL + TICKER_URI + currency.ToSymbol("_") - //log.Println("tickerUrl:", tickerUri) - bodyDataMap, err := HttpGet(cta.httpClient, tickerUri) - //log.Println("Cryptopia bodyDataMap:", tickerUri, bodyDataMap) - - if err != nil { - //log.Println(err) - return nil, err - } - tickerMap, isok := bodyDataMap["Data"].(map[string]interface{}) - if isok != true { - //log.Println("Cryptopia bodyDataMap:", tickerUri, bodyDataMap) - //log.Println("bodyDataMap[\"Error\"]", bodyDataMap["Error"].(string)) - //return nil, errors.New(bodyDataMap["Error"].(string)) - return nil, errors.New("ERR") - } - var ticker Ticker - - timestamp := time.Now().Unix() - - //fmt.Println(bodyDataMap) - ticker.Date = uint64(timestamp) - ticker.Last, _ = tickerMap["LastPrice"].(float64) - - ticker.Buy, _ = tickerMap["BidPrice"].(float64) - ticker.Sell, _ = tickerMap["AskPrice"].(float64) - ticker.Vol, _ = tickerMap["Volume"].(float64) - //log.Println("Cryptopia", currency, "ticker:", ticker) - return &ticker, nil -} - -func (cta *Cryptopia) GetTickerInBuf(currency CurrencyPair) (*Ticker, error) { - return cta.GetTicker(currency) -} - -//GetDepth get orderbook -func (cta *Cryptopia) GetDepth(size int, currency CurrencyPair) (*Depth, error) { - currency = cta.adaptCurrencyPair(currency) - - depthURI := fmt.Sprintf("%s%s/%s/%d", API_BASE_URL, DEPTH_URI, currency.ToSymbol("_"), size) - bodyDataMap, err := HttpGet(cta.httpClient, depthURI) - if err != nil { - return nil, err - } - depthMap, isok := bodyDataMap["Data"].(map[string]interface{}) - if isok != true { - return nil, err - } - bids := depthMap["Buy"].([]interface{}) - asks := depthMap["Sell"].([]interface{}) - - depth := new(Depth) - for _, bid := range bids { - _bid := bid.(map[string]interface{}) - amount := ToFloat64(_bid["Volume"]) - price := ToFloat64(_bid["Price"]) - dr := DepthRecord{Amount: amount, Price: price} - depth.BidList = append(depth.BidList, dr) - } - for _, ask := range asks { - _ask := ask.(map[string]interface{}) - amount := ToFloat64(_ask["Volume"]) - price := ToFloat64(_ask["Price"]) - dr := DepthRecord{Amount: amount, Price: price} - depth.AskList = append(depth.AskList, dr) - } - - return depth, nil -} - -func (cta *Cryptopia) adaptCurrencyPair(pair CurrencyPair) CurrencyPair { - var currencyA Currency - var currencyB Currency - - if pair.CurrencyA == BCC { - currencyA = BCH - } else { - currencyA = pair.CurrencyA - } - currencyB = pair.CurrencyB - //if pair.BaseCurrency == USDT { - // currencyB = USD - //} else { - // currencyB = pair.BaseCurrency - //} - - return NewCurrencyPair(currencyA, currencyB) -} - -func (cta *Cryptopia) currencyPairToSymbol(currencyPair CurrencyPair) string { - return strings.ToUpper(currencyPair.ToSymbol("_")) -} - -func (cta *Cryptopia) placeOrder(orderType, side, amount, price string, pair CurrencyPair) (*Order, error) { - payload := map[string]interface{}{ - "Market": cta.currencyPairToSymbol(pair), - "Amount": amount, - "Rate": price, - "Type": orderType, - "Exchange": "cryptopia"} - p, err := json.Marshal(&payload) - if err != nil { - return nil, err - } - resp, err := cta.do("POST", SUBMIT_ORDER_URI, string(p), true) - if err != nil { - return nil, err - } - - var jsonResp jsonResponse - err = json.Unmarshal(resp, &jsonResp) - if err != nil { - log.Println(string(resp)) - return nil, err - } - order := new(Order) - - if jsonResp.Success { - data := new(placedOrderResponse) - err = json.Unmarshal(jsonResp.Result, &data) - if err != nil { - return nil, err - } - order.Currency = pair - order.OrderID = data.OrderId - order.Amount = ToFloat64(amount) - order.Price = ToFloat64(price) - } else { - return nil, errors.New(jsonResp.Error) - } - - switch side { - case "buy": - order.Side = BUY - case "sell": - order.Side = SELL - } - return order, nil -} - -//LimitBuy ... -func (cta *Cryptopia) LimitBuy(amount, price string, currency CurrencyPair) (*Order, error) { - return cta.placeOrder("Buy", "Buy", amount, price, currency) -} - -//LimitSell ... -func (cta *Cryptopia) LimitSell(amount, price string, currency CurrencyPair) (*Order, error) { - return cta.placeOrder("Sell", "Sell", amount, price, currency) -} - -func (cta *Cryptopia) MarketBuy(amount, price string, currency CurrencyPair) (*Order, error) { - panic("not implements") -} - -func (cta *Cryptopia) MarketSell(amount, price string, currency CurrencyPair) (*Order, error) { - panic("not implements") -} - -func (cta *Cryptopia) CancelOrder(orderId string, currency CurrencyPair) (bool, error) { - payload := map[string]interface{}{ - "OrderId": ToInt(orderId), - } - p, err := json.Marshal(&payload) - if err != nil { - return false, err - } - resp, err := cta.do("POST", CANCEL_URI, string(p), true) - if err != nil { - return false, err - } - var jsonResp jsonResponse - err = json.Unmarshal(resp, &jsonResp) - if err != nil { - log.Println(string(resp)) - return false, err - } - return jsonResp.Success, nil -} - -func (cta *Cryptopia) GetOneOrder(orderId string, currency CurrencyPair) (*Order, error) { - panic("not implements") -} -func (cta *Cryptopia) GetUnfinishOrders(currency CurrencyPair) ([]Order, error) { - panic("not implements") -} - -func (cta *Cryptopia) GetOrderHistorys(currency CurrencyPair, currentPage, pageSize int) ([]Order, error) { - panic("not implements") -} - -func (cta *Cryptopia) GetAccount() (*Account, error) { - panic("not implements") -} -func (cta *Cryptopia) GetKlineRecords(currency CurrencyPair, period, size, since int) ([]Kline, error) { - panic("not implements") -} -func (cta *Cryptopia) GetTrades(currencyPair CurrencyPair, since int64) ([]Trade, error) { - panic("not implements") -} - -func (cta *Cryptopia) do(method string, resource string, payload string, authNeeded bool) (response []byte, err error) { - connectTimer := time.NewTimer(DEFAULT_HTTPCLIENT_TIMEOUT * time.Second) - - var rawurl string - if strings.HasPrefix(resource, "http") { - rawurl = resource - } else { - rawurl = fmt.Sprintf("%s%s", API_BASE_URL, resource) - } - - req, err := http.NewRequest(method, rawurl, strings.NewReader(payload)) - if err != nil { - return - } - if method == "POST" || method == "PUT" { - req.Header.Add("Content-Type", "application/json;charset=utf-8") - } - req.Header.Add("Accept", "application/json") - - // Auth - if authNeeded { - if len(cta.accessKey) == 0 || len(cta.secretKey) == 0 { - err = errors.New("You need to set API Key and API Secret to call this method") - return - } - nonce := strconv.FormatInt(time.Now().UnixNano(), 10) - md5 := md5.Sum([]byte(payload)) - signature := cta.accessKey + method + strings.ToLower(url.QueryEscape(req.URL.String())) + - nonce + base64.StdEncoding.EncodeToString(md5[:]) - secret, _ := base64.StdEncoding.DecodeString(cta.secretKey) - mac := hmac.New(sha256.New, secret) - _, err = mac.Write([]byte(signature)) - sig := base64.StdEncoding.EncodeToString(mac.Sum(nil)) - auth := "amx " + cta.accessKey + ":" + sig + ":" + nonce - req.Header.Add("Authorization", auth) - } - - resp, err := cta.doTimeoutRequest(connectTimer, req) - if err != nil { - return - } - - defer resp.Body.Close() - response, err = ioutil.ReadAll(resp.Body) - //fmt.Println(fmt.Sprintf("reponse %s", response), err) - if err != nil { - return response, err - } - if resp.StatusCode != 200 { - err = errors.New(resp.Status) - } - return response, err -} - -func (cta Cryptopia) dumpRequest(r *http.Request) { - if r == nil { - log.Print("dumpReq ok: ") - return - } - dump, err := httputil.DumpRequest(r, true) - if err != nil { - log.Print("dumpReq err:", err) - } else { - log.Print("dumpReq ok:", string(dump)) - } -} - -func (cta Cryptopia) dumpResponse(r *http.Response) { - if r == nil { - log.Print("dumpResponse ok: ") - return - } - dump, err := httputil.DumpResponse(r, true) - if err != nil { - log.Print("dumpResponse err:", err) - } else { - log.Print("dumpResponse ok:", string(dump)) - } -} - -// doTimeoutRequest do a HTTP request with timeout -func (cta *Cryptopia) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) { - // Do the request in the background so we can check the timeout - type result struct { - resp *http.Response - err error - } - done := make(chan result, 1) - go func() { - if cta.debug { - cta.dumpRequest(req) - } - resp, err := cta.httpClient.Do(req) - if cta.debug { - cta.dumpResponse(resp) - } - done <- result{resp, err} - }() - // Wait for the read or the timeout - select { - case r := <-done: - return r.resp, r.err - case <-timer.C: - return nil, errors.New("timeout on reading data from Bittrex API") - } -} - -func (cta *Cryptopia) SetDebug(enable bool) { - cta.debug = enable -} diff --git a/cryptopia/Cryptopia_test.go b/cryptopia/Cryptopia_test.go deleted file mode 100644 index edfe0857..00000000 --- a/cryptopia/Cryptopia_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package cryptopia - -import ( - "github.com/nntaoli-project/goex" - "net/http" - "testing" -) - -var ctp = New(http.DefaultClient, "", "") - -func TestCryptopia_GetTicker(t *testing.T) { - ticker, err := ctp.GetTicker(goex.BTC_USDT) - t.Log("err=>", err) - t.Log("ticker=>", ticker) -} - -func TestCryptopia_GetDepth(t *testing.T) { - depCtp, err := ctp.GetDepth(goex.BTC_USDT) - t.Log(err) - t.Log("AskList=>", depCtp.AskList) - t.Log("BidList=>", depCtp.BidList) -} diff --git a/cryptopia/README.md b/cryptopia/README.md deleted file mode 100644 index cb9dca01..00000000 --- a/cryptopia/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Reference to Cryptopia API documentation: -https://support.cryptopia.co.nz/csm?id=kb_article&sys_id=a75703dcdbb9130084ed147a3a9619bc \ No newline at end of file From 41407cfbede3c780019f3564e1e16c9b8fd933c2 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Sat, 16 May 2020 15:35:00 +0800 Subject: [PATCH 10/27] [bitstamp] fix bug --- bitstamp/Bitstamp_test.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/bitstamp/Bitstamp_test.go b/bitstamp/Bitstamp_test.go index 08bd3116..35e3f775 100644 --- a/bitstamp/Bitstamp_test.go +++ b/bitstamp/Bitstamp_test.go @@ -47,16 +47,14 @@ func TestBitstamp_LimitSell(t *testing.T) { t.Log(ord) } - func TestBitstamp_MarketBuy(t *testing.T) { - ord, err := btmp.MarketBuy("1", goex.XRP_USD) + ord, err := btmp.MarketBuy("1", "", goex.XRP_USD) assert.Nil(t, err) t.Log(ord) } - func TestBitstamp_MarketSell(t *testing.T) { - ord, err := btmp.MarketSell("2", goex.XRP_USD) + ord, err := btmp.MarketSell("2", "", goex.XRP_USD) assert.Nil(t, err) t.Log(ord) } From 0aeb8da152d634cedf45fc286e39667aaa8f2201 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 14:45:44 +0800 Subject: [PATCH 11/27] delete aacoin ,coinpark and ocx exchange --- aacoin/aacoin.go | 445 -------------------------------------- aacoin/aacoin_test.go | 45 ---- coinpark/coinpark.go | 433 ------------------------------------- coinpark/coinpark_test.go | 39 ---- ocx/ocx.go | 315 --------------------------- ocx/ocx_test.go | 33 --- 6 files changed, 1310 deletions(-) delete mode 100755 aacoin/aacoin.go delete mode 100644 aacoin/aacoin_test.go delete mode 100644 coinpark/coinpark.go delete mode 100644 coinpark/coinpark_test.go delete mode 100644 ocx/ocx.go delete mode 100644 ocx/ocx_test.go diff --git a/aacoin/aacoin.go b/aacoin/aacoin.go deleted file mode 100755 index e4f30ca4..00000000 --- a/aacoin/aacoin.go +++ /dev/null @@ -1,445 +0,0 @@ -package aacoin - -import ( - . "github.com/nntaoli-project/goex" - "net/http" - "net/url" - - "encoding/json" - "errors" - "log" - "sort" - "strconv" - "strings" - "time" -) - -const ( - host = "https://api.aacoin.com/v1" -) - -type Aacoin struct { - accessKey, - secretKey string - httpClient *http.Client -} - -func New(client *http.Client, api_key, secret_key string) *Aacoin { - return &Aacoin{accessKey: api_key, secretKey: secret_key, httpClient: client} -} - -func (aa *Aacoin) GetExchangeName() string { - return "aacoin.com" -} - -func (aa *Aacoin) buildSigned(params *url.Values) string { - - //log.Println("params", params.Encode()) - params.Set("accessKey", aa.accessKey) - s, _ := GetParamHmacSHA256Sign(aa.secretKey, params.Encode()) - params.Set("sign", s) - - return s -} - -func (aa *Aacoin) GetAccount() (*Account, error) { - api_url := host + "/account/accounts" - - params := url.Values{} - //params.Set("accessKey", aa.accessKey) - //params.Set("sign", aa.buildSigned(¶ms)) - aa.buildSigned(¶ms) - body, err := HttpPostForm(aa.httpClient, api_url, params) - if err != nil { - return nil, err - } - //log.Println("body", string(body)) - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(body, &bodyDataMap) - if err != nil { - // log.Println("respData", string(body)) - return nil, err - } - - if bodyDataMap["status"].(string) != "1000" { - return nil, errors.New(bodyDataMap["msg"].(string)) - } - - balances, isok := bodyDataMap["data"].([]interface{}) - if isok != true { - return nil, errors.New("No account data!") - } - - acc := Account{} - acc.Exchange = aa.GetExchangeName() - acc.SubAccounts = make(map[Currency]SubAccount) - - for _, v := range balances { - vv := v.(map[string]interface{}) - currency := NewCurrency(vv["currencyCode"].(string), "") - trade := 0.0 - frozen := 0.0 - vvv := vv["accounts"].([]interface{}) - for _, vvvv := range vvv { - vvvvv := vvvv.(map[string]interface{}) - if vvvvv["type"].(string) == "trade" { - trade = vvvvv["balance"].(float64) - } else if vvvvv["type"].(string) == "frozen" { - frozen = vvvvv["balance"].(float64) - } - } - - acc.SubAccounts[currency] = SubAccount{ - Currency: currency, - Amount: trade + frozen, - ForzenAmount: frozen, - } - } - return &acc, nil -} - -func (aa *Aacoin) placeOrder(amount, price string, pair CurrencyPair, orderType, orderSide string) (*Order, error) { - path := host + "/order/place" - params := url.Values{} - params.Set("symbol", pair.String()) - params.Set("type", orderSide+"-"+orderType) - params.Set("quantity", amount) - params.Set("price", price) - aa.buildSigned(¶ms) - - resp, err := HttpPostForm(aa.httpClient, path, params) - log.Println("resp:", string(resp), "err:", err) - if err != nil { - return nil, err - } - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(resp, &bodyDataMap) - if err != nil { - // log.Println("respData", string(resp)) - return nil, err - } - - if bodyDataMap["status"].(string) != "1000" { - return nil, errors.New(bodyDataMap["msg"].(string)) - } - - side := BUY - if orderSide == "ASK" { - side = SELL - } - - return &Order{ - Currency: pair, - OrderID2: strconv.FormatFloat(ToFloat64(bodyDataMap["data"]), 'f', 30, 64), - Price: ToFloat64(price), - Amount: ToFloat64(amount), - DealAmount: 0, - AvgPrice: 0, - Side: TradeSide(side), - Status: ORDER_UNFINISH, - OrderTime: int(time.Now().Unix())}, nil -} - -func (aa *Aacoin) LimitBuy(amount, price string, currencyPair CurrencyPair) (*Order, error) { - return aa.placeOrder(amount, price, currencyPair, "limit", "buy") -} - -func (aa *Aacoin) LimitSell(amount, price string, currencyPair CurrencyPair) (*Order, error) { - return aa.placeOrder(amount, price, currencyPair, "limit", "sell") -} - -func (aa *Aacoin) MarketBuy(amount, price string, currencyPair CurrencyPair) (*Order, error) { - return aa.placeOrder(amount, price, currencyPair, "market", "sell") -} - -func (aa *Aacoin) MarketSell(amount, price string, currencyPair CurrencyPair) (*Order, error) { - return aa.placeOrder(amount, price, currencyPair, "market", "sell") -} - -func (aa *Aacoin) CancelOrder(orderId string, currencyPair CurrencyPair) (bool, error) { - path := host + "/order/cancel" - params := url.Values{} - params.Set("orderId", orderId) - aa.buildSigned(¶ms) - - resp, err := HttpPostForm(aa.httpClient, path, params) - - // log.Println("resp:", string(resp), "err:", err) - if err != nil { - return false, err - } - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(resp, &bodyDataMap) - if err != nil { - // log.Println("respData", string(resp)) - return false, err - } - - if bodyDataMap["status"].(string) != "1000" { - return false, errors.New(bodyDataMap["msg"].(string)) - } - - return true, nil -} - -func (aa *Aacoin) CancelOrders(orderId []string) (bool, error) { - path := host + "/order/batchCancel" - params := url.Values{} - - orders := strings.Join(orderId, ",") - //log.Println("orders", orders) - params.Set("orderIds", orders) - aa.buildSigned(¶ms) - - resp, err := HttpPostForm(aa.httpClient, path, params) - - // log.Println("resp:", string(resp), "err:", err) - if err != nil { - return false, err - } - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(resp, &bodyDataMap) - if err != nil { - // log.Println("respData", string(resp)) - return false, err - } - - if bodyDataMap["status"].(string) != "1000" { - return false, errors.New(bodyDataMap["msg"].(string)) - } - - return true, nil -} - -func (aa *Aacoin) GetOneOrder(orderId string, currencyPair CurrencyPair) (*Order, error) { - //path := API_BASE_URL + TRADE_URI + "/" + orderId - // - //respmap, err := HttpGet2(aa.httpClient, path, aa.privateHeader()) - ////log.Println(respmap) - //if err != nil { - // return nil, err - //} - //_order, isok := respmap["data"].(map[string]interface{}) - //if !isok { - // return nil, errors.New("no order data") - //} - //status, _ := _order["order_state"].(string) - //side, _ := _order["order_side"].(string) - // - //ord := Order{} - //ord.Currency = currencyPair - //ord.OrderID2 = orderId - // - //if side == "ASK" { - // ord.Side = SELL - //} else { - // ord.Side = BUY - //} - // - //switch status { - //case "open": - // ord.Status = ORDER_UNFINISH - //case "filled": - // ord.Status = ORDER_FINISH - // //case "PARTIALLY_FILLED": - // // ord.Status = ORDER_PART_FINISH - //case "canceled": - // ord.Status = ORDER_CANCEL - // //case "PENDING_CANCEL": - // // ord.Status = ORDER_CANCEL_ING - // //case "REJECTED": - // // ord.Status = ORDER_REJECT - //} - // - //ord.Amount = ToFloat64(_order["amount"].(string)) - //ord.Price = ToFloat64(_order["price"].(string)) - //ord.DealAmount = ToFloat64(_order["filled_amount"]) - //ord.AvgPrice = ord.Price // response no avg price , fill price - // - //return &ord, nil - return nil, nil -} -func (aa *Aacoin) GetUnfinishOrders(currencyPair CurrencyPair) ([]Order, error) { - path := host + "/order/currentOrders" - params := url.Values{} - - params.Set("symbol", currencyPair.String()) - aa.buildSigned(¶ms) - - resp, err := HttpPostForm(aa.httpClient, path, params) - - log.Println("resp:", string(resp), "err:", err) - if err != nil { - return nil, err - } - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(resp, &bodyDataMap) - if err != nil { - // log.Println("respData", string(resp)) - return nil, err - } - - if bodyDataMap["status"].(string) != "1000" { - return nil, errors.New(bodyDataMap["msg"].(string)) - } - data := bodyDataMap["data"].(map[string]interface{}) - list := data["list"].([]interface{}) - var orders []Order - for _, v := range list { - vv := v.(map[string]interface{}) - //yyyy-MM-dd HH:mm:ss - ordertime, _ := time.Parse("2016-02-02 11:11:11", vv["orderTime"].(string)) - orders = append(orders, Order{ - Currency: NewCurrencyPair2(vv["symbol"].(string)), - OrderID2: vv["orderId"].(string), - Price: ToFloat64(vv["price"]), - Amount: ToFloat64(vv["quantity"]), - DealAmount: ToFloat64(vv["filledQuantity"]), - Side: orderTypeAdapter(vv["type"].(string)), - Status: orderStatusAdapter(vv["status"].(string)), - OrderTime: int(ordertime.Unix()), - }) - - } - - return nil, nil -} -func (aa *Aacoin) GetOrderHistorys(currencyPair CurrencyPair, currentPage, pageSize int) ([]Order, error) { - return nil, nil -} -func (aa *Aacoin) GetDepth(size int, currencyPair CurrencyPair) (*Depth, error) { - path := host + "/market/depth" - params := url.Values{} - - params.Set("symbol", currencyPair.String()) - //aa.buildSigned(¶ms) - - resp, err := HttpPostForm(aa.httpClient, path, params) - - //log.Println("resp:", string(resp), "err:", err) - if err != nil { - return nil, err - } - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(resp, &bodyDataMap) - if err != nil { - // log.Println("respData", string(resp)) - return nil, err - } - - if bodyDataMap["status"].(string) != "1000" { - return nil, errors.New(bodyDataMap["msg"].(string)) - } - - dep := bodyDataMap["data"].(map[string]interface{}) - - bids, _ := dep["bids"].([]interface{}) - asks, _ := dep["asks"].([]interface{}) - - depth := new(Depth) - //i := 0 - for _, bid := range bids { - _bid := bid.([]interface{}) - amount := ToFloat64(_bid[1]) - price := ToFloat64(_bid[0]) - dr := DepthRecord{Amount: amount, Price: price} - depth.BidList = append(depth.BidList, dr) - //if i < size { - // i++ - //} else { - // break - //} - } - - //i = 0 - for _, ask := range asks { - _ask := ask.([]interface{}) - amount := ToFloat64(_ask[1]) - price := ToFloat64(_ask[0]) - dr := DepthRecord{Amount: amount, Price: price} - depth.AskList = append(depth.AskList, dr) - //if i < size { - // i++ - //} else { - // break - //} - } - sort.Sort(depth.AskList) - sort.Sort(sort.Reverse(depth.BidList)) - depth.AskList = depth.AskList[0:size] - depth.BidList = depth.BidList[0:size] - //log.Println(depth) - return depth, nil -} - -func (aa *Aacoin) GetTicker(currencyPair CurrencyPair) (*Ticker, error) { - path := host + "/market/detail" - params := url.Values{} - - params.Set("symbol", currencyPair.String()) - - resp, err := HttpPostForm(aa.httpClient, path, params) - - // log.Println("resp:", string(resp), "err:", err) - if err != nil { - return nil, err - } - - var bodyDataMap map[string]interface{} - err = json.Unmarshal(resp, &bodyDataMap) - if err != nil { - // log.Println("respData", string(resp)) - return nil, err - } - - if bodyDataMap["status"].(string) != "1000" { - return nil, errors.New(bodyDataMap["msg"].(string)) - } - tickerMap := bodyDataMap["data"].(map[string]interface{}) - var ticker Ticker - - ticker.Date = uint64(time.Now().Unix()) - ticker.Last = ToFloat64(tickerMap["current"]) - ticker.Buy = ToFloat64(tickerMap["buy"]) - ticker.Sell = ToFloat64(tickerMap["sell"]) - ticker.Low = ToFloat64(tickerMap["lowest"]) - ticker.High = ToFloat64(tickerMap["highest"]) - ticker.Vol = ToFloat64(tickerMap["totalTradeAmount"]) - return &ticker, nil - -} - -func (aa *Aacoin) GetKlineRecords(currency CurrencyPair, period, size, since int) ([]Kline, error) { - panic("not implement") -} - -//非个人,整个交易所的交易记录 -func (aa *Aacoin) GetTrades(currencyPair CurrencyPair, since int64) ([]Trade, error) { - panic("not implement") -} - -func orderTypeAdapter(t string) TradeSide { - switch t { - case "sell": - return SELL - case "buy": - return BUY - } - return BUY -} - -func orderStatusAdapter(s string) TradeStatus { - switch s { - case "open": - return ORDER_UNFINISH - case "partial_filled": - return ORDER_PART_FINISH - } - return ORDER_FINISH -} diff --git a/aacoin/aacoin_test.go b/aacoin/aacoin_test.go deleted file mode 100644 index 75fee2ed..00000000 --- a/aacoin/aacoin_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package aacoin - -import ( - "github.com/nntaoli-project/goex" - "net/http" - "net/url" - "testing" -) - -var aa = New(http.DefaultClient, "xxx", "b0xxxxxx-c6xxxxxx-94xxxxxx-dxxxx") - -func TestAacoin_GetExchangeName(t *testing.T) { - return - params := url.Values{} - params.Set("accessKey", aa.accessKey) - params.Set("price", aa.accessKey) - params.Set("quantity", aa.accessKey) - params.Set("symbol", aa.accessKey) - params.Set("type", aa.accessKey) - t.Log(aa.buildSigned(¶ms)) -} -func TestAacoin_GetAccount(t *testing.T) { - return - t.Log(aa.GetAccount()) -} -func TestAacoin_GetTicker(t *testing.T) { - return - t.Log(aa.GetTicker(goex.BTC_USDT)) -} -func TestAacoin_GetDepth(t *testing.T) { - return - t.Log(aa.GetDepth(1, goex.BTC_USDT)) -} -func TestAacoin_LimitSell(t *testing.T) { - //return - t.Log(aa.LimitSell("1", "1000000", goex.BTC_USDT)) -} - -func TestAacoin_LimitBuy(t *testing.T) { - t.Log(aa.LimitBuy("1", "1", goex.BTC_USDT)) -} - -func TestAacoin_GetUnfinishOrders(t *testing.T) { - t.Log(aa.GetUnfinishOrders(goex.BTC_USDT)) -} diff --git a/coinpark/coinpark.go b/coinpark/coinpark.go deleted file mode 100644 index 173a6a3a..00000000 --- a/coinpark/coinpark.go +++ /dev/null @@ -1,433 +0,0 @@ -package coinpark - -import ( - "net/http" - //"log" - "fmt" - . "github.com/nntaoli-project/goex" - //"net/url" - "encoding/json" - "errors" - "log" - "math/rand" - "strconv" - "strings" - "time" -) - -const ( - API_BASE_URL = "https://api.coinpark.cc/" - V1 = "v1/" - API_URL = API_BASE_URL + V1 - TICKER_API = "mdata?cmd=ticker&pair=%s" - ALL_TICKERs = "mdata?cmd=marketAll" - Pair_List = "mdata?cmd=pairList" - DEPTH_API = "mdata?cmd=depth&pair=%s&size=%d" - - TRADE_URL = "orderpending" - GET_ACCOUNT_API = "transfer" - GET_ORDER_API = "orders/%s" - //GET_ORDERS_LIST_API = "" - GET_UNFINISHED_ORDERS_API = "getUnfinishedOrdersIgnoreTradeType" - CANCEL_ORDER_API = TRADE_URL + "/%s/submit-cancel" - PLACE_ORDER_API = "order" - WITHDRAW_API = "withdraw" - CANCELWITHDRAW_API = "cancelWithdraw" -) - -type Cpk struct { - httpClient *http.Client - accessKey, - secretKey string -} - -func New(client *http.Client, apikey, secretkey string) *Cpk { - return &Cpk{accessKey: apikey, secretKey: secretkey, httpClient: client} -} - -func (c *Cpk) buildSigned(cmd string) string { - signed, _ := GetParamHmacMD5Sign(c.secretKey, cmd) - return signed -} - -func (c *Cpk) GetExchangeName() string { - return "coinpark.cc" -} - -func (c *Cpk) GetServerTime() error { - return nil -} - -func (c *Cpk) GetTicker(currencyPair CurrencyPair) (*Ticker, error) { - url := API_URL + fmt.Sprintf(TICKER_API, currencyPair.String()) - respmap, err := HttpGet(c.httpClient, url) - if err != nil { - return nil, err - } - //log.Println("ticker respmap:", respmap) - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return nil, errors.New(errcode["msg"].(string)) - } - - tickmap, ok := respmap["result"].(map[string]interface{}) - if !ok { - return nil, errors.New("tick assert error") - } - ticker := new(Ticker) - ticker.Pair = currencyPair - ticker.Date = uint64(time.Now().Nanosecond() / 1000) - ticker.Last = ToFloat64(tickmap["last"]) - ticker.Vol = ToFloat64(tickmap["vol"]) - ticker.Low = ToFloat64(tickmap["low"]) - ticker.High = ToFloat64(tickmap["high"]) - ticker.Buy = ToFloat64(tickmap["buy"]) - ticker.Sell = ToFloat64(tickmap["sell"]) - return ticker, nil - -} - -func (c *Cpk) GetDepth(size int, currency CurrencyPair) (*Depth, error) { - url := API_URL + fmt.Sprintf(DEPTH_API, currency.String(), size) - respmap, err := HttpGet(c.httpClient, url) - if err != nil { - return nil, err - } - - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return nil, errors.New(errcode["msg"].(string)) - } - - bids, ok1 := respmap["bids"].([]interface{}) - asks, ok2 := respmap["asks"].([]interface{}) - - if !ok1 || !ok2 { - return nil, errors.New("tick assert error") - } - - depth := new(Depth) - - for _, r := range asks { - var dr DepthRecord - rr := r.([]interface{}) - dr.Price = ToFloat64(rr[0]) - dr.Amount = ToFloat64(rr[1]) - depth.AskList = append(depth.AskList, dr) - } - - for _, r := range bids { - var dr DepthRecord - rr := r.([]interface{}) - dr.Price = ToFloat64(rr[0]) - dr.Amount = ToFloat64(rr[1]) - depth.BidList = append(depth.BidList, dr) - } - - return depth, nil -} - -func (c *Cpk) placeOrder(orderType, orderSide, amount, price string, pair CurrencyPair) (*Order, error) { - path := API_URL + TRADE_URL - params := make(map[string]interface{}) - params["cmd"] = "orderpending/trade" - params["index"] = strconv.Itoa(rand.Intn(1000)) - - body := make(map[string]interface{}) - body["pair"] = pair.String() - body["account_type"] = "0" - if orderType == "limit" { - body["order_type"] = "2" - } else if orderType == "market" { - body["order_type"] = "1" - body["money"] = ToFloat64(price) * ToFloat64(amount) - } - if orderSide == "buy" { - body["order_side"] = "1" - } else if orderSide == "sell" { - body["order_side"] = "2" - } - body["price"] = price - body["amount"] = amount - params["body"] = body - - cmd, _ := json.Marshal(params) - cmds := "[" + string(cmd) + "]" - sign := c.buildSigned(cmds) - - param := make(map[string]string) - //param["cmds"] = strconv.Quote("["+string(cmds)+"]") - param["cmds"] = cmds - param["apikey"] = c.accessKey - param["sign"] = sign - resp, err := HttpPostForm4(c.httpClient, path, param, nil) - if err != nil { - return nil, err - } - respmap := make(map[string]interface{}) - json.Unmarshal(resp, &respmap) - - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return nil, errors.New(errcode["msg"].(string)) - } - - orderId := ToInt(respmap["result"]) - if orderId <= 0 { - return nil, errors.New(string(resp)) - } - - side := BUY - if orderSide == "sell" { - side = SELL - } - - return &Order{ - Currency: pair, - OrderID: ToInt(respmap["index"]), - OrderID2: respmap["result"].(string), - Price: ToFloat64(price), - Amount: ToFloat64(amount), - DealAmount: 0, - AvgPrice: 0, - Side: TradeSide(side), - Status: ORDER_UNFINISH, - OrderTime: int(time.Now().Unix())}, nil -} - -func (c *Cpk) LimitBuy(amount, price string, currency CurrencyPair) (*Order, error) { - return c.placeOrder("limit", "buy", amount, price, currency) -} - -func (c *Cpk) LimitSell(amount, price string, currency CurrencyPair) (*Order, error) { - return c.placeOrder("limit", "sell", amount, price, currency) -} - -func (c *Cpk) MarketBuy(amount, price string, currency CurrencyPair) (*Order, error) { - return c.placeOrder("market", "buy", amount, price, currency) -} -func (c *Cpk) MarketSell(amount, price string, currency CurrencyPair) (*Order, error) { - return c.placeOrder("market", "sell", amount, price, currency) -} - -func (c *Cpk) CancelOrder(orderId string, currency CurrencyPair) (bool, error) { - path := API_URL + TRADE_URL - params := make(map[string]interface{}) - params["cmd"] = "orderpending/cancelTrade" - params["index"] = strconv.Itoa(rand.Intn(1000)) - - body := make(map[string]interface{}) - body["orders_id"] = orderId - params["body"] = body - - cmd, _ := json.Marshal(params) - cmds := "[" + string(cmd) + "]" - sign := c.buildSigned(cmds) - - param := make(map[string]string) - //param["cmds"] = strconv.Quote("["+string(cmds)+"]") - param["cmds"] = cmds - param["apikey"] = c.accessKey - param["sign"] = sign - resp, err := HttpPostForm4(c.httpClient, path, param, nil) - if err != nil { - return false, err - } - respmap := make(map[string]interface{}) - json.Unmarshal(resp, &respmap) - - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return false, errors.New(errcode["msg"].(string)) - } - - status := respmap["result"].(string) - if strings.Contains(status, "撤销中") { - return true, nil - } - return false, errors.New("fail") -} - -func (c *Cpk) GetOneOrder(orderId string, currency CurrencyPair) (*Order, error) { - path := API_URL + TRADE_URL - params := make(map[string]interface{}) - params["cmd"] = "orderpending/order" - - body := make(map[string]interface{}) - body["id"] = orderId - params["body"] = body - - cmd, _ := json.Marshal(params) - cmds := "[" + string(cmd) + "]" - sign := c.buildSigned(cmds) - - param := make(map[string]string) - //param["cmds"] = strconv.Quote("["+string(cmds)+"]") - param["cmds"] = cmds - param["apikey"] = c.accessKey - param["sign"] = sign - resp, err := HttpPostForm4(c.httpClient, path, param, nil) - if err != nil { - return nil, err - } - respmap := make(map[string]interface{}) - json.Unmarshal(resp, &respmap) - - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return nil, errors.New(errcode["msg"].(string)) - } - - orderInfo := respmap["result"].(map[string]interface{}) - status := ToInt(orderInfo["status"]) - var orderState TradeStatus - switch status { - case 1: - orderState = ORDER_UNFINISH - case 2: - orderState = ORDER_PART_FINISH - case 3: - orderState = ORDER_FINISH - case 4, 5: - orderState = ORDER_CANCEL - case 6: - orderState = ORDER_CANCEL_ING - } - var side TradeSide - switch ToInt(orderInfo["order_side"]) { - case 1: - side = BUY - case 2: - side = SELL - } - return &Order{ - Currency: currency, - OrderID2: orderInfo["id"].(string), - Price: ToFloat64(orderInfo["price"]), - Amount: ToFloat64(orderInfo["amount"]), - DealAmount: ToFloat64(orderInfo["deal_amount"]), - AvgPrice: 0, - Side: side, - Status: orderState, - OrderTime: int(time.Now().Unix())}, nil - -} - -func (c *Cpk) GetOrdersList() { - panic("not implement") -} - -func (c *Cpk) GetUnfinishOrders(currency CurrencyPair) ([]Order, error) { - panic("not implement") -} - -func (c *Cpk) GetOrderHistorys(currency CurrencyPair, currentPage, pageSize int) ([]Order, error) { - panic("not implement") -} - -func (c *Cpk) GetAccount() (*Account, error) { - path := API_URL + GET_ACCOUNT_API - //cmds := "[{\"cmd\":\"transfer/assets\",\"body\":{\"select\":1}}]" - - params := make(map[string]interface{}) - params["cmd"] = "transfer/assets" - - body := make(map[string]interface{}) - body["select"] = 1 - - params["body"] = body - - cmd, _ := json.Marshal(params) - cmds := "[" + string(cmd) + "]" - sign := c.buildSigned(cmds) - - param := make(map[string]string) - param["cmds"] = cmds - param["apikey"] = c.accessKey - param["sign"] = sign - resp, err := HttpPostForm4(c.httpClient, path, param, nil) - - //cmds := `[{cmd:transfer/assets,body:{}}]` - //cmds := "[{\"cmd\":\"transfer/assets\",\"body\":{\"select\":1}}]" - //sign := c.buildSigned(cmds) - - //params := make(map[string]string) - //params["cmds"] = cmds - //params["apikey"]= c.accessKey - //params["sign"]= sign - - //resp, err := HttpPostForm4(c.httpClient, path, params, nil) - - if err != nil { - return nil, err - } - respmap := make(map[string]interface{}) - json.Unmarshal(resp, &respmap) - log.Println(string(resp)) - //log.Println(respmap) - - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return nil, errors.New(errcode["msg"].(string)) - } - ba := respmap["result"].([]interface{}) - ba1 := ba[0].(map[string]interface{}) - balances := ba1["result"].(map[string]interface{}) - acc := new(Account) - - acc.Asset = ToFloat64(balances["total_btc"]) - acc.SubAccounts = make(map[Currency]SubAccount) - acc.Exchange = c.GetExchangeName() - assets_list, isok := balances["assets_list"].([]interface{}) - if isok != true { - return acc, nil - } - for _, v := range assets_list { - //log.Println(v) - vv := v.(map[string]string) - currency := NewCurrency(vv["coin_symbol"], "") - acc.SubAccounts[currency] = SubAccount{ - Currency: currency, - Amount: ToFloat64(vv["balance"]), - ForzenAmount: ToFloat64(vv["freeze"]), - } - } - - return acc, nil - -} - -func (c *Cpk) GetKlineRecords(currency CurrencyPair, period, size, since int) ([]Kline, error) { - panic("not implement") -} - -//非个人,整个交易所的交易记录 -func (c *Cpk) GetTrades(currencyPair CurrencyPair, since int64) ([]Trade, error) { - panic("not implement") -} - -func (c *Cpk) GetPairList() ([]CurrencyPair, error) { - url := API_URL + Pair_List - respmap, err := HttpGet(c.httpClient, url) - if err != nil { - return nil, err - } - log.Println("respmap:", respmap) - errcode, isok := respmap["error"].(map[string]interface{}) - if isok == true { - return nil, errors.New(errcode["msg"].(string)) - } - - list, ok := respmap["result"].([]interface{}) - if !ok { - return nil, errors.New("tick assert error") - } - pairlist := make([]CurrencyPair, 0) - for _, v := range list { - vv := v.(map[string]interface{}) - pairlist = append(pairlist, NewCurrencyPair2(vv["pair"].(string))) - } - - return pairlist, nil - -} diff --git a/coinpark/coinpark_test.go b/coinpark/coinpark_test.go deleted file mode 100644 index c33040ac..00000000 --- a/coinpark/coinpark_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package coinpark - -import ( - "github.com/nntaoli-project/goex" - "net/http" - "testing" -) - -var cpk = New(http.DefaultClient, "", "") - -func TestCpk_buildSigned(t *testing.T) { - //[{"cmd":"user/userInfo","body":{}}] - return - cmds := "[{\"cmd\":\"user/userInfo\",\"body\":{}}]" - t.Log(cpk.buildSigned(cmds)) -} -func TestCpk_GetAccount(t *testing.T) { - //return - t.Log(cpk.GetAccount()) -} - -func TestCpk_LimitBuy(t *testing.T) { - return - t.Log(cpk.LimitBuy("1", "1", goex.BTC_USDT)) -} -func TestCpk_LimitSell(t *testing.T) { - return - t.Log(cpk.LimitSell("1", "999999", goex.BTC_USDT)) -} - -func TestCpk_CancelOrder(t *testing.T) { - return - t.Log(cpk.CancelOrder("123", goex.BTC_USDT)) -} - -func TestCpk_GetPairList(t *testing.T) { - return - t.Log(cpk.GetPairList()) -} diff --git a/ocx/ocx.go b/ocx/ocx.go deleted file mode 100644 index e07eb76d..00000000 --- a/ocx/ocx.go +++ /dev/null @@ -1,315 +0,0 @@ -package ocx - -import ( - "crypto" - "crypto/hmac" - "encoding/json" - "errors" - "fmt" - . "github.com/nntaoli-project/goex" - "log" - "net/http" - "net/url" - "strconv" - "strings" - "time" -) - -var TimeOffset int64 = 0 - -const ( - API_BASE_URL = "https://openapi.ocx.com" - V2 = "/api/v2/" - //API_URL = API_BASE_URL + V2 - - TICKER_API = "market/ticker/%s" - TICKERS_API = "market/tickers" - DEPTH_API = "depth?market_code=%s" - SERVER_TIME = "timestamp" - - TRADE_URL = "orders" - GET_ACCOUNT_API = "accounts" - GET_ORDER_API = "orders/%s" - - CANCEL_ORDER_API = "orders/:%s/cancel" - CANCEL_ALL_ORDER_API = "orders/clear" - - PLACE_ORDER_API = "orders" -) - -type Ocx struct { - httpClient *http.Client - accessKey, - secretKey string -} - -func New(client *http.Client, apikey, secretkey string) *Ocx { - return &Ocx{accessKey: apikey, secretKey: secretkey, httpClient: client} -} - -func (o *Ocx) GetExchangeName() string { - return "ocx.com" -} - -func (o *Ocx) GetServerTime() int64 { - url := API_BASE_URL + V2 + SERVER_TIME - respmap, err := HttpGet(o.httpClient, url) - if err != nil { - return 0 - } - data := respmap["data"].(interface{}) - d := data.(map[string]interface{}) - ts := d["timestamp"].(float64) - servertime := int64(ts) - now := time.Now().Unix() - TimeOffset = servertime - now - return servertime -} - -func (o *Ocx) GetTicker(currencyPair CurrencyPair) (*Ticker, error) { - url := API_BASE_URL + V2 + fmt.Sprintf(TICKER_API, strings.ToLower(currencyPair.ToSymbol(""))) - respmap, err := HttpGet(o.httpClient, url) - if err != nil { - return nil, err - } - //log.Println("ticker respmap:", respmap) - - tickmap, ok := respmap["data"].(map[string]interface{}) - if !ok { - return nil, errors.New("tick assert error") - } - ticker := new(Ticker) - ticker.Pair = currencyPair - ticker.Date = ToUint64(tickmap["timestamp"]) - ticker.Last = ToFloat64(tickmap["last"]) - ticker.Vol = ToFloat64(tickmap["volume"]) - ticker.Low = ToFloat64(tickmap["low"]) - ticker.High = ToFloat64(tickmap["high"]) - ticker.Buy = ToFloat64(tickmap["buy"]) - ticker.Sell = ToFloat64(tickmap["sell"]) - - return ticker, nil - -} - -func (o *Ocx) GetDepth(size int, currency CurrencyPair) (*Depth, error) { - url := API_BASE_URL + V2 + fmt.Sprintf(DEPTH_API, strings.ToLower(currency.ToSymbol(""))) - resp, err := HttpGet(o.httpClient, url) - if err != nil { - return nil, err - } - respmap, _ := resp["status"].(map[string]interface{}) - bids, ok1 := respmap["bids"].([]interface{}) - asks, ok2 := respmap["asks"].([]interface{}) - - if !ok1 || !ok2 { - return nil, errors.New("tick assert error") - } - - depth := new(Depth) - - for _, r := range asks { - var dr DepthRecord - rr := r.([]interface{}) - dr.Price = ToFloat64(rr[0]) - dr.Amount = ToFloat64(rr[1]) - depth.AskList = append(depth.AskList, dr) - } - - for _, r := range bids { - var dr DepthRecord - rr := r.([]interface{}) - dr.Price = ToFloat64(rr[0]) - dr.Amount = ToFloat64(rr[1]) - depth.BidList = append(depth.BidList, dr) - } - - return depth, nil -} - -func (o *Ocx) buildSigned(method, apiurl string, para *url.Values) string { - param := "" - if para != nil { - param = para.Encode() - } - - log.Println("param", param) - - sig_str := "" - if para != nil { - sig_str = method + "|" + apiurl + "|" + param - } else { - sig_str = method + "|" + apiurl - } - - log.Println("sig_str", sig_str) - - mac := hmac.New(crypto.SHA256.New, []byte("abc")) - - mac.Write([]byte(sig_str)) - - sum := mac.Sum(nil) - - return fmt.Sprintf("%x", sum) -} - -func (o *Ocx) placeOrder(orderType, orderSide, amount, price string, pair CurrencyPair) (*Order, error) { - uri := API_BASE_URL + V2 + TRADE_URL - method := "POST" - path := V2 + TRADE_URL - params := url.Values{} - tonce := strconv.Itoa(int(time.Now().UnixNano() / 1000000)) - params.Set("access_key", o.accessKey) - params.Set("tonce", tonce) - //params.Set("foo", "bar") - - signed := o.buildSigned(method, path, ¶ms) - - f := fmt.Sprintf("access_key=%s&tonce=%s&signature=%s&market_code=%s&price=%s&side=%s&volume=%s", - o.accessKey, tonce, signed, strings.ToLower(pair.ToSymbol("")), price, orderSide, amount) - resp, err := HttpPostForm3(o.httpClient, uri, f, nil) - //resp, err := HttpPostForm3(o.httpClient, uri, form.Encode(), nil) - log.Println("resp:", string(resp), "err:", err) - if err != nil { - return nil, err - } - - respmap := make(map[string]interface{}) - err = json.Unmarshal(resp, &respmap) - if err != nil { - log.Println(string(resp)) - return nil, err - } - - orderId := ToInt(respmap["orderId"]) - if orderId <= 0 { - return nil, errors.New(string(resp)) - } - - side := BUY - if orderSide == "SELL" { - side = SELL - } - - return &Order{ - Currency: pair, - OrderID: orderId, - OrderID2: fmt.Sprint(orderId), - Price: ToFloat64(price), - Amount: ToFloat64(amount), - DealAmount: 0, - AvgPrice: 0, - Side: TradeSide(side), - Status: ORDER_UNFINISH, - OrderTime: int(time.Now().Unix())}, nil - - panic("1") -} - -func (o *Ocx) LimitBuy(amount, price string, currency CurrencyPair) (*Order, error) { - return o.placeOrder("limit", "buy", amount, price, currency) -} - -func (o *Ocx) LimitSell(amount, price string, currency CurrencyPair) (*Order, error) { - return o.placeOrder("limit", "sell", amount, price, currency) -} - -func (o *Ocx) MarketBuy(amount, price string, currency CurrencyPair) (*Order, error) { - panic("not implement") -} -func (o *Ocx) MarketSell(amount, price string, currency CurrencyPair) (*Order, error) { - panic("not implement") -} - -func (o *Ocx) CancelOrder(orderId string, currency CurrencyPair) (bool, error) { - path := API_BASE_URL + V2 + fmt.Sprintf(CANCEL_ORDER_API, strings.ToLower(currency.ToSymbol(""))) - params := url.Values{} - - params.Set("order_id", orderId) - - sign := o.buildSigned("POST", path, ¶ms) - log.Println("path", path, "params", params.Encode(), "sign", sign) - - resp, err := HttpPostForm2(o.httpClient, path, params, nil) - log.Println("resp:", string(resp), "err:", err) - return true, nil -} - -func (o *Ocx) GetOneOrder(orderId string, currency CurrencyPair) (*Order, error) { - path := API_BASE_URL + V2 + fmt.Sprintf(GET_ORDER_API, orderId) - para := url.Values{} - para.Set("order_id", orderId) - - //sign := o.buildSigned("GET", path, ¶) - - respmap, err := HttpGet2(o.httpClient, path, nil) - - if err != nil { - return nil, err - } - - log.Println(respmap) - - return nil, nil - -} - -func (o *Ocx) GetOrdersList() { - panic("not implement") - -} - -func (o *Ocx) GetUnfinishOrders(currency CurrencyPair) ([]Order, error) { - panic("not implement") -} - -func (o *Ocx) GetOrderHistorys(currency CurrencyPair, currentPage, pageSize int) ([]Order, error) { - panic("not implement") -} - -func (o *Ocx) GetAccount() (*Account, error) { - url := API_BASE_URL + V2 + GET_ACCOUNT_API - //timestamp := strconv.FormatInt((time.Now().UnixNano() / 1000000), 10) - - //sign := o.buildSigned("GET", url, nil) - - respmap, err := HttpGet2(o.httpClient, url, nil) - - if err != nil { - return nil, err - } - - log.Println(respmap) - - if respmap["status"].(float64) != 0 { - return nil, errors.New(respmap["msg"].(string)) - } - - acc := new(Account) - acc.SubAccounts = make(map[Currency]SubAccount) - acc.Exchange = o.GetExchangeName() - - balances := respmap["data"].([]interface{}) - for _, v := range balances { - //log.Println(v) - vv := v.(map[string]interface{}) - currency := NewCurrency(vv["currency"].(string), "") - acc.SubAccounts[currency] = SubAccount{ - Currency: currency, - Amount: ToFloat64(vv["available"]), - ForzenAmount: ToFloat64(vv["frozen"]), - } - } - - return acc, nil - -} - -func (o *Ocx) GetKlineRecords(currency CurrencyPair, period, size, since int) ([]Kline, error) { - panic("not implement") -} - -//非个人,整个交易所的交易记录 -func (o *Ocx) GetTrades(currencyPair CurrencyPair, since int64) ([]Trade, error) { - panic("not implement") -} diff --git a/ocx/ocx_test.go b/ocx/ocx_test.go deleted file mode 100644 index 0f333a5c..00000000 --- a/ocx/ocx_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package ocx - -import ( - "github.com/nntaoli-project/goex" - "net/http" - "net/url" - "testing" -) - -var o = New(&http.Client{}, "", "") - -func TestOcx_GetServerTime(t *testing.T) { - return - t.Log(o.GetServerTime()) -} - -func TestOcx_buildSigned(t *testing.T) { - return - method := "GET" - path := "/api/v2/markets" - para := url.Values{} - para.Set("access_key", "xxx") - para.Set("tonce", "123456789") - para.Set("foo", "bar") - t.Log(o.buildSigned(method, path, ¶)) - -} - -func TestOcx_LimitSell(t *testing.T) { - //return - - o.LimitBuy("1", "1", goex.BTC_USDT) -} From fbc935f9328375e0b02631382b6aa41e2aa26e1e Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 15:58:27 +0800 Subject: [PATCH 12/27] [ws] optimize --- huobi/Hbdm_Ws.go | 2 +- okex/OKExWs.go | 4 +-- websocket.go | 79 ++++++++++++++++++++++++------------------------ 3 files changed, 42 insertions(+), 43 deletions(-) diff --git a/huobi/Hbdm_Ws.go b/huobi/Hbdm_Ws.go index cee722fa..5b220eaa 100644 --- a/huobi/Hbdm_Ws.go +++ b/huobi/Hbdm_Ws.go @@ -73,7 +73,7 @@ func NewHbdmWs() *HbdmWs { AutoReconnect(). //Heartbeat([]byte("{\"event\": \"ping\"} "), 30*time.Second). //Heartbeat(func() []byte { return []byte("{\"op\":\"ping\"}") }(), 5*time.Second). - UnCompressFunc(GzipUnCompress). + DecompressFunc(GzipUnCompress). ProtoHandleFunc(hbdmWs.handle) return hbdmWs } diff --git a/okex/OKExWs.go b/okex/OKExWs.go index 595fc825..11a174c9 100644 --- a/okex/OKExWs.go +++ b/okex/OKExWs.go @@ -44,10 +44,10 @@ func NewOKExV3Ws(base *OKEx, handle func(channel string, data json.RawMessage) e okV3Ws.authoriedSubs = make([]map[string]interface{}, 0) okV3Ws.WsBuilder = NewWsBuilder(). WsUrl("wss://real.okex.com:8443/ws/v3"). - ReconnectInterval(2*time.Second). + ReconnectInterval(time.Second). AutoReconnect(). Heartbeat(func() []byte { return []byte("ping") }, 28*time.Second). - UnCompressFunc(FlateUnCompress).ProtoHandleFunc(okV3Ws.handle) + DecompressFunc(FlateUnCompress).ProtoHandleFunc(okV3Ws.handle) return okV3Ws } diff --git a/websocket.go b/websocket.go index 444614c8..5ed10a7a 100644 --- a/websocket.go +++ b/websocket.go @@ -21,23 +21,29 @@ type WsConfig struct { HeartbeatData func() []byte //心跳数据2 IsAutoReconnect bool ProtoHandleFunc func([]byte) error //协议处理函数 - UnCompressFunc func([]byte) ([]byte, error) //解压函数 + DecompressFunc func([]byte) ([]byte, error) //解压函数 ErrorHandleFunc func(err error) IsDump bool readDeadLineTime time.Duration reconnectInterval time.Duration } +var dialer = &websocket.Dialer{ + Proxy: http.ProxyFromEnvironment, + HandshakeTimeout: 30 * time.Second, + EnableCompression: true, +} + type WsConn struct { c *websocket.Conn - sync.Mutex WsConfig writeBufferChan chan []byte pingMessageBufferChan chan []byte pongMessageBufferChan chan []byte closeMessageBufferChan chan []byte - subs []interface{} + subs [][]byte close chan bool + reConnectLock *sync.Mutex } type WsBuilder struct { @@ -92,8 +98,8 @@ func (b *WsBuilder) ProtoHandleFunc(f func([]byte) error) *WsBuilder { return b } -func (b *WsBuilder) UnCompressFunc(f func([]byte) ([]byte, error)) *WsBuilder { - b.wsConfig.UnCompressFunc = f +func (b *WsBuilder) DecompressFunc(f func([]byte) ([]byte, error)) *WsBuilder { + b.wsConfig.DecompressFunc = f return b } @@ -108,9 +114,6 @@ func (b *WsBuilder) Build() *WsConn { } func (ws *WsConn) NewWs() *WsConn { - ws.Lock() - defer ws.Unlock() - if ws.HeartbeatIntervalTime == 0 { ws.readDeadLineTime = time.Minute } else { @@ -126,6 +129,7 @@ func (ws *WsConn) NewWs() *WsConn { ws.pongMessageBufferChan = make(chan []byte, 10) ws.closeMessageBufferChan = make(chan []byte, 10) ws.writeBufferChan = make(chan []byte, 10) + ws.reConnectLock = new(sync.Mutex) go ws.writeRequest() go ws.receiveMessage() @@ -134,8 +138,6 @@ func (ws *WsConn) NewWs() *WsConn { } func (ws *WsConn) connect() error { - dialer := websocket.DefaultDialer - if ws.ProxyUrl != "" { proxy, err := url.Parse(ws.ProxyUrl) if err == nil { @@ -156,11 +158,7 @@ func (ws *WsConn) connect() error { return err } - ws.c = wsConn - - if ws.HeartbeatIntervalTime > 0 { - wsConn.SetReadDeadline(time.Now().Add(ws.readDeadLineTime)) - } + wsConn.SetReadDeadline(time.Now().Add(ws.readDeadLineTime)) if ws.IsDump { dumpData, _ := httputil.DumpResponse(resp, true) @@ -168,10 +166,14 @@ func (ws *WsConn) connect() error { } Log.Infof("[ws][%s] connected", ws.WsUrl) + ws.c = wsConn return nil } func (ws *WsConn) reconnect() { + ws.reConnectLock.Lock() + defer ws.reConnectLock.Unlock() + ws.c.Close() //主动关闭一次 var err error for retry := 1; retry <= 100; retry++ { @@ -185,18 +187,16 @@ func (ws *WsConn) reconnect() { } if err != nil { - Log.Errorf("[ws] [%s] retry reconnect fail , begin exiting. ", ws.WsUrl) + Log.Errorf("[ws] [%s] retry connect 100 count fail , begin exiting. ", ws.WsUrl) ws.CloseWs() if ws.ErrorHandleFunc != nil { ws.ErrorHandleFunc(errors.New("retry reconnect fail")) } } else { //re subscribe - var tmp []interface{} - copy(tmp, ws.subs) - ws.subs = ws.subs[:0] - for _, sub := range tmp { - ws.Subscribe(sub) + for _, sub := range ws.subs { + Log.Infof("[ws] re subscribe: ", string(sub)) + ws.SendMessage(sub) } } } @@ -228,15 +228,14 @@ func (ws *WsConn) writeRequest() { err = ws.c.WriteMessage(websocket.CloseMessage, d) case <-heartTimer.C: if ws.HeartbeatIntervalTime > 0 { - //Log.Debug("send heartbeat data") err = ws.c.WriteMessage(websocket.TextMessage, ws.HeartbeatData()) heartTimer.Reset(ws.HeartbeatIntervalTime) } } if err != nil { - Log.Errorf("[ws][%s] %s", ws.WsUrl, err.Error()) - time.Sleep(time.Second) + Log.Errorf("[ws][%s] write message %s", ws.WsUrl, err.Error()) + //time.Sleep(time.Second) } } } @@ -248,7 +247,7 @@ func (ws *WsConn) Subscribe(subEvent interface{}) error { return err } ws.writeBufferChan <- data - ws.subs = append(ws.subs, subEvent) + ws.subs = append(ws.subs, data) return nil } @@ -280,8 +279,8 @@ func (ws *WsConn) SendJsonMessage(m interface{}) error { func (ws *WsConn) receiveMessage() { //exit ws.c.SetCloseHandler(func(code int, text string) error { - Log.Infof("[ws][%s] websocket exiting [code=%d , text=%s]", ws.WsUrl, code, text) - ws.CloseWs() + Log.Warnf("[ws][%s] websocket exiting [code=%d , text=%s]", ws.WsUrl, code, text) + //ws.CloseWs() return nil }) @@ -304,14 +303,11 @@ func (ws *WsConn) receiveMessage() { return default: t, msg, err := ws.c.ReadMessage() - if err != nil { Log.Errorf("[ws][%s] %s", ws.WsUrl, err.Error()) if ws.IsAutoReconnect { - // if _, ok := err.(*websocket.CloseError); ok { Log.Infof("[ws][%s] Unexpected Closed , Begin Retry Connect.", ws.WsUrl) ws.reconnect() - // } continue } @@ -321,26 +317,24 @@ func (ws *WsConn) receiveMessage() { return } - + // Log.Debug(string(msg)) ws.c.SetReadDeadline(time.Now().Add(ws.readDeadLineTime)) - switch t { case websocket.TextMessage: ws.ProtoHandleFunc(msg) case websocket.BinaryMessage: - if ws.UnCompressFunc == nil { + if ws.DecompressFunc == nil { ws.ProtoHandleFunc(msg) } else { - msg2, err := ws.UnCompressFunc(msg) + msg2, err := ws.DecompressFunc(msg) if err != nil { - Log.Errorf("[ws][%s] uncompress error %s", ws.WsUrl, err.Error()) + Log.Errorf("[ws][%s] decompress error %s", ws.WsUrl, err.Error()) } else { ws.ProtoHandleFunc(msg2) } } - case websocket.CloseMessage: - ws.CloseWs() - return + // case websocket.CloseMessage: + // ws.CloseWs() default: Log.Errorf("[ws][%s] error websocket message type , content is :\n %s \n", ws.WsUrl, string(msg)) } @@ -349,11 +343,16 @@ func (ws *WsConn) receiveMessage() { } func (ws *WsConn) CloseWs() { - ws.close <- true + //ws.close <- true close(ws.close) + close(ws.writeBufferChan) + close(ws.closeMessageBufferChan) + close(ws.pingMessageBufferChan) + close(ws.pongMessageBufferChan) + err := ws.c.Close() if err != nil { - Log.Error("[ws][", ws.WsUrl, "]close websocket error ,", err) + Log.Error("[ws][", ws.WsUrl, "] close websocket error ,", err) } } From a75b03adecbc9bc50ff531d4a624b4b0a8498194 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 16:46:44 +0800 Subject: [PATCH 13/27] [okex] ws --- .vscode/launch.json | 17 ++++++ okex/OKExFuturesWs.go | 49 +----------------- okex/OKExFuturesWs_test.go | 20 +------ okex/OKExSpotWs.go | 19 +------ okex/OKExWs.go | 103 +++---------------------------------- 5 files changed, 29 insertions(+), 179 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..c23774cd --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${fileDirname}", + "env": {}, + "args": [] + } + ] +} \ No newline at end of file diff --git a/okex/OKExFuturesWs.go b/okex/OKExFuturesWs.go index dc7bf684..9c1a77dd 100644 --- a/okex/OKExFuturesWs.go +++ b/okex/OKExFuturesWs.go @@ -19,7 +19,6 @@ type OKExV3FuturesWs struct { depthCallback func(*Depth) tradeCallback func(*Trade, string) klineCallback func(*FutureKline, int) - orderCallback func(*FutureOrder, string) } func NewOKExV3FuturesWs(base *OKEx) *OKExV3FuturesWs { @@ -42,10 +41,6 @@ func (okV3Ws *OKExV3FuturesWs) TradeCallback(tradeCallback func(*Trade, string)) okV3Ws.tradeCallback = tradeCallback } -func (okV3Ws *OKExV3FuturesWs) OrderCallback(orderCallback func(*FutureOrder, string)) { - okV3Ws.orderCallback = orderCallback -} - func (okV3Ws *OKExV3FuturesWs) KlineCallback(klineCallback func(*FutureKline, int)) { okV3Ws.klineCallback = klineCallback } @@ -53,13 +48,11 @@ func (okV3Ws *OKExV3FuturesWs) KlineCallback(klineCallback func(*FutureKline, in func (okV3Ws *OKExV3FuturesWs) SetCallbacks(tickerCallback func(*FutureTicker), depthCallback func(*Depth), tradeCallback func(*Trade, string), - klineCallback func(*FutureKline, int), - orderCallback func(*FutureOrder, string)) { + klineCallback func(*FutureKline, int)) { okV3Ws.tickerCallback = tickerCallback okV3Ws.depthCallback = depthCallback okV3Ws.tradeCallback = tradeCallback okV3Ws.klineCallback = klineCallback - okV3Ws.orderCallback = orderCallback } func (okV3Ws *OKExV3FuturesWs) getChannelName(currencyPair CurrencyPair, contractType string) string { @@ -75,7 +68,7 @@ func (okV3Ws *OKExV3FuturesWs) getChannelName(currencyPair CurrencyPair, contrac } else { prefix = "futures" contractId = okV3Ws.base.OKExFuture.GetFutureContractId(currencyPair, contractType) - logger.Info("contractid=",contractId) + logger.Info("contractid=", contractId) } channelName = prefix + "/%s:" + contractId @@ -131,17 +124,6 @@ func (okV3Ws *OKExV3FuturesWs) SubscribeKline(currencyPair CurrencyPair, contrac "args": []string{fmt.Sprintf(chName, fmt.Sprintf("candle%ds", seconds))}}) } -func (okV3Ws *OKExV3FuturesWs) SubscribeOrder(currencyPair CurrencyPair, contractType string) error { - if okV3Ws.orderCallback == nil { - return errors.New("place set order callback func") - } - okV3Ws.v3Ws.Login() - chName := okV3Ws.getChannelName(currencyPair, contractType) - return okV3Ws.v3Ws.Subscribe(map[string]interface{}{ - "op": "subscribe", - "args": []string{fmt.Sprintf(chName, "order")}}) -} - func (okV3Ws *OKExV3FuturesWs) getContractAliasAndCurrencyPairFromInstrumentId(instrumentId string) (alias string, pair CurrencyPair) { if strings.HasSuffix(instrumentId, "SWAP") { ar := strings.Split(instrumentId, "-") @@ -172,7 +154,6 @@ func (okV3Ws *OKExV3FuturesWs) handle(ch string, data json.RawMessage) error { InstrumentId string `json:"instrument_id"` Timestamp string `json:"timestamp"` } - orderResp []futureOrderResponse klineResponse []struct { Candle []string `json:"candle"` InstrumentId string `json:"instrument_id"` @@ -288,32 +269,6 @@ func (okV3Ws *OKExV3FuturesWs) handle(ch string, data json.RawMessage) error { }, alias) } return nil - case "order": - //2020/03/18 18:05:00 OKExFuturesWs.go:257: [D] [ws] [response] {"table":"futures/order","data":[{"leverage":"20","last_fill_time":"2020-03-18T10:05:00.790Z","filled_qty":"4","fee":"-0.00010655","price_avg":"112.62","type":"1","client_oid":"ce1661e5cb614fd690d0463de7a2eeb0","last_fill_qty":"4","instrument_id":"BSV-USD-200327","last_fill_px":"112.62","pnl":"0","size":"4","price":"112.73","last_fill_id":"15229749","error_code":"0","state":"2","contract_val":"10","order_id":"4573750935784449","order_type":"0","timestamp":"2020-03-18T10:05:00.790Z","status":"2"}]} - err := json.Unmarshal(data, &orderResp) - if err != nil { - return err - } - for _, o := range orderResp { - alias, pair := okV3Ws.getContractAliasAndCurrencyPairFromInstrumentId(o.InstrumentId) - okV3Ws.orderCallback(&FutureOrder{ - ClientOid: o.ClientOid, - OrderID2: o.OrderId, - Price: o.Price, - Amount: o.Size, - AvgPrice: o.PriceAvg, - DealAmount: o.FilledQty, - Status: okV3Ws.base.adaptOrderState(o.State), - Currency: pair, - OrderType: o.OrderType, - OType: o.Type, - LeverRate: o.Leverage, - Fee: o.Fee, - ContractName: o.InstrumentId, - OrderTime: o.Timestamp.UnixNano() / int64(time.Millisecond), - }, alias) - } - return nil } return fmt.Errorf("[%s] unknown websocket message: %s", ch, string(data)) diff --git a/okex/OKExFuturesWs_test.go b/okex/OKExFuturesWs_test.go index 7eb04680..c266021c 100644 --- a/okex/OKExFuturesWs_test.go +++ b/okex/OKExFuturesWs_test.go @@ -1,12 +1,9 @@ package okex import ( - "context" "github.com/nntaoli-project/goex" "github.com/nntaoli-project/goex/internal/logger" - "net" "net/http" - "net/url" "os" "testing" "time" @@ -18,17 +15,6 @@ var ( func init() { logger.SetLevel(logger.DEBUG) - client = &http.Client{ - Transport: &http.Transport{Proxy: func(request *http.Request) (*url.URL, error) { - return url.Parse("socks5://127.0.0.1:1080") - }, - DialContext: func(ctx context.Context, network, addr string) (conn net.Conn, e error) { - conn, e = net.DialTimeout(network, addr, 5*time.Second) - return conn, e - }, - }, - Timeout: 10 * time.Second, - } } func TestNewOKExV3FuturesWs(t *testing.T) { @@ -45,12 +31,8 @@ func TestNewOKExV3FuturesWs(t *testing.T) { ok.OKExV3FutureWs.TradeCallback(func(trade *goex.Trade, s string) { t.Log(s, trade) }) - ok.OKExV3FutureWs.OrderCallback(func(order *goex.FutureOrder, s string) { - t.Log(s, order) - }) //ok.OKExV3FutureWs.SubscribeTicker(goex.EOS_USD, goex.QUARTER_CONTRACT) - ok.OKExV3FutureWs.SubscribeDepth(goex.EOS_USDT, goex.QUARTER_CONTRACT) + ok.OKExV3FutureWs.SubscribeDepth(goex.EOS_USD, goex.QUARTER_CONTRACT) //ok.OKExV3FutureWs.SubscribeTrade(goex.EOS_USD, goex.QUARTER_CONTRACT) - //ok.OKExV3FutureWs.SubscribeOrder(goex.BSV_USD, goex.NEXT_WEEK_CONTRACT) time.Sleep(1 * time.Minute) } diff --git a/okex/OKExSpotWs.go b/okex/OKExSpotWs.go index 6d08bd34..ef9e8179 100644 --- a/okex/OKExSpotWs.go +++ b/okex/OKExSpotWs.go @@ -19,7 +19,6 @@ type OKExV3SpotWs struct { depthCallback func(*Depth) tradeCallback func(*Trade) klineCallback func(*Kline, KlinePeriod) - orderCallback func(*Order) } func NewOKExSpotV3Ws(base *OKEx) *OKExV3SpotWs { @@ -46,20 +45,14 @@ func (okV3Ws *OKExV3SpotWs) KLineCallback(klineCallback func(kline *Kline, perio okV3Ws.klineCallback = klineCallback } -func (okV3Ws *OKExV3SpotWs) OrderCallback(orderCallback func(*Order)) { - okV3Ws.orderCallback = orderCallback -} - func (okV3Ws *OKExV3SpotWs) SetCallbacks(tickerCallback func(*Ticker), depthCallback func(*Depth), tradeCallback func(*Trade), - klineCallback func(*Kline, KlinePeriod), - orderCallback func(*Order)) { + klineCallback func(*Kline, KlinePeriod)) { okV3Ws.tickerCallback = tickerCallback okV3Ws.depthCallback = depthCallback okV3Ws.tradeCallback = tradeCallback okV3Ws.klineCallback = klineCallback - okV3Ws.orderCallback = orderCallback } func (okV3Ws *OKExV3SpotWs) SubscribeDepth(currencyPair CurrencyPair) error { @@ -105,16 +98,6 @@ func (okV3Ws *OKExV3SpotWs) SubscribeKline(currencyPair CurrencyPair, period int "args": []string{fmt.Sprintf("spot/candle%ds:%s", seconds, currencyPair.ToSymbol("-"))}}) } -func (okV3Ws *OKExV3SpotWs) SubscribeOrder(currencyPair CurrencyPair, contractType string) error { - if okV3Ws.orderCallback == nil { - return errors.New("place set order callback func") - } - okV3Ws.v3Ws.Login() - return okV3Ws.v3Ws.Subscribe(map[string]interface{}{ - "op": "subscribe", - "args": []string{fmt.Sprintf("spot/order:%s", currencyPair.ToSymbol("-"))}}) -} - func (okV3Ws *OKExV3SpotWs) getCurrencyPair(instrumentId string) CurrencyPair { return NewCurrencyPair3(instrumentId, "-") } diff --git a/okex/OKExWs.go b/okex/OKExWs.go index 11a174c9..827443ff 100644 --- a/okex/OKExWs.go +++ b/okex/OKExWs.go @@ -24,13 +24,9 @@ type wsResp struct { type OKExV3Ws struct { base *OKEx *WsBuilder - once *sync.Once - wsConn *WsConn - respHandle func(channel string, data json.RawMessage) error - loginCh chan wsResp - isLogin bool - loginLock *sync.Mutex - authoriedSubs []map[string]interface{} + once *sync.Once + WsConn *WsConn + respHandle func(channel string, data json.RawMessage) error } func NewOKExV3Ws(base *OKEx, handle func(channel string, data json.RawMessage) error) *OKExV3Ws { @@ -39,9 +35,6 @@ func NewOKExV3Ws(base *OKEx, handle func(channel string, data json.RawMessage) e base: base, respHandle: handle, } - okV3Ws.loginCh = make(chan wsResp) - okV3Ws.loginLock = &sync.Mutex{} - okV3Ws.authoriedSubs = make([]map[string]interface{}, 0) okV3Ws.WsBuilder = NewWsBuilder(). WsUrl("wss://real.okex.com:8443/ws/v3"). ReconnectInterval(time.Second). @@ -68,20 +61,9 @@ func (okV3Ws *OKExV3Ws) getTablePrefix(currencyPair CurrencyPair, contractType s return "futures" } -func (okV3Ws *OKExV3Ws) authoriedSubscribe(data map[string]interface{}) error { - okV3Ws.authoriedSubs = append(okV3Ws.authoriedSubs, data) - return okV3Ws.Subscribe(data) -} - -func (okV3Ws *OKExV3Ws) reSubscribeAuthoriedChannel() { - for _, d := range okV3Ws.authoriedSubs { - okV3Ws.wsConn.SendJsonMessage(d) - } -} - -func (okV3Ws *OKExV3Ws) connectWs() { +func (okV3Ws *OKExV3Ws) ConnectWs() { okV3Ws.once.Do(func() { - okV3Ws.wsConn = okV3Ws.WsBuilder.Build() + okV3Ws.WsConn = okV3Ws.WsBuilder.Build() }) } @@ -125,41 +107,8 @@ func (okV3Ws *OKExV3Ws) handle(msg []byte) error { case "subscribe": logger.Info("subscribed:", wsResp.Channel) return nil - case "login": - select { - case okV3Ws.loginCh <- wsResp: - return nil - default: - return nil - } case "error": - var errorCode int - switch v := wsResp.ErrorCode.(type) { - case int: - errorCode = v - case float64: - errorCode = int(v) // float64 okex牛逼嗷 - case string: - i, _ := strconv.ParseInt(v, 10, 64) - errorCode = int(i) - } - - switch errorCode { - // event:error message:Already logged in errorCode:30042 - case 30041: - //TODO: - return nil - case 30042: - return nil - } - - // TODO: clearfy which errors should be treated as login result. - select { - case okV3Ws.loginCh <- wsResp: - return nil - default: - return fmt.Errorf("error in websocket: %v", wsResp) - } + logger.Errorf(string(msg)) } return fmt.Errorf("unknown websocket message: %v", wsResp) } @@ -180,43 +129,7 @@ func (okV3Ws *OKExV3Ws) handle(msg []byte) error { return fmt.Errorf("unknown websocket message: %v", wsResp) } -func (okV3Ws *OKExV3Ws) Login() error { - // already logined - if okV3Ws.isLogin { - return nil - } - - okV3Ws.connectWs() - - okV3Ws.loginLock.Lock() - defer okV3Ws.loginLock.Unlock() - - if okV3Ws.isLogin { //double check - return nil - } - - okV3Ws.clearChan(okV3Ws.loginCh) - - sign, tm := okV3Ws.base.doParamSign("GET", "/users/self/verify", "") - op := map[string]interface{}{ - "op": "login", "args": []string{okV3Ws.base.config.ApiKey, okV3Ws.base.config.ApiPassphrase, tm, sign}} - err := okV3Ws.wsConn.SendJsonMessage(op) - if err != nil { - logger.Error("ws login error:", err) - return err - } - - //wait login response - re := <-okV3Ws.loginCh - if !re.Success { - return fmt.Errorf("login failed: %v", re) - } - logger.Info("ws login success") - okV3Ws.isLogin = true - return nil -} - func (okV3Ws *OKExV3Ws) Subscribe(sub map[string]interface{}) error { - okV3Ws.connectWs() - return okV3Ws.wsConn.Subscribe(sub) + okV3Ws.ConnectWs() + return okV3Ws.WsConn.Subscribe(sub) } From f21044a98fc64eef29ed873324febb3a7ca4d3f0 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 16:47:17 +0800 Subject: [PATCH 14/27] [ws] add connect success after handle --- websocket.go | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/websocket.go b/websocket.go index 5ed10a7a..f4635ed2 100644 --- a/websocket.go +++ b/websocket.go @@ -14,18 +14,19 @@ import ( ) type WsConfig struct { - WsUrl string - ProxyUrl string - ReqHeaders map[string][]string //连接的时候加入的头部信息 - HeartbeatIntervalTime time.Duration // - HeartbeatData func() []byte //心跳数据2 - IsAutoReconnect bool - ProtoHandleFunc func([]byte) error //协议处理函数 - DecompressFunc func([]byte) ([]byte, error) //解压函数 - ErrorHandleFunc func(err error) - IsDump bool - readDeadLineTime time.Duration - reconnectInterval time.Duration + WsUrl string + ProxyUrl string + ReqHeaders map[string][]string //连接的时候加入的头部信息 + HeartbeatIntervalTime time.Duration // + HeartbeatData func() []byte //心跳数据2 + IsAutoReconnect bool + ProtoHandleFunc func([]byte) error //协议处理函数 + DecompressFunc func([]byte) ([]byte, error) //解压函数 + ErrorHandleFunc func(err error) + ConnectSuccessAfterHandle func() + IsDump bool + readDeadLineTime time.Duration + reconnectInterval time.Duration } var dialer = &websocket.Dialer{ @@ -166,6 +167,11 @@ func (ws *WsConn) connect() error { } Log.Infof("[ws][%s] connected", ws.WsUrl) + if ws.ConnectSuccessAfterHandle != nil { + Log.Infof("[ws] [%s] execute the connect success after handle.", ws.WsUrl) + ws.ConnectSuccessAfterHandle() + } + ws.c = wsConn return nil } From 087cca64552ae856cb75a30e97ca9a4da30a6f9d Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 16:51:35 +0800 Subject: [PATCH 15/27] rename uncompress to decompress --- Utils.go | 4 ++-- huobi/Hbdm_Ws.go | 2 +- okex/OKExWs.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Utils.go b/Utils.go index 9d68b0c6..0222988e 100644 --- a/Utils.go +++ b/Utils.go @@ -110,7 +110,7 @@ func ValuesToJson(v url.Values) ([]byte, error) { return json.Marshal(parammap) } -func GzipUnCompress(data []byte) ([]byte, error) { +func GzipDecompress(data []byte) ([]byte, error) { r, err := gzip.NewReader(bytes.NewReader(data)) if err != nil { return nil, err @@ -118,7 +118,7 @@ func GzipUnCompress(data []byte) ([]byte, error) { return ioutil.ReadAll(r) } -func FlateUnCompress(data []byte) ([]byte, error) { +func FlateDecompress(data []byte) ([]byte, error) { return ioutil.ReadAll(flate.NewReader(bytes.NewReader(data))) } diff --git a/huobi/Hbdm_Ws.go b/huobi/Hbdm_Ws.go index 5b220eaa..45510fcf 100644 --- a/huobi/Hbdm_Ws.go +++ b/huobi/Hbdm_Ws.go @@ -73,7 +73,7 @@ func NewHbdmWs() *HbdmWs { AutoReconnect(). //Heartbeat([]byte("{\"event\": \"ping\"} "), 30*time.Second). //Heartbeat(func() []byte { return []byte("{\"op\":\"ping\"}") }(), 5*time.Second). - DecompressFunc(GzipUnCompress). + DecompressFunc(GzipDecompress). ProtoHandleFunc(hbdmWs.handle) return hbdmWs } diff --git a/okex/OKExWs.go b/okex/OKExWs.go index 827443ff..e431ace1 100644 --- a/okex/OKExWs.go +++ b/okex/OKExWs.go @@ -40,7 +40,7 @@ func NewOKExV3Ws(base *OKEx, handle func(channel string, data json.RawMessage) e ReconnectInterval(time.Second). AutoReconnect(). Heartbeat(func() []byte { return []byte("ping") }, 28*time.Second). - DecompressFunc(FlateUnCompress).ProtoHandleFunc(okV3Ws.handle) + DecompressFunc(FlateDecompress).ProtoHandleFunc(okV3Ws.handle) return okV3Ws } From 36fc4f15d48abf5c5993f46ea0d15c68f5bc125a Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 17:30:53 +0800 Subject: [PATCH 16/27] [ws] ConnectSuccessAfterSendMessage []byte //for reconnect --- websocket.go | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/websocket.go b/websocket.go index f4635ed2..e29bcf25 100644 --- a/websocket.go +++ b/websocket.go @@ -14,19 +14,19 @@ import ( ) type WsConfig struct { - WsUrl string - ProxyUrl string - ReqHeaders map[string][]string //连接的时候加入的头部信息 - HeartbeatIntervalTime time.Duration // - HeartbeatData func() []byte //心跳数据2 - IsAutoReconnect bool - ProtoHandleFunc func([]byte) error //协议处理函数 - DecompressFunc func([]byte) ([]byte, error) //解压函数 - ErrorHandleFunc func(err error) - ConnectSuccessAfterHandle func() - IsDump bool - readDeadLineTime time.Duration - reconnectInterval time.Duration + WsUrl string + ProxyUrl string + ReqHeaders map[string][]string //连接的时候加入的头部信息 + HeartbeatIntervalTime time.Duration // + HeartbeatData func() []byte //心跳数据2 + IsAutoReconnect bool + ProtoHandleFunc func([]byte) error //协议处理函数 + DecompressFunc func([]byte) ([]byte, error) //解压函数 + ErrorHandleFunc func(err error) + ConnectSuccessAfterSendMessage []byte //for reconnect + IsDump bool + readDeadLineTime time.Duration + reconnectInterval time.Duration } var dialer = &websocket.Dialer{ @@ -109,6 +109,11 @@ func (b *WsBuilder) ErrorHandleFunc(f func(err error)) *WsBuilder { return b } +func (b *WsBuilder) ConnectSuccessAfterSendMessage(msg []byte) *WsBuilder { + b.wsConfig.ConnectSuccessAfterSendMessage = msg + return b +} + func (b *WsBuilder) Build() *WsConn { wsConn := &WsConn{WsConfig: *b.wsConfig} return wsConn.NewWs() @@ -167,9 +172,9 @@ func (ws *WsConn) connect() error { } Log.Infof("[ws][%s] connected", ws.WsUrl) - if ws.ConnectSuccessAfterHandle != nil { - Log.Infof("[ws] [%s] execute the connect success after handle.", ws.WsUrl) - ws.ConnectSuccessAfterHandle() + if ws.ConnectSuccessAfterSendMessage != nil && len(ws.ConnectSuccessAfterSendMessage) > 0 { + Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(ws.ConnectSuccessAfterSendMessage)) + ws.SendMessage(ws.ConnectSuccessAfterSendMessage) } ws.c = wsConn From 603adb24e28efba988034ad2a47fbf1ce07c6a74 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Mon, 18 May 2020 17:50:52 +0800 Subject: [PATCH 17/27] [ws] fix connect success after send message bug --- websocket.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/websocket.go b/websocket.go index e29bcf25..5774a68b 100644 --- a/websocket.go +++ b/websocket.go @@ -140,6 +140,11 @@ func (ws *WsConn) NewWs() *WsConn { go ws.writeRequest() go ws.receiveMessage() + if ws.ConnectSuccessAfterSendMessage != nil && len(ws.ConnectSuccessAfterSendMessage) > 0 { + Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(ws.ConnectSuccessAfterSendMessage)) + ws.SendMessage(ws.ConnectSuccessAfterSendMessage) + } + return ws } @@ -171,12 +176,6 @@ func (ws *WsConn) connect() error { Log.Debugf("[ws][%s] %s", ws.WsUrl, string(dumpData)) } Log.Infof("[ws][%s] connected", ws.WsUrl) - - if ws.ConnectSuccessAfterSendMessage != nil && len(ws.ConnectSuccessAfterSendMessage) > 0 { - Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(ws.ConnectSuccessAfterSendMessage)) - ws.SendMessage(ws.ConnectSuccessAfterSendMessage) - } - ws.c = wsConn return nil } @@ -205,6 +204,11 @@ func (ws *WsConn) reconnect() { } } else { //re subscribe + if ws.ConnectSuccessAfterSendMessage != nil && len(ws.ConnectSuccessAfterSendMessage) > 0 { + Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(ws.ConnectSuccessAfterSendMessage)) + ws.SendMessage(ws.ConnectSuccessAfterSendMessage) + } + for _, sub := range ws.subs { Log.Infof("[ws] re subscribe: ", string(sub)) ws.SendMessage(sub) From 09ba3e5f920c3932f6813bd23543b92f3eae0af2 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Tue, 19 May 2020 10:26:22 +0800 Subject: [PATCH 18/27] [okex] ws --- okex/OKExFuturesWs.go | 13 +++++++++++-- okex/OKExSpotWs.go | 17 +++++------------ okex/OKExWs.go | 9 +++------ 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/okex/OKExFuturesWs.go b/okex/OKExFuturesWs.go index 9c1a77dd..05423d00 100644 --- a/okex/OKExFuturesWs.go +++ b/okex/OKExFuturesWs.go @@ -140,9 +140,10 @@ func (okV3Ws *OKExV3FuturesWs) getContractAliasAndCurrencyPairFromInstrumentId(i } } -func (okV3Ws *OKExV3FuturesWs) handle(ch string, data json.RawMessage) error { +func (okV3Ws *OKExV3FuturesWs) handle(channel string, data json.RawMessage) error { var ( err error + ch string tickers []tickerResponse depthResp []depthResponse dep Depth @@ -159,9 +160,17 @@ func (okV3Ws *OKExV3FuturesWs) handle(ch string, data json.RawMessage) error { InstrumentId string `json:"instrument_id"` } ) - if strings.Contains(ch, "candle") { + + if strings.Contains(channel, "futures/candle") { ch = "candle" + } else { + ch, err = okV3Ws.v3Ws.parseChannel(channel) + if err != nil { + logger.Errorf("[%s] parse channel err=%s , originChannel=%s", okV3Ws.base.GetExchangeName(), err, ch) + return nil + } } + switch ch { case "ticker": err = json.Unmarshal(data, &tickers) diff --git a/okex/OKExSpotWs.go b/okex/OKExSpotWs.go index ef9e8179..f0a5f527 100644 --- a/okex/OKExSpotWs.go +++ b/okex/OKExSpotWs.go @@ -120,11 +120,10 @@ func (okV3Ws *OKExV3SpotWs) handle(ch string, data json.RawMessage) error { Candle []string `json:"candle"` InstrumentId string `json:"instrument_id"` } - orderResp []futureOrderResponse ) switch ch { - case "ticker": + case "spot/ticker": err = json.Unmarshal(data, &tickers) if err != nil { return err @@ -144,7 +143,7 @@ func (okV3Ws *OKExV3SpotWs) handle(ch string, data json.RawMessage) error { }) } return nil - case "depth5": + case "spot/depth5": err := json.Unmarshal(data, &depthResp) if err != nil { logger.Error(err) @@ -170,7 +169,7 @@ func (okV3Ws *OKExV3SpotWs) handle(ch string, data json.RawMessage) error { //call back func okV3Ws.depthCallback(&dep) return nil - case "trade": + case "spot/trade": err := json.Unmarshal(data, &tradeResponse) if err != nil { logger.Error("unmarshal error :", err) @@ -199,19 +198,13 @@ func (okV3Ws *OKExV3SpotWs) handle(ch string, data json.RawMessage) error { }) } return nil - case "order": - err := json.Unmarshal(data, &orderResp) - if err != nil { - return err - } - return nil default: - if strings.HasPrefix(ch, "candle") { + if strings.HasPrefix(ch, "spot/candle") { err := json.Unmarshal(data, &candleResponse) if err != nil { return err } - periodMs := strings.TrimPrefix(ch, "candle") + periodMs := strings.TrimPrefix(ch, "spot/candle") periodMs = strings.TrimSuffix(periodMs, "s") for _, k := range candleResponse { pair := okV3Ws.getCurrencyPair(k.InstrumentId) diff --git a/okex/OKExWs.go b/okex/OKExWs.go index e431ace1..763c1b3e 100644 --- a/okex/OKExWs.go +++ b/okex/OKExWs.go @@ -109,17 +109,14 @@ func (okV3Ws *OKExV3Ws) handle(msg []byte) error { return nil case "error": logger.Errorf(string(msg)) + default: + logger.Info(string(msg)) } return fmt.Errorf("unknown websocket message: %v", wsResp) } if wsResp.Table != "" { - channel, err := okV3Ws.parseChannel(wsResp.Table) - if err != nil { - logger.Error("parse ws channel error:", err) - return err - } - err = okV3Ws.respHandle(channel, wsResp.Data) + err = okV3Ws.respHandle(wsResp.Table, wsResp.Data) if err != nil { logger.Error("handle ws data error:", err) } From 83827958c4ae79dcfc426b12d0ef37ab2dd049b8 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Tue, 19 May 2020 17:58:39 +0800 Subject: [PATCH 19/27] [ws] connect success after send message --- websocket.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/websocket.go b/websocket.go index 5774a68b..55683594 100644 --- a/websocket.go +++ b/websocket.go @@ -23,7 +23,7 @@ type WsConfig struct { ProtoHandleFunc func([]byte) error //协议处理函数 DecompressFunc func([]byte) ([]byte, error) //解压函数 ErrorHandleFunc func(err error) - ConnectSuccessAfterSendMessage []byte //for reconnect + ConnectSuccessAfterSendMessage func() []byte //for reconnect IsDump bool readDeadLineTime time.Duration reconnectInterval time.Duration @@ -109,7 +109,7 @@ func (b *WsBuilder) ErrorHandleFunc(f func(err error)) *WsBuilder { return b } -func (b *WsBuilder) ConnectSuccessAfterSendMessage(msg []byte) *WsBuilder { +func (b *WsBuilder) ConnectSuccessAfterSendMessage(msg func() []byte) *WsBuilder { b.wsConfig.ConnectSuccessAfterSendMessage = msg return b } @@ -140,9 +140,10 @@ func (ws *WsConn) NewWs() *WsConn { go ws.writeRequest() go ws.receiveMessage() - if ws.ConnectSuccessAfterSendMessage != nil && len(ws.ConnectSuccessAfterSendMessage) > 0 { - Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(ws.ConnectSuccessAfterSendMessage)) - ws.SendMessage(ws.ConnectSuccessAfterSendMessage) + if ws.ConnectSuccessAfterSendMessage != nil { + msg := ws.ConnectSuccessAfterSendMessage() + ws.SendMessage(msg) + Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(msg)) } return ws @@ -204,9 +205,10 @@ func (ws *WsConn) reconnect() { } } else { //re subscribe - if ws.ConnectSuccessAfterSendMessage != nil && len(ws.ConnectSuccessAfterSendMessage) > 0 { - Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(ws.ConnectSuccessAfterSendMessage)) - ws.SendMessage(ws.ConnectSuccessAfterSendMessage) + if ws.ConnectSuccessAfterSendMessage != nil { + msg := ws.ConnectSuccessAfterSendMessage() + ws.SendMessage(msg) + Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(msg)) } for _, sub := range ws.subs { From ea98d49432cd0835b50996b5a916498773b59078 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Tue, 19 May 2020 18:03:47 +0800 Subject: [PATCH 20/27] [ws] log --- websocket.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/websocket.go b/websocket.go index 55683594..d948be2f 100644 --- a/websocket.go +++ b/websocket.go @@ -212,7 +212,7 @@ func (ws *WsConn) reconnect() { } for _, sub := range ws.subs { - Log.Infof("[ws] re subscribe: ", string(sub)) + Log.Info("[ws] re subscribe: ", string(sub)) ws.SendMessage(sub) } } From db5c615419ab727df9a0c74cf34bf51292f9ca11 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Wed, 20 May 2020 11:41:09 +0800 Subject: [PATCH 21/27] [ws] connect success after send message and wait for moment response --- okex/OKEx.go | 3 +-- websocket.go | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/okex/OKEx.go b/okex/OKEx.go index c55c9a3a..1cd8cadb 100644 --- a/okex/OKEx.go +++ b/okex/OKEx.go @@ -52,8 +52,7 @@ func (ok *OKEx) UUID() string { func (ok *OKEx) DoRequest(httpMethod, uri, reqBody string, response interface{}) error { url := ok.config.Endpoint + uri sign, timestamp := ok.doParamSign(httpMethod, uri, reqBody) - logger.Log.Debug("sign=", sign) - logger.Log.Debug("timestamp=", timestamp) + logger.Log.Debug("timestamp=", timestamp, ", sign=", sign) resp, err := NewHttpRequest(ok.config.HttpClient, httpMethod, url, reqBody, map[string]string{ CONTENT_TYPE: APPLICATION_JSON_UTF8, ACCEPT: APPLICATION_JSON, diff --git a/websocket.go b/websocket.go index d948be2f..9d674a96 100644 --- a/websocket.go +++ b/websocket.go @@ -209,6 +209,7 @@ func (ws *WsConn) reconnect() { msg := ws.ConnectSuccessAfterSendMessage() ws.SendMessage(msg) Log.Infof("[ws] [%s] execute the connect success after send message=%s", ws.WsUrl, string(msg)) + time.Sleep(time.Second) //wait response } for _, sub := range ws.subs { From 4568b9cd6cdd2fb9ebab96840d55502a6d7450e3 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Wed, 20 May 2020 15:15:42 +0800 Subject: [PATCH 22/27] [hbdm] market ws --- builder/APIBuilder.go | 2 ++ huobi/Hbdm_Ws.go | 72 ++++++++++++++++++++++++------------------- 2 files changed, 43 insertions(+), 31 deletions(-) diff --git a/builder/APIBuilder.go b/builder/APIBuilder.go index bbec074b..6f05257e 100644 --- a/builder/APIBuilder.go +++ b/builder/APIBuilder.go @@ -320,6 +320,8 @@ func (builder *APIBuilder) BuildFuturesWs(exName string) (FuturesWsApi, error) { HttpClient: builder.client, Endpoint: builder.futuresEndPoint, })), nil + case HBDM: + return huobi.NewHbdmWs(), nil } return nil, errors.New("not support the exchange " + exName) } diff --git a/huobi/Hbdm_Ws.go b/huobi/Hbdm_Ws.go index 45510fcf..be8beffc 100644 --- a/huobi/Hbdm_Ws.go +++ b/huobi/Hbdm_Ws.go @@ -1,11 +1,12 @@ package huobi import ( + "bytes" "encoding/json" "errors" "fmt" . "github.com/nntaoli-project/goex" - "log" + "github.com/nntaoli-project/goex/internal/logger" "sort" "strings" "sync" @@ -54,6 +55,7 @@ type DetailResponse struct { type DepthResponse struct { Bids [][]float64 Asks [][]float64 + Ts int64 `json:"ts"` } type HbdmWs struct { @@ -86,6 +88,17 @@ func (hbdmWs *HbdmWs) SetCallbacks(tickerCallback func(*FutureTicker), hbdmWs.tradeCallback = tradeCallback } +func (hbdmWs *HbdmWs) TickerCallback(call func(ticker *FutureTicker)) { + hbdmWs.tickerCallback = call +} +func (hbdmWs *HbdmWs) TradeCallback(call func(trade *Trade, contract string)) { + hbdmWs.tradeCallback = call +} + +func (hbdmWs *HbdmWs) DepthCallback(call func(depth *Depth)) { + hbdmWs.depthCallback = call +} + func (hbdmWs *HbdmWs) SubscribeTicker(pair CurrencyPair, contract string) error { if hbdmWs.tickerCallback == nil { return errors.New("please set ticker callback func") @@ -95,13 +108,13 @@ func (hbdmWs *HbdmWs) SubscribeTicker(pair CurrencyPair, contract string) error "sub": fmt.Sprintf("market.%s_%s.detail", pair.CurrencyA.Symbol, hbdmWs.adaptContractSymbol(contract))}) } -func (hbdmWs *HbdmWs) SubscribeDepth(pair CurrencyPair, contract string, size int) error { +func (hbdmWs *HbdmWs) SubscribeDepth(pair CurrencyPair, contract string) error { if hbdmWs.depthCallback == nil { return errors.New("please set depth callback func") } return hbdmWs.subscribe(map[string]interface{}{ "id": "depth_2", - "sub": fmt.Sprintf("market.%s_%s.depth.step0", pair.CurrencyA.Symbol, hbdmWs.adaptContractSymbol(contract))}) + "sub": fmt.Sprintf("market.%s_%s.depth.step6", pair.CurrencyA.Symbol, hbdmWs.adaptContractSymbol(contract))}) } func (hbdmWs *HbdmWs) SubscribeTrade(pair CurrencyPair, contract string) error { @@ -114,7 +127,7 @@ func (hbdmWs *HbdmWs) SubscribeTrade(pair CurrencyPair, contract string) error { } func (hbdmWs *HbdmWs) subscribe(sub map[string]interface{}) error { -// log.Println(sub) + // log.Println(sub) hbdmWs.connectWs() return hbdmWs.wsConn.Subscribe(sub) } @@ -127,17 +140,11 @@ func (hbdmWs *HbdmWs) connectWs() { func (hbdmWs *HbdmWs) handle(msg []byte) error { //心跳 - if strings.Contains(string(msg), "ping") { - var ping struct { - Ping int64 - } - json.Unmarshal(msg, &ping) - - pong := struct { - Pong int64 `json:"pong"` - }{ping.Ping} - - hbdmWs.wsConn.SendJsonMessage(pong) + if bytes.Contains(msg, []byte("ping")) { + logger.Info(string(msg)) + pong := bytes.ReplaceAll(msg, []byte("ping"), []byte("pong")) + hbdmWs.wsConn.SendMessage(pong) + logger.Info(string(pong)) return nil } @@ -148,29 +155,16 @@ func (hbdmWs *HbdmWs) handle(msg []byte) error { } if resp.Ch == "" { - log.Println(string(msg)) + logger.Warnf("[%s] ch == \"\" , msg=%s", hbdmWs.wsConn.WsUrl, string(msg)) return nil } pair, contract, err := hbdmWs.parseCurrencyAndContract(resp.Ch) if err != nil { + logger.Errorf("[%s] parse currency and contract err=%s", hbdmWs.wsConn.WsUrl, err) return err } - if strings.HasSuffix(resp.Ch, "trade.detail") { - var tradeResp TradeResponse - err := json.Unmarshal(resp.Tick, &tradeResp) - if err != nil { - return err - } - trades := hbdmWs.parseTrade(tradeResp) - for _, v := range trades { - v.Pair = pair - hbdmWs.tradeCallback(&v, contract) - } - return nil - } - if strings.Contains(resp.Ch, ".depth.") { var depResp DepthResponse err := json.Unmarshal(resp.Tick, &depResp) @@ -181,12 +175,26 @@ func (hbdmWs *HbdmWs) handle(msg []byte) error { dep := hbdmWs.parseDepth(depResp) dep.ContractType = contract dep.Pair = pair - dep.UTime = time.Unix(resp.Ts/1000, 0) + dep.UTime = time.Unix(0, resp.Ts*int64(time.Millisecond)) hbdmWs.depthCallback(&dep) return nil } + if strings.HasSuffix(resp.Ch, "trade.detail") { + var tradeResp TradeResponse + err := json.Unmarshal(resp.Tick, &tradeResp) + if err != nil { + return err + } + trades := hbdmWs.parseTrade(tradeResp) + for _, v := range trades { + v.Pair = pair + hbdmWs.tradeCallback(&v, contract) + } + return nil + } + if strings.HasSuffix(resp.Ch, ".detail") { var detail DetailResponse err := json.Unmarshal(resp.Tick, &detail) @@ -200,6 +208,8 @@ func (hbdmWs *HbdmWs) handle(msg []byte) error { return nil } + logger.Errorf("[%s] unknown message, msg=%s", hbdmWs.wsConn.WsUrl, string(msg)) + return nil } From f65d0b3d609177f0d87fb44742f49e69eb718fda Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Wed, 20 May 2020 18:01:21 +0800 Subject: [PATCH 23/27] [huobi] spot ws --- builder/APIBuilder.go | 2 + huobi/Hbdm_Ws.go | 20 +----- huobi/HuobiSpot_Ws.go | 131 +++++++++++++++++++++++++++++++++++++ huobi/HuobiSpot_Ws_test.go | 28 ++++++++ huobi/Parser.go | 65 ++++++++++++++++++ 5 files changed, 227 insertions(+), 19 deletions(-) create mode 100644 huobi/HuobiSpot_Ws.go create mode 100644 huobi/HuobiSpot_Ws_test.go create mode 100644 huobi/Parser.go diff --git a/builder/APIBuilder.go b/builder/APIBuilder.go index 6f05257e..e2835fea 100644 --- a/builder/APIBuilder.go +++ b/builder/APIBuilder.go @@ -330,6 +330,8 @@ func (builder *APIBuilder) BuildSpotWs(exName string) (SpotWsApi, error) { switch exName { case OKEX_V3, OKEX: return okex.NewOKExSpotV3Ws(nil), nil + case HUOBI_PRO, HUOBI: + return huobi.NewSpotWs(), nil } return nil, errors.New("not support the exchange " + exName) } diff --git a/huobi/Hbdm_Ws.go b/huobi/Hbdm_Ws.go index be8beffc..e1744389 100644 --- a/huobi/Hbdm_Ws.go +++ b/huobi/Hbdm_Ws.go @@ -7,7 +7,6 @@ import ( "fmt" . "github.com/nntaoli-project/goex" "github.com/nntaoli-project/goex/internal/logger" - "sort" "strings" "sync" "time" @@ -141,10 +140,8 @@ func (hbdmWs *HbdmWs) connectWs() { func (hbdmWs *HbdmWs) handle(msg []byte) error { //心跳 if bytes.Contains(msg, []byte("ping")) { - logger.Info(string(msg)) pong := bytes.ReplaceAll(msg, []byte("ping"), []byte("pong")) hbdmWs.wsConn.SendMessage(pong) - logger.Info(string(pong)) return nil } @@ -172,7 +169,7 @@ func (hbdmWs *HbdmWs) handle(msg []byte) error { return err } - dep := hbdmWs.parseDepth(depResp) + dep := ParseDepthFromResponse(depResp) dep.ContractType = contract dep.Pair = pair dep.UTime = time.Unix(0, resp.Ts*int64(time.Millisecond)) @@ -217,21 +214,6 @@ func (hbdmWs *HbdmWs) parseTicker(r DetailResponse) FutureTicker { return FutureTicker{Ticker: &Ticker{High: r.High, Low: r.Low, Vol: r.Amount}} } -func (hbdmWs *HbdmWs) parseDepth(r DepthResponse) Depth { - var dep Depth - for _, bid := range r.Bids { - dep.BidList = append(dep.BidList, DepthRecord{bid[0], bid[1]}) - } - - for _, ask := range r.Asks { - dep.AskList = append(dep.AskList, DepthRecord{ask[0], ask[1]}) - } - - sort.Sort(sort.Reverse(dep.BidList)) - sort.Sort(sort.Reverse(dep.AskList)) - return dep -} - func (hbdmWs *HbdmWs) parseCurrencyAndContract(ch string) (CurrencyPair, string, error) { el := strings.Split(ch, ".") if len(el) < 2 { diff --git a/huobi/HuobiSpot_Ws.go b/huobi/HuobiSpot_Ws.go new file mode 100644 index 00000000..a64a1611 --- /dev/null +++ b/huobi/HuobiSpot_Ws.go @@ -0,0 +1,131 @@ +package huobi + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + . "github.com/nntaoli-project/goex" + "github.com/nntaoli-project/goex/internal/logger" + "strings" + "sync" +) + +type SpotWs struct { + *WsBuilder + sync.Once + wsConn *WsConn + + tickerCallback func(*Ticker) + depthCallback func(*Depth) + tradeCallback func(*Trade) +} + +func NewSpotWs() *SpotWs { + ws := &SpotWs{ + WsBuilder: NewWsBuilder(), + } + ws.WsBuilder = ws.WsBuilder. + WsUrl("wss://api.huobi.pro/ws"). + AutoReconnect(). + DecompressFunc(GzipDecompress). + ProtoHandleFunc(ws.handle) + return ws +} + +func (ws *SpotWs) DepthCallback(call func(depth *Depth)) { + ws.depthCallback = call +} + +func (ws *SpotWs) TickerCallback(call func(ticker *Ticker)) { + ws.tickerCallback = call +} +func (ws *SpotWs) TradeCallback(call func(trade *Trade)) { + ws.tradeCallback = call +} + +func (ws *SpotWs) connectWs() { + ws.Do(func() { + ws.wsConn = ws.WsBuilder.Build() + }) +} + +func (ws *SpotWs) subscribe(sub map[string]interface{}) error { + ws.connectWs() + return ws.wsConn.Subscribe(sub) +} + +func (ws *SpotWs) SubscribeDepth(pair CurrencyPair) error { + if ws.depthCallback == nil { + return errors.New("please set depth callback func") + } + return ws.subscribe(map[string]interface{}{ + "id": "spot.depth", + "sub": fmt.Sprintf("market.%s.depth.step0", pair.ToLower().ToSymbol(""))}) +} + +func (ws *SpotWs) SubscribeTicker(pair CurrencyPair) error { + if ws.tickerCallback == nil { + return errors.New("please set ticker call back func") + } + return ws.subscribe(map[string]interface{}{ + "id": "spot.ticker", + "sub": fmt.Sprintf("market.%s.detail", pair.ToLower().ToSymbol("")), + }) + return nil +} + +func (ws *SpotWs) SubscribeTrade(pair CurrencyPair) error { + return nil +} + +func (ws *SpotWs) handle(msg []byte) error { + if bytes.Contains(msg, []byte("ping")) { + pong := bytes.ReplaceAll(msg, []byte("ping"), []byte("pong")) + ws.wsConn.SendMessage(pong) + return nil + } + + var resp WsResponse + err := json.Unmarshal(msg, &resp) + if err != nil { + return err + } + + if strings.Contains(resp.Ch, "depth.step") { + var ( + depthResp DepthResponse + ) + + err := json.Unmarshal(resp.Tick, &depthResp) + if err != nil { + return err + } + + dep := ParseDepthFromResponse(depthResp) + ws.depthCallback(&dep) + + return nil + } + + if strings.Contains(resp.Ch, ".detail") { + var tickerResp DetailResponse + err := json.Unmarshal(resp.Tick, &tickerResp) + if err != nil { + return err + } + ws.tickerCallback(&Ticker{ + Pair: ParseCurrencyPairFromSpotWsCh(resp.Ch), + Last: tickerResp.Close, + High: tickerResp.High, + Low: tickerResp.Low, + Vol: tickerResp.Amount, + Date: uint64(resp.Ts), + }) + return nil + } + + logger.Errorf("[%s] unknown message ch , msg=%s", ws.wsConn.WsUrl, string(msg)) + + return nil +} diff --git a/huobi/HuobiSpot_Ws_test.go b/huobi/HuobiSpot_Ws_test.go new file mode 100644 index 00000000..b64d2a85 --- /dev/null +++ b/huobi/HuobiSpot_Ws_test.go @@ -0,0 +1,28 @@ +package huobi + +import ( + "github.com/nntaoli-project/goex" + "os" + "testing" + "time" +) + +func TestNewSpotWs(t *testing.T) { + os.Setenv("HTTPS_PROXY", "socks5://127.0.0.1:1080") + spotWs := NewSpotWs() + spotWs.DepthCallback(func(depth *goex.Depth) { + t.Log("asks=", depth.AskList) + t.Log("bids=", depth.BidList) + }) + spotWs.TickerCallback(func(ticker *goex.Ticker) { + t.Log(ticker) + }) + spotWs.SubscribeTicker(goex.NewCurrencyPair2("BTC_USDT")) + spotWs.SubscribeTicker(goex.NewCurrencyPair2("USDT_HUSD")) + spotWs.SubscribeTicker(goex.NewCurrencyPair2("LTC_BTC")) + spotWs.SubscribeTicker(goex.NewCurrencyPair2("EOS_ETH")) + spotWs.SubscribeTicker(goex.NewCurrencyPair2("LTC_HT")) + spotWs.SubscribeTicker(goex.NewCurrencyPair2("BTT_TRX")) + //spotWs.SubscribeDepth(goex.BTC_USDT) + time.Sleep(time.Minute) +} diff --git a/huobi/Parser.go b/huobi/Parser.go new file mode 100644 index 00000000..b38b4639 --- /dev/null +++ b/huobi/Parser.go @@ -0,0 +1,65 @@ +package huobi + +import ( + "fmt" + "github.com/nntaoli-project/goex" + "github.com/nntaoli-project/goex/internal/logger" + "sort" + "strings" +) + +func ParseDepthFromResponse(r DepthResponse) goex.Depth { + var dep goex.Depth + for _, bid := range r.Bids { + dep.BidList = append(dep.BidList, goex.DepthRecord{Price: bid[0], Amount: bid[1]}) + } + + for _, ask := range r.Asks { + dep.AskList = append(dep.AskList, goex.DepthRecord{Price: ask[0], Amount: ask[1]}) + } + + sort.Sort(sort.Reverse(dep.BidList)) + sort.Sort(sort.Reverse(dep.AskList)) + return dep +} + +func ParseCurrencyPairFromSpotWsCh(ch string) goex.CurrencyPair { + meta := strings.Split(ch, ".") + if len(meta) < 2 { + logger.Errorf("parse error, ch=%s", ch) + return goex.UNKNOWN_PAIR + } + + currencyPairStr := meta[1] + if strings.HasSuffix(currencyPairStr, "usdt") { + currencyA := strings.TrimSuffix(currencyPairStr, "usdt") + return goex.NewCurrencyPair2(fmt.Sprintf("%s_usdt", currencyA)) + } + + if strings.HasSuffix(currencyPairStr, "btc") { + currencyA := strings.TrimSuffix(currencyPairStr, "btc") + return goex.NewCurrencyPair2(fmt.Sprintf("%s_btc", currencyA)) + } + + if strings.HasSuffix(currencyPairStr, "eth") { + currencyA := strings.TrimSuffix(currencyPairStr, "eth") + return goex.NewCurrencyPair2(fmt.Sprintf("%s_eth", currencyA)) + } + + if strings.HasSuffix(currencyPairStr, "husd") { + currencyA := strings.TrimSuffix(currencyPairStr, "husd") + return goex.NewCurrencyPair2(fmt.Sprintf("%s_husd", currencyA)) + } + + if strings.HasSuffix(currencyPairStr, "ht") { + currencyA := strings.TrimSuffix(currencyPairStr, "ht") + return goex.NewCurrencyPair2(fmt.Sprintf("%s_ht", currencyA)) + } + + if strings.HasSuffix(currencyPairStr, "trx") { + currencyA := strings.TrimSuffix(currencyPairStr, "trx") + return goex.NewCurrencyPair2(fmt.Sprintf("%s_trx", currencyA)) + } + + return goex.UNKNOWN_PAIR +} From 685fd5d05c41ba4a4c00081c0fb17c05a161f7ea Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Wed, 20 May 2020 18:32:50 +0800 Subject: [PATCH 24/27] [huobi and hbdm] ws depth faster --- huobi/Hbdm_Ws.go | 4 ++-- huobi/HuobiSpot_Ws.go | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/huobi/Hbdm_Ws.go b/huobi/Hbdm_Ws.go index e1744389..19a67d74 100644 --- a/huobi/Hbdm_Ws.go +++ b/huobi/Hbdm_Ws.go @@ -112,8 +112,8 @@ func (hbdmWs *HbdmWs) SubscribeDepth(pair CurrencyPair, contract string) error { return errors.New("please set depth callback func") } return hbdmWs.subscribe(map[string]interface{}{ - "id": "depth_2", - "sub": fmt.Sprintf("market.%s_%s.depth.step6", pair.CurrencyA.Symbol, hbdmWs.adaptContractSymbol(contract))}) + "id": "futures.depth", + "sub": fmt.Sprintf("market.%s_%s.depth.size_20.high_freq", pair.CurrencyA.Symbol, hbdmWs.adaptContractSymbol(contract))}) } func (hbdmWs *HbdmWs) SubscribeTrade(pair CurrencyPair, contract string) error { diff --git a/huobi/HuobiSpot_Ws.go b/huobi/HuobiSpot_Ws.go index a64a1611..d1f9e677 100644 --- a/huobi/HuobiSpot_Ws.go +++ b/huobi/HuobiSpot_Ws.go @@ -9,6 +9,7 @@ import ( "github.com/nntaoli-project/goex/internal/logger" "strings" "sync" + "time" ) type SpotWs struct { @@ -61,7 +62,7 @@ func (ws *SpotWs) SubscribeDepth(pair CurrencyPair) error { } return ws.subscribe(map[string]interface{}{ "id": "spot.depth", - "sub": fmt.Sprintf("market.%s.depth.step0", pair.ToLower().ToSymbol(""))}) + "sub": fmt.Sprintf("market.%s.mbp.refresh.20", pair.ToLower().ToSymbol(""))}) } func (ws *SpotWs) SubscribeTicker(pair CurrencyPair) error { @@ -92,7 +93,8 @@ func (ws *SpotWs) handle(msg []byte) error { return err } - if strings.Contains(resp.Ch, "depth.step") { + currencyPair := ParseCurrencyPairFromSpotWsCh(resp.Ch) + if strings.Contains(resp.Ch, "mbp.refresh") { var ( depthResp DepthResponse ) @@ -103,6 +105,8 @@ func (ws *SpotWs) handle(msg []byte) error { } dep := ParseDepthFromResponse(depthResp) + dep.Pair = currencyPair + dep.UTime = time.Unix(0, resp.Ts*int64(time.Millisecond)) ws.depthCallback(&dep) return nil @@ -115,7 +119,7 @@ func (ws *SpotWs) handle(msg []byte) error { return err } ws.tickerCallback(&Ticker{ - Pair: ParseCurrencyPairFromSpotWsCh(resp.Ch), + Pair: currencyPair, Last: tickerResp.Close, High: tickerResp.High, Low: tickerResp.Low, From 3fbecceab40361faa18731c1628d694dda659cb5 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Thu, 21 May 2020 18:49:00 +0800 Subject: [PATCH 25/27] [huobi.pro] place order set client id --- huobi/HuobiPro.go | 1 + 1 file changed, 1 insertion(+) diff --git a/huobi/HuobiPro.go b/huobi/HuobiPro.go index fd405241..314f8766 100644 --- a/huobi/HuobiPro.go +++ b/huobi/HuobiPro.go @@ -231,6 +231,7 @@ func (hbpro *HuoBiPro) placeOrder(amount, price string, pair CurrencyPair, order path := "/v1/order/orders/place" params := url.Values{} params.Set("account-id", hbpro.accountId) + params.Set("client-order-id", GenerateOrderClientId(32)) params.Set("amount", FloatToString(ToFloat64(amount), int(symbol.AmountPrecision))) params.Set("symbol", pair.AdaptUsdToUsdt().ToLower().ToSymbol("")) params.Set("type", orderType) From be8fbd20ac105f251e962ee2dc4d56e734e48d75 Mon Sep 17 00:00:00 2001 From: nntaoli <2767415655@qq.com> Date: Fri, 22 May 2020 16:19:42 +0800 Subject: [PATCH 26/27] [hbdm] format price size --- Models.go | 15 ++++++++++ huobi/Hbdm.go | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/Models.go b/Models.go index 916a4fc4..ae341fa1 100644 --- a/Models.go +++ b/Models.go @@ -191,6 +191,21 @@ type HistoricalFunding struct { FundingTime time.Time `json:"funding_time"` } +type TickSize struct { + InstrumentID string + UnderlyingIndex string + QuoteCurrency string + PriceTickSize float64 //下单价格精度 + AmountTickSize float64 //数量精度 +} + +type FuturesContractInfo struct { + *TickSize + ContractVal float64 //合约面值(美元) + Delivery string //交割日期 + ContractType string // 本周 this_week 次周 next_week 季度 quarter +} + //api parameter struct type BorrowParameter struct { diff --git a/huobi/Hbdm.go b/huobi/Hbdm.go index 5b9f57f1..9ad23327 100644 --- a/huobi/Hbdm.go +++ b/huobi/Hbdm.go @@ -4,6 +4,8 @@ import ( "encoding/json" "errors" "fmt" + "github.com/nntaoli-project/goex/internal/logger" + "net/http" "net/url" "sort" "strings" @@ -51,6 +53,67 @@ const ( defaultBaseUrl = "https://api.hbdm.com" ) +var ( + FuturesContractInfos []FuturesContractInfo +) + +func init() { + go func() { + interval := time.Second + intervalTimer := time.NewTimer(interval) + + for { + select { + case <-intervalTimer.C: + var response struct { + Status string `json:"status"` + Data []struct { + Symbol string `json:"symbol"` + ContractCode string `json:"contract_code"` + ContractType string `json:"contract_type"` + ContractSize float64 `json:"contract_size"` + PriceTick float64 `json:"price_tick"` + DeliveryDate string `json:"delivery_date"` + CreateDate string `json:"create_date"` + ContractStatus int `json:"contract_status"` + } `json:"data"` + } + urlPath := "http://api.hbdm.pro/api/v1/contract_contract_info" + respBody, err := HttpGet5(http.DefaultClient, urlPath, map[string]string{}) + if err != nil { + logger.Error("[hbdm] get contract info error=", err) + goto reset + } + err = json.Unmarshal(respBody, &response) + if err != nil { + logger.Errorf("[hbdm] json unmarshal contract info error=%s", err) + goto reset + } + FuturesContractInfos = FuturesContractInfos[:0] + for _, info := range response.Data { + FuturesContractInfos = append(FuturesContractInfos, FuturesContractInfo{ + TickSize: &TickSize{ + InstrumentID: info.ContractCode, + UnderlyingIndex: info.Symbol, + QuoteCurrency: "", + PriceTickSize: info.PriceTick, + AmountTickSize: 0, + }, + ContractVal: info.ContractSize, + Delivery: info.DeliveryDate, + ContractType: info.ContractType, + }) + } + interval = 10 * time.Minute + reset: + intervalTimer.Reset(interval) + } + + } + + }() +} + func NewHbdm(conf *APIConfig) *Hbdm { if conf.Endpoint == "" { conf.Endpoint = defaultBaseUrl @@ -179,7 +242,7 @@ func (dm *Hbdm) PlaceFutureOrder(currencyPair CurrencyPair, contractType, price, params.Set("order_price_type", "opponent") //对手价下单 } else { params.Set("order_price_type", "limit") - params.Add("price", price) + params.Add("price", dm.formatPriceSize(contractType, currencyPair.CurrencyA, price)) } direction, offset := dm.adaptOpenType(openType) @@ -605,3 +668,20 @@ func (dm *Hbdm) doRequest(path string, params *url.Values, data interface{}) err return json.Unmarshal(ret.Data, data) } + +func (dm *Hbdm) formatPriceSize(contract string, currency Currency, price string) string { + var tickSize = 0 + for _, v := range FuturesContractInfos { + if (v.ContractType == contract || v.InstrumentID == contract) && v.UnderlyingIndex == currency.Symbol { + if v.PriceTickSize == 0 { + break + } + for v.PriceTickSize < 1 { + tickSize++ + v.PriceTickSize *= 10 + } + break + } + } + return FloatToString(ToFloat64(price), tickSize) +} From fe0a20694981c51d8a5a4eb67f5ae183262a3461 Mon Sep 17 00:00:00 2001 From: name Date: Sun, 24 May 2020 11:03:17 +0800 Subject: [PATCH 27/27] =?UTF-8?q?=E4=BF=AE=E5=A4=8DBinanceWs.SubscribeDept?= =?UTF-8?q?h=E6=96=B9=E6=B3=95=EF=BC=8C=E6=B7=B1=E5=BA=A6=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=A7=A3=E6=9E=90=E9=94=99=E8=AF=AFbug=EF=BC=8C?= =?UTF-8?q?=E5=AF=BC=E8=87=B4=E6=B2=A1=E6=9C=89=E6=B7=B1=E5=BA=A6=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=20=E4=BF=AE=E6=94=B9=E6=96=B9=E6=B3=95=E5=90=8D?= =?UTF-8?q?=EF=BC=9ABinanceWs.subscribe->BinanceWs.Subscribe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- binance/BinanceWs.go | 20 ++++++++++---------- binance/BinanceWs_test.go | 2 ++ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/binance/BinanceWs.go b/binance/BinanceWs.go index 8359a239..0bb2eb5d 100644 --- a/binance/BinanceWs.go +++ b/binance/BinanceWs.go @@ -92,7 +92,7 @@ func (bnWs *BinanceWs) SetCallbacks( bnWs.klineCallback = klineCallback } -func (bnWs *BinanceWs) subscribe(endpoint string, handle func(msg []byte) error) { +func (bnWs *BinanceWs) Subscribe(endpoint string, handle func(msg []byte) error) { wsConn := NewWsBuilder(). WsUrl(endpoint). AutoReconnect(). @@ -121,9 +121,9 @@ func (bnWs *BinanceWs) SubscribeDepth(pair CurrencyPair, size int) error { handle := func(msg []byte) error { rawDepth := struct { - LastUpdateID int64 `json:"lastUpdateId"` - Bids [][]interface{} `json:"bids"` - Asks [][]interface{} `json:"asks"` + LastUpdateID int64 `json:"T"` + Bids [][]interface{} `json:"b"` + Asks [][]interface{} `json:"a"` }{} err := json.Unmarshal(msg, &rawDepth) @@ -137,7 +137,7 @@ func (bnWs *BinanceWs) SubscribeDepth(pair CurrencyPair, size int) error { bnWs.depthCallback(depth) return nil } - bnWs.subscribe(endpoint, handle) + bnWs.Subscribe(endpoint, handle) return nil } @@ -170,7 +170,7 @@ func (bnWs *BinanceWs) SubscribeTicker(pair CurrencyPair) error { return errors.New("unknown message " + msgType) } } - bnWs.subscribe(endpoint, handle) + bnWs.Subscribe(endpoint, handle) return nil } @@ -217,7 +217,7 @@ func (bnWs *BinanceWs) SubscribeTrade(pair CurrencyPair) error { return errors.New("unknown message " + msgType) } } - bnWs.subscribe(endpoint, handle) + bnWs.Subscribe(endpoint, handle) return nil } @@ -256,7 +256,7 @@ func (bnWs *BinanceWs) SubscribeKline(pair CurrencyPair, period int) error { return errors.New("unknown message " + msgType) } } - bnWs.subscribe(endpoint, handle) + bnWs.Subscribe(endpoint, handle) return nil } @@ -341,7 +341,7 @@ func (bnWs *BinanceWs) SubscribeAggTrade(pair CurrencyPair, tradeCallback func(* return errors.New("unknown message " + msgType) } } - bnWs.subscribe(endpoint, handle) + bnWs.Subscribe(endpoint, handle) return nil } @@ -380,7 +380,7 @@ func (bnWs *BinanceWs) SubscribeDiffDepth(pair CurrencyPair, depthCallback func( depthCallback((*Depth)(unsafe.Pointer(diffDepth))) return nil } - bnWs.subscribe(endpoint, handle) + bnWs.Subscribe(endpoint, handle) return nil } diff --git a/binance/BinanceWs_test.go b/binance/BinanceWs_test.go index 1950d2af..b31d127b 100644 --- a/binance/BinanceWs_test.go +++ b/binance/BinanceWs_test.go @@ -12,6 +12,8 @@ var bnWs = NewBinanceWs() func init() { bnWs.proxyUrl = "socks5://127.0.0.1:1080" + //bnWs.SetBaseUrl("wss://fstream.binancezh.com/ws") + //bnWs.SetCombinedBaseURL("wss://fstream.binancezh.com/stream?streams=") bnWs.SetCallbacks(printfTicker, printfDepth, printfTrade, printfKline) }