-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
stock_broker.go
76 lines (64 loc) · 1.75 KB
/
stock_broker.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
package onlinestockbrokeragesystem
import (
"fmt"
"sync"
"sync/atomic"
)
type StockBroker struct {
accounts map[string]*Account
stocks map[string]*Stock
orderQueue chan Order
accountIDCount int64
mu sync.RWMutex
}
var (
instance *StockBroker
once sync.Once
)
func GetStockBroker() *StockBroker {
once.Do(func() {
instance = &StockBroker{
accounts: make(map[string]*Account),
stocks: make(map[string]*Stock),
orderQueue: make(chan Order, 100), // Buffered channel for orders
}
go instance.processOrders() // Start order processing goroutine
})
return instance
}
func (sb *StockBroker) CreateAccount(user *User, initialBalance float64) {
sb.mu.Lock()
defer sb.mu.Unlock()
accountID := sb.generateAccountID()
account := NewAccount(accountID, user, initialBalance)
sb.accounts[accountID] = account
}
func (sb *StockBroker) GetAccount(accountID string) *Account {
sb.mu.RLock()
defer sb.mu.RUnlock()
return sb.accounts[accountID]
}
func (sb *StockBroker) AddStock(stock *Stock) {
sb.mu.Lock()
defer sb.mu.Unlock()
sb.stocks[stock.Symbol] = stock
}
func (sb *StockBroker) GetStock(symbol string) *Stock {
sb.mu.RLock()
defer sb.mu.RUnlock()
return sb.stocks[symbol]
}
func (sb *StockBroker) PlaceOrder(order Order) {
sb.orderQueue <- order
}
func (sb *StockBroker) processOrders() {
for order := range sb.orderQueue {
if err := order.Execute(); err != nil {
fmt.Printf("Order failed: %v\n", err)
}
}
}
func (sb *StockBroker) generateAccountID() string {
id := atomic.AddInt64(&sb.accountIDCount, 1)
return fmt.Sprintf("A%03d", id)
}