ds.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2013-2014 Fuzamei tech Ltd. All rights reserved.
  2. package tick
  3. // 本文件实现DataSource数据源的tick数据获取下载和保存
  4. import (
  5. "log"
  6. "sync"
  7. "time"
  8. )
  9. var Debug bool = false // for debug
  10. func SetDebug(debug bool) {
  11. Debug = debug
  12. }
  13. // 数据源接口
  14. // lmax, easyforex, oanda, ctp以及未来的macoin等均实现此接口
  15. type DataSource interface {
  16. Name() string
  17. Run()
  18. GetInstrument() []Instrument
  19. GetMarket() chan *Market
  20. }
  21. type DSBase struct {
  22. conf *DsConf //配置
  23. chM chan *Market
  24. insMap map[int64]*Instrument
  25. countTotal int64
  26. countThrow int64
  27. mu sync.Mutex
  28. }
  29. func NewDsBase(confIn *DsConf) *DSBase {
  30. dsb := &DSBase{
  31. chM: make(chan *Market, 10240),
  32. insMap: make(map[int64]*Instrument),
  33. conf: confIn,
  34. }
  35. return dsb
  36. }
  37. func (dsb *DSBase) Save(m *Market) {
  38. dsb.countTotal++
  39. select {
  40. case dsb.chM <- m:
  41. default:
  42. dsb.countThrow++
  43. //if dsb.countThrow%1000 == 0 {
  44. //log.Println("@@@:Save:", DataTypeName(int(m.Type)), m, m.InsId, m.LastPrice, dsb.countTotal, dsb.countThrow)
  45. //}
  46. //if m.Type == IntTdx && m.InsId == 1 {
  47. //log.Println("[DS.Save]data trace")
  48. //}
  49. }
  50. }
  51. func (dsb *DSBase) GetInstrument() []Instrument {
  52. dsb.mu.Lock()
  53. defer dsb.mu.Unlock()
  54. var ret []Instrument
  55. for _, in := range dsb.insMap {
  56. ret = append(ret, *in)
  57. }
  58. return ret
  59. }
  60. func (dsb *DSBase) GetMarket() chan *Market {
  61. return dsb.chM
  62. }
  63. func debugDelay(prefix, insId string, ts int64) {
  64. // for debug delay
  65. now := time.Now()
  66. d := int64(float64(now.UnixNano())*1e-6) - ts
  67. if Debug && d > 1000 {
  68. //log.Println(prefix, "delay > 1000ms", insId, d, getTime(ts))
  69. }
  70. }
  71. func printDelay(prefix, insId string, ts int64) {
  72. // for debug delay
  73. now := time.Now()
  74. d := int64(float64(now.UnixNano())*1e-6) - ts
  75. log.Println(prefix, "delay ", d, insId, getTime(ts))
  76. }
  77. func getTime(ts int64) time.Time {
  78. if ts < 0 {
  79. return time.Now()
  80. }
  81. return time.Unix(ts/1000, (ts%1000)*1e6)
  82. }