Преглед изворни кода

fix: 持仓分析广期郑商

hsun пре 2 месеци
родитељ
комит
55c5422a78

+ 203 - 0
models/trade_analysis/trade_analysis.go

@@ -173,6 +173,7 @@ type OriginTradeData struct {
 	ValType      int       `description:"数据类型: 1-多单; 2-空单"`
 }
 
+// GetTradeDataByClassifyAndCompany 根据品种和公司名称获取持仓数据
 func GetTradeDataByClassifyAndCompany(exchange, classifyName string, contracts, companies []string) (items []*OriginTradeData, err error) {
 	if exchange == "" {
 		err = fmt.Errorf("数据表名称有误")
@@ -217,6 +218,49 @@ func GetTradeDataByClassifyAndCompany(exchange, classifyName string, contracts,
 	return
 }
 
+// GetTradeZhengzhouDataByClassifyAndCompany 郑商所-根据品种和公司名称获取持仓数据
+func GetTradeZhengzhouDataByClassifyAndCompany(exchange string, contracts, companies []string) (items []*OriginTradeData, err error) {
+	if exchange == "" {
+		err = fmt.Errorf("数据表名称有误")
+		return
+	}
+	if len(contracts) == 0 || len(companies) == 0 {
+		return
+	}
+	tableName := fmt.Sprintf("base_from_trade_%s_index", exchange)
+	sql := `SELECT
+			rank,
+			buy_short_name AS company_name,
+			buy_value AS val,
+			buy_change AS val_change,
+			classify_name AS classify_type,
+			data_time,
+			1 AS val_type 
+		FROM
+			%s 
+		WHERE
+			classify_name IN (%s) AND buy_short_name IN (%s)
+		UNION ALL
+		(
+		SELECT
+			rank,
+			sold_short_name,
+			sold_value,
+			sold_change,
+			classify_name AS classify_type,
+			data_time,
+			2 AS val_type 
+		FROM
+			%s 
+		WHERE
+			classify_name IN (%s) AND sold_short_name IN (%s)
+		)`
+	sql = fmt.Sprintf(sql, tableName, utils.GetOrmInReplace(len(contracts)), utils.GetOrmInReplace(len(companies)), tableName, utils.GetOrmInReplace(len(contracts)), utils.GetOrmInReplace(len(companies)))
+	o := orm.NewOrmUsingDB("data")
+	_, err = o.Raw(sql, contracts, companies, contracts, companies).QueryRows(&items)
+	return
+}
+
 // ContractCompanyTradeData [合约-期货公司]持仓数据
 type ContractCompanyTradeData struct {
 	CompanyName  string                          `description:"期货公司名称"`
@@ -237,6 +281,17 @@ const (
 
 	WarehouseDefaultUnit      = "手"
 	WarehouseDefaultFrequency = "日度"
+
+	GuangZhouTopCompanyAliasName = "日成交持仓排名" // 广期所TOP20对应的公司名称
+	GuangZhouSeatNameBuy         = "持买单量"    // 广期所指标名称中的多单名称
+	GuangZhouSeatNameSold        = "持卖单量"    // 广期所指标名称中的空单名称
+	GuangZhouTopSeatNameBuy      = "持买单量总计"  // 广期所指标名称中的TOP20多单名称
+	GuangZhouTopSeatNameSold     = "持卖单量总计"  // 广期所指标名称中的TOP20空单名称
+)
+
+const (
+	TradeExchangeZhengzhou = "zhengzhou"
+	TradeExchangeGuangzhou = "guangzhou"
 )
 
 var WarehouseTypeSuffixNames = map[int]string{
@@ -245,6 +300,14 @@ var WarehouseTypeSuffixNames = map[int]string{
 	WarehousePureBuyChartType: "席位净多单",
 }
 
+// GuangzhouSeatNameValType 广期所数据名称对应的席位方向
+var GuangzhouSeatNameValType = map[string]int{
+	GuangZhouSeatNameBuy:     1,
+	GuangZhouSeatNameSold:    2,
+	GuangZhouTopSeatNameBuy:  1,
+	GuangZhouTopSeatNameSold: 2,
+}
+
 // ContractCompanyTradeDataList [合约-期货公司]持仓数据详情
 type ContractCompanyTradeDataList struct {
 	Date              time.Time `description:"数据日期"`
@@ -328,3 +391,143 @@ func GetLastTradeDataByClassify(exchange, classifyName string, contracts []strin
 	_, err = o.Raw(sql, classifyName, contracts, classifyName, contracts, classifyName, contracts, classifyName, contracts).QueryRows(&items)
 	return
 }
+
+// GetLastTradeZhengzhouDataByClassify 郑商所-获取[合约]末位多空单数据
+func GetLastTradeZhengzhouDataByClassify(exchange string, contracts []string) (items []*OriginTradeData, err error) {
+	if exchange == "" {
+		err = fmt.Errorf("数据表名称有误")
+		return
+	}
+	if len(contracts) == 0 {
+		return
+	}
+	contractReplacer := utils.GetOrmInReplace(len(contracts))
+
+	tableName := fmt.Sprintf("base_from_trade_%s_index", exchange)
+	sql := `SELECT 
+			tpt.rank,
+			tpt.buy_short_name AS company_name,
+			tpt.buy_value AS val,
+			tpt.buy_change AS val_change,
+  			tpt.classify_name AS classify_type,
+			tpt.data_time,
+			1 AS val_type
+		FROM 
+			%s tpt
+		JOIN 
+			(
+				SELECT
+					data_time, classify_name, MAX(rank) AS max_rank
+				FROM 
+					%s
+				WHERE 
+					classify_name IN (%s) AND buy_short_name <> ''
+				GROUP BY 
+					data_time,
+					classify_name
+			) sub
+		ON
+			tpt.data_time = sub.data_time AND tpt.classify_name = sub.classify_name AND tpt.rank = sub.max_rank
+		WHERE 
+			tpt.classify_name IN (%s)
+		UNION ALL
+		(
+		SELECT 
+			tpt.rank, tpt.sold_short_name, tpt.sold_value, tpt.sold_change, tpt.classify_name AS classify_type, tpt.data_time, 2 AS val_type
+		FROM 
+			%s tpt
+		JOIN 
+			(
+				SELECT 
+					data_time, classify_name, MAX(rank) AS max_rank
+				FROM 
+					%s
+				WHERE 
+					classify_name IN (%s) AND sold_short_name <> ''
+				GROUP BY 
+					data_time, classify_name
+			) sub
+		ON 
+			tpt.data_time = sub.data_time AND tpt.classify_name = sub.classify_name AND tpt.rank = sub.max_rank
+		WHERE 
+			tpt.classify_name IN (%s)
+		)`
+	sql = fmt.Sprintf(sql, tableName, tableName, contractReplacer, contractReplacer, tableName, tableName, contractReplacer, contractReplacer)
+	o := orm.NewOrmUsingDB("data")
+	_, err = o.Raw(sql, contracts, contracts, contracts, contracts).QueryRows(&items)
+	return
+}
+
+type BaseFromTradeGuangzhouIndex struct {
+	BaseFromTradeGuangzhouIndexId    int       `orm:"column(base_from_trade_guangzhou_index_id);pk"`
+	BaseFromTradeGuangzhouClassifyId int       `description:"分类id"`
+	IndexCode                        string    `description:"指标编码"`
+	IndexName                        string    `description:"指标名称"`
+	Frequency                        string    `description:"频率"`
+	Unit                             string    `description:"单位"`
+	StartDate                        string    `description:"开始日期"`
+	EndDate                          string    `description:"结束日期"`
+	CreateTime                       time.Time `description:"创建日期"`
+	ModifyTime                       time.Time `description:"修改日期"`
+}
+
+func GetBaseFromTradeGuangzhouIndexByClassifyId(classifyId int) (list []*BaseFromTradeGuangzhouIndex, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM base_from_trade_guangzhou_index WHERE base_from_trade_guangzhou_classify_id = ?`
+	_, err = o.Raw(sql, classifyId).QueryRows(&list)
+	return
+}
+
+type BaseFromTradeGuangzhouData struct {
+	BaseFromTradeGuangzhouDataId  int       `orm:"column(base_from_trade_guangzhou_data_id);pk"`
+	BaseFromTradeGuangzhouIndexId int       `description:"指标id"`
+	IndexCode                     string    `description:"指标编码"`
+	DataTime                      time.Time `description:"数据日期"`
+	Value                         float64   `description:"数据值"`
+	QtySub                        float64   `description:"增减"`
+	CreateTime                    time.Time `description:"创建日期"`
+	ModifyTime                    time.Time `description:"修改日期"`
+}
+
+// GetBaseFromTradeGuangzhouDataByIndexIds 获取指标数据
+func GetBaseFromTradeGuangzhouDataByIndexIds(indexIds []int) (list []*BaseFromTradeGuangzhouData, err error) {
+	if len(indexIds) == 0 {
+		return
+	}
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT * FROM base_from_trade_guangzhou_data WHERE base_from_trade_guangzhou_index_id IN (%s) ORDER BY base_from_trade_guangzhou_index_id`, utils.GetOrmInReplace(len(indexIds)))
+	_, err = o.Raw(sql, indexIds).QueryRows(&list)
+	return
+}
+
+// GetBaseFromTradeGuangzhouMinDataByIndexIds 获取指标中的末位数据
+func GetBaseFromTradeGuangzhouMinDataByIndexIds(indexIds []int) (list []*BaseFromTradeGuangzhouData, err error) {
+	indexLen := len(indexIds)
+	if indexLen == 0 {
+		return
+	}
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT 
+			t1.data_time,
+			t1.min_value AS value
+		FROM 
+			(
+				SELECT 
+					data_time,
+					MIN(value) AS min_value
+				FROM 
+					base_from_trade_guangzhou_data
+				WHERE 
+					base_from_trade_guangzhou_index_id IN (%s)
+				GROUP BY 
+					data_time
+			) t1
+		JOIN 
+			base_from_trade_guangzhou_data t2
+		ON 
+			t1.data_time = t2.data_time AND t1.min_value = t2.value AND t2.base_from_trade_guangzhou_index_id IN (%s)
+		GROUP BY 
+			t1.data_time`, utils.GetOrmInReplace(indexLen), utils.GetOrmInReplace(indexLen))
+	_, err = o.Raw(sql, indexIds, indexIds).QueryRows(&list)
+	return
+}

+ 15 - 4
services/trade_analysis/trade_analysis_data.go

@@ -112,8 +112,19 @@ func GetOriginTradeData(exchange, classifyName string, contracts, companies []st
 		queryCompanies = append(queryCompanies, companyName)
 	}
 
-	// TODO:(广期所查询方式不一样)获取多单/空单原始数据
-	originList, e := tradeAnalysisModel.GetTradeDataByClassifyAndCompany(exchange, classifyName, contracts, queryCompanies)
+	// 郑商所/广期所查询方式不一样
+	var tradeAnalysis TradeAnalysisInterface
+	switch exchange {
+	case tradeAnalysisModel.TradeExchangeZhengzhou:
+		tradeAnalysis = &ZhengzhouTradeAnalysis{}
+	case tradeAnalysisModel.TradeExchangeGuangzhou:
+		tradeAnalysis = &GuangzhouTradeAnalysis{}
+	default:
+		tradeAnalysis = &BaseTradeAnalysis{}
+	}
+
+	// 获取多单/空单原始数据
+	originList, e := tradeAnalysis.GetTradeDataByClassifyAndCompany(exchange, classifyName, contracts, queryCompanies)
 	if e != nil {
 		err = fmt.Errorf("获取多空单原始数据失败, %v", e)
 		return
@@ -160,11 +171,11 @@ func GetOriginTradeData(exchange, classifyName string, contracts, companies []st
 		}
 	}
 
-	// TODO:(广期所查询方式不一样)获取[合约]每日的末位多空单
+	// 获取[合约]每日的末位多空单
 	contractLastBuyDateVal := make(map[string]map[time.Time]int)
 	contractLastSoldDateVal := make(map[string]map[time.Time]int)
 	{
-		lastOriginList, e := tradeAnalysisModel.GetLastTradeDataByClassify(exchange, classifyName, contracts)
+		lastOriginList, e := tradeAnalysis.GetLastTradeDataByClassify(exchange, classifyName, contracts)
 		if e != nil {
 			err = fmt.Errorf("获取末位多空单原始数据失败, %v", e)
 			return

+ 181 - 0
services/trade_analysis/trade_analysis_interface.go

@@ -0,0 +1,181 @@
+package trade_analysis
+
+import (
+	tradeAnalysisModel "eta/eta_index_lib/models/trade_analysis"
+	"eta/eta_index_lib/utils"
+	"fmt"
+	"strconv"
+	"strings"
+)
+
+// TradeAnalysisInterface 持仓分析查询接口
+type TradeAnalysisInterface interface {
+	GetTradeDataByClassifyAndCompany(exchange, classifyName string, contracts, queryCompanies []string) (items []*tradeAnalysisModel.OriginTradeData, err error) // 根据品种和公司获取原始数据
+	GetLastTradeDataByClassify(exchange, classifyName string, contracts []string) (items []*tradeAnalysisModel.OriginTradeData, err error)                       // 获取品种末位数据
+}
+
+// BaseTradeAnalysis 通用交易所
+type BaseTradeAnalysis struct{}
+
+func (b *BaseTradeAnalysis) GetTradeDataByClassifyAndCompany(exchange, classifyName string, contracts, queryCompanies []string) (items []*tradeAnalysisModel.OriginTradeData, err error) {
+	return tradeAnalysisModel.GetTradeDataByClassifyAndCompany(exchange, classifyName, contracts, queryCompanies)
+}
+
+func (b *BaseTradeAnalysis) GetLastTradeDataByClassify(exchange, classifyName string, contracts []string) (items []*tradeAnalysisModel.OriginTradeData, err error) {
+	return tradeAnalysisModel.GetLastTradeDataByClassify(exchange, classifyName, contracts)
+}
+
+// ZhengzhouTradeAnalysis 郑商所
+type ZhengzhouTradeAnalysis struct{}
+
+func (z *ZhengzhouTradeAnalysis) GetTradeDataByClassifyAndCompany(exchange, classifyName string, contracts, queryCompanies []string) (items []*tradeAnalysisModel.OriginTradeData, err error) {
+	return tradeAnalysisModel.GetTradeZhengzhouDataByClassifyAndCompany(exchange, contracts, queryCompanies)
+}
+
+func (z *ZhengzhouTradeAnalysis) GetLastTradeDataByClassify(exchange, classifyName string, contracts []string) (items []*tradeAnalysisModel.OriginTradeData, err error) {
+	return tradeAnalysisModel.GetLastTradeZhengzhouDataByClassify(exchange, contracts)
+}
+
+// GuangzhouTradeAnalysis 广期所
+type GuangzhouTradeAnalysis struct{}
+
+func (g *GuangzhouTradeAnalysis) GetTradeDataByClassifyAndCompany(exchange, classifyName string, contracts, queryCompanies []string) (items []*tradeAnalysisModel.OriginTradeData, err error) {
+	classifyIdMap := map[string]int{"si": 7, "lc": 8}
+	classifyId := classifyIdMap[classifyName]
+	if classifyId == 0 {
+		err = fmt.Errorf("品种有误")
+		return
+	}
+
+	// TOP20
+	seatNameArr := []string{tradeAnalysisModel.GuangZhouSeatNameBuy, tradeAnalysisModel.GuangZhouSeatNameSold}
+	if utils.InArrayByStr(queryCompanies, tradeAnalysisModel.TradeFuturesCompanyTop20) {
+		seatNameArr = append(seatNameArr, tradeAnalysisModel.GuangZhouTopSeatNameBuy, tradeAnalysisModel.GuangZhouTopSeatNameSold)
+	}
+
+	// 查询品种下所有指标
+	indexes, e := tradeAnalysisModel.GetBaseFromTradeGuangzhouIndexByClassifyId(classifyId)
+	if e != nil {
+		err = fmt.Errorf("获取广期所指标失败, %v", e)
+		return
+	}
+	var indexIds []int
+	indexInfo := make(map[int]*tradeAnalysisModel.OriginTradeData)
+	for _, v := range indexes {
+		// eg.永安期货_si2401_持买单量
+		nameArr := strings.Split(v.IndexName, "_")
+		if len(nameArr) != 3 {
+			continue
+		}
+		companyName := nameArr[0]
+		if nameArr[0] == tradeAnalysisModel.GuangZhouTopCompanyAliasName {
+			companyName = tradeAnalysisModel.TradeFuturesCompanyTop20
+		}
+		if !utils.InArrayByStr(seatNameArr, nameArr[2]) {
+			continue
+		}
+		if !utils.InArrayByStr(queryCompanies, companyName) {
+			continue
+		}
+		if !utils.InArrayByStr(contracts, nameArr[1]) {
+			continue
+		}
+		indexIds = append(indexIds, v.BaseFromTradeGuangzhouIndexId)
+		if indexInfo[v.BaseFromTradeGuangzhouIndexId] == nil {
+			if tradeAnalysisModel.GuangzhouSeatNameValType[nameArr[2]] == 0 {
+				continue
+			}
+			indexInfo[v.BaseFromTradeGuangzhouIndexId] = new(tradeAnalysisModel.OriginTradeData)
+			indexInfo[v.BaseFromTradeGuangzhouIndexId].CompanyName = companyName
+			indexInfo[v.BaseFromTradeGuangzhouIndexId].ClassifyName = classifyName
+			indexInfo[v.BaseFromTradeGuangzhouIndexId].ClassifyType = nameArr[1]
+			indexInfo[v.BaseFromTradeGuangzhouIndexId].ValType = tradeAnalysisModel.GuangzhouSeatNameValType[nameArr[2]]
+		}
+	}
+	if len(indexIds) == 0 {
+		return
+	}
+
+	// 查询指标数据
+	indexesData, e := tradeAnalysisModel.GetBaseFromTradeGuangzhouDataByIndexIds(indexIds)
+	if e != nil {
+		err = fmt.Errorf("获取广期所指标数据失败, %v", e)
+		return
+	}
+	items = make([]*tradeAnalysisModel.OriginTradeData, 0)
+	for _, v := range indexesData {
+		info, ok := indexInfo[v.BaseFromTradeGuangzhouIndexId]
+		if !ok {
+			continue
+		}
+		items = append(items, &tradeAnalysisModel.OriginTradeData{
+			CompanyName:  info.CompanyName,
+			Val:          int(v.Value),
+			ValChange:    int(v.QtySub),
+			DataTime:     v.DataTime,
+			ClassifyName: info.ClassifyName,
+			ClassifyType: info.ClassifyType,
+			ValType:      info.ValType,
+		})
+	}
+	return
+}
+
+func (g *GuangzhouTradeAnalysis) GetLastTradeDataByClassify(exchange, classifyName string, contracts []string) (items []*tradeAnalysisModel.OriginTradeData, err error) {
+	classifyIdMap := map[string]int{"si": 7, "lc": 8}
+	classifyId := classifyIdMap[classifyName]
+	if classifyId == 0 {
+		err = fmt.Errorf("品种有误")
+		return
+	}
+	seatNameArr := []string{tradeAnalysisModel.GuangZhouSeatNameBuy, tradeAnalysisModel.GuangZhouSeatNameSold}
+
+	// 查询品种下所有指标
+	indexes, e := tradeAnalysisModel.GetBaseFromTradeGuangzhouIndexByClassifyId(classifyId)
+	if e != nil {
+		err = fmt.Errorf("获取广期所指标失败, %v", e)
+		return
+	}
+
+	// 获取各合约下的指标
+	contractIndexIds := make(map[string][]int)
+	for _, v := range indexes {
+		// eg.永安期货_si2401_持买单量
+		nameArr := strings.Split(v.IndexName, "_")
+		if len(nameArr) != 3 {
+			continue
+		}
+		if !utils.InArrayByStr(contracts, nameArr[1]) {
+			continue
+		}
+		if !utils.InArrayByStr(seatNameArr, nameArr[2]) {
+			continue
+		}
+		if tradeAnalysisModel.GuangzhouSeatNameValType[nameArr[2]] == 0 {
+			continue
+		}
+		k := fmt.Sprintf("%s-%d", nameArr[1], tradeAnalysisModel.GuangzhouSeatNameValType[nameArr[2]])
+		contractIndexIds[k] = append(contractIndexIds[k], v.BaseFromTradeGuangzhouIndexId)
+	}
+
+	// ps.如果后面如果有空可以优化一下这里, 把末位数据每天写进一张表里面
+	for k, v := range contractIndexIds {
+		keyArr := strings.Split(k, "-")
+		contract := keyArr[0]
+		valType, _ := strconv.Atoi(keyArr[1])
+		lastVales, e := tradeAnalysisModel.GetBaseFromTradeGuangzhouMinDataByIndexIds(v)
+		if e != nil {
+			err = fmt.Errorf("获取合约末位数据失败, %v", e)
+			return
+		}
+		for _, vv := range lastVales {
+			items = append(items, &tradeAnalysisModel.OriginTradeData{
+				Val:          int(vv.Value),
+				DataTime:     vv.DataTime,
+				ClassifyType: contract,
+				ValType:      valType,
+			})
+		}
+	}
+	return
+}