-
Notifications
You must be signed in to change notification settings - Fork 1
/
commands_buy.go
144 lines (120 loc) · 3.44 KB
/
commands_buy.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
package main
import (
"fmt"
"strconv"
"time"
"github.com/distributeddesigns/currency"
types "github.com/distributeddesigns/shared_types"
)
type buyCmd struct {
id uint64
userID string
stock string
amount currency.Currency
purchaseAmount currency.Currency
quantityToBuy uint64
expiresAt time.Time
}
func parseBuyCmd(parts []string) buyCmd {
if len(parts) != 5 {
abortTx("BUY needs 5 parts")
}
id, err := strconv.ParseUint(parts[0], 10, 64)
abortTxOnError(err, "Could not parse ID")
amount, err := currency.NewFromString(parts[4])
abortTxOnError(err, "Could not parse amount in transaction")
return buyCmd{
id: id,
userID: parts[2],
stock: parts[3],
amount: amount,
}
}
func (b buyCmd) Name() string {
return fmt.Sprintf("[%d] BUY", b.id)
}
func (b buyCmd) ToAuditEvent() types.AuditEvent {
xmlElement := fmt.Sprintf(`
<userCommand>
<timestamp>%d</timestamp>
<server>%s</server>
<transactionNum>%d</transactionNum>
<command>BUY</command>
<username>%s</username>
<stockSymbol>%s</stockSymbol>
<funds>%.02f</funds>
</userCommand>`,
time.Now().UnixNano()/1e6, redisBaseKey, b.id, b.userID, b.stock, b.amount.ToFloat(),
)
return types.AuditEvent{
UserID: b.userID,
ID: b.id,
EventType: "command",
Content: xmlElement,
}
}
func (b buyCmd) Execute() {
abortTxIfNoAccount(b.userID)
acct := accountStore[b.userID]
acct.Lock()
defer acct.Unlock()
// Check to make sure use has enough funds for buy.
// Even though this check locks the user account for the duration of a
// quote retrieval it passes back an error message that is most informative
// for the user.
if acct.balance.ToFloat() < b.amount.ToFloat() {
abortTx(b.Name() + " Insufficient funds")
}
// Get a quote for the stock
qr := types.QuoteRequest{
Stock: b.stock,
UserID: b.userID,
AllowCache: true,
ID: b.id,
}
q := getQuote(qr)
// Get a fresh quote if quote is about to expire
quoteTTL := q.Timestamp.Add(time.Second*60).Unix() - time.Now().Unix()
if quoteTTL < config.QuotePolicy.UseInBuySell {
consoleLog.Info(" [!] Getting a fresh quote for", b.Name())
qr.AllowCache = false
q = getQuote(qr)
}
// Check if user can buy any stock at quote price
quantityToBuy, purchaseAmount := q.Price.FitsInto(b.amount)
consoleLog.Debugf("Want to buy %d stock", quantityToBuy)
if quantityToBuy < 1 {
abortTx(b.Name() + " Cannot buy less than one stock")
}
// If yes...
// 1. Populate the quantityToBuy, purchaseAmount and expiresAt fields
// 2. Remove the funds from the user
// 3. Add the buyCmd to the account's pendingBuys stack
b.quantityToBuy = uint64(quantityToBuy)
b.purchaseAmount = purchaseAmount
b.expiresAt = q.Timestamp.Add(time.Second * 60)
err := acct.RemoveFunds(purchaseAmount)
abortTxOnError(err, "This should be impossible!")
acct.pendingBuys.Push(b)
acct.AddSummaryItem("Finished " + b.Name())
consoleLog.Notice(" [✔] Finished", b.Name())
}
func (b buyCmd) Commit() {
consoleLog.Debug("Commiting", b.Name())
acct := accountStore[b.userID]
acct.Lock()
acct.AddStock(b.stock, b.quantityToBuy)
acct.AddSummaryItem("Commited " + b.Name())
acct.Unlock()
}
func (b buyCmd) RollBack() {
consoleLog.Debug("Rolling back", b.Name())
acct := accountStore[b.userID]
acct.Lock()
acct.AddFunds(b.purchaseAmount)
acct.AddSummaryItem("Rolled back " + b.Name())
acct.Unlock()
}
func (b buyCmd) IsExpired() bool {
return time.Now().After(b.expiresAt)
}