github.com/bitfinexcom/bitfinex-api-go@v0.0.0-20210608095005-9e0b26f200fb/pkg/models/candle/candle.go (about)

     1  package candle
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/bitfinexcom/bitfinex-api-go/pkg/convert"
     9  	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/common"
    10  )
    11  
    12  type Candle struct {
    13  	Symbol     string
    14  	Resolution common.CandleResolution
    15  	MTS        int64
    16  	Open       float64
    17  	Close      float64
    18  	High       float64
    19  	Low        float64
    20  	Volume     float64
    21  }
    22  
    23  type Snapshot struct {
    24  	Snapshot []*Candle
    25  }
    26  
    27  func SnapshotFromRaw(symbol string, resolution common.CandleResolution, raw [][]interface{}) (*Snapshot, error) {
    28  	if len(raw) <= 0 {
    29  		return nil, fmt.Errorf("data slice too short for candle snapshot: %#v", raw)
    30  	}
    31  
    32  	snap := make([]*Candle, 0)
    33  	for _, f := range raw {
    34  		c, err := FromRaw(symbol, resolution, f)
    35  		if err == nil {
    36  			snap = append(snap, c)
    37  		}
    38  	}
    39  
    40  	return &Snapshot{Snapshot: snap}, nil
    41  }
    42  
    43  func FromRaw(symbol string, resolution common.CandleResolution, raw []interface{}) (c *Candle, err error) {
    44  	if len(raw) < 6 {
    45  		return c, fmt.Errorf("data slice too short for candle, expected %d got %d: %#v", 6, len(raw), raw)
    46  	}
    47  
    48  	c = &Candle{
    49  		Symbol:     symbol,
    50  		Resolution: resolution,
    51  		MTS:        convert.I64ValOrZero(raw[0]),
    52  		Open:       convert.F64ValOrZero(raw[1]),
    53  		Close:      convert.F64ValOrZero(raw[2]),
    54  		High:       convert.F64ValOrZero(raw[3]),
    55  		Low:        convert.F64ValOrZero(raw[4]),
    56  		Volume:     convert.F64ValOrZero(raw[5]),
    57  	}
    58  
    59  	return
    60  }
    61  
    62  // FromWSRaw - based on condition will return snapshot of candles or single candle
    63  func FromWSRaw(key string, data []interface{}) (interface{}, error) {
    64  	if len(data) == 0 {
    65  		return nil, errors.New("empty data slice")
    66  	}
    67  
    68  	_, isSnapshot := data[0].([]interface{})
    69  	ss := strings.Split(key, ":")
    70  
    71  	// basic signature is: "trade:1m:tBTCUSD"
    72  	if len(ss) < 3 {
    73  		return nil, fmt.Errorf("invalid key:%s", key)
    74  	}
    75  
    76  	res := common.CandleResolution(ss[1])
    77  	symbol := ss[2]
    78  
    79  	if isSnapshot {
    80  		return SnapshotFromRaw(symbol, res, convert.ToInterfaceArray(data))
    81  	}
    82  	return FromRaw(symbol, res, data)
    83  }