Skip to content

Instantly share code, notes, and snippets.

@inhies
Last active December 30, 2015 13:58
Show Gist options
  • Save inhies/7838641 to your computer and use it in GitHub Desktop.
Save inhies/7838641 to your computer and use it in GitHub Desktop.
Console ticker for btc china
package main
import (
"encoding/json"
"fmt"
"github.com/kylelemons/godebug/pretty"
"io/ioutil"
"net/http"
"strconv"
"time"
)
type MarketData struct {
Ticker struct {
Ask f64 `json:"sell"`
Bid f64 `json:"buy"`
Last f64 `json:"last"`
Volume f64 `json:"vol"`
High f64 `json:"high"`
Low f64 `json:"low"`
}
}
type f64 float64
func (f *f64) UnmarshalJSON(data []byte) (err error) {
var float float64
// Trim the qoutes off the supplied data and parse it as a float64
float, err = strconv.ParseFloat(string(data[1:len(data)-1]), 64)
if err != nil {
return
}
// Set the field to the float64 value
*f = f64(float)
return
}
var url = "https://data.btcchina.com/data/ticker"
func main() {
tr := &http.Transport{}
client := &http.Client{Transport: tr}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Connection", "Keep-Alive")
var data MarketData
var newData MarketData
var i int64
i = 0
for {
if i%10 == 0 {
fmt.Println(" LAST | BID | ASK ")
}
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
jsonData, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
return
}
err = json.Unmarshal(jsonData, &newData)
if err != nil {
fmt.Println(err)
return
}
if newData != data {
d := newData.Ticker
fmt.Printf("%5.2f | %5.2f | %5.2f\n", d.Last, d.Bid, d.Ask)
i++
}
data = newData
time.Sleep(1 * time.Second)
}
}
func junk() {
pretty.Print("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment