history.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. // 注意:这里使用的是 marketRun.Tradedate2 行情交易日
  347. queryTSDataRsp := QueryTSDataRsp{
  348. GoodsCode: goods.Goodscode,
  349. OutGoodsCode: goods.Outgoodscode,
  350. TradeDate: marketRun.Tradedate2,
  351. DecimalPlace: int(goods.Decimalplace),
  352. PreSettle: preSettle,
  353. }
  354. // 构建分时图可直接使用的开休市数据
  355. // 这里有一个知识点:TRADEWEEKDAY 与 STARTWEEKDAY,以及 TRADEWEEKDAY 与 ENDWEEKDAY 之间相差最多一天(管理端限制),
  356. // 所以目前并不支持正真的周五夜盘模式。我们在实现时不用做得太复杂。
  357. // 当前交易日(周几)对应的开休市计划
  358. tradeDate, err := time.ParseInLocation("20060102", marketRun.Tradedate2, time.Local)
  359. if err != nil {
  360. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  361. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  362. return
  363. }
  364. // !!!开休市计划明细
  365. curWeekRunSteps := make([]map[string]interface{}, 0)
  366. for _, v := range runSteps {
  367. tradeWeekDay := int(v["tradeweekday"].(float64))
  368. if tradeWeekDay == int(tradeDate.Weekday()) {
  369. curWeekRunSteps = append(curWeekRunSteps, v)
  370. }
  371. }
  372. // 获取不到可用的开休市计划
  373. if len(curWeekRunSteps) == 0 {
  374. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  375. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  376. return
  377. }
  378. // 按 SECTIONID 顺序排序
  379. sort.Slice(curWeekRunSteps, func(i int, j int) bool {
  380. return curWeekRunSteps[i]["sectionid"].(float64) < curWeekRunSteps[j]["sectionid"].(float64)
  381. })
  382. // 把各开休市时间段转化为真实的时间
  383. // 关于开休市计划的时间顺序:管理端会按时间顺序添加开休市计划,所以交易日开始时间为第一条记录的开始时间,结束时间为最后一条记录的结束时间
  384. // 关于目标商品的交易日问题:目前只能从商品所属市场获取当前交易日,这样有两个问题,一是不能按常规显示最后一个有历史数据的交易日;二是目前所有外部商品的开休市计划都是一样的。
  385. timeFormat := "20060102 15:04"
  386. // 开始时间
  387. startInterval := getTradeDay(int(curWeekRunSteps[0]["tradeweekday"].(float64)), int(curWeekRunSteps[0]["startweekday"].(float64)))
  388. queryTSDataRsp.StartTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate2, curWeekRunSteps[0]["starttime"].(string)), time.Local)
  389. if startInterval != 0 {
  390. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  391. queryTSDataRsp.StartTime = queryTSDataRsp.StartTime.Add(duration)
  392. }
  393. // 结束时间
  394. index := len(curWeekRunSteps) - 1
  395. endInterval := getTradeDay(int(curWeekRunSteps[index]["tradeweekday"].(float64)), int(curWeekRunSteps[index]["endweekday"].(float64)))
  396. queryTSDataRsp.EndTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate2, curWeekRunSteps[index]["endtime"].(string)), time.Local)
  397. if endInterval != 0 {
  398. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  399. queryTSDataRsp.EndTime = queryTSDataRsp.EndTime.Add(duration)
  400. }
  401. // fmt.Printf("开始时间:%s 结束时间:%s\n", queryTSDataRsp.StartTime.Format(timeFormat), queryTSDataRsp.EndTime.Format(timeFormat))
  402. // 获取目标时间段的历史数据(1分钟周期)
  403. // 这里要注意:由于交易库和行情库由于GoodsCode大小写不一定对得上,所以在使用交易库的商品查询行情数据时间,都要使用OutGoodsCode字段
  404. cycleDatas, err := models.GetHistoryCycleDatas(models.CycleTypeMinutes1, queryTSDataRsp.OutGoodsCode, &queryTSDataRsp.StartTime, &queryTSDataRsp.EndTime, 0, true)
  405. fmt.Println(cycleDatas[len(cycleDatas)-1])
  406. if err != nil {
  407. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  408. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  409. return
  410. }
  411. // ==================== 补数据(补休市数据和缺少的数据)====================
  412. if len(cycleDatas) > 0 {
  413. // 补数据第一步:如果第一数据不是开始时间的,需要补数据
  414. sources := time.Unix(int64(cycleDatas[0].ST), 0)
  415. diff := sources.Sub(queryTSDataRsp.StartTime)
  416. if diff.Minutes() > 0 {
  417. minute := int(diff.Minutes())
  418. for i := 1; i <= minute; i++ {
  419. st := cycleDatas[0].ST - i*60
  420. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  421. cycleDatas = append(cycleDatas, models.CycleData{
  422. GC: cycleDatas[0].GC,
  423. Open: cycleDatas[0].Close,
  424. High: cycleDatas[0].Close,
  425. Low: cycleDatas[0].Close,
  426. Close: cycleDatas[0].Close,
  427. TV: 0,
  428. TT: 0,
  429. HV: 0,
  430. SP: 0,
  431. ST: st,
  432. SST: stt,
  433. FI: true,
  434. })
  435. }
  436. }
  437. // 接时间戳排序
  438. sort.Slice(cycleDatas, func(i int, j int) bool {
  439. return cycleDatas[i].ST < cycleDatas[j].ST
  440. })
  441. // 补数据第二步:按尾部的时间(当前服务器时间或最后休市时间)进行全补
  442. // 获取服务器时间
  443. s, _ := models.GetServerTime()
  444. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  445. if err != nil {
  446. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  447. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  448. return
  449. }
  450. if endTime.After(queryTSDataRsp.EndTime) {
  451. endTime = queryTSDataRsp.EndTime
  452. }
  453. index := len(cycleDatas) - 1
  454. sources = time.Unix(int64(cycleDatas[index].ST), 0)
  455. diff = endTime.Sub(sources)
  456. if diff.Minutes() > 0 {
  457. minute := int(diff.Minutes())
  458. for i := 1; i <= minute; i++ {
  459. st := cycleDatas[index].ST + i*60
  460. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  461. cycleDatas = append(cycleDatas, models.CycleData{
  462. GC: cycleDatas[index].GC,
  463. Open: cycleDatas[index].Close,
  464. High: cycleDatas[index].Close,
  465. Low: cycleDatas[index].Close,
  466. Close: cycleDatas[index].Close,
  467. TV: 0,
  468. TT: 0,
  469. HV: 0,
  470. SP: 0,
  471. ST: st,
  472. SST: stt,
  473. FI: true,
  474. })
  475. }
  476. }
  477. // 接时间戳排序
  478. sort.Slice(cycleDatas, func(i int, j int) bool {
  479. return cycleDatas[i].ST < cycleDatas[j].ST
  480. })
  481. // 补数据第三步:补中间数据
  482. fillDatas := make([]models.CycleData, 0)
  483. for i := range cycleDatas {
  484. // 第一条记录跳过
  485. if i == 0 {
  486. continue
  487. }
  488. current := time.Unix(int64(cycleDatas[i].ST), 0)
  489. prev := time.Unix(int64(cycleDatas[i-1].ST), 0)
  490. diff := current.Sub(prev)
  491. if diff.Minutes() > 0 {
  492. minute := int(diff.Minutes())
  493. // 判断是否需要补数据,与上一条数据的间距不是一分钟
  494. if minute > 1 {
  495. for j := 1; j < minute; j++ {
  496. st := cycleDatas[i-1].ST + j*60
  497. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  498. fillDatas = append(fillDatas, models.CycleData{
  499. GC: cycleDatas[i-1].GC,
  500. Open: cycleDatas[i-1].Close,
  501. High: cycleDatas[i-1].Close,
  502. Low: cycleDatas[i-1].Close,
  503. Close: cycleDatas[i-1].Close,
  504. TV: 0,
  505. TT: 0,
  506. HV: 0,
  507. SP: 0,
  508. ST: st,
  509. SST: stt,
  510. FI: true,
  511. })
  512. }
  513. }
  514. }
  515. }
  516. // 加入到源数据
  517. cycleDatas = append(cycleDatas, fillDatas...)
  518. // 接时间戳排序
  519. sort.Slice(cycleDatas, func(i int, j int) bool {
  520. return cycleDatas[i].ST < cycleDatas[j].ST
  521. })
  522. } else {
  523. // TODO: - 下面这块操作需求确认
  524. // 如果查询结果是空数据,则使用昨结价补到服务器时间(或最后休市时间)
  525. // 获取服务器时间
  526. s, _ := models.GetServerTime()
  527. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  528. if err != nil {
  529. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  530. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  531. return
  532. }
  533. if endTime.After(queryTSDataRsp.EndTime) {
  534. endTime = queryTSDataRsp.EndTime
  535. }
  536. diff := endTime.Sub(queryTSDataRsp.StartTime)
  537. minute := int(diff.Minutes())
  538. for i := 1; i <= minute; i++ {
  539. st := int(queryTSDataRsp.StartTime.Unix()) + i*60
  540. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  541. cycleDatas = append(cycleDatas, models.CycleData{
  542. GC: queryTSDataRsp.GoodsCode,
  543. Open: preSettleInt,
  544. High: preSettleInt,
  545. Low: preSettleInt,
  546. Close: preSettleInt,
  547. TV: 0,
  548. TT: 0,
  549. HV: 0,
  550. SP: 0,
  551. ST: st,
  552. SST: stt,
  553. FI: true,
  554. })
  555. }
  556. // 接时间戳排序
  557. sort.Slice(cycleDatas, func(i int, j int) bool {
  558. return cycleDatas[i].ST < cycleDatas[j].ST
  559. })
  560. }
  561. // 补数据第四步:清除掉开市计划外的数据
  562. // 先计算出每条计划明细的真正开始与结束时间
  563. for _, v := range curWeekRunSteps {
  564. // 开始时间
  565. startInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["startweekday"].(float64)))
  566. v["start"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate2, v["starttime"].(string)), time.Local)
  567. if startInterval != 0 {
  568. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  569. v["start"] = v["start"].(time.Time).Add(duration)
  570. }
  571. // 结束时间
  572. endInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["endweekday"].(float64)))
  573. v["end"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate2, v["endtime"].(string)), time.Local)
  574. if endInterval != 0 {
  575. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  576. v["end"] = v["end"].(time.Time).Add(duration)
  577. }
  578. }
  579. // 最终返回的历史数据
  580. historyDatas := make([]HistoryData, 0)
  581. for _, cycleData := range cycleDatas {
  582. needAdd := false
  583. for _, runStep := range curWeekRunSteps {
  584. // 判断是否在开市计划内
  585. if cycleData.ST >= int(runStep["start"].(time.Time).Unix()) && cycleData.ST <= int(runStep["end"].(time.Time).Unix()) {
  586. needAdd = true
  587. break
  588. }
  589. }
  590. if needAdd {
  591. historyDatas = append(historyDatas, HistoryData{
  592. Opened: utils.IntToFloat64(cycleData.Open, int(goods.Decimalplace)),
  593. Highest: utils.IntToFloat64(cycleData.High, int(goods.Decimalplace)),
  594. Lowest: utils.IntToFloat64(cycleData.Low, int(goods.Decimalplace)),
  595. Closed: utils.IntToFloat64(cycleData.Close, int(goods.Decimalplace)),
  596. TotleVolume: cycleData.TV,
  597. TotleTurnover: float64(cycleData.TT),
  598. HoldVolume: cycleData.HV,
  599. Settle: utils.IntToFloat64(cycleData.SP, int(goods.Decimalplace)),
  600. TimeStamp: time.Unix(int64(cycleData.ST), 0),
  601. IsFill: cycleData.FI,
  602. })
  603. }
  604. }
  605. queryTSDataRsp.HistoryDatas = historyDatas
  606. // 查询成功
  607. logger.GetLogger().Debugln("QueryTSData successed: %v", queryTSDataRsp)
  608. appG.Response(http.StatusOK, e.SUCCESS, queryTSDataRsp)
  609. }
  610. // getTradeDay 获取结算计划中天数间隔的方法
  611. // - tradeDay: 交易日周几
  612. // - weekDay: 开始或结束周几
  613. // - Returns: 天数间隔
  614. func getTradeDay(tradeDay, weekDay int) int {
  615. if tradeDay == weekDay {
  616. return 0
  617. }
  618. if weekDay == 0 {
  619. weekDay = 7
  620. }
  621. betWeekDay := weekDay - tradeDay
  622. if betWeekDay < 0 {
  623. betWeekDay = betWeekDay + 7
  624. }
  625. if betWeekDay >= 4 {
  626. betWeekDay = betWeekDay - 7
  627. }
  628. return betWeekDay
  629. }