types: update position metrics after adding trades

This commit is contained in:
c9s 2024-08-21 16:35:57 +08:00
parent c063df6467
commit 9136877207
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 46 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import (
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/slack-go/slack"
"github.com/c9s/bbgo/pkg/fixedpoint"
@ -534,6 +535,8 @@ func (p *Position) AddTrade(td Trade) (profit fixedpoint.Value, netProfit fixedp
p.Lock()
defer p.Unlock()
defer p.updateMetrics()
// update changedAt field before we unlock in the defer func
defer func() {
p.ChangedAt = td.Time.Time()
@ -635,3 +638,17 @@ func (p *Position) AddTrade(td Trade) (profit fixedpoint.Value, netProfit fixedp
return fixedpoint.Zero, fixedpoint.Zero, false
}
func (p *Position) updateMetrics() {
if p.StrategyInstanceID == "" || p.Strategy == "" {
return
}
labels := prometheus.Labels{
"strategy_id": p.StrategyInstanceID,
"strategy_type": p.Strategy,
}
positionAverageCostMetrics.With(labels).Set(p.AverageCost.Float64())
positionBaseQuantityMetrics.With(labels).Set(p.Base.Float64())
positionQuoteQuantityMetrics.With(labels).Set(p.Quote.Float64())
}

View File

@ -0,0 +1,29 @@
package types
import "github.com/prometheus/client_golang/prometheus"
var positionAverageCostMetrics = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "bbgo_position_avg_cost",
Help: "bbgo position average cost metrics",
}, []string{"strategy_id", "strategy_type", "symbol"})
var positionBaseQuantityMetrics = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "bbgo_position_base_qty",
Help: "bbgo position base quantity metrics",
}, []string{"strategy_id", "strategy_type", "symbol"})
var positionQuoteQuantityMetrics = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "bbgo_position_base_qty",
Help: "bbgo position base quantity metrics",
}, []string{"strategy_id", "strategy_type", "symbol"})
func init() {
prometheus.MustRegister(
positionAverageCostMetrics,
positionBaseQuantityMetrics,
positionQuoteQuantityMetrics,
)
}