8 "github.com/go-redis/redis"
9 "github.com/shopspring/decimal"
12 type PortfolioStep string
14 const SELL_BEGIN PortfolioStep = "process_sell_all__1_all_sell_begin"
15 const SELL_END PortfolioStep = "process_sell_all__1_all_sell_end"
16 const BUY_BEGIN PortfolioStep = "process_sell_all__3_all_buy_begin"
17 const BUY_END PortfolioStep = "process_sell_all__3_all_buy_end"
18 const INTERMADIATE_STATE PortfolioStep = "process_print_balances__1_print_balances_begin"
20 type ViewBalances struct {
33 Balances ReportBalances
37 type ReportTickers struct {
39 Balances map[string]decimal.Decimal
44 func (r ReportTickers) GetBTCRate(currency string) decimal.Decimal {
45 if currency == "BTC" {
46 return decimal.NewFromFloat(1.0)
49 return r.Rates[currency]
52 type BTCRates map[string]decimal.Decimal
54 func (b BTCRates) Rate(currency string) decimal.Decimal {
55 if currency == "BTC" {
56 return decimal.NewFromFloat(1.0)
62 type ReportBalances map[string]struct {
64 MarginTotal decimal.Decimal `json:"margin_total"`
65 MarginInPosition decimal.Decimal `json:"margin_in_position"`
66 MarginAvailable decimal.Decimal `json:"margin_available"`
69 func RedisReportKey(marketConfigId int64, timestamp, entity string) string {
70 return fmt.Sprintf("/cryptoportfolio/%v/%v/%v", marketConfigId, timestamp, entity)
73 func GetLatestReport(marketConfig MarketConfig) (Report, error) {
74 var reportPayload Report
79 key = RedisReportKey(marketConfig.Id, "latest", "balance")
81 payload, err := Redis.Get(key).Bytes()
83 return Report{}, fmt.Errorf("cannot find '%s' redis key", key)
84 } else if err != nil {
89 key = RedisReportKey(marketConfig.Id, "latest", "date")
90 dateString, err := Redis.Get(key).Result()
93 return Report{}, fmt.Errorf("cannot find '%s' redis key", key)
94 } else if err != nil {
98 reportPayload.Date, err = time.Parse("2006-01-02T15:04:05", dateString)
103 err = json.Unmarshal(payload, &reportPayload)
105 return reportPayload, err
108 func GetPortfolioMilestones(marketConfig MarketConfig, step PortfolioStep, limit int) ([]Report, error) {
109 viewBalances := make([]ViewBalances, 0)
110 reports := make([]Report, 0)
113 Model(&viewBalances).
114 Where("market_id = ?", marketConfig.Id).
115 Where("payload @> ?", fmt.Sprintf(`{"tag": "%s", "checkpoint": "%s"}`, step, "begin")).
116 OrderExpr("date DESC").Limit(limit).Select()
121 for _, reportLine := range viewBalances {
122 reportLine.Payload.Report.Date = reportLine.Date
123 reports = append(reports, reportLine.Payload.Report)
129 func GetLastPortfolioBegin(marketConfig MarketConfig) (*Report, error) {
130 reports, err := GetPortfolioMilestones(marketConfig, BUY_END, 1)
135 if len(reports) == 0 {
139 return &reports[0], nil