base_from_ths_http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_index_lib/models"
  6. "eta/eta_index_lib/models/future_good"
  7. "eta/eta_index_lib/services/alarm_msg"
  8. "eta/eta_index_lib/utils"
  9. "fmt"
  10. "github.com/shopspring/decimal"
  11. "io"
  12. netHttp "net/http"
  13. "reflect"
  14. "strings"
  15. "time"
  16. )
  17. var tokenRedisKey = `THS_SERVER_ACCESS_TOKEN`
  18. // getEdbDataFromThsHttp 通过url获取同花顺的普通数据
  19. func getEdbDataFromThsHttp(edbCode, startDate, endDate, thsRefreshToken, token string) (item models.EdbDataFromThs, err error) {
  20. thsUrl := `https://quantapi.51ifind.com/api/v1/edb_service`
  21. //indicators 是 半角逗号分隔的所有指标,宏观指标过多,推荐使用Windows超级命令生成。 "indicators":"M001620326,M002822183"
  22. //functionpara 否 key-value格式,省略时不进行更新时间筛选。两个时间控件更新起始时间(startrtime)和更新结束时间(endrtime),不勾选时省略见下方代码块
  23. //startdate 是 开始日期,支持”YYYYMMDD"”YYYY-MM-DD"”YYYY/MM/DD"三种时间格式 "startdate":"2018-01-01"
  24. //enddate 是 结束日期,支持”YYYYMMDD"”YYYY-MM-DD"”YYYY/MM/DD"三种日期格式 "enddate":"2018-01-01
  25. //发送创建请求
  26. dataMap := map[string]interface{}{
  27. "indicators": edbCode,
  28. "startdate": startDate,
  29. "enddate": endDate,
  30. }
  31. body, err, _ := postCurl(thsUrl, dataMap, 0, thsRefreshToken, token)
  32. if err != nil {
  33. return
  34. }
  35. tmpItems := new(EdbDataFromThsInterface)
  36. err = json.Unmarshal(body, &tmpItems)
  37. if err != nil {
  38. err = errors.New("GetEdbDataFromThs json.Unmarshal Err:" + err.Error())
  39. return
  40. }
  41. if tmpItems.Errorcode != 0 {
  42. err = errors.New(tmpItems.Errmsg)
  43. return
  44. }
  45. // 因为table里面的value有的时候返回的是string,有的是float64,所以需要用interface来反射取值
  46. tablesList := make([]models.Tables, 0)
  47. for _, table := range tmpItems.Tables {
  48. tableIdList := make([]string, 0)
  49. tableTimeList := make([]string, 0)
  50. tableValueList := make([]float64, 0)
  51. for _, tableId := range table.ID {
  52. tableIdList = append(tableIdList, tableId)
  53. }
  54. for _, tableTime := range table.Time {
  55. tableTimeList = append(tableTimeList, tableTime)
  56. }
  57. //指标数据
  58. for _, tmpValue := range table.Value {
  59. var tableValue float64
  60. if reflect.TypeOf(tmpValue).Kind() == reflect.Float64 {
  61. tableValue = reflect.ValueOf(tmpValue).Float()
  62. } else if reflect.TypeOf(tmpValue).Kind() == reflect.String {
  63. tmpTableValue, tmpErr := decimal.NewFromString(reflect.ValueOf(tmpValue).String())
  64. if tmpErr != nil {
  65. err = tmpErr
  66. return
  67. }
  68. tableValue, _ = tmpTableValue.Truncate(4).Float64()
  69. } else {
  70. err = errors.New("错误的数据类型" + reflect.TypeOf(tmpValue).String())
  71. return
  72. }
  73. tableValueList = append(tableValueList, tableValue)
  74. }
  75. tmpTable := models.Tables{
  76. ID: tableIdList,
  77. Time: tableTimeList,
  78. Value: tableValueList,
  79. }
  80. tablesList = append(tablesList, tmpTable)
  81. }
  82. item = models.EdbDataFromThs{
  83. DataVol: tmpItems.DataVol,
  84. Errmsg: tmpItems.Errmsg,
  85. Errorcode: tmpItems.Errorcode,
  86. Perf: tmpItems.Perf,
  87. Tables: tablesList,
  88. }
  89. return
  90. }
  91. // getFutureGoodDataFromThsHttp 通过url获取同花顺的商品数据
  92. func getFutureGoodDataFromThsHttp(edbCode, startDate, endDate, thsRefreshToken, token string) (item future_good.FutureGoodDataFromThs, err error) {
  93. thsUrl := `https://quantapi.51ifind.com/api/v1/cmd_history_quotation`
  94. //codes 是 半角逗号分隔的所有代码 "codes":"300033.SZ,600030.SH"
  95. //indicators 是 半角逗号分隔的所有指标 "indicators":"preClose,open"
  96. //functionpara 否 /key-value格式。所有key均取默认时,functionpara省略。 见下方说明
  97. //startdate 是 开始日期,支持"YYYYMMDD""YYYY-MMDD""YYYY/MM/DD"三种日期格式
  98. //"startdate":"2018-01-01"
  99. //enddate 是 结束日期,支持"YYYYMMDD""YYYY-MMDD""YYYY/MM/DD"三种日期格式
  100. //发送创建请求
  101. dataMap := map[string]interface{}{
  102. "codes": edbCode,
  103. "indicators": `lastclose,open,high,low,close,avgprice,change,changeper,volume,amount,hsl,lastsettlement,settlement,zdsettlement,zdfsettlement,ccl,ccbd,zf,zjlx,zjcd`,
  104. "startdate": startDate,
  105. "enddate": endDate,
  106. }
  107. body, err, _ := postCurl(thsUrl, dataMap, 0, thsRefreshToken, token)
  108. if err != nil {
  109. return
  110. }
  111. tmpItems := new(FutureGoodDataFromThsInterface)
  112. err = json.Unmarshal(body, &tmpItems)
  113. if err != nil {
  114. err = errors.New("GetEdbDataFromThs json.Unmarshal Err:" + err.Error())
  115. return
  116. }
  117. if tmpItems.Errorcode != 0 {
  118. err = errors.New(tmpItems.Errmsg)
  119. return
  120. }
  121. if len(tmpItems.Tables) <= 0 {
  122. return
  123. }
  124. table := tmpItems.Tables[0]
  125. item = future_good.FutureGoodDataFromThs{
  126. DataVol: tmpItems.DataVol,
  127. Errmsg: tmpItems.Errmsg,
  128. Errorcode: tmpItems.Errorcode,
  129. Perf: tmpItems.Perf,
  130. Tables: future_good.FutureGoodDataTables{
  131. Time: table.Time,
  132. Open: table.Table.Open,
  133. High: table.Table.High,
  134. Low: table.Table.Low,
  135. Close: table.Table.Close,
  136. Volume: table.Table.Volume,
  137. Amount: table.Table.Amount,
  138. Ccl: table.Table.Ccl,
  139. Settlement: table.Table.Settlement,
  140. },
  141. }
  142. return
  143. }
  144. // BaseThsInterface 同花顺基础返回
  145. type BaseThsInterface struct {
  146. ErrMsg string `json:"errmsg"`
  147. ErrorCode int64 `json:"errorcode"`
  148. Tables interface{} `json:"tables"`
  149. }
  150. // postCurl post请求同花顺接口
  151. func postCurl(urlStr string, dataMap map[string]interface{}, num int, thsRefreshToken, token string) (body []byte, err error, errMsg string) {
  152. logMsg := ``
  153. defer func() {
  154. if err != nil {
  155. if logMsg != `` {
  156. errMsg = logMsg
  157. go alarm_msg.SendAlarmMsg("post请求同花顺接口失败,ERR:"+err.Error()+";errMsg:"+errMsg, 3)
  158. }
  159. }
  160. }()
  161. jsonStrByte, err := json.Marshal(dataMap)
  162. if err != nil {
  163. return
  164. }
  165. reqStr := string(jsonStrByte)
  166. req, _ := netHttp.NewRequest("POST", urlStr, strings.NewReader(reqStr))
  167. req.Header.Add("Content-Type", "application/json")
  168. req.Header.Add("access_token", token)
  169. res, err := netHttp.DefaultClient.Do(req)
  170. if err != nil {
  171. return
  172. }
  173. defer res.Body.Close()
  174. //解析resp并且存入关联表
  175. body, err = io.ReadAll(res.Body)
  176. if err != nil {
  177. logMsg = fmt.Sprint("post err; request:", reqStr, "; errMsg:", err.Error())
  178. utils.FileLog.Info(logMsg)
  179. return
  180. }
  181. //logMsg = fmt.Sprint("post request:", reqStr, "; response:", string(body))
  182. //utils.FileLog.Info(logMsg)
  183. logMsg = fmt.Sprint("post request url:", urlStr, ";token:", token, ";params:", reqStr, ";response:", string(body))
  184. var response BaseThsInterface
  185. err = json.Unmarshal(body, &response)
  186. if err != nil {
  187. utils.FileLog.Info("post Err:", err.Error(), ";url:", urlStr, ";params:", reqStr, ";response:", string(body))
  188. err = errors.New("Unmarshal Err:" + err.Error())
  189. return
  190. }
  191. utils.FileLog.Info(fmt.Sprint("post request url:", urlStr, ";token:", token, ";params:", reqStr, ";response:", string(body)))
  192. //如果是token失效,同时只是第一次请求(没有尝试强制刷新token,那么重新请求)
  193. if utils.InArrayByInt([]int{-1010, -1302}, int(response.ErrorCode)) && num <= 0 {
  194. //token失效
  195. token, err = refreshAccessToken(thsRefreshToken)
  196. if err != nil {
  197. return
  198. }
  199. num++
  200. return postCurl(urlStr, dataMap, num, thsRefreshToken, token)
  201. } else if response.ErrorCode != 0 {
  202. utils.FileLog.Info(fmt.Sprint("post data err:", response.ErrMsg, ";url:", urlStr, ";params:", reqStr, ";response:", string(body)))
  203. err = errors.New(response.ErrMsg)
  204. return
  205. }
  206. return
  207. }
  208. // GetAccessToken 获取accessToken
  209. func GetAccessToken(isRefresh bool, thsRefreshToken string) (token string, err error) {
  210. defer func() {
  211. if err != nil {
  212. go alarm_msg.SendAlarmMsg("获取同花顺的token失败,ERR:"+err.Error(), 3)
  213. }
  214. }()
  215. redisKey := utils.CACHE_EDB_THS_SERVER_TOKEN + thsRefreshToken + ":"
  216. token, redisErr := utils.Rc.RedisString(redisKey)
  217. //如果从redis中accessToken 获取失败或者token为空了,再或者需要强制刷新了,那么重新获取accessToken
  218. if redisErr != nil || token == `` || isRefresh {
  219. token, _ = refreshAccessToken(thsRefreshToken)
  220. return
  221. }
  222. return
  223. }
  224. // refreshAccessToken 强制刷新获取accessToken
  225. func refreshAccessToken(thsRefreshToken string) (token string, err error) {
  226. defer func() {
  227. if err != nil {
  228. go alarm_msg.SendAlarmMsg("刷新同花顺的token失败;ERR:"+err.Error(), 3)
  229. }
  230. }()
  231. tokenInfo, tmpErr := getAccessToken(thsRefreshToken)
  232. if tmpErr != nil {
  233. err = tmpErr
  234. return
  235. }
  236. token = tokenInfo.AccessToken
  237. expireTime, err := time.ParseInLocation(utils.FormatDateTime, tokenInfo.ExpiredTime, time.Local)
  238. if err != nil {
  239. err = fmt.Errorf("获取同花顺的token失败;同花顺token截止日期转换失败,ERR:%s", err.Error())
  240. return
  241. }
  242. //token存入redis
  243. //err = utils.Rc.Put(tokenRedisKey, token, time.Duration(expireTime.Unix()-600)*time.Second)
  244. // 本来是要设置下600s的过期时间,但因为不是强制刷新token,就不获取了
  245. redisKey := utils.CACHE_EDB_THS_SERVER_TOKEN + thsRefreshToken + ":"
  246. err = utils.Rc.Put(redisKey, token, time.Duration(expireTime.Unix())*time.Second)
  247. if err != nil {
  248. err = fmt.Errorf("获取同花顺的token成功;同花顺token存入redis失败,ERR:%s", err.Error())
  249. return
  250. }
  251. return
  252. }
  253. type GetTokenResp struct {
  254. ErrorCode int `json:"errorcode"`
  255. ErrMsg string `json:"errmsg"`
  256. Data TokenData `json:"data"`
  257. }
  258. type TokenData struct {
  259. AccessToken string `json:"access_token"`
  260. //ExpireIn int `json:"expire_in"`
  261. ExpiredTime string `json:"expired_time"`
  262. }
  263. // getAccessToken token内部请求接口
  264. func getAccessToken(thsRefreshToken string) (tokenData TokenData, err error) {
  265. /*if utils.ThsRefreshToken == `` {
  266. err = errors.New("同花顺token未配置")
  267. return
  268. }*/
  269. defer func() {
  270. if err != nil {
  271. go alarm_msg.SendAlarmMsg("更新同花顺的token失败;ERR:"+err.Error(), 3)
  272. }
  273. }()
  274. if thsRefreshToken == "" {
  275. err = errors.New("同花顺token未配置")
  276. return
  277. }
  278. //getUrl := `https://quantapi.51ifind.com/api/v1/update_access_token` // 强制刷新token;目前因为生产和测试都是使用的一个账号,所以token不能因为环境的不同而改变
  279. getUrl := `https://quantapi.51ifind.com/api/v1/get_access_token` // 获取当前token
  280. req, _ := netHttp.NewRequest("GET", getUrl, nil)
  281. req.Header.Add("Content-Type", "application/json")
  282. req.Header.Add("refresh_token", thsRefreshToken)
  283. res, err := netHttp.DefaultClient.Do(req)
  284. if err != nil {
  285. return
  286. }
  287. defer res.Body.Close()
  288. body, err := io.ReadAll(res.Body)
  289. if err != nil {
  290. err = errors.New("NewRequest Err:" + err.Error())
  291. return
  292. }
  293. utils.FileLog.Info("同花顺刷新token:" + string(body))
  294. var tokenResp GetTokenResp
  295. err = json.Unmarshal(body, &tokenResp)
  296. if err != nil {
  297. err = errors.New("Unmarshal Err:" + err.Error())
  298. return
  299. }
  300. if tokenResp.ErrorCode != 0 {
  301. err = errors.New("getAccessToken err:" + tokenResp.ErrMsg)
  302. return
  303. }
  304. tokenData = tokenResp.Data
  305. return
  306. }