history.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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: 日线 10: Tik"
  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. // QueryTSDataReq 分时图数据查询请求参数
  117. type QueryTSDataReq struct {
  118. GoodsCode string `form:"goodsCode" binding:"required"` // 商品代码
  119. }
  120. // QueryTSDataRsp 分时图数据查询返回模型
  121. type QueryTSDataRsp struct {
  122. GoodsCode string `json:"goodsCode"` // 商品代码
  123. OutGoodsCode string `json:"outGoodsCode"` // 外部商品代码
  124. DecimalPlace int `json:"decimalPlace"` // 小数位
  125. TradeDate string `json:"tradeDate"` // 交易日
  126. StartTime time.Time `json:"startTime"` // 开始时间
  127. EndTime time.Time `json:"endTime"` // 结束时间
  128. PreSettle float64 `json:"preSettle"` // 昨结
  129. HistoryDatas []HistoryData `json:"historyDatas"` // 历史数据
  130. }
  131. // QueryTSData 分时图数据查询
  132. // @Summary 分时图数据查询
  133. // @Produce json
  134. // @Param goodsCode query string true "商品代码"
  135. // @Success 200 {object} QueryTSDataRsp
  136. // @Failure 500 {object} app.Response
  137. // @Router /Quote/QueryTSData [get]
  138. // @Tags 行情服务
  139. func QueryTSData(c *gin.Context) {
  140. appG := app.Gin{C: c}
  141. // 获取请求参数
  142. var req QueryTSDataReq
  143. if err := appG.C.ShouldBindQuery(&req); err != nil {
  144. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  145. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  146. return
  147. }
  148. // FIXME: - 一些不常变化的数据(如市场信息、商品信息等)应缓存到Redis中, 或缓存到服务内存
  149. // 获取商品信息
  150. goods, err := models.GetGoodsByGoodsCode(req.GoodsCode)
  151. if goods == nil {
  152. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  153. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  154. return
  155. }
  156. // 获取市场
  157. market, err := models.GetMarketByGoodsCode(req.GoodsCode)
  158. if err != nil {
  159. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  160. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  161. return
  162. }
  163. if market == nil {
  164. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  165. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKET_FAILED, nil)
  166. return
  167. }
  168. // 获取目标品种交易日
  169. // FIXME: - 由于mtp2.0目前未同步外部交易所品种的当前交易日,
  170. // 故通道交易的品种目前只能在交易系统的外部市场中获
  171. // 取统一的交易日,后期应要求服务端同步外部数据
  172. marketRun, err := models.GetMarketRun(int(market.Marketid))
  173. if marketRun == nil {
  174. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  175. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKETRUN_FAILED, nil)
  176. return
  177. }
  178. // 获取目标品种的开休市计划
  179. var runSteps []map[string]interface{}
  180. // 通道交易外部市场开休市计划表 - QuoteSourceGroupRunStep; 其它市场的 - MarketRunStepDetail
  181. if market.Trademode == 15 {
  182. // 外部市场
  183. sourceRunSteps, err := models.FindQuoteSourceGroupRunSteps(*goods)
  184. if err != nil {
  185. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  186. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  187. return
  188. }
  189. for _, v := range sourceRunSteps {
  190. // struct -> json
  191. if jsonBytes, err := json.Marshal(v); err == nil {
  192. // json -> struct
  193. var runStepMap map[string]interface{}
  194. json.Unmarshal(jsonBytes, &runStepMap)
  195. runSteps = append(runSteps, runStepMap)
  196. }
  197. }
  198. }
  199. // 非外部市场或外部市场没有配置QuoteSourceGroupRunStep表数据的情况下,都从MarketRunStepDetail中获取数据
  200. if len(runSteps) == 0 {
  201. sourceRunSteps, err := models.FindMarketRunStepDetails(int(market.Marketid))
  202. if err != nil {
  203. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  204. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  205. return
  206. }
  207. for _, v := range sourceRunSteps {
  208. // struct -> json
  209. if jsonBytes, err := json.Marshal(v); err == nil {
  210. // json -> struct
  211. var runStepMap map[string]interface{}
  212. json.Unmarshal(jsonBytes, &runStepMap)
  213. runSteps = append(runSteps, runStepMap)
  214. }
  215. }
  216. }
  217. // 获取目标商品的盘面信息
  218. quoteDays, err := models.GetQuoteDays("'" + goods.Outgoodscode + "'")
  219. if err != nil {
  220. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  221. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  222. return
  223. }
  224. var preSettle float64
  225. var preSettleInt int
  226. if len(quoteDays) > 0 {
  227. if quoteDays[0].Presettle != 0 {
  228. preSettleInt = int(quoteDays[0].Presettle)
  229. preSettle = utils.IntToFloat64(preSettleInt, int(goods.Decimalplace))
  230. }
  231. if preSettle == 0 && quoteDays[0].Preclose != 0 {
  232. preSettleInt = int(quoteDays[0].Preclose)
  233. preSettle = utils.IntToFloat64(preSettleInt, int(goods.Decimalplace))
  234. }
  235. }
  236. // 构建返回数据
  237. queryTSDataRsp := QueryTSDataRsp{
  238. GoodsCode: goods.Goodscode,
  239. OutGoodsCode: goods.Outgoodscode,
  240. TradeDate: marketRun.Tradedate,
  241. DecimalPlace: int(goods.Decimalplace),
  242. PreSettle: preSettle,
  243. }
  244. // 构建分时图可直接使用的开休市数据
  245. // 这里有一个知识点:TRADEWEEKDAY 与 STARTWEEKDAY,以及 TRADEWEEKDAY 与 ENDWEEKDAY 之间相差最多一天(管理端限制),
  246. // 所以目前并不支持正真的周五夜盘模式。我们在实现时不用做得太复杂。
  247. // 当前交易日(周几)对应的开休市计划
  248. tradeDate, err := time.ParseInLocation("20060102", marketRun.Tradedate, time.Local)
  249. if err != nil {
  250. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  251. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  252. return
  253. }
  254. // !!!开休市计划明细
  255. curWeekRunSteps := make([]map[string]interface{}, 0)
  256. for _, v := range runSteps {
  257. tradeWeekDay := int(v["tradeweekday"].(float64))
  258. if tradeWeekDay == int(tradeDate.Weekday()) {
  259. curWeekRunSteps = append(curWeekRunSteps, v)
  260. }
  261. }
  262. // 获取不到可用的开休市计划
  263. if len(curWeekRunSteps) == 0 {
  264. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  265. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  266. return
  267. }
  268. // 按 SECTIONID 顺序排序
  269. sort.Slice(curWeekRunSteps, func(i int, j int) bool {
  270. return curWeekRunSteps[i]["sectionid"].(int) < curWeekRunSteps[j]["sectionid"].(int)
  271. })
  272. // 把各开休市时间段转化为真实的时间
  273. // 关于开休市计划的时间顺序:管理端会按时间顺序添加开休市计划,所以交易日开始时间为第一条记录的开始时间,结束时间为最后一条记录的结束时间
  274. // 关于目标商品的交易日问题:目前只能从商品所属市场获取当前交易日,这样有两个问题,一是不能按常规显示最后一个有历史数据的交易日;二是目前所有外部商品的开休市计划都是一样的。
  275. timeFormat := "20060102 15:04"
  276. // 开始时间
  277. startInterval := getTradeDay(int(curWeekRunSteps[0]["tradeweekday"].(float64)), int(curWeekRunSteps[0]["startweekday"].(float64)))
  278. queryTSDataRsp.StartTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, curWeekRunSteps[0]["starttime"].(string)), time.Local)
  279. if startInterval != 0 {
  280. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  281. queryTSDataRsp.StartTime = queryTSDataRsp.StartTime.Add(duration)
  282. }
  283. // 结束时间
  284. index := len(curWeekRunSteps) - 1
  285. endInterval := getTradeDay(int(curWeekRunSteps[index]["tradeweekday"].(float64)), int(curWeekRunSteps[index]["endweekday"].(float64)))
  286. queryTSDataRsp.EndTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, curWeekRunSteps[index]["endtime"].(string)), time.Local)
  287. if endInterval != 0 {
  288. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  289. queryTSDataRsp.EndTime = queryTSDataRsp.EndTime.Add(duration)
  290. }
  291. // fmt.Printf("开始时间:%s 结束时间:%s\n", queryTSDataRsp.StartTime.Format(timeFormat), queryTSDataRsp.EndTime.Format(timeFormat))
  292. // 获取目标时间段的历史数据
  293. // 这里要注意:由于交易库和行情库由于GoodsCode大小写不一定对得上,所以在使用交易库的商品查询行情数据时间,都要使用OutGoodsCode字段
  294. cycleDatas, err := models.GetHistoryCycleDatas(models.CycleTypeMinutes1, queryTSDataRsp.OutGoodsCode, &queryTSDataRsp.StartTime, &queryTSDataRsp.EndTime, 0, true)
  295. if err != nil {
  296. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  297. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  298. return
  299. }
  300. // ==================== 补数据(补休市数据和缺少的数据)====================
  301. if len(cycleDatas) > 0 {
  302. // 补数据第一步:如果第一数据不是开始时间的,需要补数据
  303. sources := time.Unix(int64(cycleDatas[0].ST), 0)
  304. diff := sources.Sub(queryTSDataRsp.StartTime)
  305. if diff.Minutes() > 0 {
  306. minute := int(diff.Minutes())
  307. for i := 0; i < minute; i++ {
  308. st := cycleDatas[0].ST - i*60
  309. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  310. cycleDatas = append(cycleDatas, models.CycleData{
  311. GC: cycleDatas[0].GC,
  312. Open: cycleDatas[0].Open,
  313. High: cycleDatas[0].High,
  314. Low: cycleDatas[0].Low,
  315. Close: cycleDatas[0].Close,
  316. TV: cycleDatas[0].TV,
  317. TT: cycleDatas[0].TT,
  318. HV: cycleDatas[0].HV,
  319. SP: cycleDatas[0].SP,
  320. ST: st,
  321. SST: stt,
  322. FI: true,
  323. })
  324. }
  325. }
  326. // 接时间戳排序
  327. sort.Slice(cycleDatas, func(i int, j int) bool {
  328. return cycleDatas[i].ST < cycleDatas[j].ST
  329. })
  330. // 补数据第二步:按尾部的时间(当前服务器时间或最后休市时间)进行全补
  331. // 获取服务器时间
  332. s, _ := models.GetServerTime()
  333. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  334. if err != nil {
  335. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  336. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  337. return
  338. }
  339. if endTime.After(queryTSDataRsp.EndTime) {
  340. endTime = queryTSDataRsp.EndTime
  341. }
  342. index := len(cycleDatas) - 1
  343. sources = time.Unix(int64(cycleDatas[index].ST), 0)
  344. diff = endTime.Sub(sources)
  345. if diff.Minutes() > 0 {
  346. minute := int(diff.Minutes())
  347. for i := 0; i < minute; i++ {
  348. st := cycleDatas[index].ST + i*60
  349. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  350. cycleDatas = append(cycleDatas, models.CycleData{
  351. GC: cycleDatas[index].GC,
  352. Open: cycleDatas[index].Open,
  353. High: cycleDatas[index].High,
  354. Low: cycleDatas[index].Low,
  355. Close: cycleDatas[index].Close,
  356. TV: cycleDatas[index].TV,
  357. TT: cycleDatas[index].TT,
  358. HV: cycleDatas[index].HV,
  359. SP: cycleDatas[index].SP,
  360. ST: st,
  361. SST: stt,
  362. FI: true,
  363. })
  364. }
  365. }
  366. // 接时间戳排序
  367. sort.Slice(cycleDatas, func(i int, j int) bool {
  368. return cycleDatas[i].ST < cycleDatas[j].ST
  369. })
  370. // 补数据第三步:补中间数据
  371. fillDatas := make([]models.CycleData, 0)
  372. for i := range cycleDatas {
  373. // 第一条记录跳过
  374. if i == 0 {
  375. continue
  376. }
  377. current := time.Unix(int64(cycleDatas[i].ST), 0)
  378. prev := time.Unix(int64(cycleDatas[i-1].ST), 0)
  379. diff := current.Sub(prev)
  380. if diff.Minutes() > 0 {
  381. minute := int(diff.Minutes())
  382. // 判断是否需要补数据,与上一条数据的间距不是一分钟
  383. if minute > 1 {
  384. for j := 1; j < minute; j++ {
  385. st := cycleDatas[i-1].ST + j*60
  386. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  387. fillDatas = append(fillDatas, models.CycleData{
  388. GC: cycleDatas[i-1].GC,
  389. Open: cycleDatas[i-1].Open,
  390. High: cycleDatas[i-1].High,
  391. Low: cycleDatas[i-1].Low,
  392. Close: cycleDatas[i-1].Close,
  393. TV: cycleDatas[i-1].TV,
  394. TT: cycleDatas[i-1].TT,
  395. HV: cycleDatas[i-1].HV,
  396. SP: cycleDatas[i-1].SP,
  397. ST: st,
  398. SST: stt,
  399. FI: true,
  400. })
  401. }
  402. }
  403. }
  404. }
  405. // 加入到源数据
  406. cycleDatas = append(cycleDatas, fillDatas...)
  407. // 接时间戳排序
  408. sort.Slice(cycleDatas, func(i int, j int) bool {
  409. return cycleDatas[i].ST < cycleDatas[j].ST
  410. })
  411. } else {
  412. // TODO: - 下面这块操作需求确认
  413. // 如果查询结果是空数据,则使用昨结价补到服务器时间(或最后休市时间)
  414. // 获取服务器时间
  415. s, _ := models.GetServerTime()
  416. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  417. if err != nil {
  418. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  419. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  420. return
  421. }
  422. if endTime.After(queryTSDataRsp.EndTime) {
  423. endTime = queryTSDataRsp.EndTime
  424. }
  425. diff := endTime.Sub(queryTSDataRsp.StartTime)
  426. minute := int(diff.Minutes())
  427. for i := 0; i < minute; i++ {
  428. st := int(queryTSDataRsp.StartTime.Unix()) + i*60
  429. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  430. cycleDatas = append(cycleDatas, models.CycleData{
  431. GC: queryTSDataRsp.GoodsCode,
  432. Open: preSettleInt,
  433. High: preSettleInt,
  434. Low: preSettleInt,
  435. Close: preSettleInt,
  436. TV: 0,
  437. TT: 0,
  438. HV: 0,
  439. SP: 0,
  440. ST: st,
  441. SST: stt,
  442. FI: true,
  443. })
  444. }
  445. // 接时间戳排序
  446. sort.Slice(cycleDatas, func(i int, j int) bool {
  447. return cycleDatas[i].ST < cycleDatas[j].ST
  448. })
  449. }
  450. // 补数据第四步:清除掉开市计划外的数据
  451. // 先计算出每条计划明细的真正开始与结束时间
  452. for _, v := range curWeekRunSteps {
  453. // 开始时间
  454. startInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["startweekday"].(float64)))
  455. v["start"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, v["starttime"].(string)), time.Local)
  456. if startInterval != 0 {
  457. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  458. v["start"] = v["start"].(time.Time).Add(duration)
  459. }
  460. // 结束时间
  461. endInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["endweekday"].(float64)))
  462. v["end"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", marketRun.Tradedate, v["endtime"].(string)), time.Local)
  463. if endInterval != 0 {
  464. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  465. v["end"] = v["end"].(time.Time).Add(duration)
  466. }
  467. }
  468. // 最终返回的历史数据
  469. historyDatas := make([]HistoryData, 0)
  470. for _, cycleData := range cycleDatas {
  471. needAdd := false
  472. for _, runStep := range curWeekRunSteps {
  473. // 判断是否在开市计划内
  474. if cycleData.ST >= int(runStep["start"].(time.Time).Unix()) && cycleData.ST <= int(runStep["end"].(time.Time).Unix()) {
  475. needAdd = true
  476. break
  477. }
  478. }
  479. if needAdd {
  480. historyDatas = append(historyDatas, HistoryData{
  481. Opened: utils.IntToFloat64(cycleData.Open, int(goods.Decimalplace)),
  482. Highest: utils.IntToFloat64(cycleData.High, int(goods.Decimalplace)),
  483. Lowest: utils.IntToFloat64(cycleData.Low, int(goods.Decimalplace)),
  484. Closed: utils.IntToFloat64(cycleData.Close, int(goods.Decimalplace)),
  485. TotleVolume: cycleData.TV,
  486. TotleTurnover: float64(cycleData.TT),
  487. HoldVolume: cycleData.HV,
  488. Settle: utils.IntToFloat64(cycleData.SP, int(goods.Decimalplace)),
  489. TimeStamp: time.Unix(int64(cycleData.ST), 0),
  490. IsFill: cycleData.FI,
  491. })
  492. }
  493. }
  494. queryTSDataRsp.HistoryDatas = historyDatas
  495. // 查询成功
  496. logger.GetLogger().Debugln("QueryTSData successed: %v", queryTSDataRsp)
  497. appG.Response(http.StatusOK, e.SUCCESS, queryTSDataRsp)
  498. }
  499. // getTradeDay 获取结算计划中天数间隔的方法
  500. // - tradeDay: 交易日周几
  501. // - weekDay: 开始或结束周几
  502. // - Returns: 天数间隔
  503. func getTradeDay(tradeDay, weekDay int) int {
  504. if tradeDay == weekDay {
  505. return 0
  506. }
  507. if weekDay == 0 {
  508. weekDay = 7
  509. }
  510. betWeekDay := weekDay - tradeDay
  511. if betWeekDay < 0 {
  512. betWeekDay = betWeekDay + 7
  513. }
  514. if betWeekDay >= 4 {
  515. betWeekDay = betWeekDay - 7
  516. }
  517. return betWeekDay
  518. }