forked from gofinance/ib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_account_manager.go
89 lines (78 loc) · 2.1 KB
/
single_account_manager.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
package ib
import (
"fmt"
)
// SingleAccountManager tracks the account's values and portfolio.
type SingleAccountManager struct {
*AbstractManager
id int64
values map[AccountValueKey]AccountValue
portfolio map[PortfolioValueKey]PortfolioValue
loaded bool
}
// NewSingleAccountManager .
func NewSingleAccountManager(e *Engine) (*SingleAccountManager, error) {
am, err := NewAbstractManager(e)
if err != nil {
return nil, err
}
s := &SingleAccountManager{
AbstractManager: am,
id: UnmatchedReplyID,
values: map[AccountValueKey]AccountValue{},
portfolio: map[PortfolioValueKey]PortfolioValue{},
}
go s.startMainLoop(s.preLoop, s.receive, s.preDestroy)
return s, nil
}
func (s *SingleAccountManager) preLoop() error {
s.eng.Subscribe(s.rc, s.id)
return s.eng.Send(&RequestAccountUpdates{Subscribe: true, AccountCode: "primary"})
}
func (s *SingleAccountManager) receive(r Reply) (UpdateStatus, error) {
switch r := r.(type) {
case *ErrorMessage:
if r.SeverityWarning() {
return UpdateFalse, nil
}
return UpdateTrue, r.Error()
case *AccountUpdateTime:
if s.loaded {
return UpdateTrue, nil
}
return UpdateFalse, nil
case *AccountValue:
s.values[r.Key] = *r
if s.loaded {
return UpdateTrue, nil
}
return UpdateFalse, nil
case *PortfolioValue:
s.portfolio[r.Key] = *r
if s.loaded {
return UpdateTrue, nil
}
return UpdateFalse, nil
case *AccountDownloadEnd:
s.loaded = true
return UpdateTrue, nil
default:
return UpdateTrue, fmt.Errorf("Unexpected type %v", r)
}
}
func (s *SingleAccountManager) preDestroy() {
s.eng.Send(&RequestAccountUpdates{Subscribe: false, AccountCode: "primary"})
s.eng.Unsubscribe(s.rc, s.id)
}
// Values returns the most recent snapshot of account information.
func (s *SingleAccountManager) Values() map[AccountValueKey]AccountValue {
s.rwm.RLock()
defer s.rwm.RUnlock()
return s.values
}
// Portfolio returns the most recent snapshot of account portfolio.
func (s *SingleAccountManager) Portfolio() map[PortfolioValueKey]PortfolioValue {
s.rwm.RLock()
defer s.rwm.RUnlock()
return s.portfolio
}