history.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. package quote
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "mtp2_if/global/app"
  6. "mtp2_if/global/e"
  7. "mtp2_if/logger"
  8. "mtp2_if/models"
  9. "mtp2_if/utils"
  10. "net/http"
  11. "sort"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // HistoryData 历史数据
  16. type HistoryData struct {
  17. Opened float64 `json:"o"` // 开盘价
  18. Highest float64 `json:"h"` // 最高价
  19. Lowest float64 `json:"l"` // 最低价
  20. Closed float64 `json:"c"` // 收盘价
  21. TotleVolume int `json:"tv"` // 总量
  22. TotleTurnover float64 `json:"tt"` // 总金额
  23. HoldVolume int `json:"hv"` // 持仓量
  24. Settle float64 `json:"s"` // 结算价,日线周期(包括)以上才有
  25. TimeStamp time.Time `json:"ts"` // 时间
  26. IsFill bool `json:"f"` // 是否补充数据
  27. }
  28. // QueryHistoryDatasReq 查询行情历史数据请求参数
  29. type QueryHistoryDatasReq struct {
  30. CycleType int `form:"cycleType" binding:"required"`
  31. GoodsCode string `form:"goodsCode" binding:"required"`
  32. StartTime string `form:"startTime"`
  33. EndTime string `form:"endTime"`
  34. Count int `form:"count"`
  35. IsAsc bool `form:"isAsc"`
  36. }
  37. // QueryHistoryDatas 查询行情历史数据
  38. // @Summary 查询行情历史数据
  39. // @Produce json
  40. // @Security ApiKeyAuth
  41. // @Param cycleType query int true "周期类型, 0-秒 1: 1分钟 2: 5分钟 3: 30分钟 4: 60分钟 120: 2小时 240: 4小时 11: 日线"
  42. // @Param goodsCode query string true "商品代码"
  43. // @Param startTime query string false "开始时间,格式:yyyy-MM-dd HH:mm:ss"
  44. // @Param endTime query string false "结束时间,格式:yyyy-MM-dd HH:mm:ss"
  45. // @Param count query int false "条数"
  46. // @Param isAsc query bool false "是否按时间顺序排序(默认为时间倒序排序)"
  47. // @Success 200 {object} HistoryData
  48. // @Failure 500 {object} app.Response
  49. // @Router /Quote/QueryHistoryDatas [get]
  50. // @Tags 行情服务
  51. func QueryHistoryDatas(c *gin.Context) {
  52. appG := app.Gin{C: c}
  53. // 获取请求参数
  54. var req QueryHistoryDatasReq
  55. if err := appG.C.ShouldBindQuery(&req); err != nil {
  56. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  57. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  58. return
  59. }
  60. // 转换时间
  61. timeFormat := "2006-01-02 15:04:05" // go中的时间格式化必须是这个时间
  62. var startTime *time.Time
  63. if len(req.StartTime) > 0 {
  64. st, err := time.ParseInLocation(timeFormat, req.StartTime, time.Local)
  65. if err != nil {
  66. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  67. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  68. return
  69. }
  70. startTime = &st
  71. }
  72. var endTime *time.Time
  73. if len(req.EndTime) > 0 {
  74. et, err := time.ParseInLocation(timeFormat, req.EndTime, time.Local)
  75. if err != nil {
  76. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  77. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  78. return
  79. }
  80. endTime = &et
  81. }
  82. // 查询数据
  83. cycleDatas, err := models.GetHistoryCycleDatas(models.CycleType(req.CycleType), req.GoodsCode, startTime, endTime, req.Count, req.IsAsc)
  84. if err != nil {
  85. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  86. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  87. return
  88. }
  89. // 获取目标商品信息
  90. goods, err := models.GetGoodsByGoodsCode(req.GoodsCode)
  91. if err != nil {
  92. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  93. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  94. return
  95. }
  96. // 计算最终价格
  97. rst := make([]HistoryData, 0)
  98. for _, v := range cycleDatas {
  99. historyData := HistoryData{
  100. Opened: utils.IntToFloat64(v.Open, int(goods.Decimalplace)),
  101. Highest: utils.IntToFloat64(v.High, int(goods.Decimalplace)),
  102. Lowest: utils.IntToFloat64(v.Low, int(goods.Decimalplace)),
  103. Closed: utils.IntToFloat64(v.Close, int(goods.Decimalplace)),
  104. TotleVolume: v.TV,
  105. TotleTurnover: float64(v.TT),
  106. HoldVolume: v.HV,
  107. Settle: utils.IntToFloat64(v.SP, int(goods.Decimalplace)),
  108. TimeStamp: time.Unix(int64(v.ST), 0),
  109. }
  110. rst = append(rst, historyData)
  111. }
  112. // 查询成功
  113. logger.GetLogger().Debugln("QueryHistoryDatas successed: %v", rst)
  114. appG.Response(http.StatusOK, e.SUCCESS, rst)
  115. }
  116. // HistoryTikData Tik数据
  117. type HistoryTikData struct {
  118. TimeStamp time.Time `json:"TS"` // 行情时间文本
  119. PE float64 `json:"PE"` // 现价
  120. Vol int `json:"Vol"` // 现量
  121. TT float64 `json:"TT"` // 现金额
  122. Bid float64 `json:"Bid"` // 买价
  123. BV int `json:"BV"` // 买量
  124. Ask float64 `json:"Ask"` // 卖价
  125. AV int `json:"AV"` // 卖量
  126. HV int `json:"HV"` // 持仓量
  127. HI int `json:"HI"` // 单笔持仓
  128. TDR int `json:"TDR"` // 交易方向,0:买 1:卖
  129. TK int `json:"TK"` // 交易类型
  130. }
  131. // QueryHistoryTikDatasReq 查询行情Tik数据请求参数
  132. type QueryHistoryTikDatasReq struct {
  133. GoodsCode string `form:"goodsCode" binding:"required"`
  134. StartTime string `form:"startTime"`
  135. EndTime string `form:"endTime"`
  136. Count int `form:"count"`
  137. IsAsc bool `form:"isAsc"`
  138. }
  139. // QueryHistoryTikDatas 查询行情Tik数据
  140. // @Summary 查询行情Tik数据
  141. // @Produce json
  142. // @Security ApiKeyAuth
  143. // @Param goodsCode query string true "商品代码"
  144. // @Param startTime query string false "开始时间,格式:yyyy-MM-dd HH:mm:ss"
  145. // @Param endTime query string false "结束时间,格式:yyyy-MM-dd HH:mm:ss"
  146. // @Param count query int false "条数"
  147. // @Param isAsc query bool false "是否按时间顺序排序(默认为时间倒序排序)"
  148. // @Success 200 {object} HistoryTikData
  149. // @Failure 500 {object} app.Response
  150. // @Router /Quote/QueryHistoryTikDatas [get]
  151. // @Tags 行情服务
  152. func QueryHistoryTikDatas(c *gin.Context) {
  153. appG := app.Gin{C: c}
  154. // 获取请求参数
  155. var req QueryHistoryTikDatasReq
  156. if err := appG.C.ShouldBindQuery(&req); err != nil {
  157. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  158. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  159. return
  160. }
  161. // 转换时间
  162. timeFormat := "2006-01-02 15:04:05" // go中的时间格式化必须是这个时间
  163. var startTime *time.Time
  164. if len(req.StartTime) > 0 {
  165. st, err := time.ParseInLocation(timeFormat, req.StartTime, time.Local)
  166. if err != nil {
  167. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  168. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  169. return
  170. }
  171. startTime = &st
  172. }
  173. var endTime *time.Time
  174. if len(req.EndTime) > 0 {
  175. et, err := time.ParseInLocation(timeFormat, req.EndTime, time.Local)
  176. if err != nil {
  177. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  178. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  179. return
  180. }
  181. endTime = &et
  182. }
  183. // 查询数据
  184. tikDatas, err := models.GetHistoryTikDatas(req.GoodsCode, startTime, endTime, req.Count, req.IsAsc)
  185. if err != nil {
  186. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  187. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  188. return
  189. }
  190. // 获取目标商品信息
  191. goods, err := models.GetGoodsByGoodsCode(req.GoodsCode)
  192. if err != nil {
  193. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  194. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  195. return
  196. }
  197. // 计算最终价格
  198. rst := make([]HistoryTikData, 0)
  199. for _, v := range tikDatas {
  200. // 获取方向
  201. buyOrSell := 0
  202. if v.TDR == 83 { // (Ascii) B-66 S-83
  203. buyOrSell = 1
  204. }
  205. rst = append(rst, HistoryTikData{
  206. TimeStamp: time.Unix(int64(v.AT), 0),
  207. PE: utils.IntToFloat64(v.PE, int(goods.Decimalplace)),
  208. Vol: v.Vol,
  209. TT: float64(v.TT),
  210. Bid: utils.IntToFloat64(v.Bid, int(goods.Decimalplace)),
  211. BV: v.BV,
  212. Ask: utils.IntToFloat64(v.Ask, int(goods.Decimalplace)),
  213. AV: v.AV,
  214. HV: v.HV,
  215. HI: v.HI,
  216. TDR: buyOrSell,
  217. TK: v.TK,
  218. })
  219. }
  220. // 查询成功
  221. logger.GetLogger().Debugln("QueryHistoryTikDatas successed: %v", rst)
  222. appG.Response(http.StatusOK, e.SUCCESS, rst)
  223. }
  224. // QueryTSDataReq 分时图数据查询请求参数
  225. type QueryTSDataReq struct {
  226. GoodsCode string `form:"goodsCode" binding:"required"` // 商品代码
  227. }
  228. // QueryTSDataRsp 分时图数据查询返回模型
  229. type QueryTSDataRsp struct {
  230. GoodsCode string `json:"goodsCode"` // 商品代码
  231. OutGoodsCode string `json:"outGoodsCode"` // 外部商品代码
  232. DecimalPlace int `json:"decimalPlace"` // 小数位
  233. TradeDate string `json:"tradeDate"` // 交易日
  234. StartTime time.Time `json:"startTime"` // 开始时间
  235. EndTime time.Time `json:"endTime"` // 结束时间
  236. PreSettle float64 `json:"preSettle"` // 昨结
  237. HistoryDatas []HistoryData `json:"historyDatas"` // 历史数据
  238. }
  239. // QueryTSData 分时图数据查询
  240. // @Summary 分时图数据查询
  241. // @Produce json
  242. // @Security ApiKeyAuth
  243. // @Param goodsCode query string true "商品代码"
  244. // @Success 200 {object} QueryTSDataRsp
  245. // @Failure 500 {object} app.Response
  246. // @Router /Quote/QueryTSData [get]
  247. // @Tags 行情服务
  248. func QueryTSData(c *gin.Context) {
  249. appG := app.Gin{C: c}
  250. // 获取请求参数
  251. var req QueryTSDataReq
  252. if err := appG.C.ShouldBindQuery(&req); err != nil {
  253. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  254. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  255. return
  256. }
  257. // FIXME: - 一些不常变化的数据(如市场信息、商品信息等)应缓存到Redis中, 或缓存到服务内存
  258. // 获取商品信息
  259. goods, err := models.GetGoodsByGoodsCode(req.GoodsCode)
  260. if goods == nil {
  261. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  262. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  263. return
  264. }
  265. // 获取市场
  266. market, err := models.GetMarketByGoodsCode(req.GoodsCode)
  267. if err != nil {
  268. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  269. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  270. return
  271. }
  272. if market == nil {
  273. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  274. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKET_FAILED, nil)
  275. return
  276. }
  277. // 获取目标品种交易日
  278. // FIXME: - 由于mtp2.0目前未同步外部交易所品种的当前交易日,
  279. // 故通道交易的品种目前只能在交易系统的外部市场中获
  280. // 取统一的交易日,后期应要求服务端同步外部数据
  281. marketRun, err := models.GetMarketRun(int(market.Marketid))
  282. if marketRun == nil {
  283. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  284. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKETRUN_FAILED, nil)
  285. return
  286. }
  287. // 获取目标品种的开休市计划
  288. var runSteps []map[string]interface{}
  289. // 通道交易外部市场开休市计划表 - QuoteSourceGroupRunStep; 其它市场的 - MarketRunStepDetail
  290. if market.Trademode == 15 {
  291. // 外部市场
  292. sourceRunSteps, err := models.FindQuoteSourceGroupRunSteps(*goods)
  293. if err != nil {
  294. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  295. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  296. return
  297. }
  298. for _, v := range sourceRunSteps {
  299. // struct -> json
  300. if jsonBytes, err := json.Marshal(v); err == nil {
  301. // json -> struct
  302. var runStepMap map[string]interface{}
  303. json.Unmarshal(jsonBytes, &runStepMap)
  304. runSteps = append(runSteps, runStepMap)
  305. }
  306. }
  307. }
  308. // 非外部市场或外部市场没有配置QuoteSourceGroupRunStep表数据的情况下,都从MarketRunStepDetail中获取数据
  309. if len(runSteps) == 0 {
  310. sourceRunSteps, err := models.FindMarketRunStepDetails(int(market.Marketid))
  311. if err != nil {
  312. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  313. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  314. return
  315. }
  316. for _, v := range sourceRunSteps {
  317. // struct -> json
  318. if jsonBytes, err := json.Marshal(v); err == nil {
  319. // json -> struct
  320. var runStepMap map[string]interface{}
  321. json.Unmarshal(jsonBytes, &runStepMap)
  322. runSteps = append(runSteps, runStepMap)
  323. }
  324. }
  325. }
  326. // 获取目标商品的盘面信息
  327. quoteDays, err := models.GetQuoteDays("'" + goods.Outgoodscode + "'")
  328. if err != nil {
  329. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  330. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  331. return
  332. }
  333. var preSettle float64
  334. var preSettleInt int
  335. if len(quoteDays) > 0 {
  336. if quoteDays[0].Presettle != 0 {
  337. preSettleInt = int(quoteDays[0].Presettle)
  338. preSettle = utils.IntToFloat64(preSettleInt, int(goods.Decimalplace))
  339. }
  340. if preSettle == 0 && quoteDays[0].Preclose != 0 {
  341. preSettleInt = int(quoteDays[0].Preclose)
  342. preSettle = utils.IntToFloat64(preSettleInt, int(goods.Decimalplace))
  343. }
  344. }
  345. // 构建返回数据
  346. queryTSDataRsp := QueryTSDataRsp{
  347. GoodsCode: goods.Goodscode,
  348. OutGoodsCode: goods.Outgoodscode,
  349. TradeDate: marketRun.Tradedate,
  350. DecimalPlace: int(goods.Decimalplace),
  351. PreSettle: preSettle,
  352. }
  353. // 构建分时图可直接使用的开休市数据
  354. // 这里有一个知识点:TRADEWEEKDAY 与 STARTWEEKDAY,以及 TRADEWEEKDAY 与 ENDWEEKDAY 之间相差最多一天(管理端限制),
  355. // 所以目前并不支持正真的周五夜盘模式。我们在实现时不用做得太复杂。
  356. // 当前交易日(周几)对应的开休市计划
  357. tradeDate, err := time.ParseInLocation("20060102", marketRun.Tradedate, time.Local)
  358. if err != nil {
  359. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  360. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  361. return
  362. }
  363. // !!!开休市计划明细
  364. curWeekRunSteps := make([]map[string]interface{}, 0)
  365. for _, v := range runSteps {
  366. tradeWeekDay := int(v["tradeweekday"].(float64))
  367. if tradeWeekDay == int(tradeDate.Weekday()) {
  368. curWeekRunSteps = append(curWeekRunSteps, v)
  369. }
  370. }
  371. // 获取不到可用的开休市计划
  372. if len(curWeekRunSteps) == 0 {
  373. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  374. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  375. return
  376. }
  377. // 按 SECTIONID 顺序排序
  378. sort.Slice(curWeekRunSteps, func(i int, j int) bool {
  379. return curWeekRunSteps[i]["sectionid"].(float64) < curWeekRunSteps[j]["sectionid"].(float64)
  380. })
  381. // 把各开休市时间段转化为真实的时间
  382. // 关于开休市计划的时间顺序:管理端会按时间顺序添加开休市计划,所以交易日开始时间为第一条记录的开始时间,结束时间为最后一条记录的结束时间
  383. // 关于目标商品的交易日问题:目前只能从商品所属市场获取当前交易日,这样有两个问题,一是不能按常规显示最后一个有历史数据的交易日;二是目前所有外部商品的开休市计划都是一样的。
  384. timeFormat := "20060102 15:04"
  385. // 开始时间
  386. startInterval := getTradeDay(int(curWeekRunSteps[0]["tradeweekday"].(float64)), int(curWeekRunSteps[0]["startweekday"].(float64)))
  387. queryTSDataRsp.StartTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, curWeekRunSteps[0]["starttime"].(string)), time.Local)
  388. if startInterval != 0 {
  389. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  390. queryTSDataRsp.StartTime = queryTSDataRsp.StartTime.Add(duration)
  391. }
  392. // 结束时间
  393. index := len(curWeekRunSteps) - 1
  394. endInterval := getTradeDay(int(curWeekRunSteps[index]["tradeweekday"].(float64)), int(curWeekRunSteps[index]["endweekday"].(float64)))
  395. queryTSDataRsp.EndTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, curWeekRunSteps[index]["endtime"].(string)), time.Local)
  396. if endInterval != 0 {
  397. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  398. queryTSDataRsp.EndTime = queryTSDataRsp.EndTime.Add(duration)
  399. }
  400. // fmt.Printf("开始时间:%s 结束时间:%s\n", queryTSDataRsp.StartTime.Format(timeFormat), queryTSDataRsp.EndTime.Format(timeFormat))
  401. // 获取目标时间段的历史数据(1分钟周期)
  402. // 这里要注意:由于交易库和行情库由于GoodsCode大小写不一定对得上,所以在使用交易库的商品查询行情数据时间,都要使用OutGoodsCode字段
  403. cycleDatas, err := models.GetHistoryCycleDatas(models.CycleTypeMinutes1, queryTSDataRsp.OutGoodsCode, &queryTSDataRsp.StartTime, &queryTSDataRsp.EndTime, 0, true)
  404. if err != nil {
  405. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  406. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  407. return
  408. }
  409. // ==================== 补数据(补休市数据和缺少的数据)====================
  410. if len(cycleDatas) > 0 {
  411. // 补数据第一步:如果第一数据不是开始时间的,需要补数据
  412. sources := time.Unix(int64(cycleDatas[0].ST), 0)
  413. diff := sources.Sub(queryTSDataRsp.StartTime)
  414. if diff.Minutes() > 0 {
  415. minute := int(diff.Minutes())
  416. for i := 0; i < minute; i++ {
  417. st := cycleDatas[0].ST - i*60
  418. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  419. cycleDatas = append(cycleDatas, models.CycleData{
  420. GC: cycleDatas[0].GC,
  421. Open: cycleDatas[0].Close,
  422. High: cycleDatas[0].Close,
  423. Low: cycleDatas[0].Close,
  424. Close: cycleDatas[0].Close,
  425. TV: 0,
  426. TT: 0,
  427. HV: 0,
  428. SP: 0,
  429. ST: st,
  430. SST: stt,
  431. FI: true,
  432. })
  433. }
  434. }
  435. // 接时间戳排序
  436. sort.Slice(cycleDatas, func(i int, j int) bool {
  437. return cycleDatas[i].ST < cycleDatas[j].ST
  438. })
  439. // 补数据第二步:按尾部的时间(当前服务器时间或最后休市时间)进行全补
  440. // 获取服务器时间
  441. s, _ := models.GetServerTime()
  442. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  443. if err != nil {
  444. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  445. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  446. return
  447. }
  448. if endTime.After(queryTSDataRsp.EndTime) {
  449. endTime = queryTSDataRsp.EndTime
  450. }
  451. index := len(cycleDatas) - 1
  452. sources = time.Unix(int64(cycleDatas[index].ST), 0)
  453. diff = endTime.Sub(sources)
  454. if diff.Minutes() > 0 {
  455. minute := int(diff.Minutes())
  456. for i := 0; i < minute; i++ {
  457. st := cycleDatas[index].ST + i*60
  458. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  459. cycleDatas = append(cycleDatas, models.CycleData{
  460. GC: cycleDatas[index].GC,
  461. Open: cycleDatas[index].Close,
  462. High: cycleDatas[index].Close,
  463. Low: cycleDatas[index].Close,
  464. Close: cycleDatas[index].Close,
  465. TV: 0,
  466. TT: 0,
  467. HV: 0,
  468. SP: 0,
  469. ST: st,
  470. SST: stt,
  471. FI: true,
  472. })
  473. }
  474. }
  475. // 接时间戳排序
  476. sort.Slice(cycleDatas, func(i int, j int) bool {
  477. return cycleDatas[i].ST < cycleDatas[j].ST
  478. })
  479. // 补数据第三步:补中间数据
  480. fillDatas := make([]models.CycleData, 0)
  481. for i := range cycleDatas {
  482. // 第一条记录跳过
  483. if i == 0 {
  484. continue
  485. }
  486. current := time.Unix(int64(cycleDatas[i].ST), 0)
  487. prev := time.Unix(int64(cycleDatas[i-1].ST), 0)
  488. diff := current.Sub(prev)
  489. if diff.Minutes() > 0 {
  490. minute := int(diff.Minutes())
  491. // 判断是否需要补数据,与上一条数据的间距不是一分钟
  492. if minute > 1 {
  493. for j := 1; j < minute; j++ {
  494. st := cycleDatas[i-1].ST + j*60
  495. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  496. fillDatas = append(fillDatas, models.CycleData{
  497. GC: cycleDatas[i-1].GC,
  498. Open: cycleDatas[i-1].Close,
  499. High: cycleDatas[i-1].Close,
  500. Low: cycleDatas[i-1].Close,
  501. Close: cycleDatas[i-1].Close,
  502. TV: 0,
  503. TT: 0,
  504. HV: 0,
  505. SP: 0,
  506. ST: st,
  507. SST: stt,
  508. FI: true,
  509. })
  510. }
  511. }
  512. }
  513. }
  514. // 加入到源数据
  515. cycleDatas = append(cycleDatas, fillDatas...)
  516. // 接时间戳排序
  517. sort.Slice(cycleDatas, func(i int, j int) bool {
  518. return cycleDatas[i].ST < cycleDatas[j].ST
  519. })
  520. } else {
  521. // TODO: - 下面这块操作需求确认
  522. // 如果查询结果是空数据,则使用昨结价补到服务器时间(或最后休市时间)
  523. // 获取服务器时间
  524. s, _ := models.GetServerTime()
  525. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  526. if err != nil {
  527. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  528. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  529. return
  530. }
  531. if endTime.After(queryTSDataRsp.EndTime) {
  532. endTime = queryTSDataRsp.EndTime
  533. }
  534. diff := endTime.Sub(queryTSDataRsp.StartTime)
  535. minute := int(diff.Minutes())
  536. for i := 0; i < minute; i++ {
  537. st := int(queryTSDataRsp.StartTime.Unix()) + i*60
  538. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  539. cycleDatas = append(cycleDatas, models.CycleData{
  540. GC: queryTSDataRsp.GoodsCode,
  541. Open: preSettleInt,
  542. High: preSettleInt,
  543. Low: preSettleInt,
  544. Close: preSettleInt,
  545. TV: 0,
  546. TT: 0,
  547. HV: 0,
  548. SP: 0,
  549. ST: st,
  550. SST: stt,
  551. FI: true,
  552. })
  553. }
  554. // 接时间戳排序
  555. sort.Slice(cycleDatas, func(i int, j int) bool {
  556. return cycleDatas[i].ST < cycleDatas[j].ST
  557. })
  558. }
  559. // 补数据第四步:清除掉开市计划外的数据
  560. // 先计算出每条计划明细的真正开始与结束时间
  561. for _, v := range curWeekRunSteps {
  562. // 开始时间
  563. startInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["startweekday"].(float64)))
  564. v["start"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, v["starttime"].(string)), time.Local)
  565. if startInterval != 0 {
  566. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  567. v["start"] = v["start"].(time.Time).Add(duration)
  568. }
  569. // 结束时间
  570. endInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["endweekday"].(float64)))
  571. v["end"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, v["endtime"].(string)), time.Local)
  572. if endInterval != 0 {
  573. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  574. v["end"] = v["end"].(time.Time).Add(duration)
  575. }
  576. }
  577. // 最终返回的历史数据
  578. historyDatas := make([]HistoryData, 0)
  579. for _, cycleData := range cycleDatas {
  580. needAdd := false
  581. for _, runStep := range curWeekRunSteps {
  582. // 判断是否在开市计划内
  583. if cycleData.ST >= int(runStep["start"].(time.Time).Unix()) && cycleData.ST <= int(runStep["end"].(time.Time).Unix()) {
  584. needAdd = true
  585. break
  586. }
  587. }
  588. if needAdd {
  589. historyDatas = append(historyDatas, HistoryData{
  590. Opened: utils.IntToFloat64(cycleData.Open, int(goods.Decimalplace)),
  591. Highest: utils.IntToFloat64(cycleData.High, int(goods.Decimalplace)),
  592. Lowest: utils.IntToFloat64(cycleData.Low, int(goods.Decimalplace)),
  593. Closed: utils.IntToFloat64(cycleData.Close, int(goods.Decimalplace)),
  594. TotleVolume: cycleData.TV,
  595. TotleTurnover: float64(cycleData.TT),
  596. HoldVolume: cycleData.HV,
  597. Settle: utils.IntToFloat64(cycleData.SP, int(goods.Decimalplace)),
  598. TimeStamp: time.Unix(int64(cycleData.ST), 0),
  599. IsFill: cycleData.FI,
  600. })
  601. }
  602. }
  603. queryTSDataRsp.HistoryDatas = historyDatas
  604. // 查询成功
  605. logger.GetLogger().Debugln("QueryTSData successed: %v", queryTSDataRsp)
  606. appG.Response(http.StatusOK, e.SUCCESS, queryTSDataRsp)
  607. }
  608. // getTradeDay 获取结算计划中天数间隔的方法
  609. // - tradeDay: 交易日周几
  610. // - weekDay: 开始或结束周几
  611. // - Returns: 天数间隔
  612. func getTradeDay(tradeDay, weekDay int) int {
  613. if tradeDay == weekDay {
  614. return 0
  615. }
  616. if weekDay == 0 {
  617. weekDay = 7
  618. }
  619. betWeekDay := weekDay - tradeDay
  620. if betWeekDay < 0 {
  621. betWeekDay = betWeekDay + 7
  622. }
  623. if betWeekDay >= 4 {
  624. betWeekDay = betWeekDay - 7
  625. }
  626. return betWeekDay
  627. }