Tidied up HTTP request code.

This commit is contained in:
Adrian Gallagher
2015-03-14 18:34:19 +11:00
parent 6e6542001a
commit ba4cda2491
15 changed files with 180 additions and 271 deletions

View File

@@ -1,8 +1,6 @@
package main
import (
"net/http"
"io/ioutil"
"fmt"
"log"
"encoding/json"
@@ -260,36 +258,28 @@ func (b *Bitfinex) SendAuthenticatedHTTPRequest(method, path string, params map[
PayloadBase64 := Base64Encode(PayloadJson)
hmac := GetHMAC(sha512.New384, []byte(PayloadBase64), []byte(b.APISecret))
req, err := http.NewRequest(method, BITFINEX_API_URL + path, strings.NewReader(""))
req.Header.Set("X-BFX-APIKEY", b.APIKey)
req.Header.Set("X-BFX-PAYLOAD", PayloadBase64)
req.Header.Set("X-BFX-SIGNATURE", HexEncodeToString(hmac))
headers := make(map[string]string)
headers["X-BFX-APIKEY"] = b.APIKey
headers["X-BFX-PAYLOAD"] = PayloadBase64
headers["X-BFX-SIGNATURE"] = HexEncodeToString(hmac)
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("SendAuthenticatedHTTPRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
resp, err := SendHTTPRequest(method, BITFINEX_API_URL + path, headers, strings.NewReader(""))
if b.Verbose {
log.Printf("Recieved raw: \n%s\n", string(contents))
log.Printf("Recieved raw: \n%s\n", resp)
}
err = json.Unmarshal(contents, &result)
err = json.Unmarshal([]byte(resp), &result)
if err != nil {
return errors.New("Unable to JSON response.")
return errors.New("Unable to JSON Unmarshal response.")
}
return nil
}
func (b *Bitfinex) GetTicker(symbol string) (BitfinexTicker) {
err := SendHTTPRequest(BITFINEX_API_URL + BITFINEX_TICKER + symbol, true, &b.Ticker)
err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_TICKER + symbol, true, &b.Ticker)
if err != nil {
log.Println(err)
return BitfinexTicker{}
@@ -298,7 +288,7 @@ func (b *Bitfinex) GetTicker(symbol string) (BitfinexTicker) {
}
func (b *Bitfinex) GetStats(symbol string) (bool) {
err := SendHTTPRequest(BITFINEX_API_URL + BITFINEX_STATS + symbol, true, &b.Stats)
err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_STATS + symbol, true, &b.Stats)
if err != nil {
log.Println(err)
return false
@@ -307,7 +297,7 @@ func (b *Bitfinex) GetStats(symbol string) (bool) {
}
func (b *Bitfinex) GetOrderbook(symbol string) (bool) {
err := SendHTTPRequest(BITFINEX_API_URL + BITFINEX_ORDERBOOK + symbol, true, &b.Orderbook)
err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_ORDERBOOK + symbol, true, &b.Orderbook)
if err != nil {
log.Println(err)
return false
@@ -316,7 +306,7 @@ func (b *Bitfinex) GetOrderbook(symbol string) (bool) {
}
func (b *Bitfinex) GetTrades(symbol string) (bool) {
err := SendHTTPRequest(BITFINEX_API_URL + BITFINEX_TRADES + symbol, true, &b.Trades)
err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_TRADES + symbol, true, &b.Trades)
if err != nil {
log.Println(err)
return false
@@ -325,7 +315,7 @@ func (b *Bitfinex) GetTrades(symbol string) (bool) {
}
func (b *Bitfinex) GetSymbols() (bool) {
err := SendHTTPRequest(BITFINEX_API_URL + BITFINEX_SYMBOLS, false, nil)
err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_SYMBOLS, false, nil)
if err != nil {
log.Println(err)
return false
@@ -334,7 +324,7 @@ func (b *Bitfinex) GetSymbols() (bool) {
}
func (b *Bitfinex) GetSymbolsDetails() (bool) {
err := SendHTTPRequest(BITFINEX_API_URL + BITFINEX_SYMBOLS_DETAILS, false, &b.SymbolsDetails)
err := SendHTTPGetRequest(BITFINEX_API_URL + BITFINEX_SYMBOLS_DETAILS, false, &b.SymbolsDetails)
if err != nil {
log.Println(err)
return false

View File

@@ -1,9 +1,7 @@
package main
import (
"net/http"
"net/url"
"io/ioutil"
"log"
"encoding/json"
"crypto/sha256"
@@ -112,7 +110,7 @@ func (b *Bitstamp) SetAPIKeys(clientID, apiKey, apiSecret string) {
}
func (b *Bitstamp) GetTicker() (BitstampTicker) {
err := SendHTTPRequest(BITSTAMP_API_URL + BITSTAMP_API_TICKER, true, &b.Ticker)
err := SendHTTPGetRequest(BITSTAMP_API_URL + BITSTAMP_API_TICKER, true, &b.Ticker)
if err != nil {
log.Println(err)
@@ -123,7 +121,7 @@ func (b *Bitstamp) GetTicker() (BitstampTicker) {
}
func (b *Bitstamp) GetOrderbook() {
err := SendHTTPRequest(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)
@@ -132,7 +130,7 @@ func (b *Bitstamp) GetOrderbook() {
}
func (b *Bitstamp) GetTransactions() {
err := SendHTTPRequest(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)
@@ -141,7 +139,7 @@ func (b *Bitstamp) GetTransactions() {
}
func (b *Bitstamp) GetEURUSDConversionRate() {
err := SendHTTPRequest(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)
@@ -278,31 +276,22 @@ func (b *Bitstamp) SendAuthenticatedHTTPRequest(path string, values url.Values,
log.Println("Sending POST request to " + path)
}
req, err := http.NewRequest("POST", path, strings.NewReader(values.Encode()))
headers := make(map[string]string)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", path, headers, strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if b.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n", resp)
}
err = json.Unmarshal(contents, &result)
err = json.Unmarshal([]byte(resp), &result)
if err != nil {
return errors.New("Unable to JSON response.")
return errors.New("Unable to JSON Unmarshal response.")
}
return nil

View File

@@ -1,7 +1,6 @@
package main
import (
"net/http"
"net/url"
"strconv"
"crypto/sha1"
@@ -9,7 +8,6 @@ import (
"errors"
"strings"
"time"
"io/ioutil"
"fmt"
"log"
)
@@ -204,7 +202,7 @@ func (b *BTCChina) GetTicker(symbol string) (BTCChinaTicker) {
resp := Response{}
req := fmt.Sprintf("%sdata/ticker?market=%s", BTCCHINA_API_URL, symbol)
err := SendHTTPRequest(req, true, &resp)
err := SendHTTPGetRequest(req, true, &resp)
if err != nil {
log.Println(err)
return BTCChinaTicker{}
@@ -214,7 +212,7 @@ func (b *BTCChina) GetTicker(symbol string) (BTCChinaTicker) {
func (b *BTCChina) GetTradesLast24h(symbol string) (bool) {
req := fmt.Sprintf("%sdata/trades?market=%s", BTCCHINA_API_URL, symbol)
err := SendHTTPRequest(req, true, nil)
err := SendHTTPGetRequest(req, true, nil)
if err != nil {
log.Println(err)
return false
@@ -241,7 +239,7 @@ func (b *BTCChina) GetTradeHistory(symbol string, limit, sinceTid int64, time ti
req += "?" + values
}
err := SendHTTPRequest(req, true, nil)
err := SendHTTPGetRequest(req, true, nil)
if err != nil {
log.Println(err)
return false
@@ -251,7 +249,7 @@ func (b *BTCChina) GetTradeHistory(symbol string, limit, sinceTid int64, time ti
func (b *BTCChina) GetOrderBook(symbol string, limit int) (bool) {
req := fmt.Sprintf("%sdata/orderbook?market=%s&limit=%d", BTCCHINA_API_URL, symbol, limit)
err := SendHTTPRequest(req, true, nil)
err := SendHTTPGetRequest(req, true, nil)
if err != nil {
log.Println(err)
return false
@@ -686,37 +684,27 @@ func (b *BTCChina) SendAuthenticatedHTTPRequest(method string, params []interfac
data, err := json.Marshal(postData)
if err != nil {
return errors.New("Unable to JSON POST data")
return errors.New("Unable to JSON Marshal POST data")
}
if b.Verbose {
log.Printf("Sending POST request to %s calling method %s with params %s\n", "https://api.btcchina.com/api_trade_v1.php", method, data)
}
req, err := http.NewRequest("POST", "https://api.btcchina.com/api_trade_v1.php", strings.NewReader(string(data)))
headers := make(map[string]string)
headers["Content-type"] = "application/json-rpc"
headers["Authorization"] = "Basic " + Base64Encode([]byte(b.APIKey + ":" + HexEncodeToString(hmac)))
headers["Json-Rpc-Tonce"] = nonce
resp, err := SendHTTPRequest("POST", "https://api.btcchina.com/api_trade_v1.php", headers, strings.NewReader(string(data)))
if err != nil {
return err
}
req.Header.Add("Content-type", "application/json-rpc")
req.Header.Add("Authorization", "Basic " + Base64Encode([]byte(b.APIKey + ":" + HexEncodeToString(hmac))))
req.Header.Add("Json-Rpc-Tonce", nonce)
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if b.Verbose {
log.Printf("Recv'd :%s\n", string(contents))
log.Printf("Recv'd :%s\n", resp)
}
return nil
}

View File

@@ -1,14 +1,11 @@
package main
import (
"net/http"
"net/url"
"strconv"
"crypto/sha512"
"errors"
"strings"
"time"
"io/ioutil"
"fmt"
"log"
)
@@ -93,7 +90,7 @@ func (b *BTCE) GetFee() (float64) {
func (b *BTCE) GetInfo() {
req := fmt.Sprintf("%s/%s/%s/", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_INFO)
err := SendHTTPRequest(req, true, nil)
err := SendHTTPGetRequest(req, true, nil)
if err != nil {
log.Println(err)
@@ -107,7 +104,7 @@ func (b *BTCE) GetTicker(symbol string) (BTCeTicker) {
response := Response{}
req := fmt.Sprintf("%s/%s/%s/%s", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_TICKER, symbol)
err := SendHTTPRequest(req, true, &response.Data)
err := SendHTTPGetRequest(req, true, &response.Data)
if err != nil {
log.Println(err)
@@ -123,7 +120,7 @@ func (b *BTCE) GetDepth(symbol string) () {
response := Response{}
req := fmt.Sprintf("%s/%s/%s/%s", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_DEPTH, symbol)
err := SendHTTPRequest(req, true, &response.Data)
err := SendHTTPGetRequest(req, true, &response.Data)
if err != nil {
log.Println(err)
@@ -141,7 +138,7 @@ func (b *BTCE) GetTrades(symbol string) () {
response := Response{}
req := fmt.Sprintf("%s/%s/%s/%s", BTCE_API_PUBLIC_URL, BTCE_API_PUBLIC_VERSION, BTCE_TRADES, symbol)
err := SendHTTPRequest(req, true, &response.Data)
err := SendHTTPGetRequest(req, true, &response.Data)
if err != nil {
log.Println(err)
@@ -243,31 +240,20 @@ func (b *BTCE) SendAuthenticatedHTTPRequest(method string, values url.Values) (e
log.Printf("Sending POST request to %s calling method %s with params %s\n", BTCE_API_PRIVATE_URL, method, encoded)
}
req, err := http.NewRequest("POST", BTCE_API_PRIVATE_URL, strings.NewReader(encoded))
headers := make(map[string]string)
headers["Key"] = b.APIKey
headers["Sign"] = HexEncodeToString(hmac)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", BTCE_API_PRIVATE_URL, headers, strings.NewReader(encoded))
if err != nil {
return err
}
req.Header.Add("Key", b.APIKey)
req.Header.Add("Sign", HexEncodeToString(hmac))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if b.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n",resp)
}
return nil
}

View File

@@ -1,14 +1,11 @@
package main
import (
"net/http"
"strconv"
"crypto/sha512"
"errors"
"strings"
"time"
"log"
"io/ioutil"
"fmt"
)
@@ -65,7 +62,7 @@ func (b *BTCMarkets) GetFee() (float64) {
func (b *BTCMarkets) GetTicker(symbol string) (BTCMarketsTicker) {
ticker := BTCMarketsTicker{}
path := fmt.Sprintf("/market/%s/AUD/tick", symbol)
err := SendHTTPRequest(BTCMARKETS_API_URL + path, true, &ticker)
err := SendHTTPGetRequest(BTCMARKETS_API_URL + path, true, &ticker)
if err != nil {
log.Println(err)
return BTCMarketsTicker{}
@@ -75,7 +72,7 @@ func (b *BTCMarkets) GetTicker(symbol string) (BTCMarketsTicker) {
func (b *BTCMarkets) GetOrderbook(symbol string) {
path := fmt.Sprintf("/market/%s/AUD/orderbook", symbol)
err := SendHTTPRequest(BTCMARKETS_API_URL + path, true, nil)
err := SendHTTPGetRequest(BTCMARKETS_API_URL + path, true, nil)
if err != nil {
log.Println(err)
}
@@ -88,7 +85,7 @@ func (b *BTCMarkets) GetTrades(symbol, since string) {
} else {
path = fmt.Sprintf("/market/%s/AUD/trades", symbol)
}
err := SendHTTPRequest(BTCMARKETS_API_URL + path, true, nil)
err := SendHTTPGetRequest(BTCMARKETS_API_URL + path, true, nil)
if err != nil {
log.Println(err)
}
@@ -109,33 +106,23 @@ func (b *BTCMarkets) SendAuthenticatedRequest(reqType, path, data string) (error
if b.Verbose {
log.Printf("Sending %s request to %s path %s with params %s\n", reqType, BTCMARKETS_API_URL + path, path, request)
}
req, err := http.NewRequest(reqType, BTCMARKETS_API_URL + path, strings.NewReader(""))
headers := make(map[string]string)
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
headers["Accept-Charset"] = "UTF-8"
headers["apikey"] = b.APIKey
headers["timestamp"] = nonce
headers["signature"] = Base64Encode(hmac)
resp, err := SendHTTPRequest(reqType, BTCMARKETS_API_URL + path, headers, strings.NewReader(""))
if err != nil {
return err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", "btc markets python client")
req.Header.Add("Accept-Charset", "UTF-8")
req.Header.Add("apikey", b.APIKey)
req.Header.Add("timestamp", nonce)
req.Header.Add("signature", Base64Encode(hmac))
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if b.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n", resp)
}
return nil

View File

@@ -116,7 +116,7 @@ func (c *Coinbase) SetAPIKeys(password, apiKey, apiSecret string) {
func (c *Coinbase) GetProducts() {
products := []CoinbaseProduct{}
err := SendHTTPRequest(COINBASE_API_URL + COINBASE_PRODUCTS, true, &products)
err := SendHTTPGetRequest(COINBASE_API_URL + COINBASE_PRODUCTS, true, &products)
if err != nil {
log.Println(err)
@@ -135,7 +135,7 @@ func (c *Coinbase) GetOrderbook(symbol string, level int) {
path = fmt.Sprintf("%s/%s/%s", COINBASE_API_URL + COINBASE_PRODUCTS, symbol, COINBASE_ORDERBOOK)
}
err := SendHTTPRequest(path, true, &orderbook)
err := SendHTTPGetRequest(path, true, &orderbook)
if err != nil {
log.Println(err)
@@ -146,7 +146,7 @@ func (c *Coinbase) GetOrderbook(symbol string, level int) {
func (c *Coinbase) GetTicker(symbol string) (CoinbaseTicker) {
ticker := CoinbaseTicker{}
path := fmt.Sprintf("%s/%s/%s", COINBASE_API_URL + COINBASE_PRODUCTS, symbol, COINBASE_TICKER)
err := SendHTTPRequest(path, true, &ticker)
err := SendHTTPGetRequest(path, true, &ticker)
if err != nil {
log.Println(err)
@@ -158,7 +158,7 @@ func (c *Coinbase) GetTicker(symbol string) (CoinbaseTicker) {
func (c *Coinbase) GetTrades(symbol string) {
trades := []CoinbaseTrade{}
path := fmt.Sprintf("%s/%s/%s", COINBASE_API_URL + COINBASE_PRODUCTS, symbol, COINBASE_TRADES)
err := SendHTTPRequest(path, true, &trades)
err := SendHTTPGetRequest(path, true, &trades)
if err != nil {
log.Println(err)
@@ -189,7 +189,7 @@ func (c *Coinbase) GetHistoricRates(symbol string, start, end, granularity int64
path += encoded
}
err := SendHTTPRequest(path, true, &history)
err := SendHTTPGetRequest(path, true, &history)
if err != nil {
log.Println(err)
@@ -200,7 +200,7 @@ func (c *Coinbase) GetHistoricRates(symbol string, start, end, granularity int64
func (c *Coinbase) GetStats(symbol string) (CoinbaseStats) {
stats := CoinbaseStats{}
path := fmt.Sprintf("%s/%s/%s", COINBASE_API_URL + COINBASE_PRODUCTS, symbol, COINBASE_STATS)
err := SendHTTPRequest(path, true, &stats)
err := SendHTTPGetRequest(path, true, &stats)
if err != nil {
log.Println(err)
@@ -211,7 +211,7 @@ func (c *Coinbase) GetStats(symbol string) (CoinbaseStats) {
func (c *Coinbase) GetCurrencies() {
currencies := []CoinbaseCurrency{}
err := SendHTTPRequest(COINBASE_API_URL + COINBASE_CURRENCIES, true, &currencies)
err := SendHTTPGetRequest(COINBASE_API_URL + COINBASE_CURRENCIES, true, &currencies)
if err != nil {
log.Println(err)

View File

@@ -10,8 +10,10 @@ import (
"encoding/base64"
"encoding/json"
"encoding/hex"
"io"
"io/ioutil"
"errors"
"strings"
"math"
"log"
)
@@ -92,9 +94,42 @@ func CalculateNetProfit(amount, priceThen, priceNow, costs float64) (float64) {
return (priceNow * amount) - (priceThen * amount) - costs
}
func SendHTTPRequest(url string, jsonDecode bool, result interface{}) (err error) {
func SendHTTPRequest(method, path string, headers map[string]string, body io.Reader) (string, error) {
result := strings.ToUpper(method)
if result != "POST" && result != "GET" {
return "", errors.New("Invalid HTTP method specified.")
}
req, err := http.NewRequest(method, path, body)
if err != nil {
return "", err
}
for k, v := range headers {
req.Header.Add(k, v)
}
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
contents, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return "", err
}
return string(contents), nil
}
func SendHTTPGetRequest(url string, jsonDecode bool, result interface{}) (err error) {
res, err := http.Get(url)
defer res.Body.Close()
if err != nil {
log.Println(err)
@@ -108,6 +143,7 @@ func SendHTTPRequest(url string, jsonDecode bool, result interface{}) (err error
contents, _ := ioutil.ReadAll(res.Body)
//log.Printf("Recieved raw: %s\n", string(contents))
defer res.Body.Close()
if jsonDecode {
err := json.Unmarshal(contents, &result)
@@ -118,5 +154,6 @@ func SendHTTPRequest(url string, jsonDecode bool, result interface{}) (err error
} else {
result = contents
}
return
return nil
}

View File

@@ -1,10 +1,8 @@
package main
import (
"net/http"
"net/url"
"fmt"
"io/ioutil"
"net/url"
"encoding/json"
"strings"
"time"
@@ -111,29 +109,21 @@ func QueryYahooCurrencyValues(currencies string) (error) {
values.Set("q", fmt.Sprintf("SELECT * from yahoo.finance.xchange WHERE pair in (\"%s\")", currencyPairs))
values.Set("format", "json")
values.Set("env", YAHOO_DATABASE)
path := YAHOO_YQL_URL+"?"+values.Encode()
req, err := http.NewRequest("GET", path, strings.NewReader(""))
headers := make(map[string]string)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", YAHOO_YQL_URL, headers, strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
err = json.Unmarshal([]byte(resp), &CurrencyStore)
if err != nil {
return err
}
contents, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(contents, &CurrencyStore)
if err != nil {
return err
}
resp.Body.Close()
return nil
}

View File

@@ -1,11 +1,8 @@
package main
import (
"net/http"
"net/url"
"errors"
"strings"
"io/ioutil"
"strconv"
"time"
"fmt"
@@ -70,7 +67,7 @@ func (h *HUOBI) GetFee() (float64) {
func (h *HUOBI) GetTicker(symbol string) (HuobiTicker) {
resp := HuobiTickerResponse{}
path := fmt.Sprintf("http://market.huobi.com/staticmarket/ticker_%s_json.js", symbol)
err := SendHTTPRequest(path, true, &resp)
err := SendHTTPGetRequest(path, true, &resp)
if err != nil {
log.Println(err)
@@ -81,7 +78,7 @@ func (h *HUOBI) GetTicker(symbol string) (HuobiTicker) {
func (h *HUOBI) GetOrderBook(symbol string) (bool) {
path := fmt.Sprintf("http://market.huobi.com/staticmarket/depth_%s_json.js", symbol)
err := SendHTTPRequest(path, true, nil)
err := SendHTTPGetRequest(path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -206,26 +203,17 @@ func (h *HUOBI) SendAuthenticatedRequest(method string, v url.Values) (error) {
log.Printf("Sending POST request to %s with params %s\n", HUOBI_API_URL, encoded)
}
req, err := http.NewRequest("POST", HUOBI_API_URL, strings.NewReader(encoded))
headers := make(map[string]string)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", HUOBI_API_URL, headers, strings.NewReader(encoded))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if h.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n", resp)
}
return nil

View File

@@ -8,7 +8,6 @@ import (
"strings"
"time"
"encoding/json"
"io/ioutil"
"log"
)
@@ -81,7 +80,7 @@ func (i *ItBit) GetFee(maker bool) (float64) {
func (i *ItBit) GetTicker(currency string) (ItBitTicker) {
path := ITBIT_API_URL + "/markets/" + currency + "/ticker"
var itbitTicker ItBitTicker
err := SendHTTPRequest(path, true, &itbitTicker)
err := SendHTTPGetRequest(path, true, &itbitTicker)
if err != nil {
log.Println(err)
return ItBitTicker{}
@@ -91,7 +90,7 @@ func (i *ItBit) GetTicker(currency string) (ItBitTicker) {
func (i *ItBit) GetOrderbook(currency string) (bool) {
path := ITBIT_API_URL + "/markets/" + currency + "/orders"
err := SendHTTPRequest(path , true, nil)
err := SendHTTPGetRequest(path , true, nil)
if err != nil {
log.Println(err)
return false
@@ -101,7 +100,7 @@ func (i *ItBit) GetOrderbook(currency string) (bool) {
func (i *ItBit) GetTradeHistory(currency, timestamp string) (bool) {
req := "/trades?since=" + timestamp
err := SendHTTPRequest(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
@@ -261,35 +260,31 @@ func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params
PayloadJson, err := json.Marshal(request)
if err != nil {
return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON Marshal request")
}
if i.Verbose {
log.Printf("Request JSON: %s\n", PayloadJson)
}
if err != nil {
return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON request")
}
hmac := GetHMAC(sha512.New, []byte(nonce + string(PayloadJson)), []byte(i.APISecret))
signature := Base64Encode([]byte(HexEncodeToString(hmac)))
req, err := http.NewRequest(method, path, strings.NewReader(""))
req.Header.Add("Authorization", i.ClientKey + ":" + signature)
req.Header.Add("X-Auth-Timestamp", nonce)
req.Header.Add("X-Auth-Nonce", nonce)
req.Header.Add("Content-Type", "application/json")
headers := make(map[string]string)
headers["Authorization"] = i.ClientKey + ":" + signature
headers["X-Auth-Timestamp"] = nonce
headers["X-Auth-Nonce"] = nonce
headers["Content-Type"] = "application/json"
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
resp, err := http.NewRequest(method, path, strings.NewReader(""))
if err != nil {
return errors.New("SendAuthenticatedHTTPRequest: Unable to send request")
if resp != nil {
return nil
}
contents, _ := ioutil.ReadAll(resp.Body)
if i.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n", resp)
}
return nil

View File

@@ -10,8 +10,6 @@ import (
"time"
"strings"
"net/url"
"net/http"
"io/ioutil"
)
const (
@@ -196,7 +194,7 @@ func (k *Kraken) GetSpread(symbol string) {
func (k *Kraken) SendKrakenRequest(method string) (map[string]interface{}, error) {
path := fmt.Sprintf("%s/%s/public/%s", KRAKEN_API_URL, KRAKEN_API_VERSION, method)
resp := KrakenResponse{}
err := SendHTTPRequest(path, true, &resp)
err := SendHTTPGetRequest(path, true, &resp)
log.Printf("Sending GET request to %s\n", path)
@@ -511,26 +509,22 @@ func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values)
log.Printf("Sending POST request to %s, path: %s.", KRAKEN_API_URL, path)
}
req, err := http.NewRequest("POST", KRAKEN_API_URL + path, strings.NewReader(values.Encode()))
req.Header.Set("API-Key", k.ClientKey)
req.Header.Set("API-Sign", signature)
headers := make(map[string]string)
headers["API-Key"] = k.ClientKey
headers["API-Sign"] = signature
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
resp, err := SendHTTPRequest("POST", KRAKEN_API_URL + path, headers, strings.NewReader(values.Encode()))
if err != nil {
return nil, errors.New("SendAuthenticatedHTTPRequest: Unable to send request")
return nil, err
}
contents, _ := ioutil.ReadAll(resp.Body)
if k.Verbose {
log.Printf("Recieved raw: \n%s\n", string(contents))
log.Printf("Recieved raw: \n%s\n", resp)
}
kresp := KrakenResponse{}
err = json.Unmarshal(contents, &kresp)
err = json.Unmarshal([]byte(resp), &kresp)
if err != nil {
return nil, errors.New("Unable to JSON response.")

View File

@@ -1,14 +1,12 @@
package main
import (
"net/http"
"net/url"
"strconv"
"crypto/sha256"
"errors"
"strings"
"time"
"io/ioutil"
"log"
)
@@ -83,7 +81,7 @@ func (l *LakeBTC) GetFee(maker bool) (float64) {
func (l *LakeBTC) GetTicker() (LakeBTCTickerResponse) {
response := LakeBTCTickerResponse{}
err := SendHTTPRequest(LAKEBTC_API_URL + LAKEBTC_TICKER, true, &response)
err := SendHTTPGetRequest(LAKEBTC_API_URL + LAKEBTC_TICKER, true, &response)
if err != nil {
log.Println(err)
return response
@@ -97,7 +95,7 @@ func (l *LakeBTC) GetOrderBook(currency string) (bool) {
req = LAKEBTC_ORDERBOOK_CNY
}
err := SendHTTPRequest(LAKEBTC_API_URL + req, true, nil)
err := SendHTTPGetRequest(LAKEBTC_API_URL + req, true, nil)
if err != nil {
log.Println(err)
return false
@@ -106,7 +104,7 @@ func (l *LakeBTC) GetOrderBook(currency string) (bool) {
}
func (l *LakeBTC) GetTradeHistory() (bool) {
err := SendHTTPRequest(LAKEBTC_API_URL + LAKEBTC_TRADES, true, nil)
err := SendHTTPGetRequest(LAKEBTC_API_URL + LAKEBTC_TRADES, true, nil)
if err != nil {
log.Println(err)
return false
@@ -182,28 +180,19 @@ func (l *LakeBTC) SendAuthenticatedHTTPRequest(method, params string) (err error
log.Printf("Sending POST request to %s calling method %s with params %s\n", LAKEBTC_API_URL, method, encoded)
}
req, err := http.NewRequest("POST", LAKEBTC_API_URL, strings.NewReader(encoded))
headers := make(map[string]string)
headers["Json-Rpc-Tonce"] = nonce
headers["Authorization: Basic"] = Base64Encode([]byte(l.Email + ":" + HexEncodeToString(hmac)))
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", LAKEBTC_API_URL, headers, strings.NewReader(encoded))
if err != nil {
return err
}
req.Header.Add("Json-Rpc-Tonce", nonce)
req.Header.Add("Authorization: Basic", Base64Encode([]byte(l.Email + ":" + HexEncodeToString(hmac))))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if l.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n", resp)
}
return nil

View File

@@ -301,7 +301,7 @@ func main() {
}
}
}
err = RetrieveConfigCurrencyPairs(bot.config)
if err != nil {

View File

@@ -1,11 +1,8 @@
package main
import (
"net/http"
"net/url"
"errors"
"strings"
"io/ioutil"
"strconv"
"fmt"
"log"
@@ -100,7 +97,7 @@ func (o *OKCoin) GetFee(maker bool) (float64) {
func (o *OKCoin) GetTicker(symbol string) (OKCoinTicker) {
resp := OKCoinTickerResponse{}
path := fmt.Sprintf("ticker.do?symbol=%s&ok=1", symbol)
err := SendHTTPRequest(o.APIUrl + path, true, &resp)
err := SendHTTPGetRequest(o.APIUrl + path, true, &resp)
if err != nil {
log.Println(err)
@@ -112,7 +109,7 @@ func (o *OKCoin) GetTicker(symbol string) (OKCoinTicker) {
func (o *OKCoin) GetFuturesTicker(symbol, contractType string) (OKCoinFuturesTicker) {
resp := OKCoinFuturesTickerResponse{}
path := fmt.Sprintf("future_ticker.do?symbol=%s&contract_type=%s", symbol, contractType)
err := SendHTTPRequest(o.APIUrl + path, true, &resp)
err := SendHTTPGetRequest(o.APIUrl + path, true, &resp)
if err != nil {
log.Println(err)
return OKCoinFuturesTicker{}
@@ -122,7 +119,7 @@ func (o *OKCoin) GetFuturesTicker(symbol, contractType string) (OKCoinFuturesTic
func (o *OKCoin) GetOrderBook(symbol string) (bool) {
path := "depth.do?symbol=" + symbol
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -132,7 +129,7 @@ func (o *OKCoin) GetOrderBook(symbol string) (bool) {
func (o *OKCoin) GetFuturesDepth(symbol, contractType string) (bool) {
path := fmt.Sprintf("future_depth.do?symbol=%s&contract_type=%s", symbol, contractType)
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -142,7 +139,7 @@ func (o *OKCoin) GetFuturesDepth(symbol, contractType string) (bool) {
func (o *OKCoin) GetTradeHistory(symbol string) (bool) {
path := "trades.do?symbol=" + symbol
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -152,7 +149,7 @@ func (o *OKCoin) GetTradeHistory(symbol string) (bool) {
func (o *OKCoin) GetFuturesTrades(symbol, contractType string) (bool) {
path := fmt.Sprintf("future_trades.do?symbol=%s&contract_type=%s", symbol, contractType)
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -162,7 +159,7 @@ func (o *OKCoin) GetFuturesTrades(symbol, contractType string) (bool) {
func (o *OKCoin) GetFuturesIndex(symbol string) (bool) {
path := "future_index.do?symbol=" + symbol
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -171,7 +168,7 @@ func (o *OKCoin) GetFuturesIndex(symbol string) (bool) {
}
func (o *OKCoin) GetFuturesExchangeRate() (bool) {
err := SendHTTPRequest(o.APIUrl + "exchange_rate.do", true, nil)
err := SendHTTPGetRequest(o.APIUrl + "exchange_rate.do", true, nil)
if err != nil {
log.Println(err)
}
@@ -180,7 +177,7 @@ func (o *OKCoin) GetFuturesExchangeRate() (bool) {
func (o *OKCoin) GetFuturesEstimatedPrice(symbol string) (bool) {
path := "future_estimated_price.do?symbol=" + symbol
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -190,7 +187,7 @@ func (o *OKCoin) GetFuturesEstimatedPrice(symbol string) (bool) {
func (o *OKCoin) GetFuturesTradeHistory(symbol, date string, since int64) (bool) {
path := fmt.Sprintf("future_trades.do?symbol=%s&date%s&since=%d", symbol, date, since)
err := SendHTTPRequest(o.APIUrl + path, true, nil)
err := SendHTTPGetRequest(o.APIUrl + path, true, nil)
if err != nil {
log.Println(err)
return false
@@ -416,26 +413,17 @@ func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values) (err
log.Printf("Sending POST request to %s with params %s\n", path, encoded)
}
req, err := http.NewRequest("POST", path, strings.NewReader(encoded))
headers := make(map[string]string)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", path, headers, strings.NewReader(encoded))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
if o.Verbose {
log.Printf("Recieved raw: %s\n", string(contents))
log.Printf("Recieved raw: %s\n", resp)
}
return nil

View File

@@ -1,12 +1,9 @@
package main
import (
"net/http"
"net/url"
"strings"
"log"
"io/ioutil"
"errors"
)
const (
@@ -43,24 +40,15 @@ func SMSNotify(to, message string) (error) {
values.Set("to", to)
values.Set("text", message)
reqBody := strings.NewReader(values.Encode())
req, err := http.NewRequest("POST", SMSGLOBAL_API_URL, reqBody)
headers := make(map[string]string)
headers["Content-Type"] = "application/x-www-form-urlencoded"
resp, err := SendHTTPRequest("POST", SMSGLOBAL_API_URL, headers, strings.NewReader(values.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return errors.New("PostRequest: Unable to send request")
}
contents, _ := ioutil.ReadAll(resp.Body)
log.Printf("Recieved raw: %s\n", string(contents))
resp.Body.Close()
log.Printf("Recieved raw: %s\n", resp)
return nil
}