-
-
Notifications
You must be signed in to change notification settings - Fork 274
/
quota.go
67 lines (55 loc) · 1.06 KB
/
quota.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
package bbgo
import (
"sync"
"github.com/c9s/bbgo/pkg/fixedpoint"
)
type Quota struct {
mu sync.Mutex
Available fixedpoint.Value
Locked fixedpoint.Value
}
func (q *Quota) Add(fund fixedpoint.Value) {
q.mu.Lock()
q.Available = q.Available.Add(fund)
q.mu.Unlock()
}
func (q *Quota) Lock(fund fixedpoint.Value) bool {
if fund.Compare(q.Available) > 0 {
return false
}
q.mu.Lock()
q.Available = q.Available.Sub(fund)
q.Locked = q.Locked.Add(fund)
q.mu.Unlock()
return true
}
func (q *Quota) Commit() {
q.mu.Lock()
q.Locked = fixedpoint.Zero
q.mu.Unlock()
}
func (q *Quota) Rollback() {
q.mu.Lock()
q.Available = q.Available.Add(q.Locked)
q.Locked = fixedpoint.Zero
q.mu.Unlock()
}
type QuotaTransaction struct {
mu sync.Mutex
BaseAsset Quota
QuoteAsset Quota
}
func (m *QuotaTransaction) Commit() bool {
m.mu.Lock()
m.BaseAsset.Commit()
m.QuoteAsset.Commit()
m.mu.Unlock()
return true
}
func (m *QuotaTransaction) Rollback() bool {
m.mu.Lock()
m.BaseAsset.Rollback()
m.QuoteAsset.Rollback()
m.mu.Unlock()
return true
}