-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
2184 lines (2004 loc) · 57 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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"compress/gzip"
"encoding/gob"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/forthxu/goredis"
"github.com/forthxu/websocket"
"github.com/larspensjo/config"
"github.com/tidwall/gjson"
"golang.org/x/net/proxy"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
var usage = `Usage: %s [options]
Options are:
-f configuration file
`
func infoExit(info string) {
fmt.Print(info)
os.Exit(0)
}
func main() {
//根据CPU数量设置多核运行
runtime.GOMAXPROCS(runtime.NumCPU())
//获取配置文件
var configFile string
flag.Usage = func() {
infoExit(fmt.Sprintf(usage, os.Args[0]))
}
flag.StringVar(&configFile, "f", "config.ini", "configuration file")
flag.Parse()
if len(configFile) <= 0 {
infoExit(fmt.Sprintf(usage, os.Args[0]))
} else if _, err := os.Stat(configFile); err != nil && os.IsNotExist(err) {
infoExit(fmt.Sprintf("%s configFile not exist", configFile))
}
//解析配置文件参数
var (
host string = "127.0.0.1"
port int = 9999
token string = "" // Server酱通知(http://sc.ftqq.com/3.version) token
gap int = 1000 // 取数据的的基础间隔时间,默认1000毫秒
savegap int = 600 // 保存24H数据的间隔时间,用于比较涨跌幅
proxy string = "" // 代理的地址
nginxProxy string = "" // nginx代理的地址
outDir string = "" // 数据输出成文件,默认空不输出成文件
info string = "default" // 程序运行标志
bind string = "" // 绑定本地出口ip
redisConfig map[string]string = make(map[string]string)
debug bool = false
)
cfg, err := config.ReadDefault(configFile)
if err != nil {
infoExit(fmt.Sprintf("%s configFile parse fail: %s", configFile, err.Error()))
}
if cfg.HasSection("redis") {
section, err := cfg.SectionOptions("redis")
if err == nil {
for _, v := range section {
options, err := cfg.String("redis", v)
if err == nil {
redisConfig[v] = options
}
}
}
}
if cfg.HasSection("app") {
if data, err := cfg.String("app", "host"); err == nil {
host = data
}
if data, err := cfg.Int("app", "port"); err == nil {
port = data
}
if data, err := cfg.String("app", "token"); err == nil {
token = data
}
if data, err := cfg.Int("app", "gap"); err == nil {
gap = data
}
if data, err := cfg.Int("app", "savegap"); err == nil {
savegap = data
}
if data, err := cfg.String("app", "proxy"); err == nil {
proxy = data
}
if data, err := cfg.String("app", "nginxproxy"); err == nil {
nginxProxy = data
}
if data, err := cfg.String("app", "outdir"); err == nil {
outDir = data
}
if data, err := cfg.String("app", "info"); err == nil {
info = data
}
if data, err := cfg.String("app", "bind"); err == nil {
bind = data
}
if data, err := cfg.Bool("app", "debug"); err == nil {
debug = data
}
}
//日志配置
if debug {
log.SetFlags(log.LstdFlags | log.Lshortfile) //带文件行号的日志
} else {
log.SetFlags(log.LstdFlags)
}
//初始工作对象
w := Work{
Host: host,
Port: port,
Token: token,
Gap: gap,
SaveGap: savegap,
Proxy: proxy,
NginxProxy: nginxProxy,
OutDir: outDir,
RedisConfig: redisConfig,
Info: info,
Bind: bind,
}
w.Platform = make(map[string]*currentPrices)
w.Platform24 = make(map[string]*currentPrices)
w.NotifyCount.Num = make(map[string]int)
//提示信息
log.Println("[app] config:", configFile)
log.Println("[app] listen:", w.Host, w.Port)
log.Println("[app] gap time:", w.Gap, "Millisecond")
log.Println("[app] savegap time:", w.SaveGap, "Second")
log.Println("[app] proxy:", w.Proxy)
log.Println("[app] nginxProxy:", w.NginxProxy)
log.Println("[app] bind local ip:", w.Bind)
log.Println("[app] outDir:", w.OutDir)
log.Println("[app] info:", w.Info)
log.Println("[app] debug:", debug)
//开始工作
w.initRedis()
w.runWorkers()
w.RunHttp()
w.notify("[currentPrice] 程序结束", "")
}
//redis初始化
func (w *Work) initRedis() {
//连接数据库
if _, existHost := w.RedisConfig["host"]; !existHost {
log.Fatalln("[redis] host error")
}
if _, existPort := w.RedisConfig["port"]; !existPort {
log.Fatalln("[redis] host error")
}
w.Redis.Addr = w.RedisConfig["host"] + ":" + w.RedisConfig["port"]
//授权密码
if _, existAuth := w.RedisConfig["auth"]; existAuth {
w.Redis.Password = w.RedisConfig["auth"]
}
//选择DB
if _, existDB := w.RedisConfig["db"]; !existDB {
w.Redis.Db = 0
} else {
redisdb, err := strconv.Atoi(w.RedisConfig["db"])
if err != nil {
log.Fatalln("[redis] config select db error")
}
w.Redis.Db = redisdb
}
//测试连接
_, err := w.Redis.Ping()
if err != nil {
log.Fatalln("[redis] ping ", err)
}
}
//绑定本地出口ip
func (w *Work) bindIP() (*http.Transport, error) {
if len(w.Bind) < 0 {
return nil, errors.New(fmt.Sprintf("[%s] local bind ip not exist", w.Bind))
}
localAddr, err := net.ResolveIPAddr("ip", w.Bind)
if err != nil {
return nil, errors.New(fmt.Sprintf("[%s] local bind ip error:%s", w.Bind, err.Error()))
}
localTCPAddr := net.TCPAddr{
IP: localAddr.IP,
}
d := net.Dialer{
LocalAddr: &localTCPAddr,
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: d.Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
return tr, nil
}
func (w *Work) getHttpClient() (*http.Client, error) {
var timeout int = 30
var client *http.Client
if strings.HasPrefix(w.Proxy, "http") {
urlParse := url.URL{}
urlProxy, err := urlParse.Parse(w.Proxy)
if err != nil {
return nil, err
}
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(urlProxy),
},
Timeout: time.Duration(timeout) * time.Second,
}
} else if strings.HasPrefix(w.Proxy, "socks5://") {
var auths_hosts, auths []string
var hosts string
var auth *proxy.Auth
auths_hosts = strings.Split(strings.Replace(w.Proxy, "socks5://", "", -1), "@")
if len(auths_hosts) == 2 {
auths = strings.Split(auths_hosts[0], ":")
if len(auths) == 2 {
auth = &proxy.Auth{User: auths[0], Password: auths[1]}
} else {
auth = &proxy.Auth{User: auths[0], Password: ""}
}
hosts = auths_hosts[1]
} else {
auth = nil
hosts = auths_hosts[0]
}
dialer, err := proxy.SOCKS5(
"tcp",
hosts,
auth,
&net.Dialer{
Timeout: time.Duration(timeout) * time.Second,
KeepAlive: time.Duration(timeout) * time.Second,
},
)
if err != nil {
return nil, err
}
client = &http.Client{
Transport: &http.Transport{
Proxy: nil,
Dial: dialer.Dial,
TLSHandshakeTimeout: time.Duration(timeout) * time.Second,
},
Timeout: time.Duration(timeout) * time.Second,
}
} else {
client = &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
}
if len(w.Bind) > 0 {
localAddr, err := net.ResolveIPAddr("ip", w.Bind)
if err != nil {
return nil, errors.New(fmt.Sprintf("bind local ip[%s] error:%s", w.Bind, err.Error()))
}
localTCPAddr := net.TCPAddr{
IP: localAddr.IP,
}
d := net.Dialer{
LocalAddr: &localTCPAddr,
Timeout: time.Duration(timeout) * time.Second,
KeepAlive: time.Duration(timeout) * time.Second,
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: d.Dial,
TLSHandshakeTimeout: time.Duration(timeout) * time.Second,
}
client.Transport = tr
}
return client, nil
}
func (w *Work) getWebsocketClient() (*websocket.Dialer, error) {
var timeout int = 30
var client *websocket.Dialer
if strings.HasPrefix(w.Proxy, "http://") {
urlParse := url.URL{}
urlProxy, err := urlParse.Parse(w.Proxy)
if err != nil {
return nil, err
}
client = &websocket.Dialer{
Proxy: http.ProxyURL(urlProxy),
}
} else if strings.HasPrefix(w.Proxy, "socks5://") {
var auths_hosts, auths []string
var hosts string
var auth *proxy.Auth
auths_hosts = strings.Split(strings.Replace(w.Proxy, "socks5://", "", -1), "@")
if len(auths_hosts) == 2 {
auths = strings.Split(auths_hosts[0], ":")
if len(auths) == 2 {
auth = &proxy.Auth{User: auths[0], Password: auths[1]}
} else {
auth = &proxy.Auth{User: auths[0], Password: ""}
}
hosts = auths_hosts[1]
} else {
auth = nil
hosts = auths_hosts[0]
}
dialer, err := proxy.SOCKS5(
"tcp",
hosts,
auth,
&net.Dialer{
Timeout: time.Duration(timeout) * time.Second,
//KeepAlive: time.Duration(timeout) * time.Second,
},
)
if err != nil {
return nil, err
}
client = &websocket.Dialer{
NetDial: dialer.Dial,
}
} else {
client = &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
}
}
if len(w.Bind) > 0 {
client.LocalAddr = w.Bind
}
return client, nil
}
//http线程返回结果结构函数
func retrunJson(msg string, status bool, data interface{}) []byte {
if data == nil {
data = struct{}{}
}
b, err := json.Marshal(Result{status, msg, data})
if err != nil {
log.Println("[retrunJson] Marshal", err)
}
return b
}
//http线程返回结果结构
type Result struct {
Status bool `json:"status"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type Count struct {
sync.Mutex
Num map[string]int
}
//工作线程结构
type Work struct {
sync.Mutex
Host string
Port int
Token string
Platform map[string]*currentPrices
Platform24 map[string]*currentPrices
NotifyCount Count
Gap int
SaveGap int
Proxy string
NginxProxy string
OutDir string
RedisConfig map[string]string
Redis goredis.Client
Info string
Bind string
}
type currentPrices struct {
sync.Mutex
Data map[string]currentPrice
}
//数据格式
type currentPrice struct {
Symbol string `json:"symbol"`
Coin string `json:"coin"`
Market string `json:"market"`
Price float64 `json:"price"`
Time string `json:"time"`
UpPrice float64 `json:"upprice"`
Upime string `json:"uptime"`
Change float64 `json:"change"`
}
//http线程
func (w *Work) RunHttp() {
// info
http.HandleFunc("/api/debug/", w.Debug)
// 涨跌幅排行榜
http.HandleFunc("/api/currentPrices/", w.CurrentPrices)
// 现价
http.HandleFunc("/api/currentRank/", w.CurrentRank)
listen := (w.Host + ":" + strconv.Itoa(w.Port))
err := http.ListenAndServe(listen, nil)
if err != nil {
log.Fatalln("[http] ListenAndServe: ", err)
return
}
log.Println("[http] start ", w.Host, w.Port)
}
//http线程信息接口函数
func (w *Work) Debug(resp http.ResponseWriter, req *http.Request) {
resp.Write(retrunJson(w.Info, true, nil))
}
//http线程涨跌幅排行榜接口函数
func (w *Work) CurrentRank(resp http.ResponseWriter, req *http.Request) {
//up涨榜 down跌榜
req.ParseForm()
var change string = "up"
if len(req.Form["change"]) > 0 && len(req.Form["change"][0]) > 0 {
change = req.Form["change"][0]
}
if len(req.Form["test"]) < 1 || len(req.Form["test"][0]) < 1 {
resp.Write(retrunJson("[currentRank] 暂时关闭旧接口", false, nil))
return
}
//获取涨跌榜对象
var markets map[int]string = make(map[int]string)
var data [][]byte
var err error
if change == "down" {
data, err = w.Redis.Zrangebyscore("currentRank", float64(-100), float64(-0.00000000000000000001), 0, 10)
} else {
data, err = w.Redis.Zrevrangebyscore("currentRank", float64(100), float64(0.00000000000000000001), 0, 10)
}
if err == nil {
for k, v := range data {
if k%2 == 0 {
markets[k] = string(v)
}
}
} else {
resp.Write(retrunJson("[currentRank] found invail", false, nil))
return
}
//根据涨跌榜对象获取涨跌榜数据
var resultData map[string]map[string]currentPrice = make(map[string]map[string]currentPrice)
for _, marketValue := range markets {
tmp := strings.Split(strings.Trim(strings.ToLower(marketValue), " "), "|")
if len(tmp) != 3 {
resp.Write(retrunJson("[currentRank] markets invail", false, nil))
return
}
symbol := tmp[0] + "-" + tmp[1]
site := tmp[2]
data, platformExist := w.Platform[site]
if !platformExist {
log.Println("[currentRank] site no exist", site)
continue
}
_, siteExist := resultData[site]
if !siteExist {
resultData[site] = make(map[string]currentPrice)
}
currentPrice, symbolExist := data.Data[symbol]
if symbolExist {
resultData[site][symbol] = currentPrice
} else {
log.Println("[currentRank] symbol no exist", symbol)
}
}
resp.Write(retrunJson("ok", true, resultData))
}
// http线程现价接口函数
func (w *Work) CurrentPrices(resp http.ResponseWriter, req *http.Request) {
req.ParseForm()
if len(req.Form["markets[]"]) > 0 && len(req.Form["markets[]"][0]) > 0 { //指定市场对
markets := req.Form["markets[]"]
var resultData map[string]map[string]currentPrice = make(map[string]map[string]currentPrice)
for marketIndex := range markets {
tmp := strings.Split(strings.ToLower(markets[marketIndex]), "|")
if len(tmp) != 3 {
resp.Write(retrunJson("[CurrentPrices] markets invail", false, nil))
return
}
symbol := tmp[0] + "-" + tmp[1]
site := tmp[2]
data, platformExist := w.Platform[site]
if !platformExist {
continue
}
_, siteExist := resultData[site]
if !siteExist {
resultData[site] = make(map[string]currentPrice)
}
data.Lock()
currentPrice, symbolExist := data.Data[symbol]
if symbolExist {
resultData[site][symbol] = currentPrice
}
data.Unlock()
}
resp.Write(retrunJson("ok", true, resultData))
return
} else if len(req.Form["site"]) > 0 && len(req.Form["site"][0]) > 0 { //指定平台
site := req.Form["site"][0]
data, platformExist := w.Platform[site]
if !platformExist {
resp.Write(retrunJson("[CurrentPrices] data invail", false, nil))
return
}
var resultData map[string]map[string]currentPrice = make(map[string]map[string]currentPrice)
if len(req.Form["market"]) > 0 && len(req.Form["market"][0]) > 0 { //同时指定了市场
market := strings.ToLower(req.Form["market"][0])
resultData[site] = make(map[string]currentPrice)
data.Lock()
for k, v := range data.Data {
if v.Market == market {
resultData[site][k] = v
}
}
resp.Write(retrunJson("ok", true, resultData))
data.Unlock()
return
} else { //平台内所有市场对
data.Lock()
resultData[site] = data.Data
resp.Write(retrunJson("ok", true, resultData))
data.Unlock()
return
}
}
resp.Write(retrunJson("[CurrentPrices] site invail", false, nil))
}
//工作线程,分协程读取个平台现价、存储涨跌幅、存储平台现价文件,存储历史现价
func (w *Work) runWorkers() {
// huobi websocket 实时读取推送过来的数据
go func() {
w.Lock()
w.Platform["huobi"] = new(currentPrices)
w.Unlock()
w.Platform["huobi"].Lock()
w.Platform["huobi"].Data = make(map[string]currentPrice)
w.Platform["huobi"].Unlock()
w.setNotify("huobi", 0)
for {
w.runWorkerHuobi()
// 超过5次错误后休息一分钟
if w.getNotify("huobi") > 5 {
log.Println("[huobi] 读取现价接口超过五次错误休息一分钟 ")
w.notify("[huobi] currentPrice fail", "读取现价接口超过五次错误休息一分钟")
w.setNotify("huobi", 0)
time.Sleep(60 * time.Second)
}
log.Println("[huobi] websocket reconnecting ", w.getNotify("huobi"))
}
w.notify("[huobi] 协程结束", "")
}()
/*
// hadax websocket
go func() {
w.Lock()
w.Platform["hadax"] = new(currentPrices)
w.Unlock()
w.Platform["hadax"].Lock()
w.Platform["hadax"].Data = make(map[string]currentPrice)
w.Platform["hadax"].Unlock()
w.setNotify("hadax", 0)
for {
w.runWorkerHadax()
// 超过5次错误后休息一分钟
if w.getNotify("hadax") > 5 {
log.Println("[hadax] 读取现价接口超过五次错误休息一分钟 ")
w.notify("[hadax] currentPrice fail", "读取现价接口超过五次错误休息一分钟")
w.setNotify("hadax", 0)
time.Sleep(60 * time.Second)
}
log.Println("[hadax] websocket reconnecting ", w.getNotify("hadax"))
}
w.notify("[hadax] 协程结束", "")
}()
*/
/*
// fcoin websocket
go func() {
w.Lock()
w.Platform["fcoin"] = new(currentPrices)
w.Unlock()
w.Platform["fcoin"].Lock()
w.Platform["fcoin"].Data = make(map[string]currentPrice)
w.Platform["fcoin"].Unlock()
w.setNotify("fcoin", 0)
for {
w.runWorkerFcoin()
// 超过5次错误后休息一分钟
if w.getNotify("fcoin") > 5 {
log.Println("[fcoin] 读取现价接口超过五次错误休息一分钟 ")
w.notify("[fcoin] currentPrice fail", "读取现价接口超过五次错误休息一分钟")
w.setNotify("fcoin", 0)
time.Sleep(60 * time.Second)
}
log.Println("[fcoin] websocket reconnecting ", w.getNotify("fcoin"))
}
w.notify("[fcoin] 协程结束", "")
}()
*/
// okex http
go func() {
w.Lock()
w.Platform["okex"] = new(currentPrices)
w.Unlock()
w.Platform["okex"].Lock()
w.Platform["okex"].Data = make(map[string]currentPrice)
w.Platform["okex"].Unlock()
w.setNotify("okex", 0)
ticker := time.NewTicker(time.Duration(w.Gap) * time.Millisecond)
w.runWorkerOkex()
for range ticker.C {
w.runWorkerOkex()
// 超过10次错误后休息两分钟
if w.getNotify("okex") > 10 {
log.Println("[okex] 读取现价接口超过十次错误休息两分钟 ")
w.notify("[okex] currentPrice fail", "读取现价接口超过十次错误休息两分钟")
w.setNotify("okex", 0)
time.Sleep(120 * time.Second)
}
}
w.notify("[okex] 协程结束", "")
}()
// binance http
go func() {
w.Lock()
w.Platform["binance"] = new(currentPrices)
w.Unlock()
w.Platform["binance"].Lock()
w.Platform["binance"].Data = make(map[string]currentPrice)
w.Platform["binance"].Unlock()
w.setNotify("binance", 0)
ticker := time.NewTicker(time.Duration(w.Gap) * time.Millisecond)
w.runWorkerBinance()
for range ticker.C {
w.runWorkerBinance()
// 超过10次错误后休息两分钟
if w.getNotify("binance") > 10 {
log.Println("[binance] 读取现价接口超过十次错误休息两分钟 ")
w.notify("[binance] currentPrice fail", "读取现价接口超过十次错误休息两分钟")
w.setNotify("binance", 0)
time.Sleep(120 * time.Second)
}
}
w.notify("[binance] 协程结束", "")
}()
// gate http
go func() {
w.Lock()
w.Platform["gate"] = new(currentPrices)
w.Unlock()
w.Platform["gate"].Lock()
w.Platform["gate"].Data = make(map[string]currentPrice)
w.Platform["gate"].Unlock()
w.setNotify("gate", 0)
ticker := time.NewTicker(time.Duration(w.Gap) * time.Millisecond)
w.runWorkerGate()
for range ticker.C {
w.runWorkerGate()
// 超过10次错误后休息两分钟
if w.getNotify("gate") > 10 {
log.Println("[gate] 读取现价接口超过十次错误休息两分钟 ")
w.notify("[gate] currentPrice fail", "读取现价接口超过十次错误休息两分钟")
w.setNotify("gate", 0)
time.Sleep(120 * time.Second)
}
}
w.notify("[gate] 协程结束", "")
}()
// zb http
/*
go func() {
w.Lock()
w.Platform["zb"] = new(currentPrices)
w.Unlock()
w.Platform["zb"].Lock()
w.Platform["zb"].Data = make(map[string]currentPrice)
w.Platform["zb"].Unlock()
w.setNotify("zb", 0)
ticker := time.NewTicker(time.Duration(w.Gap) * time.Millisecond)
w.runWorkerZb()
for range ticker.C {
//for {
w.runWorkerZb()
// 超过10次错误后休息两分钟
if w.getNotify("zb") > 10 {
log.Println("[zb] 读取现价接口超过十次错误休息两分钟 ")
w.notify("[zb] currentPrice fail", "读取现价接口超过十次错误休息两分钟")
w.setNotify("zb", 0)
time.Sleep(120 * time.Second)
}
}
w.notify("[zb] 协程结束", "")
}()
*/
// huilv http
go func() {
w.Lock()
w.Platform["huilv"] = new(currentPrices)
w.Unlock()
w.Platform["huilv"].Lock()
w.Platform["huilv"].Data = make(map[string]currentPrice)
w.Platform["huilv"].Unlock()
w.setNotify("huilv", 0)
ticker := time.NewTicker(time.Duration(w.Gap) * time.Millisecond * 100)
w.runWorkerHuilv()
for range ticker.C {
w.runWorkerHuilv()
// 超过10次错误后休息两分钟
if w.getNotify("huilv") > 10 {
log.Println("[huilv] 读取现价接口超过十次错误休息两分钟 ")
w.notify("[huilv] currentPrice fail", "读取现价接口超过十次错误休息两分钟")
w.setNotify("huilv", 0)
time.Sleep(120 * time.Second)
}
}
w.notify("[huilv] 协程结束", "")
}()
// 存储历史现价用于计算涨跌幅
go func() {
var storeKey string = "currentZset"
// 立即获取24小时历史现价,供涨跌幅计算
w.save24History(storeKey)
// 定时处理
ticker := time.NewTicker(time.Duration(w.SaveGap) * time.Second) //存储时间间隔由配置决定
for range ticker.C {
// 存储现价成历史数据
w.saveHistory(storeKey)
// 获取24小时历史现价,供涨跌幅计算
w.save24History(storeKey)
}
w.notify("[platform24] 协程结束", "")
}()
}
// 存储现价成历史数据
func (w *Work) saveHistory(storeKey string) {
var now time.Time = time.Now()
var resultData map[string]map[string]currentPrice = make(map[string]map[string]currentPrice)
for k, v := range w.Platform {
v.Lock()
defer v.Unlock()
resultData[k] = v.Data
}
//存储
var encodeBuffer bytes.Buffer
enc := gob.NewEncoder(&encodeBuffer)
err := enc.Encode(resultData)
if err != nil {
log.Println("[saveHistory] encode:", err)
} else {
w.Redis.Zadd(storeKey, []byte(encodeBuffer.String()), float64(now.Unix()))
//w.Redis.Expire(storeKey, int64(87000))
}
}
// 获取24小时历史现价,供涨跌幅计算
func (w *Work) save24History(storeKey string) {
var now time.Time = time.Now()
data1, err := w.Redis.Zrevrangebyscore(storeKey, float64(now.Unix()-86400), float64(now.Unix()-87000), 0, 1)
if err == nil && len(data1) == 2 {
var platformData map[string]map[string]currentPrice = make(map[string]map[string]currentPrice)
dec := gob.NewDecoder(bytes.NewBuffer(data1[0]))
err = dec.Decode(&platformData)
if err != nil {
log.Println("[save24History] decode data1:", err)
return
}
for k, v := range platformData {
if _, platformExist := w.Platform24[k]; !platformExist {
w.Platform24[k] = new(currentPrices)
}
w.Platform24[k].Lock()
w.Platform24[k].Data = v
w.Platform24[k].Unlock()
}
//删除过期的数据
w.Redis.Zremrangebyscore(storeKey, float64(0), float64(now.Unix()-87000))
} else {
data2, err := w.Redis.Zrangebyscore(storeKey, float64(now.Unix()-86400), float64(now.Unix()), 0, 1)
if err == nil && len(data2) == 2 {
var platformData map[string]map[string]currentPrice = make(map[string]map[string]currentPrice)
dec := gob.NewDecoder(bytes.NewBuffer(data2[0]))
err = dec.Decode(&platformData)
if err != nil {
log.Println("[save24History] decode data2:", err)
return
}
for k, v := range platformData {
if _, platformExist := w.Platform24[k]; !platformExist {
w.Platform24[k] = new(currentPrices)
}
w.Platform24[k].Lock()
w.Platform24[k].Data = v
w.Platform24[k].Unlock()
}
} else {
for k, v := range w.Platform {
if _, platformExist := w.Platform24[k]; !platformExist {
w.Platform24[k] = new(currentPrices)
}
v.Lock()
w.Platform24[k].Data = v.Data
v.Unlock()
}
}
}
}
// 计数器用来计数通知和任务休息
func (w *Work) incrNotify(site string) {
w.NotifyCount.Lock()
defer w.NotifyCount.Unlock()
_, siteExist := w.NotifyCount.Num[site]
if siteExist {
w.NotifyCount.Num[site] = w.NotifyCount.Num[site] + 1
return
}
w.NotifyCount.Num[site] = 1
return
}
func (w *Work) setNotify(site string, value int) {
w.NotifyCount.Lock()
defer w.NotifyCount.Unlock()
_, siteExist := w.NotifyCount.Num[site]
if siteExist {
w.NotifyCount.Num[site] = value
return
}
w.NotifyCount.Num[site] = value
return
}
func (w *Work) getNotify(site string) int {
w.NotifyCount.Lock()
defer w.NotifyCount.Unlock()
_, siteExist := w.NotifyCount.Num[site]
if siteExist {
return w.NotifyCount.Num[site]
}
return 0
}
// gzip压缩用于wesocket
func GzipEncode(in []byte) ([]byte, error) {
var (
buffer bytes.Buffer
out []byte
err error
)
writer := gzip.NewWriter(&buffer)
_, err = writer.Write(in)
if err != nil {
writer.Close()
return out, err
}
err = writer.Close()
if err != nil {
return out, err
}
return buffer.Bytes(), nil
}
// gzip解压用于wesocket
func GzipDecode(in []byte) ([]byte, error) {
reader, err := gzip.NewReader(bytes.NewReader(in))
if err != nil {
var out []byte
return out, err
}
defer reader.Close()
return ioutil.ReadAll(reader)
}
// huobi现价
func (w *Work) runWorkerHuobi() {
//连接websocket
var u url.URL
if len(w.NginxProxy) == 0 {
u = url.URL{Scheme: "wss", Host: "api.huobi.br.com", Path: "/ws"}
} else {
u = url.URL{Scheme: "wss", Host: w.NginxProxy, Path: "/huobi/ws"}
}
DefaultDialer, err := w.getWebsocketClient()
if err != nil {
log.Println("[huobi] ", err.Error())
w.incrNotify("huobi")
return
}
header := http.Header{"User-Agent": []string{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"}}
ws, _, err := DefaultDialer.Dial(u.String(), header)
if err != nil {
log.Println("[huobi] ", err.Error())
w.incrNotify("huobi")
return
}
ws.SetReadDeadline(time.Now().Add(3 * time.Minute))
ws.SetWriteDeadline(time.Now().Add(1 * time.Minute))
defer ws.Close()
//订阅现价数据