-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
accounts.go
506 lines (451 loc) · 18.1 KB
/
accounts.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package tdameritrade
import (
"context"
"encoding/json"
"fmt"
"time"
)
type Accounts []*Account
type Account struct {
SecuritiesAccount `json:"securitiesAccount"`
}
type _Instrument Instrument
type Instrument struct {
AssetType string `json:"assetType"`
Data interface{}
}
type OptionDeliverable struct {
Symbol string `json:"symbol"`
DeliverableUnits float64 `json:"deliverableUnits"`
CurrencyType string `json:"currencyType"`
AssetType string `json:"assetType"`
}
type OptionA struct {
Cusip string `json:"cusip,omitempty"`
Symbol string `json:"symbol"`
Description string `json:"description,omitempty"`
Type string `json:"type"`
PutCall string `json:"putCall"`
UnderlyingSymbol string `json:"underlyingSymbol"`
OptionMultiplier float64 `json:"optionMultiplier"`
OptionDeliverables []*OptionDeliverable `json:"optionDeliverables"`
}
type MutualFund struct {
Cusip string `json:"cusip,omitempty"`
Symbol string `json:"symbol"`
Description string `json:"description,omitempty"`
Type string `json:"type"` //"'NOT_APPLICABLE' or 'OPEN_END_NON_TAXABLE' or 'OPEN_END_TAXABLE' or 'NO_LOAD_NON_TAXABLE' or 'NO_LOAD_TAXABLE'"
}
type CashEquivalent struct {
Cusip string `json:"cusip,omitempty"`
Symbol string `json:"symbol"`
Description string `json:"description,omitempty"`
Type string `json:"type"` //"'SAVINGS' or 'MONEY_MARKET_FUND'"
}
type Equity struct {
Cusip string `json:"cusip,omitempty"`
Symbol string `json:"symbol"`
Description string `json:"description,omitempty"`
}
type FixedIncome struct {
Cusip string `json:"cusip"`
Symbol string `json:"symbol"`
Description string `json:"description"`
MaturityDate string `json:"maturityDate"`
VariableRate float64 `json:"variableRate"`
Factor float64 `json:"factor"`
}
type OrderActivity struct {
ActivityType string `json:"activityType"`
ActivityId int64 `json:"activityId"`
ExecutionType string `json:"executionType"`
Quantity float64 `json:"quantity"`
OrderRemainingQuantity float64 `json:"orderRemainingQuantity"`
ExecutionLegs []*ExecutionLeg `json:"executionLegs"`
}
type SecuritiesAccount struct {
Type string `json:"type"`
AccountID string `json:"accountId"`
RoundTrips float64 `json:"roundTrips"`
IsDayTrader bool `json:"isDayTrader"`
IsClosingOnlyRestricted bool `json:"isClosingOnlyRestricted"`
Positions []Position `json:"positions"`
OrderStrategies []OrderStrategy `json:"orderStrategies"`
InitialBalances Balance `json:"initialBalances"`
CurrentBalances Balance `json:"currentBalances"`
ProjectedBalances Balance `json:"projectedBalances"`
}
type Position struct {
ShortQuantity float64 `json:"shortQuantity"`
AveragePrice float64 `json:"averagePrice"`
CurrentDayProfitLoss float64 `json:"currentDayProfitLoss"`
CurrentDayProfitLossPercentage float64 `json:"currentDayProfitLossPercentage"`
LongQuantity float64 `json:"longQuantity"`
SettledLongQuantity float64 `json:"settledLongQuantity"`
SettledShortQuantity float64 `json:"settledShortQuantity"`
AgedQuantity float64 `json:"agedQuantity"`
Instrument Instrument `json:"instrument"`
MarketValue float64 `json:"marketValue"`
}
type OrderStrategy struct {
Session string `json:"session"`
Duration string `json:"duration"`
OrderType string `json:"orderType"`
CancelTime CancelTime `json:"cancelTime"`
ComplexOrderStrategyType string `json:"complexOrderStrategyType"`
Quantity float64 `json:"quantity"`
FilledQuantity float64 `json:"filledQuantity"`
RemainingQuantity float64 `json:"remainingQuantity"`
RequestedDestination string `json:"requestedDestination"`
DestinationLinkName string `json:"destinationLinkName"`
ReleaseTime string `json:"releaseTime"`
StopPrice float64 `json:"stopPrice"`
StopPriceLinkBasis string `json:"stopPriceLinkBasis"`
StopPriceLinkType string `json:"stopPriceLinkType"`
StopPriceOffset float64 `json:"stopPriceOffset"`
StopType string `json:"stopType"`
PriceLinkBasis string `json:"priceLinkBasis"`
PriceLinkType string `json:"priceLinkType"`
Price float64 `json:"price"`
TaxLotMethod string `json:"taxLotMethod"`
OrderLegCollection []OrderLegCollection `json:"orderLegCollection"`
ActivationPrice float64 `json:"activationPrice"`
SpecialInstruction string `json:"specialInstruction"`
OrderStrategyType string `json:"orderStrategyType"`
OrderID int64 `json:"orderId"`
Cancelable bool `json:"cancelable"`
Editable bool `json:"editable"`
Status string `json:"status"`
EnteredTime string `json:"enteredTime"`
CloseTime string `json:"closeTime"`
Tag string `json:"tag"`
AccountID int64 `json:"accountId"`
OrderActivityCollection []OrderActivity `json:"orderActivityCollection"`
ReplacingOrderCollection []struct {
} `json:"replacingOrderCollection"`
ChildOrderStrategies []struct {
} `json:"childOrderStrategies"`
StatusDescription string `json:"statusDescription"`
}
type Balance struct {
AccruedInterest float64 `json:"accruedInterest"`
CashBalance float64 `json:"cashBalance"`
CashReceipts float64 `json:"cashReceipts"`
LongOptionMarketValue float64 `json:"longOptionMarketValue"`
LiquidationValue float64 `json:"liquidationValue"`
LongMarketValue float64 `json:"longMarketValue"`
MoneyMarketFund float64 `json:"moneyMarketFund"`
Savings float64 `json:"savings"`
ShortMarketValue float64 `json:"shortMarketValue"`
PendingDeposits float64 `json:"pendingDeposits"`
CashAvailableForTrading float64 `json:"cashAvailableForTrading"`
CashAvailableForWithdrawal float64 `json:"cashAvailableForWithdrawal"`
CashCall float64 `json:"cashCall"`
LongNonMarginableMarketValue float64 `json:"longNonMarginableMarketValue"`
TotalCash float64 `json:"totalCash"`
ShortOptionMarketValue float64 `json:"shortOptionMarketValue"`
MutualFundValue float64 `json:"mutualFundValue"`
BondValue float64 `json:"bondValue"`
CashDebitCallValue float64 `json:"cashDebitCallValue"`
UnsettledCash float64 `json:"unsettledCash"`
}
type OrderLegCollection struct {
OrderLegType string `json:"orderLegType,omitempty"`
LegID int `json:"legId,omitempty"`
Instrument Instrument `json:"instrument"`
Instruction string `json:"instruction"`
PositionEffect string `json:"positionEffect,omitempty"`
Quantity float64 `json:"quantity"`
QuantityType string `json:"quantityType,omitempty"`
}
type CancelTime struct {
Date string `json:"date,omitempty"`
ShortFormat bool `json:"shortFormat,omitempty"`
}
type Orders []Order
type Order struct {
Session string `json:"session"`
Duration string `json:"duration"`
OrderType string `json:"orderType"`
CancelTime *CancelTime `json:"cancelTime,omitempty"`
ComplexOrderStrategyType string `json:"complexOrderStrategyType,omitempty"`
Quantity float64 `json:"quantity,omitempty"`
FilledQuantity float64 `json:"filledQuantity,omitempty"`
RemainingQuantity float64 `json:"remainingQuantity,omitempty"`
RequestedDestination string `json:"requestedDestination,omitempty"`
DestinationLinkName string `json:"destinationLinkName,omitempty"`
ReleaseTime string `json:"releaseTime,omitempty"`
StopPrice float64 `json:"stopPrice,omitempty"`
StopPriceLinkBasis string `json:"stopPriceLinkBasis,omitempty"`
StopPriceLinkType string `json:"stopPriceLinkType,omitempty"`
StopPriceOffset float64 `json:"stopPriceOffset,omitempty"`
StopType string `json:"stopType,omitempty"`
PriceLinkBasis string `json:"priceLinkBasis,omitempty"`
PriceLinkType string `json:"priceLinkType,omitempty"`
Price float64 `json:"price,omitempty"`
TaxLotMethod string `json:"taxLotMethod,omitempty"`
OrderLegCollection []*OrderLegCollection `json:"orderLegCollection"`
ActivationPrice float64 `json:"activationPrice,omitempty"`
SpecialInstruction string `json:"specialInstruction,omitempty"`
OrderStrategyType string `json:"orderStrategyType"`
OrderID int64 `json:"orderId,omitempty"`
Cancelable bool `json:"cancelable,omitempty"`
Editable bool `json:"editable,omitempty"`
Status string `json:"status,omitempty"`
EnteredTime string `json:"enteredTime,omitempty"`
CloseTime string `json:"closeTime,omitempty"`
Tag string `json:"tag,omitempty"`
AccountID float64 `json:"accountId,omitempty"`
OrderActivityCollection []*Execution `json:"orderActivityCollection,omitempty"`
ReplacingOrderCollection []*Order `json:"replacingOrderCollection,omitempty"`
ChildOrderStrategies []*Order `json:"childOrderStrategies,omitempty"`
StatusDescription string `json:"statusDescription,omitempty"`
}
type ExecutionLeg struct {
LegID int64 `json:"legId"`
Quantity float64 `json:"quantity"`
MismarkedQuantity float64 `json:"mismarkedQuantity"`
Price float64 `json:"price"`
Time string `json:"time"`
}
type Execution struct {
ActivityType string `json:"activityType"` //"'EXECUTION' or 'ORDER_ACTION'",
ExecutionType string `json:"executionType"` //"'FILL'",
Quantity float64 `json:"quantity"`
OrderRemainingQuantity float64 `json:"orderRemainingQuantity"`
ExecutionLegs []*ExecutionLeg `json:"executionLegs"`
}
// AccountsService handles communication with the account related methods of
// the TDAmeritrade API.
//
// TDAmeritrade API docs: https://developer.tdameritrade.com/account-access/apis
type AccountsService struct {
client *Client
}
type AccountOptions struct {
Position bool
Orders bool
}
type OrderParams struct {
MaxResults int
From time.Time
To time.Time
Status string
}
func (i *Instrument) UnmarshalJSON(bs []byte) (err error) {
instrument := _Instrument{}
err = json.Unmarshal(bs, &instrument)
if err != nil {
return err
}
switch instrument.AssetType {
case "EQUITY":
instrument.Data = &Equity{}
case "OPTION":
instrument.Data = &OptionA{}
case "MUTUAL_FUND":
instrument.Data = &MutualFund{}
case "CASH_EQUIVALENT":
instrument.Data = &CashEquivalent{}
case "FIXED_INCOME":
instrument.Data = &FixedIncome{}
default:
return fmt.Errorf("unsupported type %s", instrument.AssetType)
}
err = json.Unmarshal(bs, instrument.Data)
*i = Instrument(instrument)
return err
}
func (i *Instrument) MarshalJSON() ([]byte, error) {
switch data := i.Data.(type) {
case *Equity:
return json.Marshal(&struct {
AssetType string `json:"assetType"`
*Equity
}{
AssetType: i.AssetType,
Equity: data,
})
case *OptionA:
return json.Marshal(&struct {
AssetType string `json:"assetType"`
*OptionA
}{
AssetType: i.AssetType,
OptionA: data,
})
case *MutualFund:
return json.Marshal(&struct {
AssetType string `json:"assetType"`
*MutualFund
}{
AssetType: i.AssetType,
MutualFund: data,
})
case *CashEquivalent:
return json.Marshal(&struct {
AssetType string `json:"assetType"`
*CashEquivalent
}{
AssetType: i.AssetType,
CashEquivalent: data,
})
case *FixedIncome:
return json.Marshal(&struct {
AssetType string `json:"assetType"`
*FixedIncome
}{
AssetType: i.AssetType,
FixedIncome: data,
})
default:
return nil, fmt.Errorf("unexpected type %T: %v", data, data)
}
}
func (s *AccountsService) GetAccounts(ctx context.Context, opts *AccountOptions) (*Accounts, *Response, error) {
u := "accounts"
if opts != nil {
if opts.Position {
u = fmt.Sprintf("%s?fields=%s", u, "positions")
}
if opts.Orders {
u = fmt.Sprintf("%s,%s", u, "orders")
}
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
accounts := new(Accounts)
resp, err := s.client.Do(ctx, req, accounts)
if err != nil {
return nil, resp, err
}
return accounts, resp, err
}
func (s *AccountsService) GetAccount(ctx context.Context, accountID string, opts *AccountOptions) (*Account, *Response, error) {
u := fmt.Sprintf("accounts/%s", accountID)
if opts != nil {
if opts.Position {
u = fmt.Sprintf("%s?fields=%s", u, "positions")
}
if opts.Orders {
u = fmt.Sprintf("%s,%s", u, "orders")
}
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
account := new(Account)
resp, err := s.client.Do(ctx, req, account)
if err != nil {
return nil, resp, err
}
return account, resp, err
}
func (s *AccountsService) PlaceOrder(ctx context.Context, accountID string, order *Order) (*Response, error) {
u := fmt.Sprintf("accounts/%s/orders", accountID)
if order == nil {
return nil, fmt.Errorf("order is nil")
}
req, err := s.client.NewRequest("POST", u, order)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) CancelOrder(ctx context.Context, accountID, orderID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/orders/%s", accountID, orderID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) ReplaceOrder(ctx context.Context, accountID string, orderID string, order *Order) (*Response, error) {
u := fmt.Sprintf("accounts/%s/orders/%s", accountID, orderID)
if order == nil {
return nil, fmt.Errorf("order is nil")
}
req, err := s.client.NewRequest("PUT", u, order)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) GetOrder(ctx context.Context, accountID, orderID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/orders/%s", accountID, orderID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) GetOrderByPath(ctx context.Context, accountID string, orderParams *OrderParams) (*Orders, *Response, error) {
u := fmt.Sprintf("accounts/%s/orders", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
orders := new(Orders)
resp, err := s.client.Do(ctx, req, orders)
if err != nil {
return nil, resp, err
}
return orders, resp, nil
}
func (s *AccountsService) GetOrderByQuery(ctx context.Context, accountID string, orderParams *OrderParams) (*Orders, *Response, error) {
u := fmt.Sprintf("accounts/%s/orders", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
orders := new(Orders)
resp, err := s.client.Do(ctx, req, orders)
if err != nil {
return nil, resp, err
}
return orders, resp, nil
}
func (s *AccountsService) CreateSavedOrder(ctx context.Context, accountID string, order *Order) (*Response, error) {
u := fmt.Sprintf("accounts/%s/savedorders", accountID)
if order == nil {
return nil, fmt.Errorf("order is nil")
}
req, err := s.client.NewRequest("POST", u, order)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) DeleteSavedOrder(ctx context.Context, accountID, savedOrderID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/savedorders/%s", accountID, savedOrderID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) GetSavedOrder(ctx context.Context, accountID, savedOrderID string, orderParams *OrderParams) (*Response, error) {
u := fmt.Sprintf("accounts/%s/savedorders/%s", accountID, savedOrderID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
func (s *AccountsService) ReplaceSavedOrder(ctx context.Context, accountID, savedOrderID string, order *Order) (*Response, error) {
u := fmt.Sprintf("accounts/%s/savedorders/%s", accountID, savedOrderID)
if order == nil {
return nil, fmt.Errorf("order is nil")
}
req, err := s.client.NewRequest("PUT", u, order)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return s.client.Do(ctx, req, nil)
}