order.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. package order
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "mtp2_if/db"
  7. "mtp2_if/global/app"
  8. "mtp2_if/global/e"
  9. "mtp2_if/logger"
  10. "mtp2_if/models"
  11. "mtp2_if/mtpcache"
  12. "mtp2_if/utils"
  13. "net/http"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/gin-gonic/gin"
  18. "github.com/shopspring/decimal"
  19. )
  20. type QtyCovert struct {
  21. QTYDECIMALPLACE int32
  22. }
  23. // CovertQty 根据数位 放大缩小
  24. func (r *QtyCovert) CovertQty(v int64) float64 {
  25. return float64(v) / math.Pow10(int(r.QTYDECIMALPLACE))
  26. }
  27. // 成交付款信息
  28. type TradePayInfo struct {
  29. PAYAMOUNT float64 `json:"payamount" xorm:"PAYAMOUNT"` // 支付金额(付款金额)
  30. ADVANCERATIO float64 `json:"advanceratio" xorm:"ADVANCERATIO"` // 首付比率
  31. TRADECHARGE float64 `json:"-" xorm:"TRADECHARGE"` // 成交手续费(买方)
  32. TOTALAMOUNT float64 `json:"totalamount"` // 订单总额 = 成交金额 + 手续费
  33. RECVAMOUNT float64 `json:"recvamount"` // 到账金额 = 成交金额 - 手续费
  34. }
  35. // QueryTradePositionReq 持仓汇总查询请求参数(合约市场)
  36. type QueryTradePositionReq struct {
  37. AccountID string `form:"accountID" binding:"required"`
  38. TradeMode string `form:"tradeMode"`
  39. }
  40. // QueryTradePositionRsp 持仓汇总查询返回模型(合约市场)
  41. type QueryTradePositionRsp struct {
  42. AccountID int64 `json:"accountid" xorm:"'ACCOUNTID'"` // 资金账户
  43. BuyOrSell int64 `json:"buyorsell" xorm:"'BUYORSELL'" ` // 方向 - 0:买 1:卖
  44. Goodsid int32 `json:"goodsid" xorm:"'GOODSID'" binding:"required"` // 商品Id
  45. GoodsCode string `json:"goodscode" xorm:"GOODSCODE"` // 商品代码
  46. GoodsName string `json:"goodsname" xorm:"GOODSNAME"` // 商品名称
  47. AgreeUnit float64 `json:"agreeunit" xorm:"'AGREEUNIT'"` // 合约单位
  48. CurrencyID int64 `json:"currencyid" xorm:"'CURRENCYID'"` // 报价货币ID - goods
  49. TaCurrencyid int64 `json:"tacurrencyid" xorm:"'TACURRENCYID'"` // 报价货币ID - taaccount
  50. GoodUnitID int64 `json:"goodunitid" xorm:"'GOODUNITID'"` // 报价单位ID
  51. Goodunit string `json:"goodunit" xorm:"'GOODUNIT'"` // 报价单位
  52. DecimalPlace int64 `json:"decimalplace" xorm:"'DECIMALPLACE'"` // 报价小数位
  53. MarketID int64 `json:"marketid" xorm:"'MARKETID'"` // 所属市场ID
  54. TradeMode int32 `json:"trademode" xorm:"'TRADEMODE'"` // 交易模式
  55. PositionQTY float64 `json:"positionqty" xorm:"'POSITIONQTY'"` // 期初持仓数量
  56. HolderAmount float64 `json:"holderamount" xorm:"'HOLDERAMOUNT'"` // 期初持仓总金额[商品币种]
  57. CurPositionQTY float64 `json:"curpositionqty" xorm:"'CURPOSITIONQTY'"` // 当前持仓总数量
  58. CurHolderAmount float64 `json:"curholderamount" xorm:"'CURHOLDERAMOUNT'"` // 当前持仓总金额[商品币种]
  59. FrozenQTY float64 `json:"frozenqty" xorm:"'FROZENQTY'"` // 持仓冻结数量
  60. OtherFrozenQTY float64 `json:"otherfrozenqty" xorm:"'OTHERFROZENQTY'"` // 持仓其他冻结数量(交割冻结)
  61. OpenReqQTY float64 `json:"openreqqty" xorm:"'OPENREQQTY'"` // 开仓申请数量(用于比较最大持仓数量)
  62. OpenTotalQTY float64 `json:"opentotalqty" xorm:"'OPENTOTALQTY'"` // 开仓总数量
  63. CloseTotalQTY float64 `json:"closetotalqty" xorm:"'CLOSETOTALQTY'"` // 平仓总数量
  64. TNQTY float64 `json:"tnqty" xorm:"'TNQTY'"` // T+N冻结总量
  65. TNUsedQTY float64 `json:"tnusedqty" xorm:"'TNUSEDQTY'"` // T+N使用量(可以使用T+N的冻结数量)
  66. CurTDPosition float64 `json:"curtdposition" xorm:"'CURTDPOSITION'"` // 期末今日头寸
  67. FreTDPosition float64 `json:"fretdposition" xorm:"'FRETDPOSITION'"` // 冻结今日头寸
  68. EnableQTY float64 `json:"enableqty" xorm:"'ENABLEQTY'"` // 可用量
  69. AveragePrice float64 `json:"averageprice" xorm:"AVERAGEPRICE"` // 持仓均价
  70. Usedmargin float64 `json:"usedmargin" xorm:"'USEDMARGIN'"` // 占用保证金[商品币种]
  71. QTYDECIMALPLACE int32 `json:"qtydecimalplace"` // 成交量小数位
  72. PositionPL float64 `json:"positionpl"` // 持仓盈亏 买方向 = (最新价 - 持仓均价) * 买期末头寸 * 合约单位;卖方向 = (持仓均价 - 最新价) * 卖期末头寸 * 合约单位
  73. PositionPLRate float64 `json:"positionplrate"` // 持仓盈亏比例【实时行情更新】 = 持仓盈亏 / 开仓成本
  74. MarketAmount float64 `json:"marketamount"` // 市值
  75. LastPrice float64 `json:"lastprice"` // 最新价
  76. Tradeproperty int32 `json:"tradeproperty"` // 交易属性
  77. REFGOODSID int32 `json:"refgoodsid" xorm:"'REFGOODSID'"` // 参考商品ID
  78. REFGOODSCODE string `json:"refgoodscode" xorm:"'REFGOODSCODE'"` // 参考商品代码
  79. MatchName string `json:"matchname" xorm:"'MATCHNAME'"` // ProviderUserID 企业名称
  80. Mindeliverylot int64 `json:"mindeliverylot" xorm:"MINDELIVERYLOT"` // 最小交收手数(50模式)
  81. PKID string `json:"pkid" xorm:"-"` // 自定义主键
  82. }
  83. // QueryTradePosition 持仓汇总查询(合约市场)
  84. // @Summary 持仓汇总查询(合约市场)
  85. // @Produce json
  86. // @Security ApiKeyAuth
  87. // @Param accountID query string true "资金账户 - 格式:1,2,3"
  88. // @Param tradeMode query string false "交易模式 - 格式:1,2,3"
  89. // @Success 200 {object} QueryTradePositionRsp
  90. // @Failure 500 {object} app.Response
  91. // @Router /Order/QueryTradePosition [get]
  92. // @Tags 通用单据
  93. // 参考通用查询:SearchTradePositionDetail
  94. func QueryTradePosition(c *gin.Context) {
  95. appG := app.Gin{C: c}
  96. // 获取请求参数
  97. var req QueryTradePositionReq
  98. if err := appG.C.ShouldBindQuery(&req); err != nil {
  99. logger.GetLogger().Errorf("QueryTradePosition failed: %s", err.Error())
  100. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  101. return
  102. }
  103. rst, ret := GetTradePosition(req.AccountID, req.TradeMode)
  104. if ret {
  105. appG.Response(http.StatusOK, e.SUCCESS, rst)
  106. } else {
  107. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  108. }
  109. }
  110. // GetTradePosition 获取持仓汇总数据, 成功返回true, 失败返回false
  111. func GetTradePosition(accIds string, tradeModes string) (rst []QueryTradePositionRsp, ret bool) {
  112. rst = make([]QueryTradePositionRsp, 0)
  113. // 查询数据
  114. type tradePosition struct {
  115. models.Tradeposition `xorm:"extends"`
  116. Goodscode string `json:"goodscode" xorm:"'GOODSCODE'"` // 商品代码(内部)
  117. Goodsname string `json:"goodsname" xorm:"'GOODSNAME'"` // 商品名称
  118. Currencyid int64 `json:"currencyid" xorm:"'CURRENCYID'"` // 报价货币ID - goods
  119. TaCurrencyid int64 `json:"tacurrencyid" xorm:"'TACURRENCYID'"` // 报价货币ID - taaccount
  120. Goodunitid int64 `json:"goodunitid" xorm:"'GOODUNITID'"` // 报价单位ID
  121. Goodunit string `json:"goodunit" xorm:"'GOODUNIT'"` // 报价单位
  122. Agreeunit float64 `json:"agreeunit" xorm:"'AGREEUNIT'"` // 合约单位
  123. Decimalplace int64 `json:"decimalplace" xorm:"'DECIMALPLACE'"` // 报价小数位
  124. Marketid int32 `json:"marketid" xorm:"'MARKETID'"` // 市场ID
  125. Trademode int32 `json:"trademode" xorm:"'TRADEMODE'"` // 交易模式
  126. QTYDECIMALPLACE int32 `json:"qtydecimalplace" xorm:"'QTYDECIMALPLACE'"` // 成交量小数位
  127. REFGOODSID int32 `json:"refgoodsid" xorm:"'REFGOODSID'"` // 参考商品ID
  128. REFGOODSCODE string `json:"refgoodscode" xorm:"'REFGOODSCODE'"` // 参考商品代码
  129. MatchName string `json:"matchname" xorm:"'MATCHNAME'"` // ProviderUserID 企业名称
  130. Mindeliverylot int64 `json:"mindeliverylot" xorm:"MINDELIVERYLOT"` // 最小交收手数(50模式)
  131. }
  132. datas := make([]tradePosition, 0)
  133. engine := db.GetEngine()
  134. // ORACLE好像在JOIN里不支持别名功能(在XORM中)
  135. s := engine.Table("TRADEPOSITION").
  136. Join("LEFT", "GOODS", "TRADEPOSITION.GOODSID = GOODS.GOODSID").
  137. Join("LEFT", "GOODSEX EX", "EX.GOODSID = GOODS.GOODSID").
  138. Join("LEFT", "MARKET", "GOODS.MARKETID = MARKET.MARKETID").
  139. Join("LEFT", "ENUMDICITEM", "GOODS.GOODUNITID = ENUMDICITEM.ENUMITEMNAME and ENUMDICITEM.ENUMDICCODE = 'goodsunit'").
  140. Join("LEFT", "USERINFO UI", "UI.USERID = GOODS.PROVIDERUSERID").
  141. Join("LEFT", "TAACCOUNT TA", "TA.ACCOUNTID = TRADEPOSITION.ACCOUNTID").
  142. Select("TRADEPOSITION.*, GOODS.GOODSCODE, GOODS.GOODSNAME, GOODS.CURRENCYID, TA.CURRENCYID TACURRENCYID, GOODS.GOODUNITID,GOODS.QTYDECIMALPLACE, GOODS.REFGOODSID, GOODS.REFGOODSCODE, " +
  143. "ENUMDICITEM.ENUMDICNAME as GOODUNIT, GOODS.AGREEUNIT, GOODS.DECIMALPLACE, MARKET.MARKETID, MARKET.TRADEMODE, UI.CUSTOMERNAME as MATCHNAME, nvl(EX.MINDELIVERYLOT, 1) MINDELIVERYLOT").
  144. Where(fmt.Sprintf(`TRADEPOSITION.ACCOUNTID in (%s)`, accIds))
  145. if len(tradeModes) > 0 {
  146. s = s.And(fmt.Sprintf(`MARKET.TRADEMODE in (%s)`, tradeModes))
  147. }
  148. if err := s.Find(&datas); err != nil {
  149. // 查询失败
  150. logger.GetLogger().Errorf("QueryTradePosition failed: %s", err.Error())
  151. return rst, false
  152. }
  153. // 获取盘面
  154. goodGuotes := make([]models.Quoteday, 0)
  155. if len(datas) > 0 {
  156. var a models.InStrBuilder
  157. for i := range datas {
  158. a.Add(datas[i].Goodscode)
  159. }
  160. goodGuotes, _ = models.GetQuoteDays(a.InStr())
  161. }
  162. // 获取汇率配置
  163. exchangeRateConfigs := make([]models.ExchangeRateConfig, 0)
  164. if err := engine.Find(&exchangeRateConfigs); err != nil {
  165. // 查询失败
  166. logger.GetLogger().Errorf("获取汇率配置失败, err: %s", err.Error())
  167. return rst, false
  168. }
  169. rateMap := make(map[string]float64)
  170. for _, item := range exchangeRateConfigs {
  171. rateMap[fmt.Sprintf("%d_%d", item.ORICURRENCYID, item.DESCURRENCYID)] = item.EXCHANGERATE
  172. }
  173. fCalcPL := func(goodsCode string,
  174. buyOrSell int64,
  175. qty,
  176. holderPrice,
  177. agreeUnit float64,
  178. decimalPlace int64,
  179. exchangeRate float64) (positionPL float64, marketAmount float64, lastPrice float64) {
  180. positionPL = 0
  181. for _, q := range goodGuotes {
  182. if goodsCode == q.Goodscode {
  183. if q.Last != 0 {
  184. lastPrice = utils.IntToFloat64(int(q.Last), int(decimalPlace))
  185. } else if q.Presettle != 0 {
  186. lastPrice = utils.IntToFloat64(int(q.Presettle), int(decimalPlace))
  187. } else {
  188. return
  189. }
  190. positionPL = (lastPrice - holderPrice) * qty * agreeUnit * exchangeRate
  191. positionPL, _ = strconv.ParseFloat(utils.FormatFloat(positionPL, 2), 64)
  192. if buyOrSell == 1 {
  193. // 卖方向 *-1
  194. positionPL *= -1.0
  195. }
  196. marketAmount = lastPrice * qty * agreeUnit * exchangeRate
  197. marketAmount, _ = strconv.ParseFloat(utils.FormatFloat(marketAmount, 2), 64)
  198. }
  199. }
  200. return
  201. }
  202. // 构建返回数据
  203. for _, v := range datas {
  204. // 获取汇率
  205. exchangeRate := 1.0
  206. if v.Currencyid != v.TaCurrencyid {
  207. if rate, ok := rateMap[fmt.Sprintf("%d_%d", v.Currencyid, v.TaCurrencyid)]; ok {
  208. exchangeRate = rate
  209. }
  210. }
  211. // 构建买方向持仓汇总
  212. if v.Buycurpositionqty > 0 {
  213. var tradePosition QueryTradePositionRsp
  214. // 反射数据
  215. // struct -> json
  216. if jsonBytes, err := json.Marshal(v); err == nil {
  217. c := QtyCovert{QTYDECIMALPLACE: v.QTYDECIMALPLACE}
  218. // json -> struct
  219. _ = json.Unmarshal(jsonBytes, &tradePosition)
  220. tradePosition.MatchName = v.MatchName
  221. tradePosition.Tradeproperty = v.Tradeproperty
  222. tradePosition.REFGOODSID = v.REFGOODSID
  223. tradePosition.REFGOODSCODE = v.REFGOODSCODE
  224. tradePosition.BuyOrSell = 0
  225. tradePosition.PositionQTY = c.CovertQty(v.Buypositionqty)
  226. tradePosition.HolderAmount = v.Buyholderamount
  227. tradePosition.CurPositionQTY = c.CovertQty(v.Buycurpositionqty)
  228. tradePosition.CurHolderAmount = v.Buycurholderamount
  229. tradePosition.FrozenQTY = c.CovertQty(v.Buyfrozenqty)
  230. tradePosition.OtherFrozenQTY = c.CovertQty(v.Buyotherfrozenqty)
  231. tradePosition.OpenReqQTY = c.CovertQty(v.Buyopenreqqty)
  232. tradePosition.OpenTotalQTY = c.CovertQty(v.Buyopentotalqty)
  233. tradePosition.CloseTotalQTY = c.CovertQty(v.Buyclosetotalqty)
  234. tradePosition.TNQTY = c.CovertQty(v.Buytnqty)
  235. tradePosition.TNUsedQTY = c.CovertQty(v.Buytnusedqty)
  236. tradePosition.CurTDPosition = c.CovertQty(v.Buycurtdposition)
  237. tradePosition.FreTDPosition = c.CovertQty(v.Buyfretdposition)
  238. tradePosition.EnableQTY = c.CovertQty(v.Buycurpositionqty - v.Buyfrozenqty - v.Buyotherfrozenqty)
  239. // 计算持仓均价
  240. averagePrice := tradePosition.CurHolderAmount / float64(tradePosition.CurPositionQTY) / tradePosition.AgreeUnit / exchangeRate
  241. // #96004 改为固定3位小数
  242. // #3524 又改为跟商品价格小数位走 2022.04.07
  243. // 运维提出, 不要四舍五入, 改为去尾法 2022.04.26
  244. tradePosition.AveragePrice, _ = decimal.NewFromFloat(averagePrice).Truncate(int32(v.Decimalplace + 2)).Float64()
  245. tradePosition.PositionPL, tradePosition.MarketAmount, tradePosition.LastPrice = fCalcPL(tradePosition.GoodsCode,
  246. tradePosition.BuyOrSell,
  247. tradePosition.CurPositionQTY,
  248. tradePosition.AveragePrice,
  249. tradePosition.AgreeUnit,
  250. tradePosition.DecimalPlace,
  251. exchangeRate)
  252. if tradePosition.CurHolderAmount > 1e-10 {
  253. tradePosition.PositionPLRate = tradePosition.PositionPL / tradePosition.CurHolderAmount
  254. tradePosition.PositionPLRate, _ = strconv.ParseFloat(utils.FormatFloat(tradePosition.PositionPLRate, 4), 64)
  255. }
  256. tradePosition.PKID = fmt.Sprintf("%v_%v_%v", tradePosition.AccountID, tradePosition.Goodsid, tradePosition.BuyOrSell)
  257. tradePosition.Mindeliverylot = v.Mindeliverylot
  258. rst = append(rst, tradePosition)
  259. }
  260. }
  261. // 构建卖方向持仓汇总
  262. if v.Tradeproperty != 2 && v.Sellcurpositionqty > 0 {
  263. var tradePosition QueryTradePositionRsp
  264. // 反射数据
  265. // struct -> json
  266. if jsonBytes, err := json.Marshal(v); err == nil {
  267. c := QtyCovert{QTYDECIMALPLACE: v.QTYDECIMALPLACE}
  268. // json -> struct
  269. _ = json.Unmarshal(jsonBytes, &tradePosition)
  270. tradePosition.MatchName = v.MatchName
  271. tradePosition.Tradeproperty = v.Tradeproperty
  272. tradePosition.REFGOODSID = v.REFGOODSID
  273. tradePosition.REFGOODSCODE = v.REFGOODSCODE
  274. tradePosition.BuyOrSell = 1
  275. tradePosition.PositionQTY = c.CovertQty(v.Sellpositionqty)
  276. tradePosition.HolderAmount = v.Sellholderamount
  277. tradePosition.CurPositionQTY = c.CovertQty(v.Sellcurpositionqty)
  278. tradePosition.CurHolderAmount = v.Sellcurholderamount
  279. tradePosition.FrozenQTY = c.CovertQty(v.Sellfrozenqty)
  280. tradePosition.OtherFrozenQTY = c.CovertQty(v.Sellotherfrozenqty)
  281. tradePosition.OpenReqQTY = c.CovertQty(v.Sellopenreqqty)
  282. tradePosition.OpenTotalQTY = c.CovertQty(v.Sellopentotalqty)
  283. tradePosition.CloseTotalQTY = c.CovertQty(v.Sellclosetotalqty)
  284. tradePosition.TNQTY = c.CovertQty(v.Selltnqty)
  285. tradePosition.TNUsedQTY = c.CovertQty(v.Selltnusedqty)
  286. tradePosition.CurTDPosition = c.CovertQty(v.Sellcurtdposition)
  287. tradePosition.FreTDPosition = c.CovertQty(v.Sellfretdposition)
  288. tradePosition.EnableQTY = c.CovertQty(v.Sellcurpositionqty - v.Sellfrozenqty - v.Sellotherfrozenqty)
  289. // 计算持仓均价
  290. averagePrice := tradePosition.CurHolderAmount / float64(tradePosition.CurPositionQTY) / tradePosition.AgreeUnit / exchangeRate
  291. tradePosition.AveragePrice, _ = decimal.NewFromFloat(averagePrice).Truncate(int32(v.Decimalplace + 2)).Float64()
  292. tradePosition.PositionPL, tradePosition.MarketAmount, tradePosition.LastPrice = fCalcPL(tradePosition.GoodsCode, tradePosition.BuyOrSell, tradePosition.CurPositionQTY,
  293. tradePosition.AveragePrice, tradePosition.AgreeUnit, tradePosition.DecimalPlace, exchangeRate)
  294. if tradePosition.CurHolderAmount > 1e-10 {
  295. tradePosition.PositionPLRate = tradePosition.PositionPL / tradePosition.CurHolderAmount
  296. tradePosition.PositionPLRate, _ = strconv.ParseFloat(utils.FormatFloat(tradePosition.PositionPLRate, 4), 64)
  297. }
  298. tradePosition.PKID = fmt.Sprintf("%v_%v_%v", tradePosition.AccountID, tradePosition.Goodsid, tradePosition.BuyOrSell)
  299. tradePosition.Mindeliverylot = v.Mindeliverylot
  300. rst = append(rst, tradePosition)
  301. }
  302. }
  303. }
  304. // 查询成功
  305. logger.GetLogger().Debugln("QueryTradePosition successed: %v", rst)
  306. return rst, true
  307. }
  308. // QueryTradeOrderDetailReq 委托单查询请求参数(合约市场)
  309. type QueryTradeOrderDetailReq struct {
  310. AccountID string `form:"accountID" binding:"required"`
  311. OrderStatus string `form:"orderStatus"`
  312. TradeMode string `form:"tradeMode"`
  313. OrderID int `form:"orderID"`
  314. IncOrderID string `form:"incOrderID"`
  315. }
  316. // QueryTradeOrderDetailRsp 委托单查询返回模型(合约市场)
  317. type QueryTradeOrderDetailRsp struct {
  318. Orderid string `json:"orderid" xorm:"'ORDERID'"` // 委托单号(100+Unix秒时间戳(10位)+2位(MarketServiceID)+xxxx)
  319. Tradedate string `json:"tradedate" xorm:"'TRADEDATE'" binding:"required"` // 交易日(yyyyMMdd)
  320. Buildtype int64 `json:"buildtype" xorm:"'BUILDTYPE'" binding:"required"` // 委托单据类型 - 1:建仓 2:平仓 3:先平后建
  321. Preorderid string `json:"preorderid" xorm:"'PREORDERID'"` // 关联预埋单号(止盈止损单时填写)
  322. Cancelorderid string `json:"cancelorderid" xorm:"'CANCELORDERID'"` // 撤单单号(撤单时填写)
  323. Relatedid string `json:"relatedid" xorm:"'RELATEDID'"` // 关联单号(交割单)
  324. Marketid int64 `json:"marketid" xorm:"'MARKETID'" binding:"required"` // 市场ID
  325. Goodsid int64 `json:"goodsid" xorm:"'GOODSID'" binding:"required"` // 商品ID
  326. Accountid int64 `json:"accountid" xorm:"'ACCOUNTID'" binding:"required"` // 账户ID[报价币种]
  327. Buyorsell int64 `json:"buyorsell" xorm:"'BUYORSELL'" binding:"required"` // 买卖 - 0:买 1:卖
  328. Pricemode int64 `json:"pricemode" xorm:"'PRICEMODE'" binding:"required"` // 取价方式 - 1:市价 2: 限价
  329. Orderprice float64 `json:"orderprice" xorm:"'ORDERPRICE'"` // 委托价格
  330. Orderqty float64 `json:"orderqty" xorm:"'ORDERQTY'" binding:"required"` // 委托数量
  331. Tradeqty float64 `json:"tradeqty" xorm:"'TRADEQTY'"` // 成交数量
  332. Cancelqty float64 `json:"cancelqty" xorm:"'CANCELQTY'"` // 撤单数量
  333. Openqty float64 `json:"openqty" xorm:"'OPENQTY'"` // 开仓数量(先建后平操作,需要记录)
  334. Closeqty float64 `json:"closeqty" xorm:"'CLOSEQTY'"` // 平仓数量(先建后平操作 需要记录)
  335. Opentradeqty float64 `json:"opentradeqty" xorm:"'OPENTRADEQTY'"` // 开仓成交数量(先建后平操作,需要记录)
  336. Closetradeqty float64 `json:"closetradeqty" xorm:"'CLOSETRADEQTY'"` // 平仓成交数量(先建后平操作,需要记录)
  337. Freezemargin float64 `json:"freezemargin" xorm:"'FREEZEMARGIN'"` // 冻结保证金(冻结交易金额)
  338. Unfreezemargin float64 `json:"unfreezemargin" xorm:"'UNFREEZEMARGIN'"` // 解冻保证金
  339. Freezecharge float64 `json:"freezecharge" xorm:"'FREEZECHARGE'"` // 冻结手续费
  340. Unfreezecharge float64 `json:"unfreezecharge" xorm:"'UNFREEZECHARGE'"` // 解冻手续费
  341. Openfreezecharge float64 `json:"openfreezecharge" xorm:"'OPENFREEZECHARGE'"` // 开仓冻结手续费(先建后平操作,需要记录)
  342. Closefreezecharge float64 `json:"closefreezecharge" xorm:"'CLOSEFREEZECHARGE'"` // 平仓冻结手续费(先建后平操作,需要记录)
  343. Openunfreezecharge float64 `json:"openunfreezecharge" xorm:"'OPENUNFREEZECHARGE'"` // 开仓解冻手续费(先建后平操作,需要记录)
  344. Closeunfreezecharge float64 `json:"closeunfreezecharge" xorm:"'CLOSEUNFREEZECHARGE'"` // 平仓解冻手续费(先建后平操作,需要记录)
  345. Validtype int64 `json:"validtype" xorm:"'VALIDTYPE'" binding:"required"` // 有效类型 - 1当日有效 2本周有效 3指定日期有效 4一直有效 5指定时间有效
  346. Validtime time.Time `json:"validtime" xorm:"'VALIDTIME'"` // 有效期限
  347. Volumetype int64 `json:"volumetype" xorm:"'VOLUMETYPE'"` // 当时间有效类型为 “立即执行否则取消 IOC” 时,需要此项 - 0:任意量 1:最小量(暂时不支持) 2:全部量
  348. Operatetype int64 `json:"operatetype" xorm:"'OPERATETYPE'" binding:"required"` // 操作类型 - 1:正常下单 2:斩仓 3:转单 4:结算撤单 5:系统卖出(适用于先平后建的卖出) 6:行情源报价 7:(结算)到期强平 8:(结算)协议转让 9:系统对冲单 10:(结算)到期无效 11:交割协议转让 12:交割协议平仓 13:交割成交(所有权) 14:管理端强行平仓 15:管理端协议转让
  349. Ordertime time.Time `json:"ordertime" xorm:"'ORDERTIME'" binding:"required"` // 委托时间
  350. Orderstatus int64 `json:"orderstatus" xorm:"'ORDERSTATUS'"` // 委托状态 - 1: 委托请求 2:待冻结 3:委托成功 4: 委托失败 5:配对成功 6: 已撤销 7:部分成交 8:已成交 9:部成部撤 10:成交失败 11:已拒绝 12:经过摘牌(先摘后挂专用-先摘后挂已摘过) 13:冻结成功(通道交易专用) 14:通道已撤 15:通道部成部撤 16:成交失败违约(荷兰式竞拍专用)
  351. Listingselecttype int64 `json:"listingselecttype" xorm:"'LISTINGSELECTTYPE'"` // 挂牌点选类型 - 1:挂牌 2:摘牌 3:先摘后挂
  352. Delistingtype int64 `json:"delistingtype" xorm:"'DELISTINGTYPE'"` // 摘牌类型 - 1:价格最优 2:点选成交
  353. Ordersrc int64 `json:"ordersrc" xorm:"'ORDERSRC'"` // 委托来源 - 1:客户端 2:管理端 3:风控服务 4:交割服务 5:交易服务 6:交易日结 7:商品强平 8:管理端商品退市强平 9:交易接口 10:交割服务商被动(受托竞价) 11:预埋触发
  354. Clienttype int64 `json:"clienttype" xorm:"'CLIENTTYPE'"` // 客户端类型 - 0:保留为未填终端类型 1:PC管理端 2:PC交易端 3:手机客户端_安卓 4:网页客户端 5:微信客户端 6:手机客户端_苹果 7:网上开户客户端 8:无效终端编号 9:报价终端(中江)
  355. Operatorid int64 `json:"operatorid" xorm:"'OPERATORID'"` // 登录账号(LoginID)
  356. GOODUNITID int32 `json:"goodunitid" xorm:"'GOODUNITID'"` // 商品单位id
  357. GoodsCode string `json:"goodscode" xorm:"GOODSCODE"` // 商品代码
  358. GoodsName string `json:"goodsname" xorm:"GOODSNAME"` // 商品名称
  359. DECIMALPLACE int32 `json:"decimalplace" xorm:"'DECIMALPLACE'"` // 商品报价小数位
  360. QTYDECIMALPLACE int `json:"qtydecimalplace" xorm:"'QTYDECIMALPLACE'"` // 商品报价小数位
  361. Marketname string `json:"marketname" xorm:"'MARKETNAME'"` // 市场名称
  362. TradeMode int32 `json:"trademode" xorm:"'TRADEMODE'"` // 交易模式
  363. ENUMDICNAME string `json:"enumdicname"` // 单位名称
  364. Enableqty float64 `json:"enableqty" xorm:"ENABLEQTY"` // 可用数量 = 委托数量 - 成交数量 - 撤单数量
  365. }
  366. func (r *QueryTradeOrderDetailRsp) calc() {
  367. fCovert := func(v *float64) {
  368. *v = *v / math.Pow10(r.QTYDECIMALPLACE)
  369. }
  370. fCovert(&r.Orderqty)
  371. fCovert(&r.Tradeqty)
  372. fCovert(&r.Cancelqty)
  373. fCovert(&r.Openqty)
  374. fCovert(&r.Closeqty)
  375. fCovert(&r.Opentradeqty)
  376. fCovert(&r.Closetradeqty)
  377. fCovert(&r.Enableqty)
  378. r.ENUMDICNAME = mtpcache.GetEnumDicitemName(r.GOODUNITID)
  379. }
  380. // QueryTradeOrderDetail 委托单查询请求(合约市场)
  381. // @Summary 委托单查询请求(合约市场)
  382. // @Produce json
  383. // @Security ApiKeyAuth
  384. // @Param accountID query string true "资金账户 - 格式:1,2,3"
  385. // @Param tradeMode query string false "交易模式 - 格式:1,2,3"
  386. // @Param orderStatus query string false "委托状态 - 格式:1,2,3"
  387. // @Param orderID query int false "委托单号"
  388. // @Param incOrderID query string false "增量委托单号"
  389. // @Success 200 {object} QueryTradeOrderDetailRsp
  390. // @Failure 500 {object} app.Response
  391. // @Router /Order/QueryTradeOrderDetail [get]
  392. // @Tags 通用单据
  393. // 参考通用查询:SearchTradeOrderDetail
  394. func QueryTradeOrderDetail(c *gin.Context) {
  395. appG := app.Gin{C: c}
  396. // 获取请求参数
  397. var req QueryTradeOrderDetailReq
  398. if err := appG.C.ShouldBindQuery(&req); err != nil {
  399. logger.GetLogger().Errorf("QueryTradeOrderDetail failed: %s", err.Error())
  400. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  401. return
  402. }
  403. datas := make([]QueryTradeOrderDetailRsp, 0)
  404. engine := db.GetEngine()
  405. // 由于int64类型数据(单号)过长是获取会有问题(可能是oci8组件问题),所以这里将可能会出问题的单号都用to_char来输出
  406. s := engine.Table("TRADE_ORDERDETAIL").
  407. Join("LEFT", "GOODS", "GOODS.GOODSID = TRADE_ORDERDETAIL.GOODSID").
  408. Join("LEFT", "MARKET", "MARKET.MARKETID = TRADE_ORDERDETAIL.MARKETID").
  409. Select(`to_char(TRADE_ORDERDETAIL.ORDERID) as ORDERID, to_char(TRADE_ORDERDETAIL.PREORDERID) as PREORDERID, to_char(TRADE_ORDERDETAIL.CANCELORDERID) as CANCELORDERID, to_char(TRADE_ORDERDETAIL.RELATEDID) as RELATEDID,
  410. TRADE_ORDERDETAIL.*, TRADE_ORDERDETAIL.ORDERQTY - TRADE_ORDERDETAIL.TRADEQTY - TRADE_ORDERDETAIL.CANCELQTY as ENABLEQTY,
  411. GOODS.GOODSCODE, GOODS.GOODSNAME,GOODS.DECIMALPLACE, GOODS.QTYDECIMALPLACE,GOODS.GOODUNITID, MARKET.MARKETNAME, MARKET.TRADEMODE`).
  412. // Where(fmt.Sprintf(`TRADE_ORDERDETAIL.ORDERSRC != 10 and TRADE_ORDERDETAIL.ACCOUNTID in (%s)`, req.AccountID)).
  413. Where("TRADE_ORDERDETAIL.ORDERSRC != 10").
  414. In("TRADE_ORDERDETAIL.ACCOUNTID", strings.Split(req.AccountID, ",")).
  415. Desc("TRADE_ORDERDETAIL.ORDERTIME")
  416. if len(req.OrderStatus) > 0 {
  417. // s = s.And(fmt.Sprintf(`TRADE_ORDERDETAIL.ORDERSTATUS in (%s)`, req.OrderStatus))
  418. s = s.In("TRADE_ORDERDETAIL.ORDERSTATUS", strings.Split(req.OrderStatus, ","))
  419. }
  420. if len(req.TradeMode) > 0 {
  421. // s = s.And(fmt.Sprintf(`MARKET.TRADEMODE in (%s)`, req.TradeMode))
  422. s = s.In("MARKET.TRADEMODE", strings.Split(req.TradeMode, ","))
  423. }
  424. if req.OrderID > 0 {
  425. s = s.And("TRADE_ORDERDETAIL.ORDERID = ?", req.OrderID)
  426. }
  427. if req.IncOrderID != "" {
  428. // s = s.And(fmt.Sprintf("TRADE_ORDERDETAIL.ORDERID > %v", req.IncOrderID))
  429. s = s.And("TRADE_ORDERDETAIL.ORDERID > ?", req.IncOrderID)
  430. }
  431. if err := s.Find(&datas); err != nil {
  432. // 查询失败
  433. logger.GetLogger().Errorf("QueryTradeOrderDetail failed: %s", err.Error())
  434. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  435. return
  436. }
  437. // 查询成功
  438. logger.GetLogger().Debugln("QueryTradeOrderDetail successed: %v", datas)
  439. for i := range datas {
  440. datas[i].calc()
  441. }
  442. appG.Response(http.StatusOK, e.SUCCESS, datas)
  443. }
  444. // QueryHisTradeOrderDetailReq 历史委托单查询请求参数(合约市场)
  445. type QueryHisTradeOrderDetailReq struct {
  446. app.PageInfo
  447. AccountID string `form:"accountID" binding:"required"` // 资金账户 - 格式:1,2,3
  448. OrderStatus string `form:"orderStatus"` // 委托状态 - 格式:1,2,3
  449. TradeMode string `form:"tradeMode"` // 交易模式 - 格式:1,2,3
  450. OrderID int `form:"orderID"` // 委托单号
  451. StartDate string `form:"startDate"` // 开始时间
  452. EndDate string `form:"endDate"` // 结束时间
  453. }
  454. // QueryHisTradeOrderDetailRsp 历史委托单查询返回模型(合约市场)
  455. type QueryHisTradeOrderDetailRsp struct {
  456. models.Histradeorderdetail `xorm:"extends"`
  457. GoodsCode string `json:"goodscode" xorm:"GOODSCODE"` // 商品代码
  458. GoodsName string `json:"goodsname" xorm:"GOODSNAME"` // 商品名称
  459. DECIMALPLACE int32 `json:"decimalplace" xorm:"'DECIMALPLACE'"` // 商品报价小数位
  460. QTYDECIMALPLACE int `json:"qtydecimalplace" xorm:"'QTYDECIMALPLACE'"` // 成交量小数位
  461. GOODUNITID int32 `json:"goodunitid" xorm:"'GOODUNITID'"` // 商品单位id
  462. Marketname string `json:"marketname" xorm:"'MARKETNAME'"` // 市场名称
  463. TradeMode int32 `json:"trademode" xorm:"'TRADEMODE'"` // 交易模式
  464. ENUMDICNAME string `json:"enumdicname"` // 单位名称
  465. }
  466. func (r *QueryHisTradeOrderDetailRsp) calc() {
  467. fCovert := func(v *float64) {
  468. *v = *v / math.Pow10(r.QTYDECIMALPLACE)
  469. }
  470. fCovert(&r.Orderqty)
  471. fCovert(&r.Tradeqty)
  472. fCovert(&r.Cancelqty)
  473. fCovert(&r.Openqty)
  474. fCovert(&r.Closeqty)
  475. fCovert(&r.Opentradeqty)
  476. fCovert(&r.Closetradeqty)
  477. r.ENUMDICNAME = mtpcache.GetEnumDicitemName(r.GOODUNITID)
  478. }
  479. // QueryHisTradeOrderDetail 历史委托单查询请求(合约市场)
  480. // @Summary 历史委托单查询请求(合约市场)
  481. // @Produce json
  482. // @Security ApiKeyAuth
  483. // @Param accountID query string true "资金账户 - 格式:1,2,3"
  484. // @Param tradeMode query string false "交易模式 - 格式:1,2,3"
  485. // @Param orderStatus query string false "委托状态 - 格式:1,2,3"
  486. // @Param orderID query int false "委托单号"
  487. // @Param startDate query string false "开始时间 - 闭区间,格式:yyyy-MM-dd"
  488. // @Param endDate query string false "结束时间 - 闭区间,格式:yyyy-MM-dd"
  489. // @Param page query int false "页码"
  490. // @Param pagesize query int false "每页条数"
  491. // @Param pageflag query int false "分页标志 0-page从0开始 1-page从1开始"
  492. // @Success 200 {object} QueryHisTradeOrderDetailRsp
  493. // @Failure 500 {object} app.Response
  494. // @Router /Order/QueryHisTradeOrderDetail [get]
  495. // @Tags 通用单据
  496. // 参考通用查询:Client_QueryHis_trade_orderdetail
  497. func QueryHisTradeOrderDetail(c *gin.Context) {
  498. appG := app.Gin{C: c}
  499. // 获取请求参数
  500. var req QueryHisTradeOrderDetailReq
  501. if err := appG.C.ShouldBindQuery(&req); err != nil {
  502. logger.GetLogger().Errorf("QueryHisTradeOrderDetail failed: %s", err.Error())
  503. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  504. return
  505. }
  506. datas := make([]QueryHisTradeOrderDetailRsp, 0)
  507. engine := db.GetEngine()
  508. s := engine.Table("HIS_TRADE_ORDERDETAIL").
  509. Join("LEFT", "GOODS", "GOODS.GOODSID = HIS_TRADE_ORDERDETAIL.GOODSID").
  510. Join("LEFT", "MARKET", "MARKET.MARKETID = HIS_TRADE_ORDERDETAIL.MARKETID").
  511. Select(`to_char(HIS_TRADE_ORDERDETAIL.ORDERID) as ORDERID, to_char(HIS_TRADE_ORDERDETAIL.PREORDERID) as PREORDERID, to_char(HIS_TRADE_ORDERDETAIL.CANCELORDERID) as CANCELORDERID, to_char(HIS_TRADE_ORDERDETAIL.RELATEDID) as RELATEDID,
  512. HIS_TRADE_ORDERDETAIL.*,
  513. GOODS.GOODSCODE, GOODS.GOODSNAME,GOODS.DECIMALPLACE, GOODS.QTYDECIMALPLACE,GOODS.GOODUNITID, MARKET.MARKETNAME, MARKET.TRADEMODE`).
  514. // Where(fmt.Sprintf(`HIS_TRADE_ORDERDETAIL.ORDERSRC != 10 and HIS_TRADE_ORDERDETAIL.ISVALIDDATA = 1 and HIS_TRADE_ORDERDETAIL.ACCOUNTID in (%s)`, req.AccountID)).
  515. Where("HIS_TRADE_ORDERDETAIL.ORDERSRC != 10 and HIS_TRADE_ORDERDETAIL.ISVALIDDATA = 1").
  516. In("HIS_TRADE_ORDERDETAIL.ACCOUNTID", strings.Split(req.AccountID, ",")).
  517. Desc("HIS_TRADE_ORDERDETAIL.ORDERTIME")
  518. if len(req.OrderStatus) > 0 {
  519. // s = s.And(fmt.Sprintf(`HIS_TRADE_ORDERDETAIL.ORDERSTATUS in (%s)`, req.OrderStatus))
  520. s = s.In("HIS_TRADE_ORDERDETAIL.ORDERSTATUS", strings.Split(req.OrderStatus, ","))
  521. }
  522. if len(req.TradeMode) > 0 {
  523. // s = s.And(fmt.Sprintf(`MARKET.TRADEMODE in (%s)`, req.TradeMode))
  524. s = s.In("MARKET.TRADEMODE", strings.Split(req.TradeMode, ","))
  525. }
  526. if req.OrderID > 0 {
  527. s = s.And("HIS_TRADE_ORDERDETAIL.ORDERID = ?", req.OrderID)
  528. }
  529. if len(req.StartDate) > 0 {
  530. // s = s.And(fmt.Sprintf("to_date(HIS_TRADE_ORDERDETAIL.HISTRADEDATE,'yyyyMMdd') >= to_date('%s','yyyy-MM-dd')", req.StartDate))
  531. s = s.And("HIS_TRADE_ORDERDETAIL.HISTRADEDATE >= ?", strings.Replace(req.StartDate, "-", "", -1))
  532. }
  533. if len(req.EndDate) > 0 {
  534. // s = s.And(fmt.Sprintf("to_date(HIS_TRADE_ORDERDETAIL.HISTRADEDATE,'yyyyMMdd') <= to_date('%s','yyyy-MM-dd')", req.EndDate))
  535. s = s.And("HIS_TRADE_ORDERDETAIL.HISTRADEDATE <= ?", strings.Replace(req.EndDate, "-", "", -1))
  536. }
  537. if err := s.Find(&datas); err != nil {
  538. // 查询失败
  539. logger.GetLogger().Errorf("QueryHisTradeOrderDetail failed: %s", err.Error())
  540. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  541. return
  542. }
  543. // 查询成功
  544. logger.GetLogger().Debugln("QueryHisTradeOrderDetail successed: %v", datas)
  545. for i := range datas {
  546. datas[i].calc()
  547. }
  548. // appG.Response(http.StatusOK, e.SUCCESS, datas)
  549. // 查询成功返回
  550. if req.PageSize > 0 {
  551. // 分页
  552. var rst []QueryHisTradeOrderDetailRsp
  553. // 开始上标
  554. // 终端分页1开始
  555. p := req.Page
  556. if req.PageFlag != 0 {
  557. p -= 1
  558. if p < 0 {
  559. p = 0
  560. }
  561. }
  562. start := p * req.PageSize
  563. // 结束下标
  564. end := start + req.PageSize
  565. if start <= len(datas) {
  566. // 判断结束下标是否越界
  567. if end > len(datas) {
  568. end = len(datas)
  569. }
  570. rst = datas[start:end]
  571. } else {
  572. rst = datas[0:0]
  573. }
  574. logger.GetLogger().Debugln("QueryHisTradeOrderDetail successed: %v", rst)
  575. appG.ResponseByPage(http.StatusOK, e.SUCCESS, rst, app.PageInfo{Page: req.Page, PageSize: req.PageSize, Total: len(datas)})
  576. } else {
  577. // 不分页
  578. logger.GetLogger().Debugln("QueryHisTradeOrderDetail successed: %v", datas)
  579. appG.Response(http.StatusOK, e.SUCCESS, datas)
  580. }
  581. }
  582. // QueryTradeDetailReq 成交单查询请求参数
  583. type QueryTradeDetailReq struct {
  584. AccountID string `form:"accountID" binding:"required"`
  585. TradeID int `form:"tradeID"`
  586. OrderID int `form:"orderID"`
  587. TradeMode string `form:"tradeMode"`
  588. BuildType int `form:"buildType"`
  589. TradeType string `form:"tradeType"`
  590. GoodsID int `form:"goodsID"`
  591. IncTradeID string `form:"incTradeID"`
  592. }
  593. // QueryTradeDetailRsp 成交单查询返回模型
  594. type QueryTradeDetailRsp struct {
  595. models.Tradetradedetail `xorm:"extends"`
  596. TradePayInfo `xorm:"extends"`
  597. GoodsCode string `json:"goodscode" xorm:"GOODSCODE"` // 商品代码
  598. GoodsName string `json:"goodsname" xorm:"GOODSNAME"` // 商品名称
  599. DECIMALPLACE int32 `json:"decimalplace" xorm:"'DECIMALPLACE'"` // 商品报价小数位
  600. QTYDECIMALPLACE int `json:"qtydecimalplace" xorm:"'QTYDECIMALPLACE'"` // 商品报价小数位
  601. GOODUNITID int32 `json:"goodunitid" xorm:"'GOODUNITID'"` // 商品单位id
  602. Marketname string `json:"marketname" xorm:"'MARKETNAME'"` // 市场名称
  603. TradeMode int32 `json:"trademode" xorm:"'TRADEMODE'"` // 交易模式
  604. ListingSelectType int32 `json:"listingselecttype" xorm:"'LISTINGSELECTTYPE'"` // 关联委托单挂牌点选类型 - 1:挂牌 2:摘牌 3:先摘后挂
  605. Charge float64 `json:"charge" xorm:"CHARGE"` // 手续费
  606. ENUMDICNAME string `json:"enumdicname"` // 单位名称
  607. }
  608. func (r *QueryTradeDetailRsp) calc() {
  609. fCovert := func(v *float64) {
  610. *v = *v / math.Pow10(r.QTYDECIMALPLACE)
  611. }
  612. fCovert(&r.Tradeqty)
  613. fCovert(&r.Openqty)
  614. fCovert(&r.Closeqty)
  615. r.ENUMDICNAME = mtpcache.GetEnumDicitemName(r.GOODUNITID)
  616. r.TOTALAMOUNT = r.Tradeamount + r.Opencharge + r.Closecharge
  617. r.RECVAMOUNT = r.Tradeamount - r.Opencharge - r.Closecharge
  618. }
  619. // QueryTradeDetail 成交单查询(合约市场)
  620. // @Summary 成交单查询(合约市场)
  621. // @Produce json
  622. // @Security ApiKeyAuth
  623. // @Param accountID query string true "资金账户 - 格式:1,2,3"
  624. // @Param tradeID query int false "成交单号"
  625. // @Param orderID query int false "委托单号"
  626. // @Param tradeMode query string false "交易模式 - 格式:1,2,3"
  627. // @Param buildType query int false "委托单据类型"
  628. // @Param tradeType query string false "成交类别 - 格式:1,2,3"
  629. // @Param goodsID query int false "商品ID"
  630. // @Param incTradeID query string false "增量成交单号,用于增量查询"
  631. // @Success 200 {object} QueryTradeDetailRsp
  632. // @Failure 500 {object} app.Response
  633. // @Router /Order/QueryTradeDetail [get]
  634. // @Tags 通用单据
  635. // 参考通用查询:SearchAllTransactionDetailOrder
  636. func QueryTradeDetail(c *gin.Context) {
  637. appG := app.Gin{C: c}
  638. // 获取请求参数
  639. var req QueryTradeDetailReq
  640. if err := appG.C.ShouldBindQuery(&req); err != nil {
  641. logger.GetLogger().Errorf("QueryTradeDetail failed: %s", err.Error())
  642. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  643. return
  644. }
  645. datas := make([]QueryTradeDetailRsp, 0)
  646. engine := db.GetEngine()
  647. s := engine.Table("TRADE_TRADEDETAIL").
  648. Join("LEFT", "GOODS", "GOODS.GOODSID = TRADE_TRADEDETAIL.GOODSID").
  649. Join("LEFT", "MARKET", "MARKET.MARKETID = TRADE_TRADEDETAIL.MARKETID").
  650. Join("LEFT", "TRADE_ORDERDETAIL", "TRADE_ORDERDETAIL.ORDERID = TRADE_TRADEDETAIL.ORDERID").
  651. Join("LEFT", "TRADE_PAYORDER", "TRADE_PAYORDER.TRADEID = TRADE_TRADEDETAIL.TRADEID").
  652. Select(`to_char(TRADE_TRADEDETAIL.TRADEID) as TRADEID, to_char(TRADE_TRADEDETAIL.ORDERID) as ORDERID,
  653. TRADE_TRADEDETAIL.*, CASE TRADE_TRADEDETAIL.BUILDTYPE WHEN 1 THEN TRADE_TRADEDETAIL.OPENCHARGE ELSE TRADE_TRADEDETAIL.CLOSECHARGE END as CHARGE,
  654. GOODS.GOODSCODE, GOODS.GOODSNAME, GOODS.DECIMALPLACE, GOODS.QTYDECIMALPLACE,GOODS.GOODUNITID, MARKET.MARKETNAME, MARKET.TRADEMODE,
  655. TRADE_ORDERDETAIL.LISTINGSELECTTYPE, TRADE_PAYORDER.ADVANCERATIO, TRADE_PAYORDER.PAYAMOUNT, TRADE_PAYORDER.TRADECHARGE`).
  656. Where(fmt.Sprintf("TRADE_TRADEDETAIL.ACCOUNTID in (%s)", req.AccountID)).
  657. Desc("TRADE_TRADEDETAIL.TRADEID")
  658. if req.IncTradeID != "" {
  659. s = s.And(fmt.Sprintf("TRADE_TRADEDETAIL.TRADEID > %v", req.IncTradeID))
  660. }
  661. if req.TradeID > 0 {
  662. s = s.And("TRADE_TRADEDETAIL.TRADEID = ?", req.TradeID)
  663. }
  664. if req.OrderID > 0 {
  665. s = s.And("TRADE_TRADEDETAIL.ORDERID = ?", req.OrderID)
  666. }
  667. if req.GoodsID > 0 {
  668. s = s.And("TRADE_TRADEDETAIL.GOODSID = ?", req.GoodsID)
  669. }
  670. if len(req.TradeMode) > 0 {
  671. s = s.And(fmt.Sprintf("MARKET.TRADEMODE in (%s)", req.TradeMode))
  672. }
  673. if req.BuildType > 0 {
  674. s = s.And("TRADE_TRADEDETAIL.BUILDTYPE = ?", req.BuildType)
  675. }
  676. if len(req.TradeType) > 0 {
  677. s = s.And(fmt.Sprintf("TRADE_TRADEDETAIL.TRADETYPE in (%s)", req.TradeType))
  678. }
  679. if err := s.Find(&datas); err != nil {
  680. // 查询失败
  681. logger.GetLogger().Errorf("QueryTradeDetail failed: %s", err.Error())
  682. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  683. return
  684. }
  685. // 查询成功
  686. logger.GetLogger().Debugln("QueryTradeDetail successed: %v", datas)
  687. for i := range datas {
  688. datas[i].calc()
  689. }
  690. appG.Response(http.StatusOK, e.SUCCESS, datas)
  691. }
  692. // QueryHisTradeDetailReq 历史成交单查询请求参数
  693. type QueryHisTradeDetailReq struct {
  694. app.PageInfo
  695. AccountID string `form:"accountID" binding:"required"`
  696. TradeID int `form:"tradeID"`
  697. OrderID int `form:"orderID"`
  698. GoodsID int `form:"goodsID"`
  699. TradeMode string `form:"tradeMode"`
  700. BuildType int `form:"buildType"`
  701. TradeType string `form:"tradeType"`
  702. StartDate string `form:"startDate"` // 开始时间
  703. EndDate string `form:"endDate"` // 结束时间
  704. }
  705. // QueryHisTradeDetailRsp 历史成交单查询返回模型
  706. type QueryHisTradeDetailRsp struct {
  707. models.Histradetradedetail `xorm:"extends"`
  708. TradePayInfo `xorm:"extends"`
  709. GoodsCode string `json:"goodscode" xorm:"GOODSCODE"` // 商品代码
  710. GoodsName string `json:"goodsname" xorm:"GOODSNAME"` // 商品名称
  711. DECIMALPLACE int32 `json:"decimalplace" xorm:"'DECIMALPLACE'"` // 商品报价小数位
  712. QTYDECIMALPLACE int `json:"qtydecimalplace" xorm:"'QTYDECIMALPLACE'"` // 商品报价小数位
  713. GOODUNITID int32 `json:"goodunitid" xorm:"'GOODUNITID'"` // 商品单位id
  714. Marketname string `json:"marketname" xorm:"'MARKETNAME'"` // 市场名称
  715. TradeMode int32 `json:"trademode" xorm:"'TRADEMODE'"` // 交易模式
  716. ListingSelectType int32 `json:"listingselecttype" xorm:"'LISTINGSELECTTYPE'"` // 关联委托单挂牌点选类型 - 1:挂牌 2:摘牌 3:先摘后挂
  717. Charge float64 `json:"charge" xorm:"CHARGE"` // 手续费
  718. ENUMDICNAME string `json:"enumdicname"` // 单位名称
  719. }
  720. func (r *QueryHisTradeDetailRsp) calc() {
  721. fCovert := func(v *float64) {
  722. *v = *v / math.Pow10(r.QTYDECIMALPLACE)
  723. }
  724. fCovert(&r.Tradeqty)
  725. fCovert(&r.Openqty)
  726. fCovert(&r.Closeqty)
  727. r.ENUMDICNAME = mtpcache.GetEnumDicitemName(r.GOODUNITID)
  728. r.TOTALAMOUNT = r.Tradeamount + r.Opencharge + r.Closecharge
  729. r.RECVAMOUNT = r.Tradeamount - r.Opencharge - r.Closecharge
  730. }
  731. // QueryHisTradeDetail 历史成交单查询(合约市场)
  732. // @Summary 历史成交单查询(合约市场)
  733. // @Produce json
  734. // @Security ApiKeyAuth
  735. // @Param accountID query string true "资金账户 - 格式:1,2,3"
  736. // @Param tradeID query int false "成交单号"
  737. // @Param orderID query int false "委托单号"
  738. // @Param goodsID query int false "商品ID"
  739. // @Param tradeMode query string false "交易模式 - 格式:1,2,3"
  740. // @Param buildType query int false "委托单据类型"
  741. // @Param tradeType query string false "成交类别 - 格式:1,2,3"
  742. // @Param startDate query string false "开始时间 - 闭区间,格式:yyyy-MM-dd"
  743. // @Param endDate query string false "结束时间 - 闭区间,格式:yyyy-MM-dd"
  744. // @Param page query int false "页码"
  745. // @Param pagesize query int false "每页条数"
  746. // @Param pageflag query int false "分页标志 0-page从0开始 1-page从1开始"
  747. // @Success 200 {object} QueryHisTradeDetailRsp
  748. // @Failure 500 {object} app.Response
  749. // @Router /Order/QueryHisTradeDetail [get]
  750. // @Tags 通用单据
  751. // 参考通用查询:Client_QueryHis_trade_transactiondetail
  752. func QueryHisTradeDetail(c *gin.Context) {
  753. appG := app.Gin{C: c}
  754. // 获取请求参数
  755. var req QueryHisTradeDetailReq
  756. if err := appG.C.ShouldBindQuery(&req); err != nil {
  757. logger.GetLogger().Errorf("QueryHisTradeDetail failed: %s", err.Error())
  758. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  759. return
  760. }
  761. accountIds := strings.Split(req.AccountID, ",")
  762. datas := make([]QueryHisTradeDetailRsp, 0)
  763. engine := db.GetEngine()
  764. s := engine.Table("HIS_TRADE_TRADEDETAIL").
  765. Join("LEFT", "GOODS", "GOODS.GOODSID = HIS_TRADE_TRADEDETAIL.GOODSID").
  766. Join("LEFT", "MARKET", "MARKET.MARKETID = HIS_TRADE_TRADEDETAIL.MARKETID").
  767. Join("LEFT", "TRADE_PAYORDER", "TRADE_PAYORDER.TRADEID = HIS_TRADE_TRADEDETAIL.TRADEID").
  768. Select(`to_char(HIS_TRADE_TRADEDETAIL.TRADEID) as TRADEID, to_char(HIS_TRADE_TRADEDETAIL.ORDERID) as ORDERID,
  769. HIS_TRADE_TRADEDETAIL.*, CASE HIS_TRADE_TRADEDETAIL.BUILDTYPE WHEN 1 THEN HIS_TRADE_TRADEDETAIL.OPENCHARGE ELSE HIS_TRADE_TRADEDETAIL.CLOSECHARGE END as CHARGE,
  770. GOODS.GOODSCODE, GOODS.GOODSNAME,GOODS.DECIMALPLACE, GOODS.QTYDECIMALPLACE, GOODS.GOODUNITID, MARKET.MARKETNAME, MARKET.TRADEMODE,
  771. TRADE_PAYORDER.ADVANCERATIO, TRADE_PAYORDER.PAYAMOUNT, TRADE_PAYORDER.TRADECHARGE`).
  772. // Where(fmt.Sprintf("HIS_TRADE_TRADEDETAIL.ISVALIDDATA = 1 and HIS_TRADE_TRADEDETAIL.ACCOUNTID in (%s)", req.AccountID)).
  773. Where("HIS_TRADE_TRADEDETAIL.ISVALIDDATA = 1").
  774. In("HIS_TRADE_TRADEDETAIL.ACCOUNTID", accountIds).
  775. Desc("HIS_TRADE_TRADEDETAIL.TRADEID")
  776. if req.TradeID > 0 {
  777. s = s.And("HIS_TRADE_TRADEDETAIL.TRADEID = ?", req.TradeID)
  778. }
  779. if req.OrderID > 0 {
  780. s = s.And("HIS_TRADE_TRADEDETAIL.ORDERID = ?", req.OrderID)
  781. }
  782. if req.GoodsID > 0 {
  783. s = s.And("HIS_TRADE_TRADEDETAIL.GOODSID = ?", req.GoodsID)
  784. }
  785. if len(req.TradeMode) > 0 {
  786. // s = s.And(fmt.Sprintf("MARKET.TRADEMODE in (%s)", req.TradeMode))
  787. tradeModes := strings.Split(req.TradeMode, ",")
  788. s = s.In("MARKET.TRADEMODE", tradeModes)
  789. }
  790. if req.BuildType > 0 {
  791. s = s.And("HIS_TRADE_TRADEDETAIL.BUILDTYPE = ?", req.BuildType)
  792. }
  793. if len(req.TradeType) > 0 {
  794. // s = s.And(fmt.Sprintf("HIS_TRADE_TRADEDETAIL.TRADETYPE in (%s)", req.TradeType))
  795. tradeTypes := strings.Split(req.TradeType, ",")
  796. s = s.In("HIS_TRADE_TRADEDETAIL.TRADETYPE", tradeTypes)
  797. }
  798. if len(req.StartDate) > 0 {
  799. // s = s.And(fmt.Sprintf("to_date(HIS_TRADE_TRADEDETAIL.HISTRADEDATE,'yyyyMMdd') >= to_date('%s','yyyy-MM-dd')", req.StartDate))
  800. s = s.And("HIS_TRADE_TRADEDETAIL.HISTRADEDATE >= ?", strings.Replace(req.StartDate, "-", "", -1))
  801. }
  802. if len(req.EndDate) > 0 {
  803. // s = s.And(fmt.Sprintf("to_date(HIS_TRADE_TRADEDETAIL.HISTRADEDATE,'yyyyMMdd') <= to_date('%s','yyyy-MM-dd')", req.EndDate))
  804. s = s.And("HIS_TRADE_TRADEDETAIL.HISTRADEDATE <= ?", strings.Replace(req.EndDate, "-", "", -1))
  805. }
  806. if err := s.Find(&datas); err != nil {
  807. // 查询失败
  808. logger.GetLogger().Errorf("QueryHisTradeDetail failed: %s", err.Error())
  809. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  810. return
  811. }
  812. // 查询成功
  813. logger.GetLogger().Debugln("QueryHisTradeDetail successed: %v", datas)
  814. for i := range datas {
  815. datas[i].calc()
  816. }
  817. // appG.Response(http.StatusOK, e.SUCCESS, datas)
  818. // 查询成功返回
  819. if req.PageSize > 0 {
  820. // 分页
  821. var rst []QueryHisTradeDetailRsp
  822. // 开始上标
  823. // 终端分页1开始
  824. p := req.Page
  825. if req.PageFlag != 0 {
  826. p -= 1
  827. if p < 0 {
  828. p = 0
  829. }
  830. }
  831. start := p * req.PageSize
  832. // 结束下标
  833. end := start + req.PageSize
  834. if start <= len(datas) {
  835. // 判断结束下标是否越界
  836. if end > len(datas) {
  837. end = len(datas)
  838. }
  839. rst = datas[start:end]
  840. } else {
  841. rst = datas[0:0]
  842. }
  843. logger.GetLogger().Debugln("QueryHisTradeDetail successed: %v", rst)
  844. appG.ResponseByPage(http.StatusOK, e.SUCCESS, rst, app.PageInfo{Page: req.Page, PageSize: req.PageSize, Total: len(datas)})
  845. } else {
  846. // 不分页
  847. logger.GetLogger().Debugln("QueryHisTradeDetail successed: %v", datas)
  848. appG.Response(http.StatusOK, e.SUCCESS, datas)
  849. }
  850. }