github.com/diadata-org/diadata@v1.4.593/pkg/model/benchmarkedIndex.go (about)

     1  package models
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	clientInfluxdb "github.com/influxdata/influxdb1-client/v2"
     8  )
     9  
    10  type BenchmarkedIndex struct {
    11  	Name   string
    12  	Values []BenchmarkedIndexValue
    13  }
    14  
    15  type BenchmarkedIndexValue struct {
    16  	CalculationTime time.Time
    17  	Value           string
    18  }
    19  
    20  func (datastore *DB) SaveIndexEngineTimeInflux(tags map[string]string, fields map[string]interface{}, timestamp time.Time) error {
    21  	pt, err := clientInfluxdb.NewPoint(influxDbBenchmarkedIndexTableName, tags, fields, timestamp)
    22  	if err != nil {
    23  		log.Errorln("newPoint:", err)
    24  	} else {
    25  		datastore.addPoint(pt)
    26  		errWriteBatchInflux := datastore.WriteBatchInflux()
    27  		if errWriteBatchInflux != nil {
    28  			log.Errorln("newPoint:", errWriteBatchInflux)
    29  		}
    30  	}
    31  	return err
    32  }
    33  
    34  func (datastore *DB) GetBenchmarkedIndexValuesInflux(symbol string, starttime time.Time, endtime time.Time) (BenchmarkedIndex, error) {
    35  	var retval BenchmarkedIndex
    36  	q := fmt.Sprintf("SELECT time,\"name\",value from %s WHERE time > %d and time < %d and \"name\" = '%s' ORDER BY time DESC", influxDbBenchmarkedIndexTableName, starttime.UnixNano(), endtime.UnixNano(), symbol)
    37  	res, err := queryInfluxDB(datastore.influxClient, q)
    38  	if err != nil {
    39  		return retval, err
    40  	}
    41  
    42  	currentIndex := BenchmarkedIndex{}
    43  	var indexValues []BenchmarkedIndexValue
    44  	if len(res) > 0 && len(res[0].Series) > 0 {
    45  		for i := 0; i < len(res[0].Series[0].Values); i++ {
    46  			// Get benchmarked index symbol/name
    47  			currentIndex.Name = res[0].Series[0].Values[i][1].(string)
    48  			// Value
    49  			curValue := res[0].Series[0].Values[i][2].(string)
    50  			// Calculation time
    51  			curCalculationTime, err := time.Parse(time.RFC3339, res[0].Series[0].Values[i][0].(string))
    52  			if err != nil {
    53  				return currentIndex, err
    54  			}
    55  			indexValue := BenchmarkedIndexValue{
    56  				Value:           curValue,
    57  				CalculationTime: curCalculationTime,
    58  			}
    59  			indexValues = append(indexValues, indexValue)
    60  		}
    61  	}
    62  	currentIndex.Values = indexValues
    63  	return currentIndex, nil
    64  }