-
Notifications
You must be signed in to change notification settings - Fork 2
/
schedule.go
312 lines (249 loc) · 6.19 KB
/
schedule.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package main
import (
"errors"
"fmt"
"math"
"time"
exchange "github.com/blampe/go-coinbase-exchange"
"go.uber.org/zap"
)
var skippedForDebug = errors.New("Skipping because trades are not enabled")
type gdaxSchedule struct {
logger *zap.SugaredLogger
client *exchange.Client
debug bool
usd float64
every time.Duration
until time.Time
autoFund bool
coin string
}
func newGdaxSchedule(
c *exchange.Client,
l *zap.SugaredLogger,
debug bool,
autoFund bool,
usd float64,
every time.Duration,
until time.Time,
coin string,
) (*gdaxSchedule, error) {
schedule := gdaxSchedule{
logger: l,
client: c,
debug: debug,
usd: usd,
every: every,
until: until,
autoFund: autoFund,
coin: coin,
}
minimum, err := schedule.minimumUSDPurchase()
if err != nil {
return nil, err
}
if schedule.usd == 0.0 {
schedule.usd = minimum + 0.1
}
if schedule.usd < minimum {
return nil, errors.New(fmt.Sprintf(
"GDAX's minimum %s trade amount is $%.02f, but you're trying to purchase $%f",
schedule.coin, minimum, schedule.usd,
))
}
// GDAX has a limit of 8 decimal places.
schedule.usd = roundFloat(schedule.usd, 8)
return &schedule, nil
}
func roundFloat(f float64, places int) (float64) {
shift := math.Pow(10, float64(places))
return math.Floor(f * shift + .5) / shift;
}
// Sync initiates trades & funding with a DCA strategy.
func (s *gdaxSchedule) Sync() error {
now := time.Now()
until := s.until
if until.IsZero() {
until = time.Now()
}
if now.After(until) {
return errors.New("Deadline has passed, not taking any action")
}
s.logger.Infow("Dollar cost averaging",
"USD", s.usd,
"every", every,
"until", until.String(),
)
if time, err := s.timeToPurchase(); err != nil {
return err
} else if !time {
return errors.New("Detected a recent purchase, waiting for next purchase window")
}
if funded, err := s.sufficientUsdAvailable(); err != nil {
return err
} else if !funded {
needed, err := s.additionalUsdNeeded()
if err != nil {
return err
}
if needed == 0 {
return errors.New("Not enough available funds, wait for transfers to settle")
}
if needed > 0 {
s.logger.Infow(
"Insufficient funds",
"needed", needed,
)
if s.autoFund {
s.logger.Infow(
"TODO: Creating a transfer request for $%.02f",
"needed", needed,
)
s.makeDeposit(needed)
}
}
return nil
}
s.logger.Infow(
"Placing an order",
"coin", s.coin,
"purchaseCurrency", "USD",
"purchaseAmount", s.usd,
)
productId := s.coin + "-" + "USD"
if err := s.makePurchase(productId); err != nil {
s.logger.Warn(err)
}
return nil
}
func (s *gdaxSchedule) minimumUSDPurchase() (float64, error) {
productId := s.coin + "-" + "USD"
ticker, err := s.client.GetTicker(productId)
if err != nil {
return 0, err
}
products, err := s.client.GetProducts()
if err != nil {
return 0, err
}
for _, p := range products {
if p.BaseCurrency == s.coin {
return math.Max(p.BaseMinSize * ticker.Price, 1.0), nil
}
}
return 0, errors.New(productId + " not found")
}
func (s *gdaxSchedule) timeToPurchase() (bool, error) {
timeSinceLastPurchase, err := s.timeSinceLastPurchase()
if err != nil {
return false, err
}
if timeSinceLastPurchase.Seconds() < s.every.Seconds() {
// We purchased something recently, so hang tight.
return false, nil
}
return true, nil
}
func (s *gdaxSchedule) sufficientUsdAvailable() (bool, error) {
usdAccount, err := s.accountFor("USD")
if err != nil {
return false, err
}
return (usdAccount.Available >= s.usd), nil
}
func (s *gdaxSchedule) additionalUsdNeeded() (float64, error) {
if funded, err := s.sufficientUsdAvailable(); err != nil {
return 0, err
} else if funded {
return 0, nil
}
usdAccount, err := s.accountFor("USD")
if err != nil {
return 0, nil
}
dollarsNeeded := s.usd - usdAccount.Available
if dollarsNeeded < 0 {
return 0, errors.New("Invalid account balance")
}
// Dang, we don't have enough funds. Let's see if money is on the way.
var transfers []exchange.Transfer
cursor := s.client.ListAccountTransfers(usdAccount.Id)
dollarsInbound := 0.0
for cursor.HasMore {
if err := cursor.NextPage(&transfers); err != nil {
return 0, err
}
for _, t := range transfers {
unprocessed := (t.ProcessedAt.Time() == time.Time{})
notCanceled := (t.CanceledAt.Time() == time.Time{})
// This transfer is stil pending, so count it.
if unprocessed && notCanceled {
dollarsInbound += t.Amount
}
}
}
// If our incoming transfers don't cover our purchase need then we'll need
// to cover that with an additional deposit.
return math.Max(dollarsNeeded-dollarsInbound, 0), nil
}
func (s *gdaxSchedule) timeSinceLastPurchase() (time.Duration, error) {
var transactions []exchange.LedgerEntry
account, err := s.accountFor(s.coin)
if err != nil {
return 0, err
}
cursor := s.client.ListAccountLedger(account.Id)
lastTransactionTime := time.Time{}
now := time.Now()
for cursor.HasMore {
if err := cursor.NextPage(&transactions); err != nil {
return 0, err
}
// Consider trade transactions
for _, t := range transactions {
if t.CreatedAt.Time().After(lastTransactionTime) && t.Type == "match" {
lastTransactionTime = t.CreatedAt.Time()
}
}
}
return now.Sub(lastTransactionTime), nil
}
func (s *gdaxSchedule) makePurchase(productId string) error {
if s.debug {
return skippedForDebug
}
order, err := s.client.CreateOrder(
&exchange.Order{
ProductId: productId,
Type: "market",
Side: "buy",
Funds: s.usd,
},
)
if err != nil {
return err
}
s.logger.Infow(
"Placed order",
"orderId", order.Id,
)
return nil
}
func (s *gdaxSchedule) makeDeposit(amount float64) error {
// TODO: Initiate funding for this amount. Need to add
// /deposits/payment-method support to client and
// client.CreateTransfer(...)
return skippedForDebug
}
func (s *gdaxSchedule) accountFor(currencyCode string) (*exchange.Account, error) {
accounts, err := s.client.GetAccounts()
if err != nil {
return nil, err
}
for _, a := range accounts {
if a.Currency == currencyCode {
return &a, nil
}
}
return nil, errors.New(fmt.Sprintf("No %s wallet on this account", currencyCode))
}