bbgo_origin/bbgo/stock.go

249 lines
4.8 KiB
Go
Raw Normal View History

2020-08-04 01:47:54 +00:00
package bbgo
import (
"fmt"
"github.com/c9s/bbgo/pkg/bbgo/types"
"math"
2020-08-11 02:24:56 +00:00
"sort"
2020-08-11 04:09:40 +00:00
"strconv"
2020-08-04 01:47:54 +00:00
"strings"
2020-08-04 12:04:15 +00:00
"sync"
2020-08-04 01:47:54 +00:00
)
2020-08-04 09:03:57 +00:00
func zero(a float64) bool {
return int(math.Round(a*1e8)) == 0
}
func round(a float64) float64 {
return math.Round(a*1e8) / 1e8
}
2020-08-04 01:47:54 +00:00
type Stock types.Trade
2020-08-04 05:50:27 +00:00
func (stock *Stock) String() string {
return fmt.Sprintf("%f (%f)", stock.Price, stock.Quantity)
}
2020-08-04 01:47:54 +00:00
func (stock *Stock) Consume(quantity float64) float64 {
2020-08-04 09:03:57 +00:00
q := math.Min(stock.Quantity, quantity)
stock.Quantity = round(stock.Quantity - q)
return q
2020-08-04 01:47:54 +00:00
}
2020-08-04 05:50:27 +00:00
type StockSlice []Stock
2020-08-04 11:05:20 +00:00
func (slice StockSlice) QuantityBelowPrice(price float64) (quantity float64) {
for _, stock := range slice {
if stock.Price < price {
quantity += stock.Quantity
}
}
return round(quantity)
}
2020-08-04 05:50:27 +00:00
func (slice StockSlice) Quantity() (total float64) {
for _, stock := range slice {
total += stock.Quantity
}
2020-08-04 09:03:57 +00:00
return round(total)
2020-08-04 05:50:27 +00:00
}
2020-08-04 01:47:54 +00:00
type StockManager struct {
2020-08-04 12:04:15 +00:00
mu sync.Mutex
2020-08-04 05:50:27 +00:00
Symbol string
2020-08-04 01:47:54 +00:00
TradingFeeCurrency string
2020-08-04 05:50:27 +00:00
Stocks StockSlice
PendingSells StockSlice
}
2020-08-11 01:54:02 +00:00
type Distribution struct {
2020-08-11 04:09:40 +00:00
PriceLevels []string `json:"priceLevels"`
2020-08-11 02:27:41 +00:00
TotalQuantity float64 `json:"totalQuantity"`
2020-08-11 04:09:40 +00:00
Quantities map[string]float64 `json:"quantities"`
Stocks map[string]StockSlice `json:"stocks"`
2020-08-11 01:54:02 +00:00
}
func (m *StockManager) Distribution(level int) *Distribution {
var d = Distribution{
2020-08-11 04:09:40 +00:00
Quantities: map[string]float64{},
Stocks: map[string]StockSlice{},
2020-08-11 01:54:02 +00:00
}
for _, stock := range m.Stocks {
n := math.Ceil(math.Log10(stock.Price))
digits := int(n - math.Max(float64(level), 1.0))
div := math.Pow10(digits)
2020-08-11 04:09:40 +00:00
priceLevel := math.Floor(stock.Price / div) * div
key := strconv.FormatFloat(priceLevel, 'f', 2, 64)
2020-08-11 01:54:02 +00:00
2020-08-11 02:27:41 +00:00
d.TotalQuantity += stock.Quantity
2020-08-11 04:09:40 +00:00
d.Stocks[key] = append(d.Stocks[key], stock)
d.Quantities[key] += stock.Quantity
2020-08-11 01:54:02 +00:00
}
2020-08-11 04:09:40 +00:00
var priceLevels []float64
for priceString := range d.Stocks {
price, _ := strconv.ParseFloat(priceString, 32)
priceLevels = append(priceLevels, price)
2020-08-11 02:24:56 +00:00
}
2020-08-11 04:09:40 +00:00
sort.Float64s(priceLevels)
for _, price := range priceLevels {
d.PriceLevels = append(d.PriceLevels, strconv.FormatFloat(price, 'f', 2, 64))
}
sort.Float64s(priceLevels)
2020-08-11 02:24:56 +00:00
2020-08-11 01:54:02 +00:00
return &d
}
2020-08-04 12:04:15 +00:00
func (m *StockManager) stock(stock Stock) error {
m.mu.Lock()
m.Stocks = append(m.Stocks, stock)
m.mu.Unlock()
2020-08-04 09:03:57 +00:00
return m.flushPendingSells()
}
2020-08-04 09:10:29 +00:00
func (m *StockManager) squash() {
2020-08-04 12:04:15 +00:00
m.mu.Lock()
defer m.mu.Unlock()
2020-08-04 09:10:29 +00:00
var squashed StockSlice
for _, stock := range m.Stocks {
if !zero(stock.Quantity) {
squashed = append(squashed, stock)
}
}
m.Stocks = squashed
}
2020-08-04 09:03:57 +00:00
func (m *StockManager) flushPendingSells() error {
2020-08-04 12:04:15 +00:00
if len(m.Stocks) == 0 || len(m.PendingSells) == 0 {
return nil
}
2020-08-04 05:50:27 +00:00
2020-08-04 12:04:15 +00:00
pendingSells := m.PendingSells
m.PendingSells = nil
2020-08-04 09:03:57 +00:00
2020-08-04 12:04:15 +00:00
for _, sell := range pendingSells {
if err := m.consume(sell); err != nil {
return err
2020-08-04 05:50:27 +00:00
}
}
return nil
2020-08-04 01:47:54 +00:00
}
2020-08-04 12:04:15 +00:00
func (m *StockManager) consume(sell Stock) error {
m.mu.Lock()
defer m.mu.Unlock()
2020-08-04 01:47:54 +00:00
if len(m.Stocks) == 0 {
2020-08-04 05:50:27 +00:00
m.PendingSells = append(m.PendingSells, sell)
return nil
2020-08-04 01:47:54 +00:00
}
idx := len(m.Stocks) - 1
for ; idx >= 0; idx-- {
stock := m.Stocks[idx]
// find any stock price is lower than the sell trade
if stock.Price >= sell.Price {
continue
}
2020-08-04 09:03:57 +00:00
if zero(stock.Quantity) {
continue
2020-08-04 01:47:54 +00:00
}
2020-08-04 09:03:57 +00:00
delta := stock.Consume(sell.Quantity)
sell.Consume(delta)
m.Stocks[idx] = stock
if zero(sell.Quantity) {
2020-08-04 05:50:27 +00:00
return nil
2020-08-04 01:47:54 +00:00
}
}
idx = len(m.Stocks) - 1
for ; idx >= 0; idx-- {
stock := m.Stocks[idx]
2020-08-04 05:50:27 +00:00
2020-08-04 09:03:57 +00:00
if zero(stock.Quantity) {
continue
2020-08-04 01:47:54 +00:00
}
2020-08-04 09:03:57 +00:00
delta := stock.Consume(sell.Quantity)
sell.Consume(delta)
m.Stocks[idx] = stock
2020-08-11 02:29:17 +00:00
if zero(sell.Quantity) {
return nil
}
2020-08-04 01:47:54 +00:00
}
2020-08-11 02:31:54 +00:00
if sell.Quantity > 0.0 {
2020-08-04 05:50:27 +00:00
m.PendingSells = append(m.PendingSells, sell)
2020-08-04 01:47:54 +00:00
}
return nil
}
2020-08-04 11:05:20 +00:00
func (m *StockManager) AddTrades(trades []types.Trade) (checkpoints []int, err error) {
2020-08-04 01:47:54 +00:00
feeSymbol := strings.HasPrefix(m.Symbol, m.TradingFeeCurrency)
for idx, trade := range trades {
// for other market trades
// convert trading fee trades to sell trade
if trade.Symbol != m.Symbol {
if feeSymbol && trade.FeeCurrency == m.TradingFeeCurrency {
trade.Symbol = m.Symbol
trade.IsBuyer = false
trade.Quantity = trade.Fee
trade.Fee = 0.0
}
}
2020-08-04 09:03:57 +00:00
if trade.Symbol != m.Symbol {
continue
}
if trade.IsBuyer {
if idx > 0 && len(m.Stocks) == 0 {
checkpoints = append(checkpoints, idx)
}
stock := toStock(trade)
2020-08-04 12:04:15 +00:00
if err := m.stock(stock); err != nil {
2020-08-04 09:03:57 +00:00
return checkpoints, err
}
} else {
stock := toStock(trade)
2020-08-04 12:04:15 +00:00
if err := m.consume(stock); err != nil {
2020-08-04 09:03:57 +00:00
return checkpoints, err
2020-08-04 01:47:54 +00:00
}
}
}
2020-08-04 09:03:57 +00:00
err = m.flushPendingSells()
2020-08-04 09:10:29 +00:00
m.squash()
2020-08-04 09:03:57 +00:00
return checkpoints, err
2020-08-04 01:47:54 +00:00
}
func toStock(trade types.Trade) Stock {
if strings.HasPrefix(trade.Symbol, trade.FeeCurrency) {
if trade.IsBuyer {
trade.Quantity -= trade.Fee
} else {
trade.Quantity += trade.Fee
}
2020-08-04 09:03:57 +00:00
trade.Fee = 0.0
2020-08-04 01:47:54 +00:00
}
return Stock(trade)
}