2020-11-23 08:47:36 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Quota struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
Available fixedpoint.Value
|
|
|
|
Locked fixedpoint.Value
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// Add adds the fund to the available quota
|
2020-11-23 08:47:36 +00:00
|
|
|
func (q *Quota) Add(fund fixedpoint.Value) {
|
|
|
|
q.mu.Lock()
|
2022-02-03 11:19:56 +00:00
|
|
|
q.Available = q.Available.Add(fund)
|
2020-11-23 08:47:36 +00:00
|
|
|
q.mu.Unlock()
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// Lock locks the fund from the available quota
|
|
|
|
// returns true if the fund is locked successfully
|
|
|
|
// returns false if the fund is not enough
|
2020-11-23 08:47:36 +00:00
|
|
|
func (q *Quota) Lock(fund fixedpoint.Value) bool {
|
2022-02-03 11:19:56 +00:00
|
|
|
if fund.Compare(q.Available) > 0 {
|
2020-11-23 08:47:36 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
q.mu.Lock()
|
2022-02-03 11:19:56 +00:00
|
|
|
q.Available = q.Available.Sub(fund)
|
|
|
|
q.Locked = q.Locked.Add(fund)
|
2020-11-23 08:47:36 +00:00
|
|
|
q.mu.Unlock()
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// Commit commits the locked fund
|
2020-11-23 08:47:36 +00:00
|
|
|
func (q *Quota) Commit() {
|
|
|
|
q.mu.Lock()
|
2022-02-03 11:19:56 +00:00
|
|
|
q.Locked = fixedpoint.Zero
|
2020-11-23 08:47:36 +00:00
|
|
|
q.mu.Unlock()
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// Rollback rolls back the locked fund
|
|
|
|
// this will move the locked fund to the available quota
|
2020-11-23 08:47:36 +00:00
|
|
|
func (q *Quota) Rollback() {
|
|
|
|
q.mu.Lock()
|
2022-02-03 11:19:56 +00:00
|
|
|
q.Available = q.Available.Add(q.Locked)
|
|
|
|
q.Locked = fixedpoint.Zero
|
2020-11-23 08:47:36 +00:00
|
|
|
q.mu.Unlock()
|
|
|
|
}
|
|
|
|
|
2024-09-02 19:26:47 +00:00
|
|
|
func (q *Quota) String() string {
|
|
|
|
q.mu.Lock()
|
|
|
|
defer q.mu.Unlock()
|
|
|
|
|
|
|
|
return q.Locked.String() + "/" + q.Available.String()
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// QuotaTransaction is a transactional quota manager
|
2020-11-23 08:47:36 +00:00
|
|
|
type QuotaTransaction struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
BaseAsset Quota
|
|
|
|
QuoteAsset Quota
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// Commit commits the transaction
|
2020-11-23 08:47:36 +00:00
|
|
|
func (m *QuotaTransaction) Commit() bool {
|
|
|
|
m.mu.Lock()
|
|
|
|
m.BaseAsset.Commit()
|
|
|
|
m.QuoteAsset.Commit()
|
|
|
|
m.mu.Unlock()
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2024-09-02 14:18:13 +00:00
|
|
|
// Rollback rolls back the transaction
|
2020-11-23 08:47:36 +00:00
|
|
|
func (m *QuotaTransaction) Rollback() bool {
|
|
|
|
m.mu.Lock()
|
|
|
|
m.BaseAsset.Rollback()
|
|
|
|
m.QuoteAsset.Rollback()
|
|
|
|
m.mu.Unlock()
|
|
|
|
return true
|
|
|
|
}
|