ds_oanda.go_ 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Copyright 2013-2014 Fuzamei tech Ltd. All rights reserved.
  2. package tick
  3. // 本文件实现oanda数据源的tick数据获取下载和保存
  4. import (
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "dev.33.cn/markinfo"
  15. "dev.33.cn/server/market"
  16. )
  17. type oandaPairStatistics struct {
  18. Date time.Time
  19. BuyPercent float64
  20. Rates float64
  21. Symbol string
  22. }
  23. var oanda_base = int(200)
  24. var oanda_prev = make(map[string]*oandaPairStatistics)
  25. //var fetchoandaurl = "http://fxtrade.oanda.com/lang/cns/analysis/open-position-ratios"
  26. var fetchoandaurl = "https://www.oanda.com/forex-trading/analysis/open-position-ratios"
  27. func getOandaStatistics(ch chan<- *oandaPairStatistics) (err error) {
  28. html, err := httpDownload(fetchoandaurl)
  29. if err != nil {
  30. return err
  31. }
  32. regex := regexp.MustCompile("(?is)<ol[\\s]+class=\"position-ratio-list\"[^>]*>(.*?)<\\/ol>")
  33. matches := regex.FindAllStringSubmatch(html, -1)
  34. if len(matches) != 2 {
  35. log.Println(html)
  36. return errors.New("regex matche error.")
  37. }
  38. //货币对--BuyPercent--SellPercent
  39. ratio_graph := get_span(matches[0][0])
  40. //货币对--Rates
  41. rates := get_span(matches[1][0])
  42. //精确到微妙
  43. t := match_time(html)
  44. if len(ratio_graph)%3 == 0 && len(rates)%2 == 0 && len(ratio_graph)/3 == len(rates)/2 {
  45. for i := 0; i < len(ratio_graph)/3; i++ {
  46. ops := &oandaPairStatistics{}
  47. ops.Symbol = strings.Replace(ratio_graph[3*i], "/", "", -1)
  48. ops.BuyPercent, _ = strconv.ParseFloat(ratio_graph[3*i+1], 64)
  49. ops.Rates, _ = strconv.ParseFloat(rates[2*i+1], 64)
  50. ops.Date = time.Unix(t/1000, (t%1000)*(1e6))
  51. sendOanda(ch, ops)
  52. }
  53. } else {
  54. return errors.New("invalid data.")
  55. }
  56. return
  57. }
  58. func sendOanda(ch chan<- *oandaPairStatistics, data *oandaPairStatistics) {
  59. if prev_data, ok := oanda_prev[data.Symbol]; ok {
  60. if *prev_data == *data {
  61. return
  62. }
  63. }
  64. // log.Println("oa client", data)
  65. oanda_prev[data.Symbol] = data
  66. select {
  67. case ch <- data:
  68. default:
  69. }
  70. }
  71. func httpDownload(url string) (string, error) {
  72. body, err := http.Get(url)
  73. if err != nil {
  74. fmt.Println(err)
  75. return "", err
  76. }
  77. defer body.Body.Close()
  78. b, err := ioutil.ReadAll(body.Body)
  79. if err != nil {
  80. fmt.Println(err)
  81. return "", err
  82. }
  83. return string(b), nil
  84. }
  85. var timeregex = regexp.MustCompile("(?is)<input.*?id=\"generation-timestamp\".*?value=\"(\\d+)\".*?>")
  86. func match_time(html string) int64 {
  87. result := timeregex.FindAllStringSubmatch(html, -1)
  88. var time int64
  89. if len(result) == 1 && len(result[0]) == 2 {
  90. time, _ = strconv.ParseInt(result[0][1], 10, 64)
  91. }
  92. return time
  93. }
  94. var spanregex = regexp.MustCompile("(?is)<span[^>]+>.*?</span>")
  95. func get_span(text string) []string {
  96. result := spanregex.FindAllString(text, -1)
  97. for i := 0; i < len(result); i++ {
  98. result[i] = strings.Trim(strip_tags(result[i]), " \t\r\n%")
  99. }
  100. return result
  101. }
  102. var stripregex = regexp.MustCompile("(?is)<[^>]+>")
  103. func strip_tags(text string) string {
  104. return stripregex.ReplaceAllString(text, "")
  105. }
  106. var oandaInss = []string{
  107. "EURCHF",
  108. "XAGUSD",
  109. "EURGBP",
  110. "USDJPY",
  111. "USDCAD",
  112. "AUDJPY",
  113. "USDCHF",
  114. "XAUUSD",
  115. "EURJPY",
  116. "EURUSD",
  117. "GBPCHF",
  118. "AUDUSD",
  119. "EURAUD",
  120. "NZDUSD",
  121. "GBPJPY",
  122. "GBPUSD",
  123. }
  124. // OandaDS 实现数据源dataSource接口的定义
  125. type OandaDS struct {
  126. *DSBase
  127. conf *DsConf
  128. //insMap map[string]*market.Instrument
  129. }
  130. func init() {
  131. drivers[Oanda] = newOandaDS
  132. }
  133. func newOandaDS(conf *DsConf) (DataSource, error) {
  134. log.Println("newOandaDS")
  135. ods := &OandaDS{
  136. DSBase: NewDsBase(conf),
  137. conf: conf,
  138. //insMap: oandaInsMap(),
  139. }
  140. ods.insMap = oandaInsMap()
  141. return ods, nil
  142. }
  143. func (ods *OandaDS) Name() string {
  144. return Oanda
  145. }
  146. //func (ods *OandaDS) SubIns() *event.Event {
  147. //return ods.insPublisher.Event()
  148. //}
  149. func (ods *OandaDS) onMarket(ps *oandaPairStatistics) {
  150. //insId := market.OandaPrefix + ps.Symbol
  151. insId, _ := markinfo.SymbolId(ps.Symbol)
  152. _, ok := ods.insMap[int64(insId)]
  153. if !ok {
  154. log.Fatal("OandaDS.onMarket error: insId is NOT in insMap:", insId)
  155. }
  156. //mk := ins.GetMk()
  157. mk := &Market{}
  158. mk.Type = IntOanda
  159. mk.InsId = int64(insId)
  160. mk.Timestamp = ps.Date.Unix() * 1000
  161. mk.LastPrice = 100 - ps.BuyPercent
  162. mk.LastVolume = 1
  163. //ins.SetMk(mk)
  164. ods.Save(mk)
  165. }
  166. /*func (ods *OandaDS) runHour() {
  167. ht := time.Tick(time.Hour)
  168. for _ = range ht {
  169. for _, ins := range ods.insMap {
  170. ods.Save(ins.GetMk())
  171. }
  172. }
  173. }*/
  174. func (ods *OandaDS) Run() {
  175. log.Println("OandaDS.run")
  176. //for _, ins := range ods.insMap {
  177. //ods.insPublisher.Publish(ins)
  178. //}
  179. // go ods.runHour()
  180. //go ods.RunSave(4)
  181. ch := make(chan *oandaPairStatistics, 1024)
  182. go func() {
  183. for {
  184. ps := <-ch
  185. ods.onMarket(ps)
  186. }
  187. }()
  188. for {
  189. var err error
  190. for {
  191. err = getOandaStatistics(ch)
  192. if err != nil {
  193. log.Println(err)
  194. }
  195. time.Sleep(3 * time.Second)
  196. }
  197. }
  198. }
  199. func oandaInsMap() map[int64]*Instrument {
  200. insMap := make(map[int64]*Instrument)
  201. for _, x := range oandaInss {
  202. //id := market.OandaPrefix + x
  203. id, _ := markinfo.SymbolId(x)
  204. u, _ := markinfo.SymbolUint(x)
  205. ins := &Instrument{
  206. Id: int64(id),
  207. Name: x,
  208. ExId: market.Oanda,
  209. Type: market.Forex,
  210. PriceInc: u,
  211. StartTime: time.Now().Unix() * 1000,
  212. }
  213. insMap[int64(id)] = ins
  214. }
  215. return insMap
  216. }