diff --git a/pkg/types/position.go b/pkg/types/position.go index 2d71ee740..60b938eab 100644 --- a/pkg/types/position.go +++ b/pkg/types/position.go @@ -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()) +} diff --git a/pkg/types/position_metrics.go b/pkg/types/position_metrics.go new file mode 100644 index 000000000..7384ae0fe --- /dev/null +++ b/pkg/types/position_metrics.go @@ -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, + ) +}