history.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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/mtpcache"
  10. "mtp2_if/utils"
  11. "net/http"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/gin-gonic/gin"
  16. )
  17. // HistoryData 历史数据
  18. type HistoryData struct {
  19. Opened float64 `json:"o"` // 开盘价
  20. Highest float64 `json:"h"` // 最高价
  21. Lowest float64 `json:"l"` // 最低价
  22. Closed float64 `json:"c"` // 收盘价
  23. TotleVolume int `json:"tv"` // 总量(成交量)
  24. TotleTurnover float64 `json:"tt"` // 总金额
  25. HoldVolume int `json:"hv"` // 持仓量
  26. Settle float64 `json:"s"` // 结算价,日线周期(包括)以上才有
  27. TimeStamp time.Time `json:"ts"` // 时间
  28. IsFill bool `json:"f"` // 是否补充数据
  29. }
  30. // QueryHistoryDatasReq 查询行情历史数据请求参数
  31. type QueryHistoryDatasReq struct {
  32. CycleType int `form:"cycleType" binding:"required"`
  33. GoodsCode string `form:"goodsCode" binding:"required"`
  34. StartTime string `form:"startTime"`
  35. EndTime string `form:"endTime"`
  36. Count int `form:"count"`
  37. IsAsc bool `form:"isAsc"`
  38. }
  39. // QueryHistoryDatas 查询行情历史数据
  40. // @Summary 查询行情历史数据
  41. // @Produce json
  42. // @Security ApiKeyAuth
  43. // @Param cycleType query int true "周期类型, 0-秒 1: 1分钟 2: 5分钟 3: 30分钟 4: 60分钟 120: 2小时 240: 4小时 11: 日线 12:周线 13:月线 14:年线"
  44. // @Param goodsCode query string true "商品代码"
  45. // @Param startTime query string false "开始时间,格式:yyyy-MM-dd HH:mm:ss"
  46. // @Param endTime query string false "结束时间,格式:yyyy-MM-dd HH:mm:ss"
  47. // @Param count query int false "条数"
  48. // @Param isAsc query bool false "是否按时间顺序排序(默认为时间倒序排序)"
  49. // @Success 200 {object} HistoryData
  50. // @Failure 500 {object} app.Response
  51. // @Router /Quote/QueryHistoryDatas [get]
  52. // @Tags 行情服务
  53. func QueryHistoryDatas(c *gin.Context) {
  54. appG := app.Gin{C: c}
  55. // 获取请求参数
  56. var req QueryHistoryDatasReq
  57. if err := appG.C.ShouldBindQuery(&req); err != nil {
  58. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  59. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  60. return
  61. }
  62. // 转换时间
  63. timeFormat := "2006-01-02 15:04:05" // go中的时间格式化必须是这个时间
  64. var startTime *time.Time
  65. if len(req.StartTime) > 0 {
  66. st, err := time.ParseInLocation(timeFormat, req.StartTime, time.Local)
  67. if err != nil {
  68. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  69. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  70. return
  71. }
  72. startTime = &st
  73. }
  74. var endTime *time.Time
  75. if len(req.EndTime) > 0 {
  76. et, err := time.ParseInLocation(timeFormat, req.EndTime, time.Local)
  77. if err != nil {
  78. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  79. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  80. return
  81. }
  82. endTime = &et
  83. }
  84. // 查询数据
  85. cycleDatas, err := models.GetHistoryCycleDatas(models.CycleType(req.CycleType), req.GoodsCode, startTime, endTime, req.Count, req.IsAsc)
  86. if err != nil {
  87. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  88. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  89. return
  90. }
  91. // 获取目标商品报价小数位
  92. var dcplace int = 0
  93. if len(cycleDatas) > 0 {
  94. dcplace = mtpcache.GetGoodsDecimalplace(req.GoodsCode)
  95. }
  96. // 计算最终价格
  97. rst := make([]HistoryData, 0)
  98. for _, v := range cycleDatas {
  99. historyData := HistoryData{
  100. Opened: utils.IntToFloat64(v.Open, dcplace),
  101. Highest: utils.IntToFloat64(v.High, dcplace),
  102. Lowest: utils.IntToFloat64(v.Low, dcplace),
  103. Closed: utils.IntToFloat64(v.Close, dcplace),
  104. TotleVolume: v.TV,
  105. TotleTurnover: float64(v.TT),
  106. HoldVolume: v.HV,
  107. Settle: utils.IntToFloat64(v.SP, dcplace),
  108. TimeStamp: time.Unix(int64(v.ST), 0),
  109. }
  110. rst = append(rst, historyData)
  111. }
  112. // 包括日线以上的周期,如果没有带当前周期则通过盘面数据生成当前周期数据
  113. if req.CycleType >= 11 {
  114. // 获取商品信息
  115. goods, err := models.GetGoodsByGoodsCode(req.GoodsCode)
  116. if goods == nil {
  117. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  118. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  119. return
  120. }
  121. // 获取市场
  122. market, err := models.GetMarketByGoodsCode(req.GoodsCode)
  123. if err != nil {
  124. logger.GetLogger().Errorf("QueryHistoryDatas failed: %s", err.Error())
  125. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  126. return
  127. }
  128. if market == nil {
  129. logger.GetLogger().Error("QueryHistoryDatas failed: not found goodscode")
  130. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKET_FAILED, nil)
  131. return
  132. }
  133. // 获取目标品种交易日
  134. // FIXME: - 由于mtp2.0目前未同步外部交易所品种的当前交易日,
  135. // 故通道交易的品种目前只能在交易系统的外部市场中获
  136. // 取统一的交易日,后期应要求服务端同步外部数据
  137. // 2021.06.30 业务更新:15、97和99市场的行情交易日要从商品盘面中获取
  138. quoteTradeDate := ""
  139. if market.Trademode == 15 || market.Trademode == 97 || market.Trademode == 99 {
  140. if quoteDays, err := models.GetQuoteDays("'" + req.GoodsCode + "'"); err == nil {
  141. if len(quoteDays) > 0 {
  142. quoteTradeDate = time.Unix(quoteDays[0].Exchangedate, 0).Format("20060102")
  143. }
  144. }
  145. } else {
  146. if marketRun, err := models.GetMarketRun(int(market.Marketid)); err == nil {
  147. quoteTradeDate = marketRun.Tradedate2
  148. }
  149. }
  150. if quoteTradeDate != "" {
  151. if tradeDate, err := time.ParseInLocation("20060102", quoteTradeDate, time.Local); err == nil {
  152. var fisrtDate time.Time
  153. switch req.CycleType {
  154. case 12: // 周
  155. fisrtDate = getFirstDateOfWeek(tradeDate)
  156. case 13: // 月
  157. fisrtDate = getFirstDateOfMonth(tradeDate)
  158. case 14: // 年
  159. fisrtDate = getFirstDateOfYear(tradeDate)
  160. default: // 日
  161. fisrtDate = tradeDate
  162. }
  163. // 获取盘面数据
  164. if quoteDays, err := models.GetQuoteDays(req.GoodsCode); err == nil && len(quoteDays) > 0 {
  165. v := quoteDays[0]
  166. if len(rst) == 0 {
  167. // 历史数据当前没数据则直接加当前盘面数据
  168. historyData := HistoryData{
  169. Opened: utils.IntToFloat64(int(v.Opened), dcplace),
  170. Highest: utils.IntToFloat64(int(v.Highest), dcplace),
  171. Lowest: utils.IntToFloat64(int(v.Lowest), dcplace),
  172. Closed: utils.IntToFloat64(int(v.Last), dcplace),
  173. TotleVolume: int(v.Totalvolume),
  174. TotleTurnover: float64(v.Totalturnover),
  175. HoldVolume: int(v.Holdvolume),
  176. Settle: utils.IntToFloat64(int(v.Settle), dcplace),
  177. TimeStamp: fisrtDate,
  178. }
  179. if req.IsAsc {
  180. rst = append(rst, historyData)
  181. } else {
  182. // 插入第一条
  183. rear := append([]HistoryData{}, rst[0:]...)
  184. rst = append(append(rst[:0], historyData), rear...)
  185. }
  186. } else {
  187. // 判断最后周期是否已经存在盘面周期
  188. hd := rst[len(rst)-1]
  189. if hd.TimeStamp.Before(fisrtDate) {
  190. // #3424 当日未开市显示了K线
  191. // 修改:这里增加判断盘面是否有开盘价
  192. if v.Opened > 0 {
  193. historyData := HistoryData{
  194. Opened: utils.IntToFloat64(int(v.Opened), dcplace),
  195. Highest: utils.IntToFloat64(int(v.Highest), dcplace),
  196. Lowest: utils.IntToFloat64(int(v.Lowest), dcplace),
  197. Closed: utils.IntToFloat64(int(v.Last), dcplace),
  198. TotleVolume: int(v.Totalvolume),
  199. TotleTurnover: float64(v.Totalturnover),
  200. HoldVolume: int(v.Holdvolume),
  201. Settle: utils.IntToFloat64(int(v.Settle), dcplace),
  202. TimeStamp: fisrtDate,
  203. }
  204. if req.IsAsc {
  205. rst = append(rst, historyData)
  206. } else {
  207. // 插入第一条
  208. rear := append([]HistoryData{}, rst[0:]...)
  209. rst = append(append(rst[:0], historyData), rear...)
  210. }
  211. }
  212. }
  213. }
  214. }
  215. }
  216. }
  217. }
  218. // 查询成功
  219. logger.GetLogger().Debugln("QueryHistoryDatas successed, rows:", len(rst))
  220. appG.Response(http.StatusOK, e.SUCCESS, rst)
  221. }
  222. // HistoryTikData Tik数据
  223. type HistoryTikData struct {
  224. TimeStamp time.Time `json:"TS"` // 行情时间文本
  225. PE float64 `json:"PE"` // 现价
  226. Vol int `json:"Vol"` // 现量
  227. TT float64 `json:"TT"` // 现金额
  228. Bid float64 `json:"Bid"` // 买价
  229. BV int `json:"BV"` // 买量
  230. Ask float64 `json:"Ask"` // 卖价
  231. AV int `json:"AV"` // 卖量
  232. HV int `json:"HV"` // 持仓量
  233. HI int `json:"HI"` // 单笔持仓
  234. TDR int `json:"TDR"` // 交易方向,0:买 1:卖
  235. TK int `json:"TK"` // 交易类型
  236. }
  237. // QueryHistoryTikDatasReq 查询行情Tik数据请求参数
  238. type QueryHistoryTikDatasReq struct {
  239. GoodsCode string `form:"goodsCode" binding:"required"`
  240. StartTime string `form:"startTime"`
  241. EndTime string `form:"endTime"`
  242. Count int `form:"count"`
  243. IsAsc bool `form:"isAsc"`
  244. }
  245. // QueryHistoryTikDatas 查询行情Tik数据
  246. // @Summary 查询行情Tik数据
  247. // @Produce json
  248. // @Security ApiKeyAuth
  249. // @Param goodsCode query string true "商品代码"
  250. // @Param startTime query string false "开始时间,格式:yyyy-MM-dd HH:mm:ss"
  251. // @Param endTime query string false "结束时间,格式:yyyy-MM-dd HH:mm:ss"
  252. // @Param count query int false "条数"
  253. // @Param isAsc query bool false "是否按时间顺序排序(默认为时间倒序排序)"
  254. // @Success 200 {object} HistoryTikData
  255. // @Failure 500 {object} app.Response
  256. // @Router /Quote/QueryHistoryTikDatas [get]
  257. // @Tags 行情服务
  258. func QueryHistoryTikDatas(c *gin.Context) {
  259. appG := app.Gin{C: c}
  260. // 获取请求参数
  261. var req QueryHistoryTikDatasReq
  262. if err := appG.C.ShouldBindQuery(&req); err != nil {
  263. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  264. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  265. return
  266. }
  267. // 转换时间
  268. timeFormat := "2006-01-02 15:04:05" // go中的时间格式化必须是这个时间
  269. var startTime *time.Time
  270. if len(req.StartTime) > 0 {
  271. st, err := time.ParseInLocation(timeFormat, req.StartTime, time.Local)
  272. if err != nil {
  273. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  274. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  275. return
  276. }
  277. startTime = &st
  278. }
  279. var endTime *time.Time
  280. if len(req.EndTime) > 0 {
  281. et, err := time.ParseInLocation(timeFormat, req.EndTime, time.Local)
  282. if err != nil {
  283. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  284. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_TIME_FORMAT_FAIL, nil)
  285. return
  286. }
  287. endTime = &et
  288. }
  289. // 查询数据
  290. tikDatas, err := models.GetHistoryTikDatas(req.GoodsCode, startTime, endTime, req.Count, req.IsAsc)
  291. if err != nil {
  292. logger.GetLogger().Errorf("QueryHistoryTikDatas failed: %s", err.Error())
  293. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  294. return
  295. }
  296. // 获取目标商品报价小数位
  297. var dcplace int = 0
  298. if len(tikDatas) > 0 {
  299. dcplace = mtpcache.GetGoodsDecimalplace(req.GoodsCode)
  300. }
  301. // 计算最终价格
  302. rst := make([]HistoryTikData, 0)
  303. for _, v := range tikDatas {
  304. // 获取方向
  305. buyOrSell := 0
  306. if v.TDR == 83 { // (Ascii) B-66 S-83
  307. buyOrSell = 1
  308. }
  309. rst = append(rst, HistoryTikData{
  310. TimeStamp: time.Unix(int64(v.AT), 0),
  311. PE: utils.IntToFloat64(v.PE, dcplace),
  312. Vol: v.Vol,
  313. TT: float64(v.TT),
  314. Bid: utils.IntToFloat64(v.Bid, dcplace),
  315. BV: v.BV,
  316. Ask: utils.IntToFloat64(v.Ask, dcplace),
  317. AV: v.AV,
  318. HV: v.HV,
  319. HI: v.HI,
  320. TDR: buyOrSell,
  321. TK: v.TK,
  322. })
  323. }
  324. // 查询成功
  325. logger.GetLogger().Debugln("QueryHistoryTikDatas successed, rows: %v", len(rst))
  326. appG.Response(http.StatusOK, e.SUCCESS, rst)
  327. }
  328. // QueryTSDataReq 分时图数据查询请求参数
  329. type QueryTSDataReq struct {
  330. GoodsCode string `form:"goodsCode" binding:"required"` // 商品代码
  331. }
  332. // QueryTSDataRsp 分时图数据查询返回模型
  333. type QueryTSDataRsp struct {
  334. GoodsCode string `json:"goodsCode"` // 商品代码
  335. OutGoodsCode string `json:"outGoodsCode"` // 外部商品代码
  336. DecimalPlace int `json:"decimalPlace"` // 小数位
  337. TradeDate string `json:"tradeDate"` // 交易日
  338. StartTime time.Time `json:"startTime"` // 开始时间
  339. EndTime time.Time `json:"endTime"` // 结束时间
  340. PreSettle float64 `json:"preSettle"` // 昨结价
  341. Count int `json:"Count"` // 交易日应有数据个数
  342. HistoryDatas []HistoryData `json:"historyDatas"` // 历史数据
  343. RunSteps []TSDataRunStep `json:"runSteps"` // 交易日开休市计划
  344. }
  345. // TSDataRunStep 分时图交易日开休市计划
  346. type TSDataRunStep struct {
  347. Groupid int32 `json:"groupid"` // 分组ID
  348. Tradeweekday int32 `json:"tradeweekday"` // 交易日归属 - 0:星期天、1:星期一、2:星期二、3:星期三、4:星期四、5:星期五、6:星期六
  349. Sectionid int32 `json:"sectionid"` // 从 1 开始 往下编 [0为系统清盘、结算时间] SectionId = 0时,开始时间=清盘时间 开始周几= 清盘周几, 结束时间=结算时间 结束周几=结算周几
  350. Runstep int32 `json:"runstep"` // 运行阶段 - 2:连续交易
  351. Startweekday int32 `json:"startweekday"` // 起始周几
  352. Starttime string `json:"starttime"` // 起始时间(HH:mm)
  353. Endweekday int32 `json:"endweekday"` // 结束周几
  354. Endtime string `json:"endtime"` // 结束时间(HH:mm)
  355. Startflag int32 `json:"startflag"` // 开始日标识 - (-1:上日 0:当日 1:次日 )
  356. Endflag int32 `json:"endflag"` // 结束日标识 - (-1:上日 0:当日 1:次日 )
  357. Start time.Time `json:"start"` // 真实开始时间
  358. End time.Time `json:"end"` // 真实结束时间
  359. }
  360. // QueryTSData 分时图数据查询
  361. // @Summary 分时图数据查询
  362. // @Produce json
  363. // @Security ApiKeyAuth
  364. // @Param goodsCode query string true "商品代码"
  365. // @Success 200 {object} QueryTSDataRsp
  366. // @Failure 500 {object} app.Response
  367. // @Router /Quote/QueryTSData [get]
  368. // @Tags 行情服务
  369. func QueryTSData(c *gin.Context) {
  370. appG := app.Gin{C: c}
  371. // 获取请求参数
  372. var req QueryTSDataReq
  373. if err := appG.C.ShouldBindQuery(&req); err != nil {
  374. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  375. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  376. return
  377. }
  378. // FIXME: - 一些不常变化的数据(如市场信息、商品信息等)应缓存到Redis中, 或缓存到服务内存
  379. // 获取商品信息
  380. goods, err := models.GetGoodsByGoodsCode(req.GoodsCode)
  381. if goods == nil {
  382. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  383. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  384. return
  385. }
  386. // 获取市场
  387. market, err := models.GetMarketByGoodsCode(req.GoodsCode)
  388. if err != nil {
  389. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  390. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  391. return
  392. }
  393. if market == nil {
  394. logger.GetLogger().Error("QueryTSData failed: not found goodscode")
  395. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKET_FAILED, nil)
  396. return
  397. }
  398. // 获取目标品种交易日
  399. // FIXME: - 由于mtp2.0目前未同步外部交易所品种的当前交易日,
  400. // 故通道交易的品种目前只能在交易系统的外部市场中获
  401. // 取统一的交易日,后期应要求服务端同步外部数据
  402. // 2021.06.30 业务更新:15、97和99市场的行情交易日要从商品盘面中获取
  403. quoteTradeDate := ""
  404. if market.Trademode == 15 || market.Trademode == 97 || market.Trademode == 99 {
  405. if quoteDays, err := models.GetQuoteDays("'" + req.GoodsCode + "'"); err == nil {
  406. if len(quoteDays) > 0 {
  407. quoteTradeDate = time.Unix(quoteDays[0].Exchangedate, 0).Format("20060102")
  408. }
  409. }
  410. } else {
  411. if marketRun, err := models.GetMarketRun(int(market.Marketid)); err == nil {
  412. quoteTradeDate = marketRun.Tradedate2
  413. }
  414. }
  415. if len(quoteTradeDate) == 0 {
  416. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  417. appG.Response(http.StatusBadRequest, e.ERROR_GET_MARKETRUN_FAILED, nil)
  418. return
  419. }
  420. // 获取目标品种的开休市计划
  421. var runSteps []map[string]interface{}
  422. // 通道交易外部市场开休市计划表 - QuoteSourceGroupRunStep; 其它市场的 - MarketRunStepDetail
  423. if market.Trademode == 15 || market.Trademode == 97 || market.Trademode == 99 {
  424. // 外部市场
  425. sourceRunSteps, err := models.FindQuoteSourceGroupRunSteps(*goods)
  426. if err != nil {
  427. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  428. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  429. return
  430. }
  431. for _, v := range sourceRunSteps {
  432. // struct -> json
  433. if jsonBytes, err := json.Marshal(v); err == nil {
  434. // json -> struct
  435. var runStepMap map[string]interface{}
  436. json.Unmarshal(jsonBytes, &runStepMap)
  437. runSteps = append(runSteps, runStepMap)
  438. }
  439. }
  440. }
  441. // 非外部市场或外部市场没有配置QuoteSourceGroupRunStep表数据的情况下,都从MarketRunStepDetail中获取数据
  442. if len(runSteps) == 0 {
  443. sourceRunSteps, err := models.FindMarketRunStepDetails(int(market.Marketid))
  444. if err != nil {
  445. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  446. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  447. return
  448. }
  449. for _, v := range sourceRunSteps {
  450. // struct -> json
  451. if jsonBytes, err := json.Marshal(v); err == nil {
  452. // json -> struct
  453. var runStepMap map[string]interface{}
  454. json.Unmarshal(jsonBytes, &runStepMap)
  455. runSteps = append(runSteps, runStepMap)
  456. }
  457. }
  458. }
  459. // 获取目标商品的盘面信息
  460. quoteDays, err := models.GetQuoteDays("'" + strings.ToUpper(goods.Goodscode) + "'")
  461. if err != nil {
  462. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  463. appG.Response(http.StatusBadRequest, e.ERROR_GET_GOODS_FAILED, nil)
  464. return
  465. }
  466. var preSettle float64
  467. var preSettleInt int
  468. if len(quoteDays) > 0 {
  469. if quoteDays[0].Presettle != 0 {
  470. preSettleInt = int(quoteDays[0].Presettle)
  471. preSettle = utils.IntToFloat64(preSettleInt, int(goods.Decimalplace))
  472. }
  473. if preSettle == 0 && quoteDays[0].Preclose != 0 {
  474. preSettleInt = int(quoteDays[0].Preclose)
  475. preSettle = utils.IntToFloat64(preSettleInt, int(goods.Decimalplace))
  476. }
  477. }
  478. // 构建返回数据
  479. // 注意:这里使用的是 marketRun.Tradedate2 行情交易日
  480. queryTSDataRsp := QueryTSDataRsp{
  481. GoodsCode: goods.Goodscode,
  482. OutGoodsCode: goods.Outgoodscode,
  483. TradeDate: quoteTradeDate,
  484. DecimalPlace: int(goods.Decimalplace),
  485. PreSettle: preSettle,
  486. }
  487. // 构建分时图可直接使用的开休市数据
  488. // 这里有一个知识点:TRADEWEEKDAY 与 STARTWEEKDAY,以及 TRADEWEEKDAY 与 ENDWEEKDAY 之间相差最多一天(管理端限制),
  489. // 所以目前并不支持正真的周五夜盘模式。我们在实现时不用做得太复杂。
  490. // 当前交易日(周几)对应的开休市计划
  491. tradeDate, err := time.ParseInLocation("20060102", quoteTradeDate, time.Local)
  492. if err != nil {
  493. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  494. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  495. return
  496. }
  497. // !!!开休市计划明细
  498. curWeekRunSteps := make([]map[string]interface{}, 0)
  499. for _, v := range runSteps {
  500. tradeWeekDay := int(v["tradeweekday"].(float64))
  501. if tradeWeekDay == int(tradeDate.Weekday()) {
  502. curWeekRunSteps = append(curWeekRunSteps, v)
  503. }
  504. }
  505. // 获取不到可用的开休市计划
  506. if len(curWeekRunSteps) == 0 {
  507. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  508. appG.Response(http.StatusBadRequest, e.ERROR_GET_RUNSTEP_FAILED, nil)
  509. return
  510. }
  511. // 按 SECTIONID 顺序排序
  512. sort.Slice(curWeekRunSteps, func(i int, j int) bool {
  513. return curWeekRunSteps[i]["sectionid"].(float64) < curWeekRunSteps[j]["sectionid"].(float64)
  514. })
  515. // 把各开休市时间段转化为真实的时间
  516. // 关于开休市计划的时间顺序:管理端会按时间顺序添加开休市计划,所以交易日开始时间为第一条记录的开始时间,结束时间为最后一条记录的结束时间
  517. // 关于目标商品的交易日问题:目前只能从商品所属市场获取当前交易日,这样有两个问题,一是不能按常规显示最后一个有历史数据的交易日;二是目前所有外部商品的开休市计划都是一样的。
  518. timeFormat := "20060102 15:04"
  519. // 开始时间
  520. startInterval := getTradeDay(int(curWeekRunSteps[0]["tradeweekday"].(float64)), int(curWeekRunSteps[0]["startweekday"].(float64)))
  521. queryTSDataRsp.StartTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", quoteTradeDate, curWeekRunSteps[0]["starttime"].(string)), time.Local)
  522. if startInterval != 0 {
  523. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  524. queryTSDataRsp.StartTime = queryTSDataRsp.StartTime.Add(duration)
  525. }
  526. // 结束时间
  527. index := len(curWeekRunSteps) - 1
  528. endInterval := getTradeDay(int(curWeekRunSteps[index]["tradeweekday"].(float64)), int(curWeekRunSteps[index]["endweekday"].(float64)))
  529. queryTSDataRsp.EndTime, _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", quoteTradeDate, curWeekRunSteps[index]["endtime"].(string)), time.Local)
  530. if endInterval != 0 {
  531. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  532. queryTSDataRsp.EndTime = queryTSDataRsp.EndTime.Add(duration)
  533. }
  534. // fmt.Printf("开始时间:%s 结束时间:%s\n", queryTSDataRsp.StartTime.Format(timeFormat), queryTSDataRsp.EndTime.Format(timeFormat))
  535. // 获取目标时间段的历史数据(1分钟周期)
  536. // 这里要注意:由于交易库和行情库由于GoodsCode大小写不一定对得上,所以在使用交易库的商品查询行情数据时间,都要使用OutGoodsCode字段
  537. // 20210702: 按行情服务要求,改用大写的GoodsCode
  538. cycleDatas, err := models.GetHistoryCycleDatas(models.CycleTypeMinutes1, strings.ToUpper(queryTSDataRsp.GoodsCode), &queryTSDataRsp.StartTime, &queryTSDataRsp.EndTime, 0, true)
  539. if err != nil {
  540. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  541. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  542. return
  543. }
  544. // ==================== 补数据(补休市数据和缺少的数据)====================
  545. if len(cycleDatas) > 0 {
  546. // 补数据第一步:如果第一数据不是开始时间的,需要补数据
  547. sources := time.Unix(int64(cycleDatas[0].ST), 0)
  548. diff := sources.Sub(queryTSDataRsp.StartTime)
  549. if diff.Minutes() > 0 {
  550. minute := int(diff.Minutes())
  551. for i := 1; i <= minute; i++ {
  552. st := cycleDatas[0].ST - i*60
  553. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  554. // 前面的数据使用昨结来补
  555. cycleDatas = append(cycleDatas, models.CycleData{
  556. GC: cycleDatas[0].GC,
  557. Open: preSettleInt,
  558. High: preSettleInt,
  559. Low: preSettleInt,
  560. Close: preSettleInt,
  561. TV: 0,
  562. TT: 0,
  563. HV: 0,
  564. SP: 0,
  565. ST: st,
  566. SST: stt,
  567. FI: true,
  568. })
  569. }
  570. }
  571. // 接时间戳排序
  572. sort.Slice(cycleDatas, func(i int, j int) bool {
  573. return cycleDatas[i].ST < cycleDatas[j].ST
  574. })
  575. // 补数据第二步:按尾部的时间(当前服务器时间或最后休市时间)进行全补
  576. // 获取服务器时间
  577. s, _ := models.GetServerTime()
  578. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  579. if err != nil {
  580. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  581. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  582. return
  583. }
  584. if endTime.After(queryTSDataRsp.EndTime) {
  585. endTime = queryTSDataRsp.EndTime
  586. }
  587. index := len(cycleDatas) - 1
  588. sources = time.Unix(int64(cycleDatas[index].ST), 0)
  589. diff = endTime.Sub(sources)
  590. if diff.Minutes() > 0 {
  591. minute := int(diff.Minutes())
  592. for i := 1; i <= minute; i++ {
  593. st := cycleDatas[index].ST + i*60
  594. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  595. cycleDatas = append(cycleDatas, models.CycleData{
  596. GC: cycleDatas[index].GC,
  597. Open: cycleDatas[index].Close,
  598. High: cycleDatas[index].Close,
  599. Low: cycleDatas[index].Close,
  600. Close: cycleDatas[index].Close,
  601. TV: 0,
  602. TT: 0,
  603. HV: 0,
  604. SP: 0,
  605. ST: st,
  606. SST: stt,
  607. FI: true,
  608. })
  609. }
  610. }
  611. // 接时间戳排序
  612. sort.Slice(cycleDatas, func(i int, j int) bool {
  613. return cycleDatas[i].ST < cycleDatas[j].ST
  614. })
  615. // 补数据第三步:补中间数据
  616. fillDatas := make([]models.CycleData, 0)
  617. for i := range cycleDatas {
  618. // 第一条记录跳过
  619. if i == 0 {
  620. continue
  621. }
  622. current := time.Unix(int64(cycleDatas[i].ST), 0)
  623. prev := time.Unix(int64(cycleDatas[i-1].ST), 0)
  624. diff := current.Sub(prev)
  625. if diff.Minutes() > 1 {
  626. minute := int(diff.Minutes())
  627. // 判断是否需要补数据,与上一条数据的间距不是一分钟
  628. if minute > 1 {
  629. // 注意补中间数据时,是不用补最后一条数据的,所以是 < minute
  630. for j := 1; j < minute; j++ {
  631. st := cycleDatas[i-1].ST + j*60
  632. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  633. fillDatas = append(fillDatas, models.CycleData{
  634. GC: cycleDatas[i-1].GC,
  635. Open: cycleDatas[i-1].Close,
  636. High: cycleDatas[i-1].Close,
  637. Low: cycleDatas[i-1].Close,
  638. Close: cycleDatas[i-1].Close,
  639. TV: 0,
  640. TT: 0,
  641. HV: 0,
  642. SP: 0,
  643. ST: st,
  644. SST: stt,
  645. FI: true,
  646. })
  647. }
  648. }
  649. }
  650. }
  651. // 加入到源数据
  652. cycleDatas = append(cycleDatas, fillDatas...)
  653. // 接时间戳排序
  654. sort.Slice(cycleDatas, func(i int, j int) bool {
  655. return cycleDatas[i].ST < cycleDatas[j].ST
  656. })
  657. } else {
  658. // TODO: - 下面这块操作需求确认
  659. // 如果查询结果是空数据,则使用昨结价补到服务器时间(或最后休市时间)
  660. // 获取服务器时间
  661. s, _ := models.GetServerTime()
  662. endTime, err := time.ParseInLocation("2006-01-02T15:04:05Z", *s, time.Local)
  663. if err != nil {
  664. logger.GetLogger().Errorf("QueryTSData failed: %s", err.Error())
  665. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  666. return
  667. }
  668. if endTime.After(queryTSDataRsp.EndTime) {
  669. endTime = queryTSDataRsp.EndTime
  670. }
  671. diff := endTime.Sub(queryTSDataRsp.StartTime)
  672. minute := int(diff.Minutes())
  673. for i := 1; i <= minute; i++ {
  674. st := int(queryTSDataRsp.StartTime.Unix()) + i*60
  675. stt := time.Unix(int64(st), 0).Format("2006-01-02 15:04:05")
  676. cycleDatas = append(cycleDatas, models.CycleData{
  677. GC: queryTSDataRsp.GoodsCode,
  678. Open: preSettleInt,
  679. High: preSettleInt,
  680. Low: preSettleInt,
  681. Close: preSettleInt,
  682. TV: 0,
  683. TT: 0,
  684. HV: 0,
  685. SP: 0,
  686. ST: st,
  687. SST: stt,
  688. FI: true,
  689. })
  690. }
  691. // 接时间戳排序
  692. sort.Slice(cycleDatas, func(i int, j int) bool {
  693. return cycleDatas[i].ST < cycleDatas[j].ST
  694. })
  695. }
  696. // 补数据第四步:清除掉开市计划外的数据
  697. // 先计算出每条计划明细的真正开始与结束时间
  698. queryTSDataRsp.RunSteps = make([]TSDataRunStep, 0)
  699. for _, v := range curWeekRunSteps {
  700. // 开始时间
  701. startInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["startweekday"].(float64)))
  702. v["start"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", quoteTradeDate, v["starttime"].(string)), time.Local)
  703. if startInterval != 0 {
  704. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", startInterval*24))
  705. v["start"] = v["start"].(time.Time).Add(duration)
  706. }
  707. // 结束时间
  708. endInterval := getTradeDay(int(v["tradeweekday"].(float64)), int(v["endweekday"].(float64)))
  709. v["end"], _ = time.ParseInLocation(timeFormat, fmt.Sprintf("%s %s", quoteTradeDate, v["endtime"].(string)), time.Local)
  710. if endInterval != 0 {
  711. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", endInterval*24))
  712. v["end"] = v["end"].(time.Time).Add(duration)
  713. }
  714. // map -> struct
  715. var tsDataRunStep TSDataRunStep
  716. jsonbody, err := json.Marshal(v)
  717. if err != nil {
  718. continue
  719. }
  720. if err := json.Unmarshal(jsonbody, &tsDataRunStep); err != nil {
  721. continue
  722. }
  723. queryTSDataRsp.RunSteps = append(queryTSDataRsp.RunSteps, tsDataRunStep)
  724. }
  725. // 最终返回的历史数据
  726. historyDatas := make([]HistoryData, 0)
  727. for _, cycleData := range cycleDatas {
  728. needAdd := false
  729. for _, runStep := range curWeekRunSteps {
  730. // 判断是否在开市计划内
  731. if cycleData.ST >= int(runStep["start"].(time.Time).Unix()) && cycleData.ST <= int(runStep["end"].(time.Time).Unix()) {
  732. needAdd = true
  733. break
  734. }
  735. }
  736. if needAdd {
  737. historyDatas = append(historyDatas, HistoryData{
  738. Opened: utils.IntToFloat64(cycleData.Open, int(goods.Decimalplace)),
  739. Highest: utils.IntToFloat64(cycleData.High, int(goods.Decimalplace)),
  740. Lowest: utils.IntToFloat64(cycleData.Low, int(goods.Decimalplace)),
  741. Closed: utils.IntToFloat64(cycleData.Close, int(goods.Decimalplace)),
  742. TotleVolume: cycleData.TV,
  743. TotleTurnover: float64(cycleData.TT),
  744. HoldVolume: cycleData.HV,
  745. Settle: utils.IntToFloat64(cycleData.SP, int(goods.Decimalplace)),
  746. TimeStamp: time.Unix(int64(cycleData.ST), 0),
  747. IsFill: cycleData.FI,
  748. })
  749. }
  750. }
  751. queryTSDataRsp.HistoryDatas = historyDatas
  752. // 计算当前交易日应该有多少个历史数据,主要用于iOS
  753. for _, v := range queryTSDataRsp.RunSteps {
  754. diff := v.End.Sub(v.Start)
  755. queryTSDataRsp.Count += int(diff.Minutes())
  756. }
  757. // 查询成功
  758. logger.GetLogger().Debugln("QueryTSData successed.")
  759. appG.Response(http.StatusOK, e.SUCCESS, queryTSDataRsp)
  760. }
  761. // getTradeDay 获取结算计划中天数间隔的方法
  762. // - tradeDay: 交易日周几
  763. // - weekDay: 开始或结束周几
  764. // - Returns: 天数间隔
  765. func getTradeDay(tradeDay, weekDay int) int {
  766. if tradeDay == weekDay {
  767. return 0
  768. }
  769. if weekDay == 0 {
  770. weekDay = 7
  771. }
  772. betWeekDay := weekDay - tradeDay
  773. if betWeekDay < 0 {
  774. betWeekDay = betWeekDay + 7
  775. }
  776. if betWeekDay >= 4 {
  777. betWeekDay = betWeekDay - 7
  778. }
  779. return betWeekDay
  780. }
  781. /**
  782. 获取某日所在周周一的日期
  783. */
  784. func getFirstDateOfWeek(d time.Time) time.Time {
  785. offset := int(time.Monday - d.Weekday())
  786. if offset > 0 {
  787. offset = -6
  788. }
  789. weekStartDate := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  790. return weekStartDate
  791. }
  792. //获取传入的时间所在月份的第一天,即某月第一天的0点。如传入time.Now(), 返回当前月份的第一天0点时间。
  793. func getFirstDateOfMonth(d time.Time) time.Time {
  794. d = d.AddDate(0, 0, -d.Day()+1)
  795. return getZeroTime(d)
  796. }
  797. //获取传入的时间所在年的第一天,即某年第一天的0点。如传入time.Now(), 返回当前年的第一天0点时间。
  798. func getFirstDateOfYear(d time.Time) time.Time {
  799. d = d.AddDate(0, -d.Year()+1, 0)
  800. return getZeroTime(d)
  801. }
  802. //获取传入的时间所在月份的最后一天,即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。
  803. func getLastDateOfMonth(d time.Time) time.Time {
  804. return getFirstDateOfMonth(d).AddDate(0, 1, -1)
  805. }
  806. //获取某一天的0点时间
  807. func getZeroTime(d time.Time) time.Time {
  808. return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
  809. }