-
-
Notifications
You must be signed in to change notification settings - Fork 274
/
cost_distribution.go
248 lines (198 loc) · 4.87 KB
/
cost_distribution.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package accounting
import (
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"github.com/c9s/bbgo/pkg/types"
)
func zero(a float64) bool {
return int(math.Round(a*1e8)) == 0
}
func round(a float64) float64 {
return math.Round(a*1e8) / 1e8
}
type Stock types.Trade
func (stock *Stock) String() string {
return fmt.Sprintf("%f (%f)", stock.Price, stock.Quantity)
}
func (stock *Stock) Consume(quantity float64) float64 {
q := math.Min(stock.Quantity, quantity)
stock.Quantity = round(stock.Quantity - q)
return q
}
type StockSlice []Stock
func (slice StockSlice) QuantityBelowPrice(price float64) (quantity float64) {
for _, stock := range slice {
if stock.Price < price {
quantity += stock.Quantity
}
}
return round(quantity)
}
func (slice StockSlice) Quantity() (total float64) {
for _, stock := range slice {
total += stock.Quantity
}
return round(total)
}
type StockDistribution struct {
mu sync.Mutex
Symbol string
TradingFeeCurrency string
Stocks StockSlice
PendingSells StockSlice
}
type DistributionStats struct {
PriceLevels []string `json:"priceLevels"`
TotalQuantity float64 `json:"totalQuantity"`
Quantities map[string]float64 `json:"quantities"`
Stocks map[string]StockSlice `json:"stocks"`
}
func (m *StockDistribution) DistributionStats(level int) *DistributionStats {
var d = DistributionStats{
Quantities: map[string]float64{},
Stocks: map[string]StockSlice{},
}
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)
priceLevel := math.Floor(stock.Price/div) * div
key := strconv.FormatFloat(priceLevel, 'f', 2, 64)
d.TotalQuantity += stock.Quantity
d.Stocks[key] = append(d.Stocks[key], stock)
d.Quantities[key] += stock.Quantity
}
var priceLevels []float64
for priceString := range d.Stocks {
price, _ := strconv.ParseFloat(priceString, 32)
priceLevels = append(priceLevels, price)
}
sort.Float64s(priceLevels)
for _, price := range priceLevels {
d.PriceLevels = append(d.PriceLevels, strconv.FormatFloat(price, 'f', 2, 64))
}
sort.Float64s(priceLevels)
return &d
}
func (m *StockDistribution) stock(stock Stock) error {
m.mu.Lock()
m.Stocks = append(m.Stocks, stock)
m.mu.Unlock()
return m.flushPendingSells()
}
func (m *StockDistribution) squash() {
m.mu.Lock()
defer m.mu.Unlock()
var squashed StockSlice
for _, stock := range m.Stocks {
if !zero(stock.Quantity) {
squashed = append(squashed, stock)
}
}
m.Stocks = squashed
}
func (m *StockDistribution) flushPendingSells() error {
if len(m.Stocks) == 0 || len(m.PendingSells) == 0 {
return nil
}
pendingSells := m.PendingSells
m.PendingSells = nil
for _, sell := range pendingSells {
if err := m.consume(sell); err != nil {
return err
}
}
return nil
}
func (m *StockDistribution) consume(sell Stock) error {
m.mu.Lock()
defer m.mu.Unlock()
if len(m.Stocks) == 0 {
m.PendingSells = append(m.PendingSells, sell)
return nil
}
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
}
if zero(stock.Quantity) {
continue
}
delta := stock.Consume(sell.Quantity)
sell.Consume(delta)
m.Stocks[idx] = stock
if zero(sell.Quantity) {
return nil
}
}
idx = len(m.Stocks) - 1
for ; idx >= 0; idx-- {
stock := m.Stocks[idx]
if zero(stock.Quantity) {
continue
}
delta := stock.Consume(sell.Quantity)
sell.Consume(delta)
m.Stocks[idx] = stock
if zero(sell.Quantity) {
return nil
}
}
if sell.Quantity > 0.0 {
m.PendingSells = append(m.PendingSells, sell)
}
return nil
}
func (m *StockDistribution) AddTrades(trades []types.Trade) (checkpoints []int, err error) {
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
}
}
if trade.Symbol != m.Symbol {
continue
}
if trade.IsBuyer {
if idx > 0 && len(m.Stocks) == 0 {
checkpoints = append(checkpoints, idx)
}
stock := toStock(trade)
if err := m.stock(stock); err != nil {
return checkpoints, err
}
} else {
stock := toStock(trade)
if err := m.consume(stock); err != nil {
return checkpoints, err
}
}
}
err = m.flushPendingSells()
m.squash()
return checkpoints, err
}
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
}
trade.Fee = 0.0
}
return Stock(trade)
}