-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
838 lines (673 loc) · 21.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/Beldur/kraken-go-api-client"
"github.com/fsnotify/fsnotify"
"github.com/gorilla/mux"
"github.com/jyap808/go-poloniex"
_ "github.com/mattn/go-sqlite3"
"github.com/op/go-logging"
"github.com/spf13/viper"
)
var err error
/*
STRUCTS CONFIGURED IN structs.go
*/
var config Config
var logFile *os.File
var log = logging.MustGetLogger("bitcoin-logger")
// Example format string. Everything except the message has a custom color
// which is dependent on the log level. Many fields have a custom output
// formatting too, eg. the time returns the hour down to the milli second.
var format = logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
// Setup global home and config folders
// File location
var fileLocation string = "/.config/kyco.bitcoin.currency.tickers/"
// Get home folder
var home string = os.Getenv("HOME") + fileLocation
// Get Exchange rate based on an API call
func get_exchange_rate(w http.ResponseWriter, req *http.Request) {
var (
params = mux.Vars(req)
)
data, err := queryExchangeSQLite(params["exchange"], params["currencyCode"])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Infof("Called: %s -> %s\n", params["exchange"], params["currencyCode"])
json.NewEncoder(w).Encode(data)
}
// Get Exchange data based on an API call
func show_exchange_methods(w http.ResponseWriter, req *http.Request) {
var (
params = mux.Vars(req)
url = ""
)
// Get the URL
url = "http://" + req.Header.Get("X-Forwarded-Server") + "/" + params["exchange"] + "/"
// Grab exchange data
data, err := queryExchangeCurrencyCodesSQLite(params["exchange"], url)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Infof("Called: %s\n", params["exchange"])
// Return exchange data
json.NewEncoder(w).Encode(data)
}
// Get list of exchanges
func showExchanges(w http.ResponseWriter, req *http.Request) {
var (
url = ""
)
// Get the URL
url = "http://" + req.Header.Get("X-Forwarded-Server") + "/"
// Grab exchange data
data, err := queryListOfExchanges(url)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Infof("Called Root Page")
// Return exchange data
json.NewEncoder(w).Encode(data)
}
// Initialises various bitcoin price tickers
func bitcoinPrices() {
// Tick on the minute
// t := minuteTicker()
for {
// wait for the tick
// <-t.C
// Start luno ticker
lunoTicker()
log.Notice("Ran Luno Ticker")
// Start bitstamp ticker
bitstampTicker()
log.Notice("Ran Bitstamp Ticker")
// Start kraken ticker
krakenTicker()
log.Notice("Ran Kraken Ticker")
// Start bitfinex ticker
bitfinexTicker()
log.Notice("Ran Bitfinex Ticker")
// Start bitsquare ticker
bitsquareTicker()
log.Notice("Ran Bitsquare Ticker")
// Start btcc ticker
btccTicker()
log.Notice("Ran BTCChina Ticker")
// Start okcoin ticker
okcoinTicker()
log.Notice("Ran OKCoin Ticker")
// Start poloniex ticker
poloniexTicker()
log.Notice("Ran Poloniex Ticker")
time.Sleep(10 * time.Minute)
}
}
// Grabs a snapshot of the current luno exchange
func lunoTicker() {
// Make API call to luno
resp := apiCall(config.Luno.URL)
// If an empty response was returned
if resp == nil {
return
}
// Callers should close resp.Body
// when done reading from it
// Defer the closing of the body
defer resp.Body.Close()
// Fill the record with the data from the JSON
var record LunoTicker
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Error(err.Error())
} else {
// Write to DB
// Loop through the slice
for i := range record.Tickers {
// Format timestamp as string
timestampString := strconv.FormatInt(time.Now().Unix(), 10)
insertIntoSQLite("Luno", timestampString, record.Tickers[i].Ask, record.Tickers[i].Bid, "1", record.Tickers[i].Pair[3:])
}
}
}
// Grabs a snapshot of the current bitstamp exchange
func bitstampTicker() {
// Make API call to bitstamp
resp := apiCall(config.Bitstamp.URL)
// If an empty response was returned
if resp == nil {
return
}
// Callers should close resp.Body
// when done reading from it
// Defer the closing of the body
defer resp.Body.Close()
// Fill the record with the data from the JSON
var record Bitstamp
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Error(err.Error())
} else {
// Insert into SQlite
insertIntoSQLite("Bitstamp", record.Timestamp, record.Ask, record.Bid, record.Volume, "USD")
}
}
// Gets ticker data from kraken
func krakenTicker() {
// If the API keys are not present, just return
if len(config.Kraken.APIKey) == 0 && len(config.Kraken.APISecret) == 0 {
return
}
api := krakenapi.New(config.Kraken.APIKey, config.Kraken.APISecret)
// There are also some strongly typed methods available
ticker, err := api.Ticker(krakenapi.XXBTZEUR, krakenapi.XXBTZUSD, krakenapi.XXBTZGBP, krakenapi.DASHXBT, krakenapi.XETCXXBT, krakenapi.XLTCXXBT)
if err != nil {
log.Error(err.Error())
} else {
v := reflect.ValueOf(ticker).Elem()
typeOfT := v.Type()
for j := 0; j < v.NumField(); j++ {
f := v.Field(j)
inter := f.Interface().(krakenapi.PairTickerInfo)
// Check if the ask value is empty
if len(inter.Ask) > 0 {
// Insert into SQlite
insertIntoSQLite("Kraken", strconv.FormatInt(int64(time.Now().Unix()), 10), inter.Ask[0], inter.Bid[0], inter.Volume[0], formatCurrencyString(typeOfT.Field(j).Name, "Kraken"))
}
}
}
}
// Grabs a snapshot of the current bitfinex exchange
func bitfinexTicker() {
// In this case, we will loop through all
// the tickers set in the config file
tickerSplit := strings.Split(config.Bitfinex.Tickers, ",")
for i := range tickerSplit {
// Check if there is any data in the string
// if not, skip this loop
if len(tickerSplit[i]) < 2 {
continue
}
// Make API call to bitfinex
resp := apiCall(config.Bitfinex.URL + tickerSplit[i])
// If an empty response was returned
if resp == nil {
continue
}
// Callers should close resp.Body
// when done reading from it
// Defer the closing of the body
defer resp.Body.Close()
// Fill the record with the data from the JSON
var record Bitfinex
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Error(err.Error())
} else {
// Insert into SQlite
insertIntoSQLite("Bitfinex", record.Timestamp, record.Ask, record.Bid, record.Volume, formatCurrencyString(tickerSplit[i], "Bitfinex"))
}
}
}
// Grabs a snapshot of the current bitsquare exchange
func bitsquareTicker() {
// In this case, we will loop through all
// the tickers set in the config file
tickerSplit := strings.Split(config.Bitsquare.Tickers, ",")
for i := range tickerSplit {
// Check if there is any data in the string
// if not, skip this loop
if len(tickerSplit[i]) < 2 {
continue
}
// Make API call to bitsquare
resp := apiCall(config.Bitsquare.URL + tickerSplit[i])
// If an empty response was returned
if resp == nil {
continue
}
// Callers should close resp.Body
// when done reading from it
// Defer the closing of the body
defer resp.Body.Close()
// Fill the record with the data from the JSON
var record []Bitsquare
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Error(err.Error())
} else {
// Create a timestamp now
ts := strconv.FormatInt(int64(time.Now().Unix()), 10)
// Insert into SQlite
insertIntoSQLite("Bitsquare", ts, record[0].Sell, record[0].Buy, record[0].VolumeRight, formatCurrencyString(tickerSplit[i], "Bitsquare"))
}
}
}
// Grabs a snapshot of the current BTCC exchange
func btccTicker() {
// In this case, we will loop through all
// the tickers set in the config file
tickerSplit := strings.Split(config.BTCC.Tickers, ",")
for i := range tickerSplit {
// Check if there is any data in the string
// if not, skip this loop
if len(tickerSplit[i]) < 2 {
continue
}
// Make API call to btcc
resp := apiCall(config.BTCC.URL + tickerSplit[i])
// Callers should close resp.Body
// when done reading from it
// Defer the closing of the body
defer resp.Body.Close()
// Fill the record with the data from the JSON
var record BTCC
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Error(err.Error())
} else {
// Insert into SQlite
insertIntoSQLite("BTCChina", strconv.FormatInt((record.Ticker.Timestamp/1000), 10), strconv.FormatFloat(record.Ticker.AskPrice, 'f', 2, 64), strconv.FormatFloat(record.Ticker.BidPrice, 'f', 2, 64), strconv.FormatFloat(record.Ticker.Volume, 'f', 2, 64), formatCurrencyString(tickerSplit[i], "btcc"))
}
}
}
// Grabs a snapshot of the current OKCoin exchange
func okcoinTicker() {
// In this case, we will loop through all
// the tickers set in the config file
tickerSplit := strings.Split(config.OKCoin.Tickers, ",")
for i := range tickerSplit {
// Check if there is any data in the string
// if not, skip this loop
if len(tickerSplit[i]) < 2 {
continue
}
// Make API call to OKCoin
resp := apiCall(config.OKCoin.URL + tickerSplit[i])
// If an empty response was returned
if resp == nil {
continue
}
// Callers should close resp.Body
// when done reading from it
// Defer the closing of the body
defer resp.Body.Close()
// Fill the record with the data from the JSON
var record OKCoin
// Use json.Decode for reading streams of JSON data
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
log.Error(err.Error())
} else {
// Insert into SQlite
insertIntoSQLite("OKCoin", record.Date, record.Ticker.Sell, record.Ticker.Buy, record.Ticker.Vol, formatCurrencyString(tickerSplit[i], "okcoin"))
}
}
}
// Grabs a snapshot of the current Poloniex exchange
func poloniexTicker() {
// Init Poloniex client
polClient := poloniex.New(config.Poloniex.APIKey, config.Poloniex.APISecret)
// Get ticker data
tickers, err := polClient.GetTickers()
// Check if we had an error, if we did, log it
if err != nil {
log.Error(err.Error())
} else {
// Create a timestamp now
ts := strconv.FormatInt(int64(time.Now().Unix()), 10)
for key, ticker := range tickers {
// Insert into SQlite
insertIntoSQLite("Poloniex", ts, strconv.FormatFloat(ticker.LowestAsk, 'f', 8, 64), strconv.FormatFloat(ticker.HighestBid, 'f', 8, 64), strconv.FormatFloat(ticker.BaseVolume, 'f', 8, 64), key)
}
}
}
// performs an API call to a URL and returns a JSON body response
func apiCall(urlRequest string) *http.Response {
url := fmt.Sprintf(urlRequest)
// Build the request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Error("NewRequest: ", err)
return nil
}
// For control over HTTP client headers,
// redirect policy, and other settings,
// create a Client
// A Client is an HTTP client
client := &http.Client{}
// Send the request via a client
// Do sends an HTTP request and
// returns an HTTP response
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return nil
}
// // Callers should close resp.Body
// // when done reading from it
// // Defer the closing of the body
// defer resp.Body.Close()
// Return the body
return resp
}
// formats the currency code into something more standard
func formatCurrencyString(currencyCode string, exchange string) string {
// Replace BTC
replaceBTC := strings.Replace(strings.ToUpper(currencyCode), "BTC", "", -1)
// Perform extra replacements with Kraken
if exchange == "Kraken" {
replaceBTC = strings.Replace(replaceBTC, "XBTC", "", -1)
replaceBTC = strings.Replace(replaceBTC, "XXBTZ", "", -1)
replaceBTC = strings.Replace(replaceBTC, "XXBT", "", -1)
replaceBTC = strings.Replace(replaceBTC, "X", "", -1)
replaceBTC = strings.Replace(replaceBTC, "DASHBT", "DASH", -1)
}
replaceBTC = strings.Replace(replaceBTC, "_", "", -1)
return replaceBTC
}
// Check for and print/panic on errors
func check(e error) {
if e != nil {
log.Error(e.Error())
}
}
// Open SQlite Connection
func sqliteOpen() *sql.DB {
db, err := sql.Open("sqlite3", home+"/data.db")
if err != nil {
log.Error(err.Error())
}
return db
}
// Sets up the sqlite databases and connections
func setupSQLiteDB() {
// Setup sqlite connection
var sqliteConnection string
// If the config file line is empty, then default
if len(config.SqliteLocation) > 0 {
sqliteConnection = config.SqliteLocation
} else {
sqliteConnection = home + "/data.db"
}
// Check if the sqlite database already exists, if it does not, continue
// else, don't care
if _, err := os.Stat(sqliteConnection); os.IsNotExist(err) {
sqliteDB := sqliteOpen()
defer sqliteDB.Close() // Don't forget to close
sqlStmt := `create table exchanges (id integer not null primary key, exchange text, timestamp real, ask real, bid real, volume real default 0, currencyCode text);`
_, err = sqliteDB.Exec(sqlStmt)
if err != nil {
log.Warning("%q: %s\n", err, sqlStmt)
return
}
}
}
// Insert function into sqlite
func insertIntoSQLite(exchange string, timestamp string, ask string, bid string, volume string, currencyCode string) {
// If the exchange name is not there, ignore, otherwise run
if len(exchange) > 0 && len(currencyCode) > 0 {
// Clean strings, if the string doesn't contain anything, default
cleanStrings(×tamp, &ask, &bid, &volume)
// Write to DB
sqliteDB := sqliteOpen()
// Insert the database record
sqlStmt := `insert into exchanges (exchange, timestamp, ask, bid, volume, currencyCode) values ('` + exchange + `',` + timestamp + `, ` + ask + `,` + bid + `, ` + volume + `, '` + currencyCode + `');`
_, err = sqliteDB.Exec(sqlStmt)
if err != nil {
log.Warning("%q: %s\n", err, sqlStmt)
return
}
// Close the sqlite connection
sqliteDB.Close()
}
}
// SELECT function ifromnto sqlite
func queryExchangeSQLite(exchange string, currencyCode string) (resp *APIStruct, err error) {
// If the exchange name is not there, ignore, otherwise run
if len(exchange) > 0 && len(currencyCode) > 0 {
// Write to DB
sqliteDB := sqliteOpen()
// Query for data
response := sqliteDB.QueryRow(`select exchange, ask, bid, ROUND((ask + bid) / 2, 8) as price,
volume as volume, datetime(timestamp, 'unixepoch') as timestamp, currencyCode
from exchanges
where currencyCode = ? and exchange = ? order by ID desc LIMIT 1;`, currencyCode, exchange)
tmp := &APIStruct{}
// Scan data into response
err := response.Scan(&tmp.Exchange, &tmp.Ask, &tmp.Bid, &tmp.Average, &tmp.Volume, &tmp.DateUpdated, &tmp.CurrencyCode)
if err != nil {
log.Warning("%q\n", err)
return nil, errors.New("No values found")
}
// Close the sqlite connection
sqliteDB.Close()
// return response
return tmp, nil
}
log.Warning("Nothing was queried!")
return nil, errors.New("Exchange or currency code empty")
}
// SELECT function ifromnto sqlite
func queryExchangeCurrencyCodesSQLite(exchange string, url string) (resp []*string, err error) {
// If the exchange name is not there, ignore, otherwise run
if len(exchange) > 0 {
// Write to DB
sqliteDB := sqliteOpen()
// Query for data
response, err := sqliteDB.Query(`select DISTINCT currencyCode from exchanges where exchange = ?;`, exchange)
// Check if there are errors
if err != nil {
log.Error(err.Error())
return nil, err
}
// Scan the values into a string slice
for response.Next() {
var tmp string
response.Scan(&tmp)
tmp = url + tmp
resp = append(resp, &tmp)
}
// If anything was returned
if len(resp) == 0 {
return nil, errors.New("Exchange doesn't exist")
}
// return response
return resp, nil
}
log.Warning("Nothing was queried!")
return nil, errors.New("Exchange doesn't exists")
}
// SELECT function sqlite
func queryListOfExchanges(url string) (resp []*string, err error) {
// Write to DB
sqliteDB := sqliteOpen()
// Query for data
response, err := sqliteDB.Query(`select DISTINCT exchange from exchanges;`)
// Check if there are errors
if err != nil {
log.Error(err.Error())
return nil, err
}
// Scan the values into a string slice
for response.Next() {
var tmp string
response.Scan(&tmp)
tmp = url + tmp
resp = append(resp, &tmp)
}
// If anything was returned
if len(resp) == 0 {
return nil, errors.New("No exchanges exist")
}
// return response
return resp, nil
}
// clean strings before inserting, to provide default values
func cleanStrings(timestamp *string, ask *string, bid *string, volume *string) {
if len(*timestamp) == 0 {
*timestamp = strconv.FormatInt(int64(time.Now().Unix()), 10)
}
if len(*ask) == 0 {
*ask = "0"
}
if len(*bid) == 0 {
*bid = "0"
}
if len(*volume) == 0 {
*volume = "0"
}
}
// Waits for the minute to tick over
func minuteTicker() *time.Ticker {
// Return new ticker that triggers on the minute
return time.NewTicker(time.Second * time.Duration(int(60*10)-time.Now().Second()))
}
// Configure logging
func configLog() {
// Check if it is already open
logFile.Close()
// Configure logging
logFile, err := os.OpenFile(config.LogFile, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
log.Info("error opening file: %v", err)
}
// For demo purposes, create two backend for os.Stderr.
loggingFile := logging.NewLogBackend(logFile, "", 0)
// For messages written to loggingFile we want to add some additional
// information to the output, including the used log level and the name of
// the function.
loggingFileFormatter := logging.NewBackendFormatter(loggingFile, format)
// Set the backends to be used.
logging.SetBackend(loggingFileFormatter)
}
// Configure configs
func configInit() {
// Config File
viper.SetConfigName("config") // no need to include file extension
viper.AddConfigPath(home) // set the path of your config file
err := viper.ReadInConfig()
if err != nil {
log.Info("Config file not found... Error %s\n", err)
} else {
// ========= CONFIG ================================================================
logFile := viper.GetString("config.logFile")
sqliteLocation := viper.GetString("config.sqliteLocation")
port := viper.GetString("config.port")
krakenurl := viper.GetString("exchanges.kraken.url")
krakenAPIKey := viper.GetString("exchanges.kraken.apiKey")
krakenAPISecret := viper.GetString("exchanges.kraken.apiSecret")
lunourl := viper.GetString("exchanges.luno.url")
bitstampurl := viper.GetString("exchanges.bitstamp.url")
bitfinexurl := viper.GetString("exchanges.bitfinex.url")
bitfinextickers := viper.GetString("exchanges.bitfinex.tickers")
bitsquareurl := viper.GetString("exchanges.bitsquare.url")
bitsquaretickers := viper.GetString("exchanges.bitsquare.tickers")
btccurl := viper.GetString("exchanges.btcc.url")
btcctickers := viper.GetString("exchanges.btcc.tickers")
okcoinurl := viper.GetString("exchanges.okcoin.url")
okcointickers := viper.GetString("exchanges.okcoin.tickers")
poloniexAPIKey := viper.GetString("exchanges.poloniex.apiKey")
poloniexAPISecret := viper.GetString("exchanges.poloniex.apiSecret")
// Kraken
kraken := KrakenConfig{
URL: krakenurl,
APIKey: krakenAPIKey,
APISecret: krakenAPISecret,
}
// Luno
luno := LunoConfig{
URL: lunourl,
}
// Bitstamp
bitstamp := BitstampConfig{
URL: bitstampurl,
}
// Bitfinex
bitfinex := BitfinexConfig{
URL: bitfinexurl,
Tickers: bitfinextickers,
}
// Bitsquare
bitsquare := BitsquareConfig{
URL: bitsquareurl,
Tickers: bitsquaretickers,
}
// BTCChina
btcc := BtccConfig{
URL: btccurl,
Tickers: btcctickers,
}
// OKCoin
okcoin := OKCoinConfig{
URL: okcoinurl,
Tickers: okcointickers,
}
// Poloniex
poloniex := PoloniexConfig{
APIKey: poloniexAPIKey,
APISecret: poloniexAPISecret,
}
// Main Config
config = Config{
LogFile: logFile,
SqliteLocation: sqliteLocation,
Port: port,
Kraken: kraken,
Luno: luno,
Bitstamp: bitstamp,
Bitfinex: bitfinex,
Bitsquare: bitsquare,
BTCC: btcc,
OKCoin: okcoin,
Poloniex: poloniex,
}
}
// Monitor the config file for changes and reload
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
// Re-configure config
configInit()
// Print out what the new config is
log.Info("Log file %+v", config)
// Re-configure logging
configLog()
log.Info("Config file changed")
})
}
func main() {
// Initialise config file and settings
configInit()
// Configure logging
configLog()
// don't forget to close the log file
defer logFile.Close()
// Setup Sqlite DB
setupSQLiteDB()
// Start bitcoin ticker
go bitcoinPrices()
// Notify log that we are up and running
log.Info("started kyco.bitcoin.currency.tickers")
// Setup API
router := mux.NewRouter()
// Setup Route
router.HandleFunc("/{exchange}/{currencyCode}", get_exchange_rate).Methods("GET")
router.HandleFunc("/{exchange}", show_exchange_methods).Methods("GET")
router.HandleFunc("/", showExchanges).Methods("GET")
// Create listen and serve
http.ListenAndServe(":"+config.Port, router)
}