bbgo_origin/pkg/bbgo/position.go

43 lines
948 B
Go
Raw Normal View History

2021-01-20 08:08:14 +00:00
package bbgo
import (
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
type Position struct {
2021-01-20 08:30:44 +00:00
Symbol string `json:"symbol"`
2021-01-20 08:15:34 +00:00
Base fixedpoint.Value `json:"base"`
Quote fixedpoint.Value `json:"quote"`
AverageCost fixedpoint.Value `json:"averageCost"`
2021-01-20 08:08:14 +00:00
}
func (p *Position) AddTrade(t types.Trade) (fixedpoint.Value, bool) {
price := fixedpoint.NewFromFloat(t.Price)
quantity := fixedpoint.NewFromFloat(t.Quantity)
switch t.Side {
case types.SideTypeBuy:
if p.AverageCost == 0 {
p.AverageCost = price
} else {
p.AverageCost = (p.AverageCost.Mul(p.Base) + price.Mul(quantity)).Div(p.Base + quantity)
}
p.Base += quantity
p.Quote -= fixedpoint.NewFromFloat(t.QuoteQuantity)
return 0, false
case types.SideTypeSell:
p.Base -= quantity
p.Quote += fixedpoint.NewFromFloat(t.QuoteQuantity)
2021-01-20 08:14:02 +00:00
return (price - p.AverageCost).Mul(quantity), true
2021-01-20 08:08:14 +00:00
}
return 0, false
}