diff --git a/anxhttp.go b/anxhttp.go index 72323cde..901d1b4f 100644 --- a/anxhttp.go +++ b/anxhttp.go @@ -1,88 +1,90 @@ package main import ( - "strconv" "bytes" "errors" - "time" - "log" "fmt" + "log" + "strconv" + "time" ) const ( - ANX_API_URL = "https://anxpro.com/" - ANX_API_VERSION = "3" - ANX_APIKEY = "apiKey" - ANX_DATA_TOKEN = "dataToken" - ANX_ORDER_NEW = "order/new" - ANX_ORDER_INFO = "order/info" - ANX_SEND = "send" - ANX_SUBACCOUNT_NEW = "subaccount/new" + ANX_API_URL = "https://anxpro.com/" + ANX_API_VERSION = "3" + ANX_APIKEY = "apiKey" + ANX_DATA_TOKEN = "dataToken" + ANX_ORDER_NEW = "order/new" + ANX_ORDER_INFO = "order/info" + ANX_SEND = "send" + ANX_SUBACCOUNT_NEW = "subaccount/new" ANX_RECEIVE_ADDRESS = "receive" - ANX_CREATE_ADDRESS = "receive/create" - ANX_TICKER = "money/ticker" + ANX_CREATE_ADDRESS = "receive/create" + ANX_TICKER = "money/ticker" ) type ANX struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration - APIKey, APISecret string + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration + APIKey, APISecret string TakerFee, MakerFee float64 + BaseCurrencies []string + Pairs []string } type ANXOrder struct { - OrderType string `json:"orderType"` - BuyTradedCurrency bool `json:"buyTradedCurrency"` - TradedCurrency string `json:"tradedCurrency"` - SettlementCurrency string `json:"settlementCurrency"` - TradedCurrencyAmount string `json:"tradedCurrencyAmount"` - SettlementCurrencyAmount string `json:"settlementCurrencyAmount"` + OrderType string `json:"orderType"` + BuyTradedCurrency bool `json:"buyTradedCurrency"` + TradedCurrency string `json:"tradedCurrency"` + SettlementCurrency string `json:"settlementCurrency"` + TradedCurrencyAmount string `json:"tradedCurrencyAmount"` + SettlementCurrencyAmount string `json:"settlementCurrencyAmount"` LimitPriceInSettlementCurrency string `json:"limitPriceInSettlementCurrency"` - ReplaceExistingOrderUUID string `json:"replaceExistingOrderUuid"` - ReplaceOnlyIfActive bool `json:"replaceOnlyIfActive"` + ReplaceExistingOrderUUID string `json:"replaceExistingOrderUuid"` + ReplaceOnlyIfActive bool `json:"replaceOnlyIfActive"` } type ANXOrderResponse struct { - BuyTradedCurrency bool `json:"buyTradedCurrency"` - ExecutedAverageRate string `json:"executedAverageRate"` + BuyTradedCurrency bool `json:"buyTradedCurrency"` + ExecutedAverageRate string `json:"executedAverageRate"` LimitPriceInSettlementCurrency string `json:"limitPriceInSettlementCurrency"` - OrderID string `json:"orderId"` - OrderStatus string `json:"orderStatus"` - OrderType string `json:"orderType"` - ReplaceExistingOrderUUID string `json:"replaceExistingOrderId"` - SettlementCurrency string `json:"settlementCurrency"` - SettlementCurrencyAmount string `json:"settlementCurrencyAmount"` - SettlementCurrencyOutstanding string `json:"settlementCurrencyOutstanding"` - Timestamp int64 `json:"timestamp"` - TradedCurrency string `json:"tradedCurrency"` - TradedCurrencyAmount string `json:"tradedCurrencyAmount"` - TradedCurrencyOutstanding string `json:"tradedCurrencyOutstanding"` + OrderID string `json:"orderId"` + OrderStatus string `json:"orderStatus"` + OrderType string `json:"orderType"` + ReplaceExistingOrderUUID string `json:"replaceExistingOrderId"` + SettlementCurrency string `json:"settlementCurrency"` + SettlementCurrencyAmount string `json:"settlementCurrencyAmount"` + SettlementCurrencyOutstanding string `json:"settlementCurrencyOutstanding"` + Timestamp int64 `json:"timestamp"` + TradedCurrency string `json:"tradedCurrency"` + TradedCurrencyAmount string `json:"tradedCurrencyAmount"` + TradedCurrencyOutstanding string `json:"tradedCurrencyOutstanding"` } type ANXTickerComponent struct { - Currency string `json:"currency"` - Display string `json:"display"` - DisplayShort string `json:"display_short"` - Value float64 `json:"value,string"` - ValueInt int64 `json:"value_int,string"` + Currency string `json:"currency"` + Display string `json:"display"` + DisplayShort string `json:"display_short"` + Value float64 `json:"value,string"` + ValueInt int64 `json:"value_int,string"` } type ANXTicker struct { Result string `json:"result"` - Data struct { - High ANXTickerComponent `json:"high"` - Low ANXTickerComponent `json:"low"` - Avg ANXTickerComponent `json:"avg"` - Vwap ANXTickerComponent `json:"vwap"` - Vol ANXTickerComponent `json:"vol"` - Last ANXTickerComponent `json:"last"` - Buy ANXTickerComponent `json:buy"` - Sell ANXTickerComponent `json:"sell"` - Now float64 `json:"now"` - UpdateTime float64 `json:"dataUpdateTime"` + Data struct { + High ANXTickerComponent `json:"high"` + Low ANXTickerComponent `json:"low"` + Avg ANXTickerComponent `json:"avg"` + Vwap ANXTickerComponent `json:"vwap"` + Vol ANXTickerComponent `json:"vol"` + Last ANXTickerComponent `json:"last"` + Buy ANXTickerComponent `json:buy"` + Sell ANXTickerComponent `json:"sell"` + Now float64 `json:"now"` + UpdateTime float64 `json:"dataUpdateTime"` } `json:"data"` } @@ -96,7 +98,7 @@ func (a *ANX) SetDefaults() { a.RESTPollingDelay = 10 } -func (a *ANX) GetName() (string) { +func (a *ANX) GetName() string { return a.Name } @@ -104,7 +106,7 @@ func (a *ANX) SetEnabled(enabled bool) { a.Enabled = enabled } -func (a *ANX) IsEnabled() (bool) { +func (a *ANX) IsEnabled() bool { return a.Enabled } @@ -121,8 +123,8 @@ func (a *ANX) SetAPIKeys(apiKey, apiSecret string) { a.APISecret = string(result) } -func (a *ANX) GetFee(maker bool) (float64) { - if (maker) { +func (a *ANX) GetFee(maker bool) float64 { + if maker { return a.MakerFee } else { return a.TakerFee @@ -138,13 +140,13 @@ func (a *ANX) Run() { go func() { ANXBTC := a.GetTicker("BTCUSD") log.Printf("ANX BTC: Last %f High %f Low %f Volume %f\n", ANXBTC.Data.Last.Value, ANXBTC.Data.High.Value, ANXBTC.Data.Low.Value, ANXBTC.Data.Vol.Value) - AddExchangeInfo(a.GetName(), "BTC", ANXBTC.Data.Last.Value, ANXBTC.Data.Vol.Value) + AddExchangeInfo(a.GetName(), "BTC", ANXBTC.Data.Last.Value, ANXBTC.Data.Vol.Value) }() time.Sleep(time.Second * a.RESTPollingDelay) } } -func (a *ANX) GetTicker(currency string) (ANXTicker) { +func (a *ANX) GetTicker(currency string) ANXTicker { var ticker ANXTicker err := SendHTTPGetRequest(fmt.Sprintf("%sapi/2/%s/%s", ANX_API_URL, currency, ANX_TICKER), true, &ticker) if err != nil { @@ -167,12 +169,12 @@ func (a *ANX) GetAPIKey(username, password, otp, deviceID string) (string, strin request["deviceId"] = deviceID type APIKeyResponse struct { - APIKey string `json:"apiKey"` - APISecret string `json:"apiSecret"` + APIKey string `json:"apiKey"` + APISecret string `json:"apiSecret"` ResultCode string `json:"resultCode"` - Timestamp int64 `json:"timestamp"` + Timestamp int64 `json:"timestamp"` } - var response APIKeyResponse + var response APIKeyResponse err := a.SendAuthenticatedHTTPRequest(ANX_APIKEY, request, &response) @@ -189,14 +191,14 @@ func (a *ANX) GetAPIKey(username, password, otp, deviceID string) (string, strin return response.APIKey, response.APISecret } -func (a *ANX) GetDataToken() (string) { +func (a *ANX) GetDataToken() string { request := make(map[string]interface{}) type DataTokenResponse struct { ResultCode string `json:"resultCode"` - Timestamp int64 `json:"timestamp"` - Token string `json:"token"` - UUID string `json:"uuid"` + Timestamp int64 `json:"timestamp"` + Token string `json:"token"` + UUID string `json:"uuid"` } var response DataTokenResponse @@ -215,7 +217,7 @@ func (a *ANX) GetDataToken() (string) { return response.Token } -func (a *ANX) NewOrder(orderType string, buy bool, tradedCurrency, tradedCurrencyAmount, settlementCurrency, settlementCurrencyAmount, limitPriceSettlement string, +func (a *ANX) NewOrder(orderType string, buy bool, tradedCurrency, tradedCurrencyAmount, settlementCurrency, settlementCurrencyAmount, limitPriceSettlement string, replace bool, replaceUUID string, replaceIfActive bool) { request := make(map[string]interface{}) @@ -241,8 +243,8 @@ func (a *ANX) NewOrder(orderType string, buy bool, tradedCurrency, tradedCurrenc request["order"] = order type OrderResponse struct { - OrderID string `json:"orderId"` - Timestamp int64 `json:"timestamp"` + OrderID string `json:"orderId"` + Timestamp int64 `json:"timestamp"` ResultCode string `json:"resultCode"` } var response OrderResponse @@ -265,9 +267,9 @@ func (a *ANX) OrderInfo(orderID string) (ANXOrderResponse, error) { request["orderId"] = orderID type OrderInfoResponse struct { - Order ANXOrderResponse `json:"order"` - ResultCode string `json:"resultCode"` - Timestamp int64 `json:"timestamp"` + Order ANXOrderResponse `json:"order"` + ResultCode string `json:"resultCode"` + Timestamp int64 `json:"timestamp"` } var response OrderInfoResponse @@ -277,7 +279,7 @@ func (a *ANX) OrderInfo(orderID string) (ANXOrderResponse, error) { log.Println(err) return ANXOrderResponse{}, err } - + if response.ResultCode != "OK" { log.Printf("Response code is not OK: %s\n", response.ResultCode) return ANXOrderResponse{}, errors.New(response.ResultCode) @@ -297,8 +299,8 @@ func (a *ANX) Send(currency, address, otp, amount string) (string, error) { type SendResponse struct { TransactionID string `json:"transactionId"` - ResultCode string `json:"resultCode"` - Timestamp int64 `json:"timestamp"` + ResultCode string `json:"resultCode"` + Timestamp int64 `json:"timestamp"` } var response SendResponse @@ -307,7 +309,7 @@ func (a *ANX) Send(currency, address, otp, amount string) (string, error) { if err != nil { return "", err } - + if response.ResultCode != "OK" { log.Printf("Response code is not OK: %s\n", response.ResultCode) return "", errors.New(response.ResultCode) @@ -323,7 +325,7 @@ func (a *ANX) CreateNewSubAccount(currency, name string) (string, error) { type SubaccountResponse struct { SubAccount string `json:"subAccount"` ResultCode string `json:"resultCode"` - Timestamp int64 `json:"timestamp"` + Timestamp int64 `json:"timestamp"` } var response SubaccountResponse @@ -349,10 +351,10 @@ func (a *ANX) GetDepositAddress(currency, name string, new bool) (string, error) } type AddressResponse struct { - Address string `json:"address"` + Address string `json:"address"` SubAccount string `json:"subAccount"` ResultCode string `json:"resultCode"` - Timestamp int64 `json:"timestamp"` + Timestamp int64 `json:"timestamp"` } var response AddressResponse @@ -381,7 +383,7 @@ func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interf path = fmt.Sprintf("api/%s/%s", ANX_API_VERSION, path) if params != nil { - for key, value:= range params { + for key, value := range params { request[key] = value } } @@ -396,23 +398,23 @@ func (a *ANX) SendAuthenticatedHTTPRequest(path string, params map[string]interf log.Printf("Request JSON: %s\n", PayloadJson) } - hmac := GetHMAC(HASH_SHA512, []byte(path + string("\x00") + string(PayloadJson)), []byte(a.APISecret)) + hmac := GetHMAC(HASH_SHA512, []byte(path+string("\x00")+string(PayloadJson)), []byte(a.APISecret)) headers := make(map[string]string) headers["Rest-Key"] = a.APIKey headers["Rest-Sign"] = Base64Encode([]byte(hmac)) headers["Content-Type"] = "application/json" - resp, err := SendHTTPRequest("POST", ANX_API_URL + path, headers, bytes.NewBuffer(PayloadJson)) + resp, err := SendHTTPRequest("POST", ANX_API_URL+path, headers, bytes.NewBuffer(PayloadJson)) if a.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - + err = JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") } - + return nil -} \ No newline at end of file +} diff --git a/bitfinexhttp.go b/bitfinexhttp.go index 64bb684c..43fceb28 100644 --- a/bitfinexhttp.go +++ b/bitfinexhttp.go @@ -1,44 +1,44 @@ package main import ( + "errors" "fmt" "log" - "errors" - "strings" "strconv" + "strings" "time" ) const ( - BITFINEX_API_URL = "https://api.bitfinex.com/v1/" - BITFINEX_API_VERSION = "1" - BITFINEX_TICKER = "pubticker/" - BITFINEX_STATS = "stats/" - BITFINEX_ORDERBOOK = "book/" - BITFINEX_TRADES = "trades/" - BITFINEX_SYMBOLS = "symbols/" - BITFINEX_SYMBOLS_DETAILS = "symbols_details/" - BITFINEX_DEPOSIT = "deposit/new" - BITFINEX_ORDER_NEW = "order/new" - BITFINEX_ORDER_CANCEL = "order/cancel" + BITFINEX_API_URL = "https://api.bitfinex.com/v1/" + BITFINEX_API_VERSION = "1" + BITFINEX_TICKER = "pubticker/" + BITFINEX_STATS = "stats/" + BITFINEX_ORDERBOOK = "book/" + BITFINEX_TRADES = "trades/" + BITFINEX_SYMBOLS = "symbols/" + BITFINEX_SYMBOLS_DETAILS = "symbols_details/" + BITFINEX_DEPOSIT = "deposit/new" + BITFINEX_ORDER_NEW = "order/new" + BITFINEX_ORDER_CANCEL = "order/cancel" BITFINEX_ORDER_CANCEL_MULTI = "order/cancel/multi" - BITFINEX_ORDER_CANCEL_ALL = "order/cancel/all" - BITFINEX_ORDER_STATUS = "order/status" - BITFINEX_ORDERS = "orders" - BITFINEX_POSITIONS = "positions" - BITFINEX_CLAIM_POSITION = "position/claim" - BITFINEX_HISTORY = "history" - BITFINEX_TRADE_HISTORY = "mytrades" - BITFINEX_OFFER_NEW = "offer/new" - BITFINEX_OFFER_CANCEL = "offer/cancel" - BITFINEX_OFFER_STATUS = "offer/status" - BITFINEX_OFFERS = "offers" - BITFINEX_CREDITS = "credits" - BITFINEX_SWAP_ACTIVE = "taken_swaps" - BITFINEX_SWAP_CLOSE = "swap/close" - BITFINEX_BALANCES = "balances" - BITFINEX_ACCOUNT_INFO = "account_infos" - BITFINEX_MARGIN_INFO = "margin_infos" + BITFINEX_ORDER_CANCEL_ALL = "order/cancel/all" + BITFINEX_ORDER_STATUS = "order/status" + BITFINEX_ORDERS = "orders" + BITFINEX_POSITIONS = "positions" + BITFINEX_CLAIM_POSITION = "position/claim" + BITFINEX_HISTORY = "history" + BITFINEX_TRADE_HISTORY = "mytrades" + BITFINEX_OFFER_NEW = "offer/new" + BITFINEX_OFFER_CANCEL = "offer/cancel" + BITFINEX_OFFER_STATUS = "offer/status" + BITFINEX_OFFERS = "offers" + BITFINEX_CREDITS = "credits" + BITFINEX_SWAP_ACTIVE = "taken_swaps" + BITFINEX_SWAP_CLOSE = "swap/close" + BITFINEX_BALANCES = "balances" + BITFINEX_ACCOUNT_INFO = "account_infos" + BITFINEX_MARGIN_INFO = "margin_infos" ) type BitfinexStats struct { @@ -47,72 +47,72 @@ type BitfinexStats struct { } type BitfinexTicker struct { - Mid float64 `json:",string"` - Bid float64 `json:",string"` - Ask float64 `json:",string"` - Last float64 `json:"Last_price,string"` - Low float64 `json:",string"` - High float64 `json:",string"` - Volume float64 `json:",string"` + Mid float64 `json:",string"` + Bid float64 `json:",string"` + Ask float64 `json:",string"` + Last float64 `json:"Last_price,string"` + Low float64 `json:",string"` + High float64 `json:",string"` + Volume float64 `json:",string"` Timestamp string } type MarginLimits struct { - On_Pair string - InitialMargin float64 `json:"initial_margin,string"` + On_Pair string + InitialMargin float64 `json:"initial_margin,string"` MarginRequirement float64 `json:"margin_requirement,string"` - TradableBalance float64 `json:"tradable_balance,string"` + TradableBalance float64 `json:"tradable_balance,string"` } type BitfinexMarginInfo struct { - MarginBalance float64 `json:"margin_balance,string"` - TradableBalance float64 `json:"tradable_balance,string"` - UnrealizedPL int64 `json:"unrealized_pl"` - UnrealizedSwap int64 `json:"unrealized_swap"` - NetValue float64 `json:"net_value,string"` - RequiredMargin int64 `json:"required_margin"` - Leverage float64 `json:"leverage,string"` - MarginRequirement float64 `json:"margin_requirement,string"` - MarginLimits []MarginLimits `json:"margin_limits"` - Message string + MarginBalance float64 `json:"margin_balance,string"` + TradableBalance float64 `json:"tradable_balance,string"` + UnrealizedPL int64 `json:"unrealized_pl"` + UnrealizedSwap int64 `json:"unrealized_swap"` + NetValue float64 `json:"net_value,string"` + RequiredMargin int64 `json:"required_margin"` + Leverage float64 `json:"leverage,string"` + MarginRequirement float64 `json:"margin_requirement,string"` + MarginLimits []MarginLimits `json:"margin_limits"` + Message string } type BitfinexActiveOrder struct { - ID int64 - Symbol string - Exchange string - Price float64 `json:"Price,string"` + ID int64 + Symbol string + Exchange string + Price float64 `json:"Price,string"` Avg_Execution_Price float64 `json:"Price,string"` - Side string - Type string - Timestamp string - Is_Live bool - Is_Cancelled bool - Was_Forced bool - OriginalAmount float64 `json:"original_amount,string"` - RemainingAmount float64 `json:"remaining_amount,string"` - ExecutedAmount float64 `json:"executed_amount,string"` + Side string + Type string + Timestamp string + Is_Live bool + Is_Cancelled bool + Was_Forced bool + OriginalAmount float64 `json:"original_amount,string"` + RemainingAmount float64 `json:"remaining_amount,string"` + ExecutedAmount float64 `json:"executed_amount,string"` } type BitfinexBalance struct { - Type string - Currency string - Amount string + Type string + Currency string + Amount string Available string } type BitfinexOffer struct { - Currency string - Rate float64 - Period int64 - Direction string - Type string - Timestamp time.Time - Is_Live bool - Is_Cancelled bool - Executed_Amount float64 + Currency string + Rate float64 + Period int64 + Direction string + Type string + Timestamp time.Time + Is_Live bool + Is_Cancelled bool + Executed_Amount float64 Remaining_Amount float64 - Original_Amount float64 + Original_Amount float64 } type BookStructure struct { @@ -120,7 +120,7 @@ type BookStructure struct { } type BitfinexFee struct { - Currency string + Currency string TakerFees float64 MakerFees float64 } @@ -131,30 +131,32 @@ type BitfinexOrderbook struct { } type TradeStructure struct { - Timestamp, Tid int64 + Timestamp, Tid int64 Price, Amount, Exchange, Type string } type SymbolsDetails struct { Pair, Initial_margin, Minimum_margin, Maximum_order_size, Minimum_order_size, Expiration string - Price_precision int + Price_precision int } type Bitfinex struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration APIKey, APISecret string - Ticker BitfinexTicker - Stats []BitfinexStats - Orderbook BitfinexOrderbook - Trades []TradeStructure - SymbolsDetails []SymbolsDetails - Fees []BitfinexFee - ActiveOrders []BitfinexActiveOrder - AccountBalance []BitfinexBalance + Ticker BitfinexTicker + Stats []BitfinexStats + Orderbook BitfinexOrderbook + Trades []TradeStructure + SymbolsDetails []SymbolsDetails + Fees []BitfinexFee + ActiveOrders []BitfinexActiveOrder + AccountBalance []BitfinexBalance + BaseCurrencies []string + Pairs []string } func (b *Bitfinex) SetDefaults() { @@ -165,7 +167,7 @@ func (b *Bitfinex) SetDefaults() { b.RESTPollingDelay = 10 } -func (b *Bitfinex) GetName() (string) { +func (b *Bitfinex) GetName() string { return b.Name } @@ -173,7 +175,7 @@ func (b *Bitfinex) SetEnabled(enabled bool) { b.Enabled = enabled } -func (b *Bitfinex) IsEnabled() (bool) { +func (b *Bitfinex) IsEnabled() bool { return b.Enabled } @@ -231,7 +233,7 @@ func (b *Bitfinex) GetAccountBalance() (bool, error) { func (b *Bitfinex) GetAccountFeeInfo() (bool, error) { type Fee struct { - Pairs string `json:"pairs"` + Pairs string `json:"pairs"` MakerFees string `json:"maker_fees"` TakerFees string `json:"taker_fees"` } @@ -267,7 +269,7 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ request["nonce"] = strconv.FormatInt(time.Now().UnixNano(), 10) if params != nil { - for key, value:= range params { + for key, value := range params { request[key] = value } } @@ -289,23 +291,23 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[ headers["X-BFX-PAYLOAD"] = PayloadBase64 headers["X-BFX-SIGNATURE"] = HexEncodeToString(hmac) - resp, err := SendHTTPRequest(method, BITFINEX_API_URL + path, headers, strings.NewReader("")) + resp, err := SendHTTPRequest(method, BITFINEX_API_URL+path, headers, strings.NewReader("")) if b.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - + err = JSONDecode([]byte(resp), &result) if err != nil { return errors.New("Unable to JSON Unmarshal response.") } - + return nil } -func (b *Bitfinex) GetTicker(symbol string) (BitfinexTicker) { - err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_TICKER + symbol, true, &b.Ticker) +func (b *Bitfinex) GetTicker(symbol string) BitfinexTicker { + err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_TICKER+symbol, true, &b.Ticker) if err != nil { log.Println(err) return BitfinexTicker{} @@ -313,8 +315,8 @@ func (b *Bitfinex) GetTicker(symbol string) (BitfinexTicker) { return b.Ticker } -func (b *Bitfinex) GetStats(symbol string) (bool) { - err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_STATS + symbol, true, &b.Stats) +func (b *Bitfinex) GetStats(symbol string) bool { + err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_STATS+symbol, true, &b.Stats) if err != nil { log.Println(err) return false @@ -322,8 +324,8 @@ func (b *Bitfinex) GetStats(symbol string) (bool) { return true } -func (b *Bitfinex) GetOrderbook(symbol string) (bool) { - err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_ORDERBOOK + symbol, true, &b.Orderbook) +func (b *Bitfinex) GetOrderbook(symbol string) bool { + err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_ORDERBOOK+symbol, true, &b.Orderbook) if err != nil { log.Println(err) return false @@ -331,8 +333,8 @@ func (b *Bitfinex) GetOrderbook(symbol string) (bool) { return true } -func (b *Bitfinex) GetTrades(symbol string) (bool) { - err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_TRADES + symbol, true, &b.Trades) +func (b *Bitfinex) GetTrades(symbol string) bool { + err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_TRADES+symbol, true, &b.Trades) if err != nil { log.Println(err) return false @@ -340,8 +342,8 @@ func (b *Bitfinex) GetTrades(symbol string) (bool) { return true } -func (b *Bitfinex) GetSymbols() (bool) { - err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_SYMBOLS, false, nil) +func (b *Bitfinex) GetSymbols() bool { + err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_SYMBOLS, false, nil) if err != nil { log.Println(err) return false @@ -349,8 +351,8 @@ func (b *Bitfinex) GetSymbols() (bool) { return true } -func (b *Bitfinex) GetSymbolsDetails() (bool) { - err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_SYMBOLS_DETAILS, false, &b.SymbolsDetails) +func (b *Bitfinex) GetSymbolsDetails() bool { + err := SendHTTPGetRequest(BITFINEX_API_URL+BITFINEX_SYMBOLS_DETAILS, false, &b.SymbolsDetails) if err != nil { log.Println(err) return false @@ -386,7 +388,7 @@ func (b *Bitfinex) NewOrder(Symbol string, Amount float64, Price float64, Buy bo //request["is_hidden"] - currently not implemented request["type"] = Type - + err := b.SendAuthenticatedHTTPRequest("POST", BITFINEX_ORDER_NEW, request, nil) if err != nil { @@ -394,7 +396,7 @@ func (b *Bitfinex) NewOrder(Symbol string, Amount float64, Price float64, Buy bo } } -func (b *Bitfinex) CancelOrder(OrderID int64) (bool) { +func (b *Bitfinex) CancelOrder(OrderID int64) bool { request := make(map[string]interface{}) request["order_id"] = OrderID @@ -432,7 +434,7 @@ func (b *Bitfinex) ReplaceOrder(OrderID int) { request["order_id"] = OrderID } -func (b *Bitfinex) GetOrderStatus(OrderID int64) (BitfinexActiveOrder) { +func (b *Bitfinex) GetOrderStatus(OrderID int64) BitfinexActiveOrder { request := make(map[string]interface{}) request["order_id"] = OrderID orderStatus := BitfinexActiveOrder{} @@ -447,7 +449,7 @@ func (b *Bitfinex) GetOrderStatus(OrderID int64) (BitfinexActiveOrder) { return orderStatus } -func (b *Bitfinex) GetActiveOrders() (bool) { +func (b *Bitfinex) GetActiveOrders() bool { err := b.SendAuthenticatedHTTPRequest("POST", BITFINEX_ORDERS, nil, &b.ActiveOrders) if err != nil { @@ -487,7 +489,7 @@ func (b *Bitfinex) GetBalanceHistory(symbol string, timeSince time.Time, timeUnt if limit > 0 { request["limit"] = limit } - + if len(wallet) > 0 { request["wallet"] = wallet } @@ -504,7 +506,7 @@ func (b *Bitfinex) GetTradeHistory(symbol string, timestamp time.Time, limit int request["currency"] = symbol request["timestamp"] = timestamp - if (limit > 0) { + if limit > 0 { request["limit_trades"] = limit } @@ -515,7 +517,7 @@ func (b *Bitfinex) GetTradeHistory(symbol string, timestamp time.Time, limit int } } -func (b *Bitfinex) NewOffer(symbol string, amount, rate float64, period int64, direction string) (int64) { +func (b *Bitfinex) NewOffer(symbol string, amount, rate float64, period int64, direction string) int64 { request := make(map[string]interface{}) request["currency"] = symbol request["amount"] = amount @@ -609,4 +611,3 @@ func (b *Bitfinex) GetMarginInfo() { log.Println(err) } } - diff --git a/bitstamphttp.go b/bitstamphttp.go index 5ecd4883..181c77bb 100644 --- a/bitstamphttp.go +++ b/bitstamphttp.go @@ -1,83 +1,85 @@ package main import ( - "net/url" - "log" - "strings" - "strconv" "errors" + "log" + "net/url" + "strconv" + "strings" "time" ) const ( - BITSTAMP_API_URL = "https://www.bitstamp.net/api/" - BITSTAMP_API_VERSION = "0" - BITSTAMP_API_TICKER = "ticker/" - BITSTAMP_API_ORDERBOOK = "order_book/" - BITSTAMP_API_TRANSACTIONS = "transactions/" - BITSTAMP_API_EURUSD = "eur_usd/" - BITSTAMP_API_BALANCE = "balance/" - BITSTAMP_API_USER_TRANSACTIONS = "user_transactions/" - BITSTAMP_API_OPEN_ORDERS = "open_orders/" - BITSTAMP_API_CANCEL_ORDER = "cancel_order/" - BITSTAMP_API_BUY = "buy/" - BITSTAMP_API_SELL = "sell/" + BITSTAMP_API_URL = "https://www.bitstamp.net/api/" + BITSTAMP_API_VERSION = "0" + BITSTAMP_API_TICKER = "ticker/" + BITSTAMP_API_ORDERBOOK = "order_book/" + BITSTAMP_API_TRANSACTIONS = "transactions/" + BITSTAMP_API_EURUSD = "eur_usd/" + BITSTAMP_API_BALANCE = "balance/" + BITSTAMP_API_USER_TRANSACTIONS = "user_transactions/" + BITSTAMP_API_OPEN_ORDERS = "open_orders/" + BITSTAMP_API_CANCEL_ORDER = "cancel_order/" + BITSTAMP_API_BUY = "buy/" + BITSTAMP_API_SELL = "sell/" BITSTAMP_API_WITHDRAWAL_REQUESTS = "withdrawal_requests/" - BITSTAMP_API_BITCOIN_WITHDRAWAL = "bitcoin_withdrawal/" - BITSTAMP_API_BITCOIN_DEPOSIT = "bitcoin_deposit_address/" + BITSTAMP_API_BITCOIN_WITHDRAWAL = "bitcoin_withdrawal/" + BITSTAMP_API_BITCOIN_DEPOSIT = "bitcoin_deposit_address/" BITSTAMP_API_UNCONFIRMED_BITCOIN = "unconfirmed_btc/" - BITSTAMP_API_RIPPLE_WITHDRAWAL = "ripple_withdrawal/" - BITSTAMP_API_RIPPLE_DESPOIT = "ripple_address/" + BITSTAMP_API_RIPPLE_WITHDRAWAL = "ripple_withdrawal/" + BITSTAMP_API_RIPPLE_DESPOIT = "ripple_address/" ) -type Bitstamp struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration +type Bitstamp struct { + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration ClientID, APIKey, APISecret string - Ticker BitstampTicker - Orderbook Orderbook - ConversionRate ConversionRate - Transactions []Transactions - Balance BitstampAccountBalance - TakerFee, MakerFee float64 + Ticker BitstampTicker + Orderbook Orderbook + ConversionRate ConversionRate + Transactions []Transactions + Balance BitstampAccountBalance + TakerFee, MakerFee float64 + BaseCurrencies []string + Pairs []string } type BitstampTicker struct { - Last float64 `json:",string"` - High float64 `json:",string"` - Low float64 `json:",string"` - Vwap float64 `json:",string"` + Last float64 `json:",string"` + High float64 `json:",string"` + Low float64 `json:",string"` + Vwap float64 `json:",string"` Volume float64 `json:",string"` - Bid float64 `json:",string"` - Ask float64 `json:",string"` + Bid float64 `json:",string"` + Ask float64 `json:",string"` } type BitstampAccountBalance struct { - BTCReserved float64 `json:"usd_balance,string"` - Fee float64 `json:",string"` + BTCReserved float64 `json:"usd_balance,string"` + Fee float64 `json:",string"` BTCAvailable float64 `json:"btc_balance,string"` - USDReserved float64 `json:"usd_reserved,string"` - BTCBalance float64 `json:"btc_balance,string"` - USDBalance float64 `json:"usd_balance,string"` + USDReserved float64 `json:"usd_reserved,string"` + BTCBalance float64 `json:"btc_balance,string"` + USDBalance float64 `json:"usd_balance,string"` USDAvailable float64 `json:"usd_available,string"` } type Orderbook struct { Timestamp string - Bids [][]string - Asks [][]string + Bids [][]string + Asks [][]string } type Transactions struct { Date, Price, Amount string - Tid int64 + Tid int64 } type ConversionRate struct { - Buy string + Buy string Sell string } @@ -89,7 +91,7 @@ func (b *Bitstamp) SetDefaults() { b.RESTPollingDelay = 10 } -func (b *Bitstamp) GetName() (string) { +func (b *Bitstamp) GetName() string { return b.Name } @@ -97,11 +99,11 @@ func (b *Bitstamp) SetEnabled(enabled bool) { b.Enabled = enabled } -func (b *Bitstamp) IsEnabled() (bool) { +func (b *Bitstamp) IsEnabled() bool { return b.Enabled } -func (b *Bitstamp) GetFee() (float64) { +func (b *Bitstamp) GetFee() float64 { return b.Balance.Fee } @@ -133,11 +135,11 @@ func (b *Bitstamp) Run() { } } -func (b *Bitstamp) GetTicker() (BitstampTicker) { - err := SendHTTPGetRequest(BITSTAMP_API_URL + BITSTAMP_API_TICKER, true, &b.Ticker) +func (b *Bitstamp) GetTicker() BitstampTicker { + err := SendHTTPGetRequest(BITSTAMP_API_URL+BITSTAMP_API_TICKER, true, &b.Ticker) if err != nil { - log.Println(err) + log.Println(err) return BitstampTicker{} } @@ -145,28 +147,28 @@ func (b *Bitstamp) GetTicker() (BitstampTicker) { } func (b *Bitstamp) GetOrderbook() { - err := SendHTTPGetRequest(BITSTAMP_API_URL + BITSTAMP_API_ORDERBOOK, true, &b.Orderbook) + err := SendHTTPGetRequest(BITSTAMP_API_URL+BITSTAMP_API_ORDERBOOK, true, &b.Orderbook) if err != nil { - log.Println(err) + log.Println(err) return } } func (b *Bitstamp) GetTransactions() { - err := SendHTTPGetRequest(BITSTAMP_API_URL + BITSTAMP_API_TRANSACTIONS, true, &b.Transactions) + err := SendHTTPGetRequest(BITSTAMP_API_URL+BITSTAMP_API_TRANSACTIONS, true, &b.Transactions) if err != nil { - log.Println(err) + log.Println(err) return } } func (b *Bitstamp) GetEURUSDConversionRate() { - err := SendHTTPGetRequest(BITSTAMP_API_URL + BITSTAMP_API_EURUSD, true, &b.ConversionRate) + err := SendHTTPGetRequest(BITSTAMP_API_URL+BITSTAMP_API_EURUSD, true, &b.ConversionRate) if err != nil { - log.Println(err) + log.Println(err) return } } @@ -220,7 +222,7 @@ func (b *Bitstamp) PlaceOrder(price float64, amount float64, Type int) { if Type == 1 { orderType = BITSTAMP_API_SELL - } + } log.Printf("Placing %s order at price %f for %f amount.\n", orderType, price, amount) @@ -292,7 +294,7 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, values url.Values, nonce := strconv.FormatInt(time.Now().UnixNano(), 10) values.Set("key", b.APIKey) values.Set("nonce", nonce) - hmac := GetHMAC(HASH_SHA256, []byte(nonce + b.ClientID + b.APIKey), []byte(b.APISecret)) + hmac := GetHMAC(HASH_SHA256, []byte(nonce+b.ClientID+b.APIKey), []byte(b.APISecret)) values.Set("signature", strings.ToUpper(HexEncodeToString(hmac))) path = BITSTAMP_API_URL + path @@ -319,4 +321,4 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, values url.Values, } return nil -} \ No newline at end of file +} diff --git a/btcchinahttp.go b/btcchinahttp.go index 944ac585..bad817eb 100644 --- a/btcchinahttp.go +++ b/btcchinahttp.go @@ -1,129 +1,131 @@ package main import ( - "net/url" - "strconv" "errors" - "strings" - "time" "fmt" "log" + "net/url" + "strconv" + "strings" + "time" ) const ( - BTCCHINA_API_URL = "https://api.btcchina.com/" + BTCCHINA_API_URL = "https://api.btcchina.com/" BTCCHINA_API_AUTHENTICATED_METHOD = "api_trade_v1.php" - BTCCHINA_API_VER = "2.0.1.3" - BTCCHINA_ORDER_BUY = "buyOrder2" - BTCCHINA_ORDER_SELL = "sellOrder2" - BTCCHINA_ORDER_CANCEL = "cancelOrder" - BTCCHINA_ICEBERG_BUY = "buyIcebergOrder" - BTCCHINA_ICEBERG_SELL = "sellIcebergOrder" - BTCCHINA_ICEBERG_ORDER = "getIcebergOrder" - BTCCHINA_ICEBERG_ORDERS = "getIcebergOrders" - BTCCHINA_ICEBERG_CANCEL = "cancelIcebergOrder" - BTCCHINA_ACCOUNT_INFO = "getAccountInfo" - BTCCHINA_DEPOSITS = "getDeposits" - BTCCHINA_MARKETDEPTH = "getMarketDepth2" - BTCCHINA_ORDER = "getOrder" - BTCCHINA_ORDERS = "getOrders" - BTCCHINA_TRANSACTIONS = "getTransactions" - BTCCHINA_WITHDRAWAL = "getWithdrawal" - BTCCHINA_WITHDRAWALS = "getWithdrawals" - BTCCHINA_WITHDRAWAL_REQUEST = "requestWithdrawal" - BTCCHINA_STOPORDER_BUY = "buyStopOrder" - BTCCHINA_STOPORDER_SELL = "sellStopOrder" - BTCCHINA_STOPORDER_CANCEL = "cancelStopOrder" - BTCCHINA_STOPORDER = "getStopOrder" - BTCCHINA_STOPORDERS = "getStopOrders" + BTCCHINA_API_VER = "2.0.1.3" + BTCCHINA_ORDER_BUY = "buyOrder2" + BTCCHINA_ORDER_SELL = "sellOrder2" + BTCCHINA_ORDER_CANCEL = "cancelOrder" + BTCCHINA_ICEBERG_BUY = "buyIcebergOrder" + BTCCHINA_ICEBERG_SELL = "sellIcebergOrder" + BTCCHINA_ICEBERG_ORDER = "getIcebergOrder" + BTCCHINA_ICEBERG_ORDERS = "getIcebergOrders" + BTCCHINA_ICEBERG_CANCEL = "cancelIcebergOrder" + BTCCHINA_ACCOUNT_INFO = "getAccountInfo" + BTCCHINA_DEPOSITS = "getDeposits" + BTCCHINA_MARKETDEPTH = "getMarketDepth2" + BTCCHINA_ORDER = "getOrder" + BTCCHINA_ORDERS = "getOrders" + BTCCHINA_TRANSACTIONS = "getTransactions" + BTCCHINA_WITHDRAWAL = "getWithdrawal" + BTCCHINA_WITHDRAWALS = "getWithdrawals" + BTCCHINA_WITHDRAWAL_REQUEST = "requestWithdrawal" + BTCCHINA_STOPORDER_BUY = "buyStopOrder" + BTCCHINA_STOPORDER_SELL = "sellStopOrder" + BTCCHINA_STOPORDER_CANCEL = "cancelStopOrder" + BTCCHINA_STOPORDER = "getStopOrder" + BTCCHINA_STOPORDERS = "getStopOrders" ) type BTCChina struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration APISecret, APIKey string - Fee float64 + Fee float64 + BaseCurrencies []string + Pairs []string } type BTCChinaTicker struct { - High float64 `json:",string"` - Low float64 `json:",string"` - Buy float64 `json:",string"` - Sell float64 `json:",string"` - Last float64 `json:",string"` - Vol float64 `json:",string"` - Date int64 - Vwap float64 `json:",string"` + High float64 `json:",string"` + Low float64 `json:",string"` + Buy float64 `json:",string"` + Sell float64 `json:",string"` + Last float64 `json:",string"` + Vol float64 `json:",string"` + Date int64 + Vwap float64 `json:",string"` Prev_close float64 `json:",string"` - Open float64 `json:",string"` + Open float64 `json:",string"` } type BTCChinaProfile struct { - Username string - TradePasswordEnabled bool `json:"trade_password_enabled,bool"` - OTPEnabled bool `json:"otp_enabled,bool"` - TradeFee float64 `json:"trade_fee"` - TradeFeeCNYLTC float64 `json:"trade_fee_cnyltc"` - TradeFeeBTCLTC float64 `json:"trade_fee_btcltc"` - DailyBTCLimit float64 `json:"daily_btc_limit"` - DailyLTCLimit float64 `json:"daily_ltc_limit"` - BTCDespoitAddress string `json:"btc_despoit_address"` - BTCWithdrawalAddress string `json:"btc_withdrawal_address"` - LTCDepositAddress string `json:"ltc_deposit_address"` - LTCWithdrawalAddress string `json:"ltc_withdrawal_request"` - APIKeyPermission int64 `json:"api_key_permission"` + Username string + TradePasswordEnabled bool `json:"trade_password_enabled,bool"` + OTPEnabled bool `json:"otp_enabled,bool"` + TradeFee float64 `json:"trade_fee"` + TradeFeeCNYLTC float64 `json:"trade_fee_cnyltc"` + TradeFeeBTCLTC float64 `json:"trade_fee_btcltc"` + DailyBTCLimit float64 `json:"daily_btc_limit"` + DailyLTCLimit float64 `json:"daily_ltc_limit"` + BTCDespoitAddress string `json:"btc_despoit_address"` + BTCWithdrawalAddress string `json:"btc_withdrawal_address"` + LTCDepositAddress string `json:"ltc_deposit_address"` + LTCWithdrawalAddress string `json:"ltc_withdrawal_request"` + APIKeyPermission int64 `json:"api_key_permission"` } type BTCChinaCurrencyGeneric struct { - Currency string - Symbol string - Amount string - AmountInt int64 `json:"amount_integer"` + Currency string + Symbol string + Amount string + AmountInt int64 `json:"amount_integer"` AmountDecimal float64 `json:"amount_decimal"` } type BTCChinaOrder struct { - ID int64 - Type string - Price float64 - Currency string - Amount float64 + ID int64 + Type string + Price float64 + Currency string + Amount float64 AmountOrig float64 `json:"amount_original"` - Date int64 - Status string - Detail BTCChinaOrderDetail + Date int64 + Status string + Detail BTCChinaOrderDetail } type BTCChinaOrderDetail struct { Dateline int64 - Price float64 - Amount float64 + Price float64 + Amount float64 } type BTCChinaWithdrawal struct { - ID int64 - Address string - Currency string - Amount float64 - Date int64 + ID int64 + Address string + Currency string + Amount float64 + Date int64 Transaction string - Status string + Status string } type BTCChinaDeposit struct { - ID int64 - Address string + ID int64 + Address string Currency string - Amount float64 - Date int64 - Status string + Amount float64 + Date int64 + Status string } type BTCChinaBidAsk struct { - Price float64 + Price float64 Amount float64 } @@ -133,39 +135,39 @@ type BTCChinaDepth struct { } type BTCChinaTransaction struct { - ID int64 - Type string + ID int64 + Type string BTCAmount float64 `json:"btc_amount"` LTCAmount float64 `json:"ltc_amount"` CNYAmount float64 `json:"cny_amount"` - Date int64 + Date int64 } type BTCChinaIcebergOrder struct { - ID int64 - Type string - Price float64 - Market string - Amount float64 - AmountOrig float64 `json:"amount_original"` + ID int64 + Type string + Price float64 + Market string + Amount float64 + AmountOrig float64 `json:"amount_original"` DisclosedAmount float64 `json:"disclosed_amount"` - Variance float64 - Date int64 - Status string + Variance float64 + Date int64 + Status string } type BTCChinaStopOrder struct { - ID int64 - Type string - StopPrice float64 `json:"stop_price"` + ID int64 + Type string + StopPrice float64 `json:"stop_price"` TrailingAmt float64 `json:"trailing_amount"` TrailingPct float64 `json:"trailing_percentage"` - Price float64 - Market string - Amount float64 - Date int64 - Status string - OrderID int64 `json:"order_id"` + Price float64 + Market string + Amount float64 + Date int64 + Status string + OrderID int64 `json:"order_id"` } func (b *BTCChina) SetDefaults() { @@ -177,7 +179,7 @@ func (b *BTCChina) SetDefaults() { b.RESTPollingDelay = 10 } -func (b *BTCChina) GetName() (string) { +func (b *BTCChina) GetName() string { return b.Name } @@ -185,7 +187,7 @@ func (b *BTCChina) SetEnabled(enabled bool) { b.Enabled = enabled } -func (b *BTCChina) IsEnabled() (bool) { +func (b *BTCChina) IsEnabled() bool { return b.Enabled } @@ -194,7 +196,7 @@ func (b *BTCChina) SetAPIKeys(apiKey, apiSecret string) { b.APISecret = apiSecret } -func (b *BTCChina) GetFee() (float64) { +func (b *BTCChina) GetFee() float64 { return b.Fee } @@ -206,14 +208,14 @@ func (b *BTCChina) Run() { if b.Websocket { go b.WebsocketClient() } - + for b.Enabled { go func() { BTCChinaBTC := b.GetTicker("btccny") BTCChinaBTCLastUSD, _ := ConvertCurrency(BTCChinaBTC.Last, "CNY", "USD") BTCChinaBTCHighUSD, _ := ConvertCurrency(BTCChinaBTC.High, "CNY", "USD") BTCChinaBTCLowUSD, _ := ConvertCurrency(BTCChinaBTC.Low, "CNY", "USD") - log.Printf("BTCChina BTC: Last %f (%f) High %f (%f) Low %f (%f) Volume %f\n", BTCChinaBTCLastUSD, BTCChinaBTC.Last, BTCChinaBTCHighUSD, BTCChinaBTC.High, BTCChinaBTCLowUSD, BTCChinaBTC.Low, BTCChinaBTC.Vol) + log.Printf("BTCChina BTC: Last %f (%f) High %f (%f) Low %f (%f) Volume %f\n", BTCChinaBTCLastUSD, BTCChinaBTC.Last, BTCChinaBTCHighUSD, BTCChinaBTC.High, BTCChinaBTCLowUSD, BTCChinaBTC.Low, BTCChinaBTC.Vol) AddExchangeInfo(b.GetName(), "BTC", BTCChinaBTCLastUSD, BTCChinaBTC.Vol) }() @@ -229,7 +231,7 @@ func (b *BTCChina) Run() { } } -func (b *BTCChina) GetTicker(symbol string) (BTCChinaTicker) { +func (b *BTCChina) GetTicker(symbol string) BTCChinaTicker { type Response struct { Ticker BTCChinaTicker } @@ -244,7 +246,7 @@ func (b *BTCChina) GetTicker(symbol string) (BTCChinaTicker) { return resp.Ticker } -func (b *BTCChina) GetTradesLast24h(symbol string) (bool) { +func (b *BTCChina) GetTradesLast24h(symbol string) bool { req := fmt.Sprintf("%sdata/trades?market=%s", BTCCHINA_API_URL, symbol) err := SendHTTPGetRequest(req, true, nil) if err != nil { @@ -254,7 +256,7 @@ func (b *BTCChina) GetTradesLast24h(symbol string) (bool) { return true } -func (b *BTCChina) GetTradeHistory(symbol string, limit, sinceTid int64, time time.Time) (bool) { +func (b *BTCChina) GetTradeHistory(symbol string, limit, sinceTid int64, time time.Time) bool { req := fmt.Sprintf("%sdata/historydata?market=%s", BTCCHINA_API_URL, symbol) v := url.Values{} @@ -269,7 +271,7 @@ func (b *BTCChina) GetTradeHistory(symbol string, limit, sinceTid int64, time ti } values := v.Encode() - if (len(values) > 0) { + if len(values) > 0 { req += "?" + values } @@ -281,7 +283,7 @@ func (b *BTCChina) GetTradeHistory(symbol string, limit, sinceTid int64, time ti return true } -func (b *BTCChina) GetOrderBook(symbol string, limit int) (bool) { +func (b *BTCChina) GetOrderBook(symbol string, limit int) bool { req := fmt.Sprintf("%sdata/orderbook?market=%s&limit=%d", BTCCHINA_API_URL, symbol, limit) err := SendHTTPGetRequest(req, true, nil) if err != nil { @@ -314,7 +316,7 @@ func (b *BTCChina) PlaceOrder(buyOrder bool, price, amount float64, market strin params = append(params, market) } - req := BTCCHINA_ORDER_BUY + req := BTCCHINA_ORDER_BUY if !buyOrder { req = BTCCHINA_ORDER_SELL } @@ -461,7 +463,7 @@ func (b *BTCChina) GetWithdrawal(withdrawalID int64, currency string) { params := make([]interface{}, 0) params = append(params, withdrawalID) - if (len(currency) > 0) { + if len(currency) > 0 { params = append(params, currency) } @@ -476,7 +478,7 @@ func (b *BTCChina) GetWithdrawals(currency string, pending bool) { params := make([]interface{}, 0) params = append(params, currency) - if (pending) { + if pending { params = append(params, pending) } @@ -529,7 +531,7 @@ func (b *BTCChina) GetIcebergOrder(orderID int64, market string) { if len(market) > 0 { params = append(params, market) } - + err := b.SendAuthenticatedHTTPRequest(BTCCHINA_ICEBERG_ORDER, params) if err != nil { @@ -539,7 +541,7 @@ func (b *BTCChina) GetIcebergOrder(orderID int64, market string) { func (b *BTCChina) GetIcebergOrders(limit, offset int64, market string) { params := make([]interface{}, 0) - + if limit > 0 { params = append(params, limit) } @@ -547,7 +549,7 @@ func (b *BTCChina) GetIcebergOrders(limit, offset int64, market string) { if offset > 0 { params = append(params, offset) } - + if len(market) > 0 { params = append(params, market) } @@ -566,7 +568,7 @@ func (b *BTCChina) CancelIcebergOrder(orderID int64, market string) { if len(market) > 0 { params = append(params, market) } - + err := b.SendAuthenticatedHTTPRequest(BTCCHINA_ICEBERG_CANCEL, params) if err != nil { @@ -576,7 +578,7 @@ func (b *BTCChina) CancelIcebergOrder(orderID int64, market string) { func (b *BTCChina) PlaceStopOrder(buyOder bool, stopPrice, price, amount, trailingAmt, trailingPct float64, market string) { params := make([]interface{}, 0) - + if stopPrice > 0 { params = append(params, stopPrice) } @@ -600,7 +602,7 @@ func (b *BTCChina) PlaceStopOrder(buyOder bool, stopPrice, price, amount, traili if !buyOder { req = BTCCHINA_STOPORDER_SELL } - + err := b.SendAuthenticatedHTTPRequest(req, params) if err != nil { @@ -615,7 +617,7 @@ func (b *BTCChina) GetStopOrder(orderID int64, market string) { if len(market) > 0 { params = append(params, market) } - + err := b.SendAuthenticatedHTTPRequest(BTCCHINA_STOPORDER, params) if err != nil { @@ -649,7 +651,7 @@ func (b *BTCChina) GetStopOrders(status, orderType string, stopPrice float64, li if len(market) > 0 { params = append(params, market) } - + err := b.SendAuthenticatedHTTPRequest(BTCCHINA_STOPORDERS, params) if err != nil { @@ -664,7 +666,7 @@ func (b *BTCChina) CancelStopOrder(orderID int64, market string) { if len(market) > 0 { params = append(params, market) } - + err := b.SendAuthenticatedHTTPRequest(BTCCHINA_STOPORDER_CANCEL, params) if err != nil { @@ -676,31 +678,36 @@ func (b *BTCChina) SendAuthenticatedHTTPRequest(method string, params []interfac nonce := strconv.FormatInt(time.Now().UnixNano(), 10)[0:16] encoded := fmt.Sprintf("tonce=%s&accesskey=%s&requestmethod=post&id=%d&method=%s¶ms=", nonce, b.APIKey, 1, method) - if (len(params) == 0) { + if len(params) == 0 { params = make([]interface{}, 0) } else { items := make([]string, 0) for _, x := range params { xType := fmt.Sprintf("%T", x) switch xType { - case "int64", "int": { + case "int64", "int": + { items = append(items, fmt.Sprintf("%d", x)) } - case "string": { + case "string": + { items = append(items, fmt.Sprintf("%s", x)) } - case "float64": { - items = append(items, fmt.Sprintf("%f", x)) + case "float64": + { + items = append(items, fmt.Sprintf("%f", x)) } - case "bool": { + case "bool": + { if x == true { items = append(items, "1") } else { items = append(items, "") } } - default :{ - items = append(items, fmt.Sprintf("%v", x)) + default: + { + items = append(items, fmt.Sprintf("%v", x)) } } } @@ -728,11 +735,11 @@ func (b *BTCChina) SendAuthenticatedHTTPRequest(method string, params []interfac headers := make(map[string]string) headers["Content-type"] = "application/json-rpc" - headers["Authorization"] = "Basic " + Base64Encode([]byte(b.APIKey + ":" + HexEncodeToString(hmac))) + headers["Authorization"] = "Basic " + Base64Encode([]byte(b.APIKey+":"+HexEncodeToString(hmac))) headers["Json-Rpc-Tonce"] = nonce resp, err := SendHTTPRequest("POST", apiURL, headers, strings.NewReader(string(data))) - + if err != nil { return err } @@ -742,4 +749,4 @@ func (b *BTCChina) SendAuthenticatedHTTPRequest(method string, params []interfac } return nil -} \ No newline at end of file +} diff --git a/btcehttp.go b/btcehttp.go index dd23439a..51b55372 100644 --- a/btcehttp.go +++ b/btcehttp.go @@ -1,64 +1,66 @@ package main import ( + "fmt" + "log" "net/url" "strconv" "strings" "time" - "fmt" - "log" ) const ( - BTCE_API_PUBLIC_URL = "https://btc-e.com/api" - BTCE_API_PRIVATE_URL = "https://btc-e.com/tapi" - BTCE_API_PUBLIC_VERSION = "3" + BTCE_API_PUBLIC_URL = "https://btc-e.com/api" + BTCE_API_PRIVATE_URL = "https://btc-e.com/tapi" + BTCE_API_PUBLIC_VERSION = "3" BTCE_API_PRIVATE_VERSION = "1" - BTCE_INFO = "info" - BTCE_TICKER = "ticker" - BTCE_DEPTH = "depth" - BTCE_TRADES = "trades" - BTCE_ACCOUNT_INFO = "getInfo" + BTCE_INFO = "info" + BTCE_TICKER = "ticker" + BTCE_DEPTH = "depth" + BTCE_TRADES = "trades" + BTCE_ACCOUNT_INFO = "getInfo" BTCE_TRANSACTION_HISTORY = "TransHistory" - BTCE_TRADE_HISTORY = "TradeHistory" - BTCE_ACTIVE_ORDERS = "ActiveOrders" - BTCE_TRADE = "Trade" - BTCE_CANCEL_ORDER = "CancelOrder" + BTCE_TRADE_HISTORY = "TradeHistory" + BTCE_ACTIVE_ORDERS = "ActiveOrders" + BTCE_TRADE = "Trade" + BTCE_CANCEL_ORDER = "CancelOrder" ) type BTCE struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration APIKey, APISecret string - Fee float64 + Fee float64 + BaseCurrencies []string + Pairs []string } type BTCeTicker struct { - High float64 - Low float64 - Avg float64 - Vol float64 + High float64 + Low float64 + Avg float64 + Vol float64 Vol_cur float64 - Last float64 - Buy float64 - Sell float64 + Last float64 + Buy float64 + Sell float64 Updated int64 } type BTCEOrderbook struct { - Asks[][]float64 `json:"asks"` - Bids[][]float64 `json:"bids"` + Asks [][]float64 `json:"asks"` + Bids [][]float64 `json:"bids"` } type BTCETrades struct { - Type string `json:"type"` - Price float64 `json:"bid"` - Amount float64 `json:"amount"` - TID int64 `json:"tid"` - Timestamp int64 `json:"timestamp"` + Type string `json:"type"` + Price float64 `json:"bid"` + Amount float64 `json:"amount"` + TID int64 `json:"tid"` + Timestamp int64 `json:"timestamp"` } func (b *BTCE) SetDefaults() { @@ -70,7 +72,7 @@ func (b *BTCE) SetDefaults() { b.RESTPollingDelay = 10 } -func (b *BTCE) GetName() (string) { +func (b *BTCE) GetName() string { return b.Name } @@ -78,7 +80,7 @@ func (b *BTCE) SetEnabled(enabled bool) { b.Enabled = enabled } -func (b *BTCE) IsEnabled() (bool) { +func (b *BTCE) IsEnabled() bool { return b.Enabled } @@ -87,7 +89,7 @@ func (b *BTCE) SetAPIKeys(apiKey, apiSecret string) { b.APISecret = apiSecret } -func (b *BTCE) GetFee() (float64) { +func (b *BTCE) GetFee() float64 { return b.Fee } @@ -121,7 +123,7 @@ func (b *BTCE) GetInfo() { } } -func (b *BTCE) GetTicker(symbol string) (BTCeTicker) { +func (b *BTCE) GetTicker(symbol string) BTCeTicker { type Response struct { Data map[string]BTCeTicker } @@ -137,7 +139,7 @@ func (b *BTCE) GetTicker(symbol string) (BTCeTicker) { return response.Data[symbol] } -func (b *BTCE) GetDepth(symbol string) () { +func (b *BTCE) GetDepth(symbol string) { type Response struct { Data map[string]BTCEOrderbook } @@ -155,7 +157,7 @@ func (b *BTCE) GetDepth(symbol string) () { log.Println(depth) } -func (b *BTCE) GetTrades(symbol string) () { +func (b *BTCE) GetTrades(symbol string) { type Response struct { Data map[string][]BTCETrades } @@ -235,7 +237,7 @@ func (b *BTCE) GetTransactionHistory(TIDFrom, Count, TIDEnd int64, order, since, func (b *BTCE) GetTradeHistory(TIDFrom, Count, TIDEnd int64, order, since, end, pair string) { req := url.Values{} - + req.Add("from", strconv.FormatInt(TIDFrom, 10)) req.Add("count", strconv.FormatInt(Count, 10)) req.Add("from_id", strconv.FormatInt(TIDFrom, 10)) @@ -276,8 +278,8 @@ func (b *BTCE) SendAuthenticatedHTTPRequest(method string, values url.Values) (e } if b.Verbose { - log.Printf("Recieved raw: %s\n",resp) + log.Printf("Recieved raw: %s\n", resp) } - + return nil -} \ No newline at end of file +} diff --git a/btcmarkets.go b/btcmarkets.go index a330ddac..94ed9fd7 100644 --- a/btcmarkets.go +++ b/btcmarkets.go @@ -1,82 +1,84 @@ package main import ( - "strconv" - "time" - "log" "bytes" "fmt" + "log" + "strconv" + "time" ) const ( - BTCMARKETS_API_URL = "https://api.btcmarkets.net" - BTCMARKETS_API_VERSION = "0" - BTCMARKETS_ACCOUNT_BALANCE = "/account/balance" - BTCMARKETS_ORDER_CREATE = "/order/create" - BTCMARKETS_ORDER_CANCEL = "/order/cancel" - BTCMARKETS_ORDER_HISTORY = "/order/history" - BTCMARKETS_ORDER_OPEN = "/order/open" + BTCMARKETS_API_URL = "https://api.btcmarkets.net" + BTCMARKETS_API_VERSION = "0" + BTCMARKETS_ACCOUNT_BALANCE = "/account/balance" + BTCMARKETS_ORDER_CREATE = "/order/create" + BTCMARKETS_ORDER_CANCEL = "/order/cancel" + BTCMARKETS_ORDER_HISTORY = "/order/history" + BTCMARKETS_ORDER_OPEN = "/order/open" BTCMARKETS_ORDER_TRADE_HISTORY = "/order/trade/history" - BTCMARKETS_ORDER_DETAIL = "/order/detail" + BTCMARKETS_ORDER_DETAIL = "/order/detail" ) type BTCMarkets struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration - Fee float64 - Ticker map[string]BTCMarketsTicker + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration + Fee float64 + Ticker map[string]BTCMarketsTicker APIKey, APISecret string + BaseCurrencies []string + Pairs []string } type BTCMarketsTicker struct { - BestBID float64 - BestAsk float64 - LastPrice float64 - Currency string + BestBID float64 + BestAsk float64 + LastPrice float64 + Currency string Instrument string - Timestamp int64 + Timestamp int64 } type BTCMarketsTrade struct { - TradeID int64 `json:"tid"` - Amount float64 `json:"amount"` - Price float64 `json:"price"` - Date int64 `json:"date"` + TradeID int64 `json:"tid"` + Amount float64 `json:"amount"` + Price float64 `json:"price"` + Date int64 `json:"date"` } type BTCMarketsOrderbook struct { - Currency string `json:"currency"` - Instrument string `json:"instrument"` - Timestamp int64 `json:"timestamp"` - Asks [][]float64 `json:"asks"` - Bids [][]float64 `json:"bids"` + Currency string `json:"currency"` + Instrument string `json:"instrument"` + Timestamp int64 `json:"timestamp"` + Asks [][]float64 `json:"asks"` + Bids [][]float64 `json:"bids"` } type BTCMarketsTradeResponse struct { - ID int64 `json:"id"` + ID int64 `json:"id"` CreationTime float64 `json:"creationTime"` - Description string `json:"description"` - Price float64 `json:"price"` - Volume float64 `json:"volume"` - Fee float64 `json:"fee"` + Description string `json:"description"` + Price float64 `json:"price"` + Volume float64 `json:"volume"` + Fee float64 `json:"fee"` } type BTCMarketsOrderResponse struct { - ID float64 `json:"id"` - Currency string `json:"currency"` - Instrument string `json:"instrument"` - OrderSide string `json:"orderSide"` - OrderType string `json:"ordertype"` - CreationTime float64 `json:"creationTime"` - Status string `json:"status"` - ErrorMessage string `json:"errorMessage"` - Price float64 `json:"price"` - Volume float64 `json:"volume"` - OpenVolume float64 `json:"openVolume"` - ClientRequestId string `json:"clientRequestId"` + ID float64 `json:"id"` + Currency string `json:"currency"` + Instrument string `json:"instrument"` + OrderSide string `json:"orderSide"` + OrderType string `json:"ordertype"` + CreationTime float64 `json:"creationTime"` + Status string `json:"status"` + ErrorMessage string `json:"errorMessage"` + Price float64 `json:"price"` + Volume float64 `json:"volume"` + OpenVolume float64 `json:"openVolume"` + ClientRequestId string `json:"clientRequestId"` } func (b *BTCMarkets) SetDefaults() { @@ -89,7 +91,7 @@ func (b *BTCMarkets) SetDefaults() { b.Ticker = make(map[string]BTCMarketsTicker) } -func (b *BTCMarkets) GetName() (string) { +func (b *BTCMarkets) GetName() string { return b.Name } @@ -97,7 +99,7 @@ func (b *BTCMarkets) SetEnabled(enabled bool) { b.Enabled = enabled } -func (b *BTCMarkets) IsEnabled() (bool) { +func (b *BTCMarkets) IsEnabled() bool { return b.Enabled } @@ -114,7 +116,7 @@ func (b *BTCMarkets) SetAPIKeys(apiKey, apiSecret string) { b.APISecret = string(result) } -func (b *BTCMarkets) GetFee() (float64) { +func (b *BTCMarkets) GetFee() float64 { return b.Fee } @@ -158,7 +160,7 @@ func (b *BTCMarkets) Run() { func (b *BTCMarkets) GetTicker(symbol string) (BTCMarketsTicker, error) { ticker := BTCMarketsTicker{} path := fmt.Sprintf("/market/%s/AUD/tick", symbol) - err := SendHTTPGetRequest(BTCMARKETS_API_URL + path, true, &ticker) + err := SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &ticker) if err != nil { return BTCMarketsTicker{}, err } @@ -168,7 +170,7 @@ func (b *BTCMarkets) GetTicker(symbol string) (BTCMarketsTicker, error) { func (b *BTCMarkets) GetOrderbook(symbol string) (BTCMarketsOrderbook, error) { orderbook := BTCMarketsOrderbook{} path := fmt.Sprintf("/market/%s/AUD/orderbook", symbol) - err := SendHTTPGetRequest(BTCMARKETS_API_URL + path, true, &orderbook) + err := SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &orderbook) if err != nil { return BTCMarketsOrderbook{}, err } @@ -183,7 +185,7 @@ func (b *BTCMarkets) GetTrades(symbol, since string) ([]BTCMarketsTrade, error) } else { path = fmt.Sprintf("/market/%s/AUD/trades", symbol) } - err := SendHTTPGetRequest(BTCMARKETS_API_URL + path, true, &trades) + err := SendHTTPGetRequest(BTCMARKETS_API_URL+path, true, &trades) if err != nil { return nil, err } @@ -192,14 +194,13 @@ func (b *BTCMarkets) GetTrades(symbol, since string) ([]BTCMarketsTrade, error) func (b *BTCMarkets) Order(currency, instrument string, price, amount int64, orderSide, orderType, clientReq string) (int, error) { type Order struct { - Currency string `json:"currency"` - Instrument string `json:"instrument"` - Price int64 `json:"price"` - Volume int64 `json:"volume"` - OrderSide string `json:"orderSide"` - OrderType string `json:"ordertype"` + Currency string `json:"currency"` + Instrument string `json:"instrument"` + Price int64 `json:"price"` + Volume int64 `json:"volume"` + OrderSide string `json:"orderSide"` + OrderType string `json:"ordertype"` ClientRequestId string `json:"clientRequestId"` - } order := Order{} order.Currency = currency @@ -216,10 +217,10 @@ func (b *BTCMarkets) Order(currency, instrument string, price, amount int64, ord } type Response struct { - Success bool `json:"success"` - ErrorCode int `json:"errorCode"` - ErrorMessage string `json:"errorMessage"` - ID int `json:"id"` + Success bool `json:"success"` + ErrorCode int `json:"errorCode"` + ErrorMessage string `json:"errorMessage"` + ID int `json:"id"` ClientRequestID string `json:"clientRequestId"` } var resp Response @@ -249,14 +250,14 @@ func (b *BTCMarkets) CancelOrder(orderID []int64) (bool, error) { } type Response struct { - Success bool `json:"success"` - ErrorCode int `json:"errorCode"` + Success bool `json:"success"` + ErrorCode int `json:"errorCode"` ErrorMessage string `json:"errorMessage"` - Responses []struct { - Success bool `json:"success"` - ErrorCode int `json:"errorCode"` + Responses []struct { + Success bool `json:"success"` + ErrorCode int `json:"errorCode"` ErrorMessage string `json:"errorMessage"` - ID int64 `json:"id"` + ID int64 `json:"id"` } ClientRequestID string `json:"clientRequestId"` } @@ -337,9 +338,9 @@ func (b *BTCMarkets) GetOrderDetail(orderID []int64) { func (b *BTCMarkets) GetAccountBalance() { type Balance struct { - Balance float64 `json:"balance"` + Balance float64 `json:"balance"` PendingFunds float64 `json:"pendingFunds"` - Currency string `json:"currency"` + Currency string `json:"currency"` } balance := []Balance{} @@ -350,7 +351,7 @@ func (b *BTCMarkets) GetAccountBalance() { } } -func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data []byte, result interface{}) (error) { +func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data []byte, result interface{}) error { nonce := strconv.FormatInt(time.Now().UnixNano(), 10)[0:13] request := "" @@ -363,7 +364,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data []byte, hmac := GetHMAC(HASH_SHA512, []byte(request), []byte(b.APISecret)) if b.Verbose { - log.Printf("Sending %s request to URL %s with params %s\n", reqType, BTCMARKETS_API_URL + path, request) + log.Printf("Sending %s request to URL %s with params %s\n", reqType, BTCMARKETS_API_URL+path, request) } headers := make(map[string]string) @@ -374,7 +375,7 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data []byte, headers["timestamp"] = nonce headers["signature"] = Base64Encode(hmac) - resp, err := SendHTTPRequest(reqType, BTCMARKETS_API_URL + path, headers, bytes.NewBuffer(data)) + resp, err := SendHTTPRequest(reqType, BTCMARKETS_API_URL+path, headers, bytes.NewBuffer(data)) if err != nil { return err @@ -391,4 +392,4 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path string, data []byte, } return nil -} \ No newline at end of file +} diff --git a/coinbasehttp.go b/coinbasehttp.go index baf634eb..f74cb052 100644 --- a/coinbasehttp.go +++ b/coinbasehttp.go @@ -37,6 +37,8 @@ type Coinbase struct { RESTPollingDelay time.Duration Password, APIKey, APISecret string TakerFee, MakerFee float64 + BaseCurrencies []string + Pairs []string } type CoinbaseTicker struct { diff --git a/cryptsyhttp.go b/cryptsyhttp.go index 5af7d849..2b24e661 100644 --- a/cryptsyhttp.go +++ b/cryptsyhttp.go @@ -1,127 +1,129 @@ package main import ( - "log" - "time" "fmt" - "strconv" + "log" "net/url" + "strconv" "strings" + "time" ) const ( - CRYPTSY_API_URL = "https://api.cryptsy.com/api/v2/" - CRYPTSY_API_VERISON = "2" - CRYPTSY_MARKETS = "markets" - CRYPTSY_VOLUME = "volume" - CRYPTSY_TICKER = "ticker" - CRYPTSY_FEES = "fees" - CRYPSTY_TRIGGERS = "triggers" - CRYPTSY_CURRENCIES = "currencies" - CRYPTSY_ORDERBOOK = "orderbook" + CRYPTSY_API_URL = "https://api.cryptsy.com/api/v2/" + CRYPTSY_API_VERISON = "2" + CRYPTSY_MARKETS = "markets" + CRYPTSY_VOLUME = "volume" + CRYPTSY_TICKER = "ticker" + CRYPTSY_FEES = "fees" + CRYPSTY_TRIGGERS = "triggers" + CRYPTSY_CURRENCIES = "currencies" + CRYPTSY_ORDERBOOK = "orderbook" CRYPTSY_TRADEHISTORY = "tradehistory" - CRYPTSY_OHLC = "ohlc" - CRYPTSY_INFO = "info" - CRYPTSY_BALANCES = "balances" - CRYPTSY_DEPOSITS = "deposits" - CRYPTSY_ADDRESSES = "addresses" - CRYPTSY_ORDER = "order" - CRYPTSY_ORDERS = "orders" - CRYPSTY_TRIGGER = "trigger" + CRYPTSY_OHLC = "ohlc" + CRYPTSY_INFO = "info" + CRYPTSY_BALANCES = "balances" + CRYPTSY_DEPOSITS = "deposits" + CRYPTSY_ADDRESSES = "addresses" + CRYPTSY_ORDER = "order" + CRYPTSY_ORDERS = "orders" + CRYPSTY_TRIGGER = "trigger" ) type Cryptsy struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration - APIKey, APISecret string + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration + APIKey, APISecret string TakerFee, MakerFee float64 + BaseCurrencies []string + Pairs []string } type CryptsyMarket struct { DayStats struct { PriceHigh float64 `json:"price_high"` - PriceLow float64 `json:"price_low"` - Volume float64 `json:"volume"` + PriceLow float64 `json:"price_low"` + Volume float64 `json:"volume"` VolumeBtc float64 `json:"volume_btc"` } `json:"24hr"` CoinCurrencyID string `json:"coin_currency_id"` - ID string `json:"id"` - Label string `json:"label"` - LastTrade struct { - Date string `json:"date"` - Price float64 `json:"price"` + ID string `json:"id"` + Label string `json:"label"` + LastTrade struct { + Date string `json:"date"` + Price float64 `json:"price"` Timestamp float64 `json:"timestamp"` } `json:"last_trade"` - MaintenanceMode string `json:"maintenance_mode"` + MaintenanceMode string `json:"maintenance_mode"` MarketCurrencyID string `json:"market_currency_id"` - VerifiedOnly bool `json:"verifiedonly"` + VerifiedOnly bool `json:"verifiedonly"` } type CryptsyVolume struct { - ID string `json:"id"` - Volume float64 `json:"volume"` + ID string `json:"id"` + Volume float64 `json:"volume"` VolumeBtc float64 `json:"volume_btc"` } type CryptsyTicker struct { - ID string `json:"id"` + ID string `json:"id"` Bid float64 `json:"bid"` Ask float64 `json:"ask"` } type CryptsyOrderbook struct { BuyOrders []struct { - Price float64 `json:"price"` + Price float64 `json:"price"` Quantity float64 `json:"quantity"` - Total float64 `json:"total"` + Total float64 `json:"total"` } `json:"buyorders"` - Sellorder [] struct { - Price float64 `json:"price"` + Sellorder []struct { + Price float64 `json:"price"` Quantity float64 `json:"quantity"` - Total float64 `json:"total"` + Total float64 `json:"total"` } `json:"sellorders"` } type CryptsyTradeHistory struct { - Datetime string `json:"datetime"` - InitiateOrderType string `json:"initiate_ordertype"` - Quantity float64 `json:"quantitiy"` - Timestamp float64 `json:"timestamp"` - Total float64 `json:"total"` - TradeID float64 `json:"tradeid"` - TradePrice float64 `json:"tradeprice"` + Datetime string `json:"datetime"` + InitiateOrderType string `json:"initiate_ordertype"` + Quantity float64 `json:"quantitiy"` + Timestamp float64 `json:"timestamp"` + Total float64 `json:"total"` + TradeID float64 `json:"tradeid"` + TradePrice float64 `json:"tradeprice"` } type CryptsyOHLC struct { Close float64 `json:"close"` - Date string `json:"date"` - High float64 `json:"high"` + Date string `json:"date"` + High float64 `json:"high"` } type CryptsyInfo struct { - ID int64 `json:"id"` - Username string `json:"username"` + ID int64 `json:"id"` + Username string `json:"username"` AccountType string `json:"accounttype"` - Email string `json:"email"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - TradeKey string `json:"trade_key"` + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + TradeKey string `json:"trade_key"` } type CryptsyDeposit struct { - Currency string `json:"currency"` + Currency string `json:"currency"` Timestamp float64 `json:"timestamp"` - TRXID string `json:"txrid"` + TRXID string `json:"txrid"` } type CryptsyCurrency struct { - Code string `json:"code"` - ID string `json:"id"` + Code string `json:"code"` + ID string `json:"id"` Maintenance string `json:"maintenance"` - Name string `json:"name"` + Name string `json:"name"` } func (c *Cryptsy) SetDefaults() { @@ -135,7 +137,7 @@ func (c *Cryptsy) SetDefaults() { c.RESTPollingDelay = 10 } -func (c *Cryptsy) GetName() (string) { +func (c *Cryptsy) GetName() string { return c.Name } @@ -143,11 +145,11 @@ func (c *Cryptsy) SetEnabled(enabled bool) { c.Enabled = enabled } -func (c *Cryptsy) IsEnabled() (bool) { +func (c *Cryptsy) IsEnabled() bool { return c.Enabled } -func (c *Cryptsy) GetFee(maker bool) (float64) { +func (c *Cryptsy) GetFee(maker bool) float64 { if maker { return c.MakerFee } else { @@ -185,13 +187,13 @@ func (c *Cryptsy) SetAPIKeys(apiKey, apiSecret string) { c.APISecret = apiSecret } -func (c *Cryptsy) GetMarkets(id string) ([]CryptsyMarket) { +func (c *Cryptsy) GetMarkets(id string) []CryptsyMarket { type Response struct { - Data []CryptsyMarket `json:"data"` - Success bool `json:"success"` + Data []CryptsyMarket `json:"data"` + Success bool `json:"success"` } response := Response{} - err := SendHTTPGetRequest(CRYPTSY_API_URL + CRYPTSY_MARKETS, true, &response) + err := SendHTTPGetRequest(CRYPTSY_API_URL+CRYPTSY_MARKETS, true, &response) if err != nil { log.Println(err) return []CryptsyMarket{} @@ -216,13 +218,13 @@ func (c *Cryptsy) GetMarkets(id string) ([]CryptsyMarket) { return response.Data } -func (c *Cryptsy) GetVolume(id string) ([]CryptsyVolume) { +func (c *Cryptsy) GetVolume(id string) []CryptsyVolume { type Response struct { - Data []CryptsyVolume `json:"data"` - Success bool `json:"success"` + Data []CryptsyVolume `json:"data"` + Success bool `json:"success"` } response := Response{} - path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, CRYPTSY_VOLUME) + path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, CRYPTSY_VOLUME) err := SendHTTPGetRequest(path, true, &response) if err != nil { log.Println(err) @@ -247,13 +249,13 @@ func (c *Cryptsy) GetVolume(id string) ([]CryptsyVolume) { return response.Data } -func (c *Cryptsy) GetTicker(id string) ([]CryptsyTicker) { +func (c *Cryptsy) GetTicker(id string) []CryptsyTicker { type Response struct { - Data []CryptsyTicker `json:"data"` - Success bool `json:"success"` + Data []CryptsyTicker `json:"data"` + Success bool `json:"success"` } response := Response{} - path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, CRYPTSY_TICKER) + path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, CRYPTSY_TICKER) err := SendHTTPGetRequest(path, true, &response) if err != nil { log.Println(err) @@ -279,7 +281,7 @@ func (c *Cryptsy) GetTicker(id string) ([]CryptsyTicker) { } func (c *Cryptsy) GetMarketFees(id string) { - path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, id, CRYPTSY_FEES) + path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, id, CRYPTSY_FEES) err := c.SendAuthenticatedHTTPRequest("GET", path, url.Values{}) if err != nil { log.Println(err) @@ -287,7 +289,7 @@ func (c *Cryptsy) GetMarketFees(id string) { } func (c *Cryptsy) GetMarketTriggers(id string) { - path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, id, CRYPSTY_TRIGGERS) + path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, id, CRYPSTY_TRIGGERS) err := c.SendAuthenticatedHTTPRequest("GET", path, url.Values{}) if err != nil { log.Println(err) @@ -296,11 +298,11 @@ func (c *Cryptsy) GetMarketTriggers(id string) { func (c *Cryptsy) GetOrderbook(id string) { type Response struct { - Data CryptsyOrderbook `json:"data"` - Success bool `json:"success"` + Data CryptsyOrderbook `json:"data"` + Success bool `json:"success"` } response := Response{} - path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, id, CRYPTSY_ORDERBOOK) + path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, id, CRYPTSY_ORDERBOOK) err := SendHTTPGetRequest(path, true, &response) if err != nil { log.Println(err) @@ -310,11 +312,11 @@ func (c *Cryptsy) GetOrderbook(id string) { func (c *Cryptsy) GetTradeHistory(id string) { type Response struct { - Data []CryptsyTradeHistory `json:"data"` - Success bool `json:"success"` + Data []CryptsyTradeHistory `json:"data"` + Success bool `json:"success"` } response := Response{} - path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, id, CRYPTSY_TRADEHISTORY) + path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, id, CRYPTSY_TRADEHISTORY) err := SendHTTPGetRequest(path, true, &response) if err != nil { log.Println(err) @@ -324,11 +326,11 @@ func (c *Cryptsy) GetTradeHistory(id string) { func (c *Cryptsy) GetOHLC(id string) { type Response struct { - Data []CryptsyOHLC `json:"data"` - Success bool `json:"success"` + Data []CryptsyOHLC `json:"data"` + Success bool `json:"success"` } response := Response{} - path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL + CRYPTSY_MARKETS, id, CRYPTSY_OHLC) + path := fmt.Sprintf("%s/%s/%s", CRYPTSY_API_URL+CRYPTSY_MARKETS, id, CRYPTSY_OHLC) err := SendHTTPGetRequest(path, true, &response) if err != nil { log.Println(err) @@ -336,14 +338,14 @@ func (c *Cryptsy) GetOHLC(id string) { log.Println(response) } -func (c *Cryptsy) GetCurrencies(id string) ([]CryptsyCurrency) { +func (c *Cryptsy) GetCurrencies(id string) []CryptsyCurrency { type Response struct { - Data []CryptsyCurrency `json:"data"` - Success bool `json:"success"` + Data []CryptsyCurrency `json:"data"` + Success bool `json:"success"` } response := Response{} - err := SendHTTPGetRequest(CRYPTSY_API_URL + CRYPTSY_CURRENCIES, true, &response) + err := SendHTTPGetRequest(CRYPTSY_API_URL+CRYPTSY_CURRENCIES, true, &response) if err != nil { log.Println(err) return []CryptsyCurrency{} @@ -368,7 +370,7 @@ func (c *Cryptsy) GetCurrencies(id string) ([]CryptsyCurrency) { } func (c *Cryptsy) GetInfo() { - err := c.SendAuthenticatedHTTPRequest("GET", CRYPTSY_API_URL + CRYPTSY_INFO, url.Values{}) + err := c.SendAuthenticatedHTTPRequest("GET", CRYPTSY_API_URL+CRYPTSY_INFO, url.Values{}) if err != nil { log.Println(err) } @@ -380,7 +382,7 @@ func (c *Cryptsy) GetBalances(balanceType, id string) { if len(balanceType) > 0 { req.Set("type", balanceType) } - err := c.SendAuthenticatedHTTPRequest("GET", CRYPTSY_API_URL + CRYPTSY_BALANCES, req) + err := c.SendAuthenticatedHTTPRequest("GET", CRYPTSY_API_URL+CRYPTSY_BALANCES, req) if err != nil { log.Println(err) @@ -394,7 +396,7 @@ func (c *Cryptsy) GetDeposits(limit int, id string) { req.Set("liimt", strconv.Itoa(limit)) } - err := c.SendAuthenticatedHTTPRequest("GET", CRYPTSY_API_URL + CRYPTSY_DEPOSITS, req) + err := c.SendAuthenticatedHTTPRequest("GET", CRYPTSY_API_URL+CRYPTSY_DEPOSITS, req) if err != nil { log.Println(err) @@ -408,7 +410,7 @@ func (c *Cryptsy) CreateOrder(marketid, orderType string, amount, price float64) req.Set("quantity", strconv.FormatFloat(amount, 'f', 8, 64)) req.Set("price", strconv.FormatFloat(amount, 'f', 8, 64)) - err := c.SendAuthenticatedHTTPRequest("POST", CRYPTSY_API_URL + CRYPTSY_ORDER, req) + err := c.SendAuthenticatedHTTPRequest("POST", CRYPTSY_API_URL+CRYPTSY_ORDER, req) if err != nil { log.Println(err) @@ -416,7 +418,7 @@ func (c *Cryptsy) CreateOrder(marketid, orderType string, amount, price float64) } func (c *Cryptsy) GetOrder(orderID int64) { - path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL + CRYPTSY_ORDER, strconv.FormatInt(orderID, 10)) + path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL+CRYPTSY_ORDER, strconv.FormatInt(orderID, 10)) err := c.SendAuthenticatedHTTPRequest("GET", path, url.Values{}) if err != nil { @@ -425,7 +427,7 @@ func (c *Cryptsy) GetOrder(orderID int64) { } func (c *Cryptsy) DeleteOrder(orderID int64) { - path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL + CRYPTSY_ORDER, strconv.FormatInt(orderID, 10)) + path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL+CRYPTSY_ORDER, strconv.FormatInt(orderID, 10)) err := c.SendAuthenticatedHTTPRequest("DELETE", path, url.Values{}) if err != nil { @@ -442,11 +444,11 @@ func (c *Cryptsy) CreateTrigger(marketid int64, orderType string, quantity float req.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) req.Set("orderprice", strconv.FormatFloat(orderprice, 'f', 8, 64)) - if (expires > 0) { + if expires > 0 { req.Set("expires", strconv.FormatInt(expires, 10)) } - err := c.SendAuthenticatedHTTPRequest("POST", CRYPTSY_API_URL + CRYPSTY_TRIGGER, req) + err := c.SendAuthenticatedHTTPRequest("POST", CRYPTSY_API_URL+CRYPSTY_TRIGGER, req) if err != nil { log.Println(err) @@ -454,7 +456,7 @@ func (c *Cryptsy) CreateTrigger(marketid int64, orderType string, quantity float } func (c *Cryptsy) GetTrigger(triggerID int64) { - path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL + CRYPSTY_TRIGGER, strconv.FormatInt(triggerID, 10)) + path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL+CRYPSTY_TRIGGER, strconv.FormatInt(triggerID, 10)) err := c.SendAuthenticatedHTTPRequest("GET", path, url.Values{}) if err != nil { @@ -463,7 +465,7 @@ func (c *Cryptsy) GetTrigger(triggerID int64) { } func (c *Cryptsy) DeleteTrigger(triggerID int64) { - path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL + CRYPSTY_TRIGGER, strconv.FormatInt(triggerID, 10)) + path := fmt.Sprintf("%s/%s", CRYPTSY_API_URL+CRYPSTY_TRIGGER, strconv.FormatInt(triggerID, 10)) err := c.SendAuthenticatedHTTPRequest("DELETE", path, url.Values{}) if err != nil { @@ -502,6 +504,6 @@ func (c *Cryptsy) SendAuthenticatedHTTPRequest(method, path string, params url.V if c.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - + return nil -} \ No newline at end of file +} diff --git a/huobihttp.go b/huobihttp.go index 0668f7ca..118f0bb4 100644 --- a/huobihttp.go +++ b/huobihttp.go @@ -1,40 +1,42 @@ package main import ( - "net/url" - "strings" - "strconv" - "time" "fmt" "log" + "net/url" + "strconv" + "strings" + "time" ) const ( - HUOBI_API_URL = "https://api.huobi.com/apiv2.php" + HUOBI_API_URL = "https://api.huobi.com/apiv2.php" HUOBI_API_VERSION = "2" ) type HUOBI struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration AccessKey, SecretKey string - Fee float64 + Fee float64 + BaseCurrencies []string + Pairs []string } type HuobiTicker struct { High float64 - Low float64 - Last float64 - Vol float64 - Buy float64 - Sell float64 + Low float64 + Last float64 + Vol float64 + Buy float64 + Sell float64 } type HuobiTickerResponse struct { - Time string + Time string Ticker HuobiTicker } @@ -47,7 +49,7 @@ func (h *HUOBI) SetDefaults() { h.RESTPollingDelay = 10 } -func (h *HUOBI) GetName() (string) { +func (h *HUOBI) GetName() string { return h.Name } @@ -55,7 +57,7 @@ func (h *HUOBI) SetEnabled(enabled bool) { h.Enabled = enabled } -func (h *HUOBI) IsEnabled() (bool) { +func (h *HUOBI) IsEnabled() bool { return h.Enabled } @@ -64,7 +66,7 @@ func (h *HUOBI) SetAPIKeys(apiKey, apiSecret string) { h.SecretKey = apiSecret } -func (h *HUOBI) GetFee() (float64) { +func (h *HUOBI) GetFee() float64 { return h.Fee } @@ -100,7 +102,7 @@ func (h *HUOBI) Run() { } } -func (h *HUOBI) GetTicker(symbol string) (HuobiTicker) { +func (h *HUOBI) GetTicker(symbol string) HuobiTicker { resp := HuobiTickerResponse{} path := fmt.Sprintf("http://market.huobi.com/staticmarket/ticker_%s_json.js", symbol) err := SendHTTPGetRequest(path, true, &resp) @@ -112,7 +114,7 @@ func (h *HUOBI) GetTicker(symbol string) (HuobiTicker) { return resp.Ticker } -func (h *HUOBI) GetOrderBook(symbol string) (bool) { +func (h *HUOBI) GetOrderBook(symbol string) bool { path := fmt.Sprintf("http://market.huobi.com/staticmarket/depth_%s_json.js", symbol) err := SendHTTPGetRequest(path, true, nil) if err != nil { @@ -130,7 +132,6 @@ func (h *HUOBI) GetAccountInfo() { } } - func (h *HUOBI) GetOrders(coinType int) { values := url.Values{} values.Set("coin_type", strconv.Itoa(coinType)) @@ -159,7 +160,7 @@ func (h *HUOBI) Trade(orderType string, coinType int, price, amount float64) { } values.Set("coin_type", strconv.Itoa(coinType)) values.Set("amount", strconv.FormatFloat(amount, 'f', 8, 64)) - values.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) + values.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) err := h.SendAuthenticatedRequest(orderType, values) if err != nil { @@ -174,7 +175,7 @@ func (h *HUOBI) MarketTrade(orderType string, coinType int, price, amount float6 } values.Set("coin_type", strconv.Itoa(coinType)) values.Set("amount", strconv.FormatFloat(amount, 'f', 8, 64)) - values.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) + values.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) err := h.SendAuthenticatedRequest(orderType, values) if err != nil { @@ -198,7 +199,7 @@ func (h *HUOBI) ModifyOrder(orderType string, coinType, orderID int, price, amou values.Set("coin_type", strconv.Itoa(coinType)) values.Set("id", strconv.Itoa(orderID)) values.Set("amount", strconv.FormatFloat(amount, 'f', 8, 64)) - values.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) + values.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) err := h.SendAuthenticatedRequest("modify_order", values) if err != nil { @@ -227,7 +228,7 @@ func (h *HUOBI) GetOrderIDByTradeID(coinType, orderID int) { } } -func (h *HUOBI) SendAuthenticatedRequest(method string, v url.Values) (error) { +func (h *HUOBI) SendAuthenticatedRequest(method string, v url.Values) error { v.Set("access_key", h.AccessKey) v.Set("created", strconv.FormatInt(time.Now().Unix(), 10)) v.Set("method", method) @@ -251,6 +252,6 @@ func (h *HUOBI) SendAuthenticatedRequest(method string, v url.Values) (error) { if h.Verbose { log.Printf("Recieved raw: %s\n", resp) } - + return nil -} \ No newline at end of file +} diff --git a/itbithttp.go b/itbithttp.go index 233e79ae..3b29ff48 100644 --- a/itbithttp.go +++ b/itbithttp.go @@ -1,46 +1,48 @@ package main import ( - "strconv" "bytes" "errors" - "net/url" - "time" "log" + "net/url" + "strconv" + "time" ) const ( - ITBIT_API_URL = "https://api.itbit.com/v1" + ITBIT_API_URL = "https://api.itbit.com/v1" ITBIT_API_VERSION = "1" ) type ItBit struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration ClientKey, APISecret, UserID string - MakerFee, TakerFee float64 + MakerFee, TakerFee float64 + BaseCurrencies []string + Pairs []string } type ItBitTicker struct { - Pair string - Bid float64 `json:",string"` - BidAmt float64 `json:",string"` - Ask float64 `json:",string"` - AskAmt float64 `json:",string"` - LastPrice float64 `json:",string"` - LastAmt float64 `json:",string"` - Volume24h float64 `json:",string"` - VolumeToday float64 `json:",string"` - High24h float64 `json:",string"` - Low24h float64 `json:",string"` - HighToday float64 `json:",string"` - LowToday float64 `json:",string"` - OpenToday float64 `json:",string"` - VwapToday float64 `json:",string"` - Vwap24h float64 `json:",string"` + Pair string + Bid float64 `json:",string"` + BidAmt float64 `json:",string"` + Ask float64 `json:",string"` + AskAmt float64 `json:",string"` + LastPrice float64 `json:",string"` + LastAmt float64 `json:",string"` + Volume24h float64 `json:",string"` + VolumeToday float64 `json:",string"` + High24h float64 `json:",string"` + Low24h float64 `json:",string"` + HighToday float64 `json:",string"` + LowToday float64 `json:",string"` + OpenToday float64 `json:",string"` + VwapToday float64 `json:",string"` + Vwap24h float64 `json:",string"` ServertimeUTC string } @@ -51,10 +53,10 @@ func (i *ItBit) SetDefaults() { i.TakerFee = 0.50 i.Verbose = false i.Websocket = false - i.RESTPollingDelay = 10 + i.RESTPollingDelay = 10 } -func (i *ItBit) GetName() (string) { +func (i *ItBit) GetName() string { return i.Name } @@ -62,7 +64,7 @@ func (i *ItBit) SetEnabled(enabled bool) { i.Enabled = enabled } -func (i *ItBit) IsEnabled() (bool) { +func (i *ItBit) IsEnabled() bool { return i.Enabled } @@ -72,7 +74,7 @@ func (i *ItBit) SetAPIKeys(apiKey, apiSecret, userID string) { i.UserID = userID } -func (i *ItBit) GetFee(maker bool) (float64) { +func (i *ItBit) GetFee(maker bool) float64 { if maker { return i.MakerFee } else { @@ -95,7 +97,7 @@ func (i *ItBit) Run() { } } -func (i *ItBit) GetTicker(currency string) (ItBitTicker) { +func (i *ItBit) GetTicker(currency string) ItBitTicker { path := ITBIT_API_URL + "/markets/" + currency + "/ticker" var itbitTicker ItBitTicker err := SendHTTPGetRequest(path, true, &itbitTicker) @@ -106,9 +108,9 @@ func (i *ItBit) GetTicker(currency string) (ItBitTicker) { return itbitTicker } -func (i *ItBit) GetOrderbook(currency string) (bool) { +func (i *ItBit) GetOrderbook(currency string) bool { path := ITBIT_API_URL + "/markets/" + currency + "/orders" - err := SendHTTPGetRequest(path , true, nil) + err := SendHTTPGetRequest(path, true, nil) if err != nil { log.Println(err) return false @@ -116,9 +118,9 @@ func (i *ItBit) GetOrderbook(currency string) (bool) { return true } -func (i *ItBit) GetTradeHistory(currency, timestamp string) (bool) { +func (i *ItBit) GetTradeHistory(currency, timestamp string) bool { req := "/trades?since=" + timestamp - err := SendHTTPGetRequest(ITBIT_API_URL + "markets/" + currency + req, true, nil) + err := SendHTTPGetRequest(ITBIT_API_URL+"markets/"+currency+req, true, nil) if err != nil { log.Println(err) return false @@ -160,7 +162,7 @@ func (i *ItBit) GetWallet(walletID string) { } func (i *ItBit) GetWalletBalance(walletID, currency string) { - path := "/wallets/ " + walletID + "/balances/" + currency + path := "/wallets/ " + walletID + "/balances/" + currency err := i.SendAuthenticatedHTTPRequest("GET", path, nil) if err != nil { @@ -278,7 +280,7 @@ func (i *ItBit) WalletTransfer(walletID, sourceWallet, destWallet string, amount func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params map[string]interface{}) (err error) { timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)[0:13] - nonce, err := strconv.Atoi(timestamp) + nonce, err := strconv.Atoi(timestamp) if err != nil { return err @@ -289,7 +291,7 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params url := ITBIT_API_URL + path if params != nil { - for key, value:= range params { + for key, value := range params { request[key] = value } } @@ -297,8 +299,8 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params PayloadJson := []byte("") if params != nil { - PayloadJson, err = JSONEncode(request) - + PayloadJson, err = JSONEncode(request) + if err != nil { return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON Marshal request") } @@ -316,7 +318,7 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params } hash := GetSHA256([]byte(nonceStr + string(message))) - hmac := GetHMAC(HASH_SHA512, []byte(url + string(hash)), []byte(i.APISecret)) + hmac := GetHMAC(HASH_SHA512, []byte(url+string(hash)), []byte(i.APISecret)) signature := Base64Encode(hmac) headers := make(map[string]string) @@ -331,4 +333,4 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params log.Printf("Recieved raw: \n%s\n", resp) } return nil -} \ No newline at end of file +} diff --git a/kraken.go b/kraken.go index a2d3c39a..bd54b011 100644 --- a/kraken.go +++ b/kraken.go @@ -1,53 +1,55 @@ package main import ( - "log" - "fmt" - "strconv" "errors" - "time" - "strings" + "fmt" + "log" "net/url" + "strconv" + "strings" + "time" ) const ( - KRAKEN_API_URL = "https://api.kraken.com" - KRAKEN_API_VERSION = "0" - KRAKEN_SERVER_TIME = "Time" - KRAKEN_ASSETS = "Assets" - KRAKEN_ASSET_PAIRS = "AssetPairs" - KRAKEN_TICKER = "Ticker" - KRAKEN_OHLC = "OHLC" - KRAKEN_DEPTH = "Depth" - KRAKEN_TRADES = "Trades" - KRAKEN_SPREAD = "Spread" - KRAKEN_BALANCE = "Balance" - KRAKEN_TRADE_BALANCE = "TradeBalance" - KRAKEN_OPEN_ORDERS = "OpenOrders" - KRAKEN_CLOSED_ORDERS = "ClosedOrders" - KRAKEN_QUERY_ORDERS = "QueryOrders" + KRAKEN_API_URL = "https://api.kraken.com" + KRAKEN_API_VERSION = "0" + KRAKEN_SERVER_TIME = "Time" + KRAKEN_ASSETS = "Assets" + KRAKEN_ASSET_PAIRS = "AssetPairs" + KRAKEN_TICKER = "Ticker" + KRAKEN_OHLC = "OHLC" + KRAKEN_DEPTH = "Depth" + KRAKEN_TRADES = "Trades" + KRAKEN_SPREAD = "Spread" + KRAKEN_BALANCE = "Balance" + KRAKEN_TRADE_BALANCE = "TradeBalance" + KRAKEN_OPEN_ORDERS = "OpenOrders" + KRAKEN_CLOSED_ORDERS = "ClosedOrders" + KRAKEN_QUERY_ORDERS = "QueryOrders" KRAKEN_TRADES_HISTORY = "TradesHistory" - KRAKEN_QUERY_TRADES = "QueryTrades" + KRAKEN_QUERY_TRADES = "QueryTrades" KRAKEN_OPEN_POSITIONS = "OpenPositions" - KRAKEN_LEDGERS = "Ledgers" - KRAKEN_QUERY_LEDGERS = "QueryLedgers" - KRAKEN_TRADE_VOLUME = "TradeVolume" - KRAKEN_ORDER_CANCEL = "CancelOrder" - KRAKEN_ORDER_PLACE = "AddOrder" + KRAKEN_LEDGERS = "Ledgers" + KRAKEN_QUERY_LEDGERS = "QueryLedgers" + KRAKEN_TRADE_VOLUME = "TradeVolume" + KRAKEN_ORDER_CANCEL = "CancelOrder" + KRAKEN_ORDER_PLACE = "AddOrder" ) type Kraken struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration ClientKey, APISecret string - FiatFee, CryptoFee float64 + FiatFee, CryptoFee float64 + BaseCurrencies []string + Pairs []string } type KrakenResponse struct { - Error []string `json:error` + Error []string `json:error` Result map[string]interface{} `json:result` } @@ -61,7 +63,7 @@ func (k *Kraken) SetDefaults() { k.RESTPollingDelay = 10 } -func (k *Kraken) GetName() (string) { +func (k *Kraken) GetName() string { return k.Name } @@ -69,7 +71,7 @@ func (k *Kraken) SetEnabled(enabled bool) { k.Enabled = enabled } -func (k *Kraken) IsEnabled() (bool) { +func (k *Kraken) IsEnabled() bool { return k.Enabled } @@ -78,7 +80,7 @@ func (k *Kraken) SetAPIKeys(apiKey, apiSecret string) { k.APISecret = apiSecret } -func (k *Kraken) GetFee(cryptoTrade bool) (float64) { +func (k *Kraken) GetFee(cryptoTrade bool) float64 { if cryptoTrade { return k.CryptoFee } else { @@ -284,7 +286,7 @@ func (k *Kraken) GetOpenOrders(showTrades bool, userref int64) { func (k *Kraken) GetClosedOrders(showTrades bool, userref, start, end, offset int64, closetime string) { values := url.Values{} - + if showTrades { values.Set("trades", "true") } @@ -321,7 +323,7 @@ func (k *Kraken) GetClosedOrders(showTrades bool, userref, start, end, offset in func (k *Kraken) QueryOrdersInfo(showTrades bool, userref, txid int64) { values := url.Values{} - + if showTrades { values.Set("trades", "true") } @@ -331,7 +333,7 @@ func (k *Kraken) QueryOrdersInfo(showTrades bool, userref, txid int64) { } if txid != 0 { - values.Set("txid", strconv.FormatInt(userref, 10)) + values.Set("txid", strconv.FormatInt(userref, 10)) } result, err := k.SendAuthenticatedHTTPRequest(KRAKEN_QUERY_ORDERS, values) @@ -346,7 +348,7 @@ func (k *Kraken) QueryOrdersInfo(showTrades bool, userref, txid int64) { func (k *Kraken) GetTradesHistory(tradeType string, showRelatedTrades bool, start, end, offset int64) { values := url.Values{} - + if len(tradeType) > 0 { values.Set("aclass", tradeType) } @@ -415,7 +417,7 @@ func (k *Kraken) OpenPositions(txid int64, showPL bool) { func (k *Kraken) GetLedgers(symbol, asset, ledgerType string, start, end, offset int64) { values := url.Values{} - + if len(symbol) > 0 { values.Set("aclass", symbol) } @@ -533,7 +535,7 @@ func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) headers["API-Key"] = k.ClientKey headers["API-Sign"] = signature - resp, err := SendHTTPRequest("POST", KRAKEN_API_URL + path, headers, strings.NewReader(values.Encode())) + resp, err := SendHTTPRequest("POST", KRAKEN_API_URL+path, headers, strings.NewReader(values.Encode())) if err != nil { return nil, err @@ -542,7 +544,7 @@ func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) if k.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - + kresp := KrakenResponse{} err = JSONDecode([]byte(resp), &kresp) @@ -555,4 +557,4 @@ func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) } return kresp.Result, nil -} \ No newline at end of file +} diff --git a/lakebtchttp.go b/lakebtchttp.go index 99924bb0..38b0d35e 100644 --- a/lakebtchttp.go +++ b/lakebtchttp.go @@ -1,45 +1,47 @@ package main import ( + "errors" + "log" "net/url" "strconv" - "errors" "strings" "time" - "log" ) const ( - LAKEBTC_API_URL = "https://www.LakeBTC.com/api_v1/" - LAKEBTC_API_VERSION = "1" - LAKEBTC_TICKER = "ticker" - LAKEBTC_ORDERBOOK = "bcorderbook" - LAKEBTC_ORDERBOOK_CNY = "bcorderbook_cny" - LAKEBTC_TRADES = "bctrades" + LAKEBTC_API_URL = "https://www.LakeBTC.com/api_v1/" + LAKEBTC_API_VERSION = "1" + LAKEBTC_TICKER = "ticker" + LAKEBTC_ORDERBOOK = "bcorderbook" + LAKEBTC_ORDERBOOK_CNY = "bcorderbook_cny" + LAKEBTC_TRADES = "bctrades" LAKEBTC_GET_ACCOUNT_INFO = "getAccountInfo" - LAKEBTC_BUY_ORDER = "buyOrder" - LAKEBTC_SELL_ORDER = "sellOrder" - LAKEBTC_GET_ORDERS = "getOrders" - LAKEBTC_CANCEL_ORDER = "cancelOrder" - LAKEBTC_GET_TRADES = "getTrades" + LAKEBTC_BUY_ORDER = "buyOrder" + LAKEBTC_SELL_ORDER = "sellOrder" + LAKEBTC_GET_ORDERS = "getOrders" + LAKEBTC_CANCEL_ORDER = "cancelOrder" + LAKEBTC_GET_TRADES = "getTrades" ) type LakeBTC struct { - Name string - Enabled bool - Verbose bool - Websocket bool - RESTPollingDelay time.Duration - Email, APISecret string + Name string + Enabled bool + Verbose bool + Websocket bool + RESTPollingDelay time.Duration + Email, APISecret string TakerFee, MakerFee float64 + BaseCurrencies []string + Pairs []string } type LakeBTCTicker struct { - Last float64 - Bid float64 - Ask float64 - High float64 - Low float64 + Last float64 + Bid float64 + Ask float64 + High float64 + Low float64 Volume float64 } @@ -63,7 +65,7 @@ func (l *LakeBTC) SetDefaults() { l.RESTPollingDelay = 10 } -func (l *LakeBTC) GetName() (string) { +func (l *LakeBTC) GetName() string { return l.Name } @@ -71,7 +73,7 @@ func (l *LakeBTC) SetEnabled(enabled bool) { l.Enabled = enabled } -func (l *LakeBTC) IsEnabled() (bool) { +func (l *LakeBTC) IsEnabled() bool { return l.Enabled } @@ -80,8 +82,8 @@ func (l *LakeBTC) SetAPIKeys(apiKey, apiSecret string) { l.APISecret = apiSecret } -func (l *LakeBTC) GetFee(maker bool) (float64) { - if (maker) { +func (l *LakeBTC) GetFee(maker bool) float64 { + if maker { return l.MakerFee } else { return l.TakerFee @@ -108,9 +110,9 @@ func (l *LakeBTC) Run() { } } -func (l *LakeBTC) GetTicker() (LakeBTCTickerResponse) { +func (l *LakeBTC) GetTicker() LakeBTCTickerResponse { response := LakeBTCTickerResponse{} - err := SendHTTPGetRequest(LAKEBTC_API_URL + LAKEBTC_TICKER, true, &response) + err := SendHTTPGetRequest(LAKEBTC_API_URL+LAKEBTC_TICKER, true, &response) if err != nil { log.Println(err) return response @@ -118,13 +120,13 @@ func (l *LakeBTC) GetTicker() (LakeBTCTickerResponse) { return response } -func (l *LakeBTC) GetOrderBook(currency string) (bool) { +func (l *LakeBTC) GetOrderBook(currency string) bool { req := LAKEBTC_ORDERBOOK if currency == "CNY" { req = LAKEBTC_ORDERBOOK_CNY } - err := SendHTTPGetRequest(LAKEBTC_API_URL + req, true, nil) + err := SendHTTPGetRequest(LAKEBTC_API_URL+req, true, nil) if err != nil { log.Println(err) return false @@ -132,8 +134,8 @@ func (l *LakeBTC) GetOrderBook(currency string) (bool) { return true } -func (l *LakeBTC) GetTradeHistory() (bool) { - err := SendHTTPGetRequest(LAKEBTC_API_URL + LAKEBTC_TRADES, true, nil) +func (l *LakeBTC) GetTradeHistory() bool { + err := SendHTTPGetRequest(LAKEBTC_API_URL+LAKEBTC_TRADES, true, nil) if err != nil { log.Println(err) return false @@ -185,7 +187,7 @@ func (l *LakeBTC) GetTrades(timestamp time.Time) { if !timestamp.IsZero() { params = strconv.FormatInt(timestamp.Unix(), 10) } - + err := l.SendAuthenticatedHTTPRequest(LAKEBTC_GET_TRADES, params) if err != nil { log.Println(err) @@ -223,6 +225,6 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string) (err error if l.Verbose { log.Printf("Recieved raw: %s\n", resp) } - + return nil -} \ No newline at end of file +} diff --git a/main.go b/main.go index 6376dd8a..af7028a4 100644 --- a/main.go +++ b/main.go @@ -1,34 +1,34 @@ package main import ( + "errors" "log" "os" - "errors" "os/signal" - "syscall" - "strconv" "runtime" + "strconv" + "syscall" ) type Exchange struct { - anx ANX - btcchina BTCChina - bitstamp Bitstamp - bitfinex Bitfinex - btce BTCE - btcmarkets BTCMarkets - coinbase Coinbase - cryptsy Cryptsy + anx ANX + btcchina BTCChina + bitstamp Bitstamp + bitfinex Bitfinex + btce BTCE + btcmarkets BTCMarkets + coinbase Coinbase + cryptsy Cryptsy okcoinChina OKCoin - okcoinIntl OKCoin - itbit ItBit - lakebtc LakeBTC - huobi HUOBI - kraken Kraken + okcoinIntl OKCoin + itbit ItBit + lakebtc LakeBTC + huobi HUOBI + kraken Kraken } type Bot struct { - config Config + config Config exchange Exchange shutdown chan bool } @@ -116,6 +116,8 @@ func main() { bot.exchange.anx.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.anx.Verbose = exch.Verbose bot.exchange.anx.Websocket = exch.Websocket + bot.exchange.anx.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.anx.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.anx.Run() } } else if bot.exchange.btcchina.GetName() == exch.Name { @@ -127,6 +129,8 @@ func main() { bot.exchange.btcchina.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.btcchina.Verbose = exch.Verbose bot.exchange.btcchina.Websocket = exch.Websocket + bot.exchange.btcchina.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.btcchina.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.btcchina.Run() } } else if bot.exchange.bitstamp.GetName() == exch.Name { @@ -138,6 +142,8 @@ func main() { bot.exchange.bitstamp.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.bitstamp.Verbose = exch.Verbose bot.exchange.bitstamp.Websocket = exch.Websocket + bot.exchange.bitstamp.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.bitstamp.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.bitstamp.Run() } } else if bot.exchange.bitfinex.GetName() == exch.Name { @@ -149,6 +155,8 @@ func main() { bot.exchange.bitfinex.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.bitfinex.Verbose = exch.Verbose bot.exchange.bitfinex.Websocket = exch.Websocket + bot.exchange.bitfinex.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.bitfinex.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.bitfinex.Run() } } else if bot.exchange.btce.GetName() == exch.Name { @@ -160,6 +168,8 @@ func main() { bot.exchange.btce.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.btce.Verbose = exch.Verbose bot.exchange.btce.Websocket = exch.Websocket + bot.exchange.btce.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.btce.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.btce.Run() } } else if bot.exchange.btcmarkets.GetName() == exch.Name { @@ -171,6 +181,8 @@ func main() { bot.exchange.btcmarkets.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.btcmarkets.Verbose = exch.Verbose bot.exchange.btcmarkets.Websocket = exch.Websocket + bot.exchange.btcmarkets.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.btcmarkets.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.btcmarkets.Run() } } else if bot.exchange.coinbase.GetName() == exch.Name { @@ -182,6 +194,8 @@ func main() { bot.exchange.coinbase.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.coinbase.Verbose = exch.Verbose bot.exchange.coinbase.Websocket = exch.Websocket + bot.exchange.coinbase.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.coinbase.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.coinbase.Run() } } else if bot.exchange.cryptsy.GetName() == exch.Name { @@ -193,6 +207,8 @@ func main() { bot.exchange.cryptsy.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.cryptsy.Verbose = exch.Verbose bot.exchange.cryptsy.Websocket = exch.Websocket + bot.exchange.cryptsy.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.cryptsy.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.cryptsy.Run() } } else if bot.exchange.okcoinChina.GetName() == exch.Name { @@ -204,6 +220,8 @@ func main() { bot.exchange.okcoinChina.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.okcoinChina.Verbose = exch.Verbose bot.exchange.okcoinChina.Websocket = exch.Websocket + bot.exchange.okcoinChina.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.okcoinChina.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.okcoinChina.Run() } } else if bot.exchange.okcoinIntl.GetName() == exch.Name { @@ -215,6 +233,8 @@ func main() { bot.exchange.okcoinIntl.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.okcoinIntl.Verbose = exch.Verbose bot.exchange.okcoinIntl.Websocket = exch.Websocket + bot.exchange.okcoinIntl.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.okcoinIntl.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.okcoinIntl.Run() } } else if bot.exchange.itbit.GetName() == exch.Name { @@ -226,6 +246,8 @@ func main() { bot.exchange.itbit.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.itbit.Verbose = exch.Verbose bot.exchange.itbit.Websocket = exch.Websocket + bot.exchange.itbit.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.itbit.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.itbit.Run() } } else if bot.exchange.kraken.GetName() == exch.Name { @@ -237,6 +259,8 @@ func main() { bot.exchange.kraken.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.kraken.Verbose = exch.Verbose bot.exchange.kraken.Websocket = exch.Websocket + bot.exchange.kraken.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.kraken.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.kraken.Run() } } else if bot.exchange.lakebtc.GetName() == exch.Name { @@ -248,6 +272,8 @@ func main() { bot.exchange.lakebtc.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.lakebtc.Verbose = exch.Verbose bot.exchange.lakebtc.Websocket = exch.Websocket + bot.exchange.lakebtc.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.lakebtc.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.lakebtc.Run() } } else if bot.exchange.huobi.GetName() == exch.Name { @@ -259,6 +285,8 @@ func main() { bot.exchange.huobi.RESTPollingDelay = exch.RESTPollingDelay bot.exchange.huobi.Verbose = exch.Verbose bot.exchange.huobi.Websocket = exch.Websocket + bot.exchange.huobi.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",") + bot.exchange.huobi.Pairs = SplitStrings(exch.Pairs, ",") go bot.exchange.huobi.Run() } } @@ -273,7 +301,7 @@ func AdjustGoMaxProcs() { maxProcs := runtime.NumCPU() log.Println("Number of CPU's detected:", maxProcs) - if maxProcsEnv != "" { + if maxProcsEnv != "" { log.Println("GOMAXPROCS env =", maxProcsEnv) env, err := strconv.Atoi(maxProcsEnv) @@ -282,7 +310,7 @@ func AdjustGoMaxProcs() { } else { maxProcs = env } - } + } log.Println("Set GOMAXPROCS to:", maxProcs) runtime.GOMAXPROCS(maxProcs) } diff --git a/okcoinhttp.go b/okcoinhttp.go index 219f2ec1..01806e1c 100644 --- a/okcoinhttp.go +++ b/okcoinhttp.go @@ -1,55 +1,57 @@ package main import ( - "net/url" - "strings" - "strconv" - "time" "fmt" "log" + "net/url" + "strconv" + "strings" + "time" ) const ( - OKCOIN_API_URL = "https://www.okcoin.com/api/v1/" - OKCOIN_API_URL_CHINA = "https://www.okcoin.cn/api/v1/" - OKCOIN_API_VERSION = "1" - OKCOIN_WEBSOCKET_URL = "wss://real.okcoin.com:10440/websocket/okcoinapi" + OKCOIN_API_URL = "https://www.okcoin.com/api/v1/" + OKCOIN_API_URL_CHINA = "https://www.okcoin.cn/api/v1/" + OKCOIN_API_VERSION = "1" + OKCOIN_WEBSOCKET_URL = "wss://real.okcoin.com:10440/websocket/okcoinapi" OKCOIN_WEBSOCKET_URL_CHINA = "wss://real.okcoin.cn:10440/websocket/okcoinapi" ) type OKCoin struct { - Name string - Enabled bool - Verbose bool - Websocket bool - WebsocketURL string - RESTPollingDelay time.Duration + Name string + Enabled bool + Verbose bool + Websocket bool + WebsocketURL string + RESTPollingDelay time.Duration APIUrl, PartnerID, SecretKey string - TakerFee, MakerFee float64 - RESTErrors map[string]string - WebsocketErrors map[string]string + TakerFee, MakerFee float64 + RESTErrors map[string]string + WebsocketErrors map[string]string + BaseCurrencies []string + Pairs []string } type OKCoinTicker struct { - Buy float64 `json:",string"` + Buy float64 `json:",string"` High float64 `json:",string"` Last float64 `json:",string"` - Low float64 `json:",string"` + Low float64 `json:",string"` Sell float64 `json:",string"` - Vol float64 `json:",string"` + Vol float64 `json:",string"` } type OKCoinTickerResponse struct { - Date string + Date string Ticker OKCoinTicker } type OKCoinFuturesTicker struct { - Last float64 - Buy float64 - Sell float64 - High float64 - Low float64 - Vol float64 + Last float64 + Buy float64 + Sell float64 + High float64 + Low float64 + Vol float64 Contract_ID float64 Unit_Amount float64 } @@ -60,93 +62,93 @@ type OKCoinOrderbook struct { } type OKCoinFuturesTickerResponse struct { - Date string + Date string Ticker OKCoinFuturesTicker } type OKCoinBorrowInfo struct { - BorrowBTC float64 `json:"borrow_btc"` - BorrowLTC float64 `json:"borrow_ltc"` - BorrowCNY float64 `json:"borrow_cny"` - CanBorrow float64 `json:"can_borrow"` - InterestBTC float64 `json:"interest_btc"` - InterestLTC float64 `json:"interest_ltc"` - Result bool `json:"result"` + BorrowBTC float64 `json:"borrow_btc"` + BorrowLTC float64 `json:"borrow_ltc"` + BorrowCNY float64 `json:"borrow_cny"` + CanBorrow float64 `json:"can_borrow"` + InterestBTC float64 `json:"interest_btc"` + InterestLTC float64 `json:"interest_ltc"` + Result bool `json:"result"` DailyInterestBTC float64 `json:"today_interest_btc"` DailyInterestLTC float64 `json:"today_interest_ltc"` DailyInterestCNY float64 `json:"today_interest_cny"` } type OKCoinBorrowOrder struct { - Amount float64 `json:"amount"` - BorrowDate float64 `json:"borrow_date"` - BorrowID int64 `json:"borrow_id"` - Days int64 `json:"days"` + Amount float64 `json:"amount"` + BorrowDate float64 `json:"borrow_date"` + BorrowID int64 `json:"borrow_id"` + Days int64 `json:"days"` TradeAmount float64 `json:"deal_amount"` - Rate float64 `json:"rate"` - Status int64 `json:"status"` - Symbol string `json:"symbol"` + Rate float64 `json:"rate"` + Status int64 `json:"status"` + Symbol string `json:"symbol"` } type OKCoinRecord struct { - Address string `json:"addr"` - Account int64 `json:"account,string"` - Amount float64 `json:"amount"` - Bank string `json:"bank"` - BenificiaryAddress string `json:"benificiary_addr"` - TransactionValue float64 `json:"transaction_value"` - Fee float64 `json:"fee"` - Date float64 `json:"date"` + Address string `json:"addr"` + Account int64 `json:"account,string"` + Amount float64 `json:"amount"` + Bank string `json:"bank"` + BenificiaryAddress string `json:"benificiary_addr"` + TransactionValue float64 `json:"transaction_value"` + Fee float64 `json:"fee"` + Date float64 `json:"date"` } type OKCoinAccountRecords struct { Records []OKCoinRecord `json:"records"` - Symbol string `json:"symbol"` + Symbol string `json:"symbol"` } type OKCoinFuturesOrder struct { - Amount float64 `json:"amount"` - ContractName string `json:"contract_name"` - DateCreated float64 `json:"create_date"` - TradeAmount float64 `json:"deal_amount"` - Fee float64 `json:"fee"` + Amount float64 `json:"amount"` + ContractName string `json:"contract_name"` + DateCreated float64 `json:"create_date"` + TradeAmount float64 `json:"deal_amount"` + Fee float64 `json:"fee"` LeverageRate float64 `json:"lever_rate"` - OrderID int64 `json:"order_id"` - Price float64 `json:"price"` - AvgPrice float64 `json:"avg_price"` - Status float64 `json:"status"` - Symbol string `json:"symbol"` - Type int64 `json:"type"` - UnitAmount int64 `json:"unit_amount"` + OrderID int64 `json:"order_id"` + Price float64 `json:"price"` + AvgPrice float64 `json:"avg_price"` + Status float64 `json:"status"` + Symbol string `json:"symbol"` + Type int64 `json:"type"` + UnitAmount int64 `json:"unit_amount"` } type OKCoinFuturesHoldAmount struct { - Amount float64 `json:"amount"` - ContractName string `json:"contract_name"` + Amount float64 `json:"amount"` + ContractName string `json:"contract_name"` } type OKCoinLendDepth struct { Amount float64 `json:"amount"` - Days string `json:"days"` - Num int64 `json:"num"` - Rate float64 `json:"rate,string"` + Days string `json:"days"` + Num int64 `json:"num"` + Rate float64 `json:"rate,string"` } type OKCoinFuturesExplosive struct { - Amount float64 `json:"amount,string"` - DateCreated string `json:"create_date"` - Loss float64 `json:"loss,string"` - Type int64 `json:"type"` + Amount float64 `json:"amount,string"` + DateCreated string `json:"create_date"` + Loss float64 `json:"loss,string"` + Type int64 `json:"type"` } func (o *OKCoin) SetDefaults() { o.SetErrorDefaults() o.SetWebsocketErrorDefaults() - if (o.APIUrl == OKCOIN_API_URL) { + if o.APIUrl == OKCOIN_API_URL { o.Name = "OKCOIN International" o.WebsocketURL = OKCOIN_WEBSOCKET_URL - } else if (o.APIUrl == OKCOIN_API_URL_CHINA) { + } else if o.APIUrl == OKCOIN_API_URL_CHINA { o.Name = "OKCOIN China" o.WebsocketURL = OKCOIN_WEBSOCKET_URL_CHINA } @@ -156,7 +158,7 @@ func (o *OKCoin) SetDefaults() { o.RESTPollingDelay = 10 } -func (o *OKCoin) GetName() (string) { +func (o *OKCoin) GetName() string { return o.Name } @@ -164,7 +166,7 @@ func (o *OKCoin) SetEnabled(enabled bool) { o.Enabled = enabled } -func (o *OKCoin) IsEnabled() (bool) { +func (o *OKCoin) IsEnabled() bool { return o.Enabled } @@ -177,14 +179,14 @@ func (o *OKCoin) SetAPIKeys(apiKey, apiSecret string) { o.SecretKey = apiSecret } -func (o *OKCoin) GetFee(maker bool) (float64) { - if (o.APIUrl == OKCOIN_API_URL) { +func (o *OKCoin) GetFee(maker bool) float64 { + if o.APIUrl == OKCOIN_API_URL { if maker { return o.MakerFee } else { return o.TakerFee } - } + } // Chinese exchange does not have any trading fees return 0 } @@ -216,7 +218,7 @@ func (o *OKCoin) Run() { log.Printf("OKCoin Intl LTC: Last %f High %f Low %f Volume %f\n", OKCoinChinaIntlLTC.Last, OKCoinChinaIntlLTC.High, OKCoinChinaIntlLTC.Low, OKCoinChinaIntlLTC.Vol) AddExchangeInfo(o.GetName(), "LTC", OKCoinChinaIntlLTC.Last, OKCoinChinaIntlLTC.Vol) }() - + go func() { OKCoinFuturesBTC := o.GetFuturesTicker("btc_usd", "this_week") log.Printf("OKCoin BTC Futures (weekly): Last %f High %f Low %f Volume %f\n", OKCoinFuturesBTC.Last, OKCoinFuturesBTC.High, OKCoinFuturesBTC.Low, OKCoinFuturesBTC.Vol) @@ -262,17 +264,17 @@ func (o *OKCoin) Run() { OKCoinChinaLTCHighUSD, _ := ConvertCurrency(OKCoinChinaLTC.High, "CNY", "USD") OKCoinChinaLTCLowUSD, _ := ConvertCurrency(OKCoinChinaLTC.Low, "CNY", "USD") log.Printf("OKCoin China: Last %f (%f) High %f (%f) Low %f (%f) Volume %f\n", OKCoinChinaLTCLastUSD, OKCoinChinaLTC.Last, OKCoinChinaLTCHighUSD, OKCoinChinaLTC.High, OKCoinChinaLTCLowUSD, OKCoinChinaLTC.Low, OKCoinChinaLTC.Vol) - AddExchangeInfo(o.GetName(), "LTC",OKCoinChinaLTCLastUSD, OKCoinChinaLTC.Vol) + AddExchangeInfo(o.GetName(), "LTC", OKCoinChinaLTCLastUSD, OKCoinChinaLTC.Vol) }() } time.Sleep(time.Second * o.RESTPollingDelay) } } -func (o *OKCoin) GetTicker(symbol string) (OKCoinTicker) { +func (o *OKCoin) GetTicker(symbol string) OKCoinTicker { resp := OKCoinTickerResponse{} path := fmt.Sprintf("ticker.do?symbol=%s&ok=1", symbol) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) @@ -281,10 +283,10 @@ func (o *OKCoin) GetTicker(symbol string) (OKCoinTicker) { return resp.Ticker } -func (o *OKCoin) GetKline(symbol, klineType string, size, since int64) ([]interface{}) { +func (o *OKCoin) GetKline(symbol, klineType string, size, since int64) []interface{} { resp := []interface{}{} path := fmt.Sprintf("kline.do?symbol=%stype=%s&size=%d&since=%d&ok=1", symbol, klineType, size, since) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) @@ -293,13 +295,13 @@ func (o *OKCoin) GetKline(symbol, klineType string, size, since int64) ([]interf return resp } -func (o *OKCoin) GetLendDepth(symbol string) ([]OKCoinLendDepth) { +func (o *OKCoin) GetLendDepth(symbol string) []OKCoinLendDepth { type Response struct { LendDepth []OKCoinLendDepth `json:"lend_depth"` } resp := Response{} path := fmt.Sprintf("lend_depth.do?symbol=%s&ok=1", symbol) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) @@ -308,10 +310,10 @@ func (o *OKCoin) GetLendDepth(symbol string) ([]OKCoinLendDepth) { return resp.LendDepth } -func (o *OKCoin) GetFuturesTicker(symbol, contractType string) (OKCoinFuturesTicker) { +func (o *OKCoin) GetFuturesTicker(symbol, contractType string) OKCoinFuturesTicker { resp := OKCoinFuturesTickerResponse{} path := fmt.Sprintf("future_ticker.do?symbol=%s&contract_type=%s", symbol, contractType) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) return OKCoinFuturesTicker{} @@ -319,9 +321,9 @@ func (o *OKCoin) GetFuturesTicker(symbol, contractType string) (OKCoinFuturesTic return resp.Ticker } -func (o *OKCoin) GetOrderBook(symbol string) (bool) { +func (o *OKCoin) GetOrderBook(symbol string) bool { path := "depth.do?symbol=" + symbol - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -329,9 +331,9 @@ func (o *OKCoin) GetOrderBook(symbol string) (bool) { return true } -func (o *OKCoin) GetFuturesDepth(symbol, contractType string) (bool) { +func (o *OKCoin) GetFuturesDepth(symbol, contractType string) bool { path := fmt.Sprintf("future_depth.do?symbol=%s&contract_type=%s", symbol, contractType) - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -339,9 +341,9 @@ func (o *OKCoin) GetFuturesDepth(symbol, contractType string) (bool) { return true } -func (o *OKCoin) GetTradeHistory(symbol string) (bool) { +func (o *OKCoin) GetTradeHistory(symbol string) bool { path := "trades.do?symbol=" + symbol - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -349,9 +351,9 @@ func (o *OKCoin) GetTradeHistory(symbol string) (bool) { return true } -func (o *OKCoin) GetFuturesTrades(symbol, contractType string) (bool) { +func (o *OKCoin) GetFuturesTrades(symbol, contractType string) bool { path := fmt.Sprintf("future_trades.do?symbol=%s&contract_type=%s", symbol, contractType) - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -359,9 +361,9 @@ func (o *OKCoin) GetFuturesTrades(symbol, contractType string) (bool) { return true } -func (o *OKCoin) GetFuturesIndex(symbol string) (bool) { +func (o *OKCoin) GetFuturesIndex(symbol string) bool { path := "future_index.do?symbol=" + symbol - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -369,17 +371,17 @@ func (o *OKCoin) GetFuturesIndex(symbol string) (bool) { return true } -func (o *OKCoin) GetFuturesExchangeRate() (bool) { - err := SendHTTPGetRequest(o.APIUrl + "exchange_rate.do", true, nil) +func (o *OKCoin) GetFuturesExchangeRate() bool { + err := SendHTTPGetRequest(o.APIUrl+"exchange_rate.do", true, nil) if err != nil { log.Println(err) } return true } -func (o *OKCoin) GetFuturesEstimatedPrice(symbol string) (bool) { +func (o *OKCoin) GetFuturesEstimatedPrice(symbol string) bool { path := "future_estimated_price.do?symbol=" + symbol - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -387,9 +389,9 @@ func (o *OKCoin) GetFuturesEstimatedPrice(symbol string) (bool) { return true } -func (o *OKCoin) GetFuturesTradeHistory(symbol, date string, since int64) (bool) { +func (o *OKCoin) GetFuturesTradeHistory(symbol, date string, since int64) bool { path := fmt.Sprintf("future_trades_history.do?symbol=%s&date%s&since=%d", symbol, date, since) - err := SendHTTPGetRequest(o.APIUrl + path, true, nil) + err := SendHTTPGetRequest(o.APIUrl+path, true, nil) if err != nil { log.Println(err) return false @@ -397,10 +399,10 @@ func (o *OKCoin) GetFuturesTradeHistory(symbol, date string, since int64) (bool) return true } -func (o *OKCoin) GetFuturesKline(symbol, klineType, contractType string, size, since int64) ([]interface{}) { +func (o *OKCoin) GetFuturesKline(symbol, klineType, contractType string, size, since int64) []interface{} { resp := []interface{}{} path := fmt.Sprintf("future_kline.do?symbol=%s&type=%s&contract_type=%s&size=%d&since=%d", symbol, klineType, contractType, size, since) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) @@ -409,10 +411,10 @@ func (o *OKCoin) GetFuturesKline(symbol, klineType, contractType string, size, s return resp } -func (o *OKCoin) GetFuturesHoldAmount(symbol, contractType string) ([]OKCoinFuturesHoldAmount) { +func (o *OKCoin) GetFuturesHoldAmount(symbol, contractType string) []OKCoinFuturesHoldAmount { resp := []OKCoinFuturesHoldAmount{} path := fmt.Sprintf("future_hold_amount.do?symbol=%s&contract_type=%s", symbol, contractType) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) @@ -421,13 +423,13 @@ func (o *OKCoin) GetFuturesHoldAmount(symbol, contractType string) ([]OKCoinFutu return resp } -func (o *OKCoin) GetFuturesExplosive(symbol, contractType string, status, currentPage, pageLength int64) ([]OKCoinFuturesExplosive) { +func (o *OKCoin) GetFuturesExplosive(symbol, contractType string, status, currentPage, pageLength int64) []OKCoinFuturesExplosive { type Response struct { Data []OKCoinFuturesExplosive `json:"data"` } resp := Response{} path := fmt.Sprintf("future_explosive.do?symbol=%s&contract_type=%s&status=%d¤t_page=%d&page_length=%d", symbol, contractType, status, currentPage, pageLength) - err := SendHTTPGetRequest(o.APIUrl + path, true, &resp) + err := SendHTTPGetRequest(o.APIUrl+path, true, &resp) if err != nil { log.Println(err) @@ -466,7 +468,7 @@ func (o *OKCoin) GetFuturesPosition(symbol, contractType string) { func (o *OKCoin) Trade(amount, price float64, symbol, orderType string) { v := url.Values{} v.Set("amount", strconv.FormatFloat(amount, 'f', 8, 64)) - v.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) + v.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) v.Set("symbol", symbol) v.Set("type", orderType) @@ -481,7 +483,7 @@ func (o *OKCoin) FuturesTrade(amount, price float64, matchPrice, leverage int64, v := url.Values{} v.Set("symbol", symbol) v.Set("contract_type", contractType) - v.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) + v.Set("price", strconv.FormatFloat(price, 'f', 8, 64)) v.Set("amount", strconv.FormatFloat(amount, 'f', 8, 64)) v.Set("type", orderType) v.Set("match_price", strconv.FormatInt(matchPrice, 10)) @@ -751,7 +753,7 @@ func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values) (err v.Set("api_key", o.PartnerID) hasher := GetMD5([]byte(v.Encode() + "&secret_key=" + o.SecretKey)) v.Set("sign", strings.ToUpper(HexEncodeToString(hasher))) - + encoded := v.Encode() path := o.APIUrl + method @@ -771,7 +773,7 @@ func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values) (err if o.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } - + return nil } @@ -850,4 +852,4 @@ func (o *OKCoin) SetErrorDefaults() { "20027": "No transaction record", "20028": "No such contract", } -} \ No newline at end of file +}