-
Notifications
You must be signed in to change notification settings - Fork 4
/
accounts-trading.go
675 lines (618 loc) · 18.4 KB
/
accounts-trading.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*
Copyright (C) 2025 github.com/go-schwab
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see
<https://www.gnu.org/licenses/>.
*/
package trader
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/bytedance/sonic"
)
var (
accountEndpoint string = "https://api.schwabapi.com/trader/v1"
// Accounts
endpointAccountNumbers string = accountEndpoint + "/accounts/accountNumbers"
endpointAccounts string = accountEndpoint + "/accounts"
endpointAccount string = accountEndpoint + "/accounts/%s"
// endpointUserPreference string = accountEndpoint + "/userPreference"
// Orders
endpointOrders string = accountEndpoint + "/orders"
endpointAccountOrders string = accountEndpoint + "/accounts/%s/orders"
endpointAccountOrder string = accountEndpoint + "/accounts/%s/orders/%s"
// endpointPreviewOrder string = accountEndpoint + "/accounts/%s/previewOrder"
// Transactions
// endpointTransactions string = accountEndpoint + "/accounts/%s/transactions"
endpointTransaction string = accountEndpoint + "/accounts/%s/transactions/%s"
)
type Transaction struct {
ActivityId int
Time string
User User
Description string
AccountNumber string
Type string
Status string
SubAccount string
TradeDate string
SettlementDate string
PositionId int
OrderId int
NetAmount int
ActivityType string
TransferItems TransferItems
}
type User struct {
CdDomainId string
Login string
Type string
UserId int
SystemUserName string
FirstName string
LastName string
BrokerRepCode string
}
type TransferItems struct {
Instrument InstrumentRef
Amount int
Cost int
Price int
FeeType string
PositionEffect string
}
type InstrumentRef struct {
Cusip string
Symbol string
Description string
InstrumentId int
NetChange int
Type string
}
type AccountNumbers struct {
AccountNumber string
HashValue string
}
type Account struct {
SecuritiesAccount SecuritiesAccount
AggregatedBalance AggregatedBalance
}
type SecuritiesAccount struct {
Type string
AccountNumber string
RoundTrips int
IsDayTrader bool
IsClosingOnlyRestricted bool
PFCBFlag bool
Positions []Position
InitialBalances InitialBalance
CurrentBalances CurrentBalance
ProjectedBalances ProjectedBalance
}
type Position struct {
ShortQuantity float64
AveragePrice float64
CurrentDayProfitLoss float64
CurrentDayProfitLossPercentage float64
LongQuantity float64
SettledLongQuantity float64
SettledShortQuantity float64
AgedQuantity float64
Instrument AccountInstrument
MarketValue float64
MaintenanceRequirement float64
AverageLongPrice float64
AverageShortPrice float64
TaxLotAverageLongPrice float64
TaxLotAverageShortPrice float64
LongOpenProfitLoss float64
ShortOpenProfitLoss float64
PreviousSessionLongQuantity float64
PreviousSessionShortQuantity float64
CurrentDayCost float64
}
type AccountInstrument struct {
AssetType string
Cusip string
Symbol string
Description string
InstrumentID int
NetChange float64
}
type InitialBalance struct {
AccruedInterest float64
AvailableFundsNonMarginableTrade float64
BondValue float64
BuyingPower float64
CashBalance float64
CashAvailableForTrading float64
CashReceipts float64
DayTradingBuyingPower float64
DayTradingBuyingPowerCall float64
DayTradingEquityCall float64
Equity float64
EquityPercentage float64
LiquidationValue float64
LongMarginValue float64
LongOptionMarketValue float64
LongStockValue float64
MaintenanceCall float64
MaintenanceRequirement float64
Margin float64
MarginEquity float64
MoneyMarketFund float64
MutualFundValue float64
RegTCall float64
ShortMarginValue float64
ShortOptionMarketValue float64
ShortStockValue float64
TotalCash float64
IsInCall bool
UnsettledCash float64
PendingDeposits float64
MarginBalance float64
ShortBalance float64
AccountValue float64
}
/*type CurrentBalance struct {
AvailableFunds float64
AvailableFundsNonMarginableTrade float64
BuyingPower float64
BuyingPowerNonMarginableTrade float64
DayTradingBuyingPower float64
DayTradingBuyingPowerCall float64
Equity float64
EquityPercentage float64
LongMarginValue float64
MaintenanceCall float64
MaintenanceRequirement float64
MarginBalance float64
RegTCall float64
ShortBalance float64
ShortMarginValue float64
SMA float64
IsInCall float64
StockBuyingPower float64
OptionBuyingPower float64
}*/
type CurrentBalance struct {
AccruedInterest float64
CashBalance float64
CashReceipts float64
LongOptionMarketValue float64
LiquidationValue float64
LongMarketValue float64
MoneyMarketFund float64
Savings float64
ShortMarketValue float64
PendingDeposits float64
MutualFundValues float64
BondValue float64
ShortOptionMarketValue float64
AvailableFunds float64
AvailableFundsNonMarginableTrade float64
BuyingPower float64
BuyingPowerNonMarginableTrade float64
DayTradingBuyingPower float64
Equity float64
EquityPercentage float64
LongMarginValue float64
MaintenanceCall float64
MaintenanceRequirement float64
MarginBalance float64
RegTCall float64
ShortBalance float64
ShortMarginValue float64
SMA float64
}
type ProjectedBalance struct {
AvailableFunds float64
AvailableFundsNonMarginableTrade float64
BuyingPower float64
BuyingPowerNonMarginableTrade float64
DayTradingBuyingPower float64
DayTradingBuyingPowerCall float64
Equity float64
EquityPercentage float64
LongMarginValue float64
MaintenanceCall float64
MaintenanceRequirement float64
MarginBalance float64
RegTCall float64
ShortBalance float64
ShortMarginValue float64
SMA float64
IsInCall bool
StockBuyingPower float64
OptionBuyingPower float64
}
type AggregatedBalance struct {
CurrentLiquidationValue float64
LiquidationValue float64
}
type FullOrder struct {
Session string
Duration string
OrderType string
CancelTime string
ComplexOrderStrategyType string
Quantity int
FilledQuantity int
RemainingQuantity int
RequestedDestination string
DestinationLinkName string
ReleaseTime string
StopPrice int
StopPriceLinkBasis string
StopPriceLinkType string
StopPriceOffset int
StopType string
Price string
TaxLotMethod string
OrderLegCollection []FullOrderLeg
ActivationPrice int
SpecialInstruction string
OrderStrategyType string
OrderId int
Cancelable bool
Editable bool
Status string
EnteredTime string
CloseTime string
Tag string
AccountNumber int
OrderActivityCollection []FullOrderActivity
ReplacingOrderCollection string
ChildOrderStrategies string
StatusDescription string
}
type FullOrderActivity struct {
ActivityType string
ExecutionType string
Quantity int
OrderRemainingQuantity int
ExecutionLegs []FullExecutionLeg
}
type FullExecutionLeg struct {
LegId int
Price int
Quantity int
MismarkedQuantity int
InstrumentId int
Time string
}
type FullOrderLeg struct {
OrderLegType string
LegId int
Instrument InstrumentRef
Instruction string
PositionEffect string
Quantity int
QuantityType string
DivCapGains string
ToSymbol string
}
type SingleLegOrder struct {
OrderType string `default:"MARKET"`
Session string `default:"NORMAL"`
Duration string `default:"DAY"`
Strategy string `default:"SINGLE"`
Instruction string
Quantity float32
Instrument SimpleOrderInstrument
}
type MultiLegOrder struct {
OrderType string // LIMIT, MARKET
Session string // NORMAL
Duration string // DAY
Strategy string // SINGLE
OrderLegCollection []SimpleOrderLeg
}
type SimpleOrderLeg struct {
Instruction string
Quantity float32
Instrument SimpleOrderInstrument
}
type SimpleOrderInstrument struct {
Symbol string
AssetType string // EQUITY
}
type (
SingleLegOrderComposition func(order *SingleLegOrder)
MultiLegSimpleOrderComposition func(order *MultiLegOrder)
)
// Create a new Market order
func CreateSingleLegOrder(opts ...SingleLegOrderComposition) *SingleLegOrder {
order := &SingleLegOrder{OrderType: "MARKET"}
for _, opt := range opts {
opt(order)
}
return order
}
// Set SingleLegOrder.OrderType
func OrderType(t string) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.OrderType = t
}
}
// Set SingleLegOrder.Session
func Session(session string) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.Session = session
}
}
// Set SingleLegOrder.Duration
func Duration(duration string) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.Duration = duration
}
}
// Set SingleLegOrder.Strategy
func Strategy(strategy string) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.Strategy = strategy
}
}
// Set SingleLegOrder.Instruction
func Instruction(instruction string) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.Instruction = instruction
}
}
// Set SingleLegOrder.Quantity
func Quantity(quantity float32) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.Quantity = quantity
}
}
// Set SingleLegOrder.Instrument
func Instrument(instrument SimpleOrderInstrument) SingleLegOrderComposition {
return func(order *SingleLegOrder) {
order.Instrument = instrument
}
}
var OrderTemplate = `
{
"orderType": "%s",
"session": "%s",
"duration": "%s",
"orderStrategyType": "%s",
"orderLegCollection": [
%s
]
}
`
var LegTemplate = `
{
"instruction": "%s",
"quantity": %f,
"instrument": {
"symbol": "%s",
"assetType": "%s"
}
},
`
var LegTemplateLast = `
{
"instruction": "%s",
"quantity": %f,
"instrument": {
"symbol": "%s",
"assetType": "%s"
}
},
`
func marshalSingleLegOrder(order *SingleLegOrder) string {
return fmt.Sprintf(OrderTemplate, order.OrderType, order.Session, order.Duration, order.Strategy, fmt.Sprintf(LegTemplate, order.Instruction, order.Quantity, order.Instrument.Symbol, order.Instrument.AssetType))
}
func marshalMultiLegOrder(order *MultiLegOrder) string {
var legs string
// UNTESTED
for i, leg := range order.OrderLegCollection {
if i != len(order.OrderLegCollection)-1 {
legs += fmt.Sprintf(LegTemplate, leg.Instruction, leg.Quantity, leg.Instrument.Symbol, leg.Instrument.AssetType)
} else {
legs += fmt.Sprintf(LegTemplateLast, leg.Instruction, leg.Quantity, leg.Instrument.Symbol, leg.Instrument.AssetType)
}
}
return fmt.Sprintf(OrderTemplate)
}
// Submit a single-leg order for the specified encrypted account ID
func (agent *Agent) SubmitSingleLegOrder(hashValue string, order *SingleLegOrder) error {
orderJson := marshalSingleLegOrder(order)
req, err := http.NewRequest("POST", fmt.Sprintf(endpointAccountOrders, hashValue), strings.NewReader(orderJson))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
_, err = agent.Handler(req)
if err != nil {
return err
}
return nil
}
// Get a specific order by account number & order ID
func (agent *Agent) GetOrder(accountNumber, orderID string) (FullOrder, error) {
req, err := http.NewRequest("GET", fmt.Sprintf(endpointAccountOrder, accountNumber, orderID), nil)
if err != nil {
return FullOrder{}, err
}
resp, err := agent.Handler(req)
if err != nil {
return FullOrder{}, err
}
var order FullOrder
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return FullOrder{}, err
}
err = sonic.Unmarshal(body, &order)
if err != nil {
return FullOrder{}, err
}
return order, nil
}
// fromEnteredTime, toEnteredTime format:
// yyyy-MM-ddTHH:mm:ss.SSSZ
func (agent *Agent) GetAccountOrders(accountNumber, fromEnteredTime, toEnteredTime string) ([]FullOrder, error) {
req, err := http.NewRequest("GET", fmt.Sprintf(endpointAccountOrders, accountNumber), nil)
if err != nil {
return []FullOrder{}, err
}
q := req.URL.Query()
q.Add("fromEnteredTime", fromEnteredTime)
q.Add("toEnteredTime", toEnteredTime)
req.URL.RawQuery = q.Encode()
resp, err := agent.Handler(req)
if err != nil {
return []FullOrder{}, err
}
var orders []FullOrder
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return []FullOrder{}, err
}
err = sonic.Unmarshal(body, &orders)
if err != nil {
return []FullOrder{}, err
}
return orders, nil
}
// WIP:
// fromEnteredTime, toEnteredTime format:
// yyyy-MM-ddTHH:mm:ss.SSSZ
func (agent *Agent) GetAllOrders(fromEnteredTime, toEnteredTime string) ([]FullOrder, error) {
req, err := http.NewRequest("GET", endpointOrders, nil)
if err != nil {
return []FullOrder{}, err
}
q := req.URL.Query()
q.Add("fromEnteredTime", fromEnteredTime)
q.Add("toEnteredTime", toEnteredTime)
req.URL.RawQuery = q.Encode()
resp, err := agent.Handler(req)
if err != nil {
return []FullOrder{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return []FullOrder{}, err
}
var orders []FullOrder
/* TODO:
err = sonic.Unmarshal(body, &orders)
isErrNil(err)*/
fmt.Println(body)
return orders, nil
}
// Get encrypted account numbers for trading
func (agent *Agent) GetAccountNumbers() ([]AccountNumbers, error) {
req, err := http.NewRequest("GET", endpointAccountNumbers, nil)
if err != nil {
return []AccountNumbers{}, err
}
resp, err := agent.Handler(req)
if err != nil {
return []AccountNumbers{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return []AccountNumbers{}, err
}
var accountNumbers []AccountNumbers
err = sonic.Unmarshal(body, &accountNumbers)
if err != nil {
return []AccountNumbers{}, err
}
return accountNumbers, nil
}
// Get all accounts associated with the user logged in
func (agent *Agent) GetAccounts(fields ...string) ([]Account, error) {
var fieldsRequest string = strings.Join(fields, ",")
req, err := http.NewRequest("GET", endpointAccounts, nil)
if err != nil {
return []Account{}, err
}
q := req.URL.Query()
q.Add("fields", fieldsRequest)
req.URL.RawQuery = q.Encode()
resp, err := agent.Handler(req)
if err != nil {
return []Account{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return []Account{}, err
}
var accounts []Account
err = sonic.Unmarshal(body, &accounts)
if err != nil {
return []Account{}, err
}
return accounts, nil
}
// Get account by encrypted account id
func (agent *Agent) GetAccount(id string, fields ...string) (Account, error) {
var fieldsRequest string = strings.Join(fields, ",")
req, err := http.NewRequest("GET", fmt.Sprintf(endpointAccount, id), nil)
if err != nil {
return Account{}, err
}
q := req.URL.Query()
q.Add("fields", fieldsRequest)
req.URL.RawQuery = q.Encode()
resp, err := agent.Handler(req)
if err != nil {
return Account{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return Account{}, err
}
var account Account
err = sonic.Unmarshal(body, &account)
if err != nil {
return Account{}, err
}
return account, nil
}
// Get all transactions for the user logged in
// func (agent *Agent) GetTransactions() ([]Transaction, error) {}
// Get a transaction for a specific account id
func (agent *Agent) GetTransaction(accountNumber, transactionId string) (Transaction, error) {
req, err := http.NewRequest("GET", fmt.Sprintf(endpointTransaction, accountNumber, transactionId), nil)
if err != nil {
return Transaction{}, err
}
resp, err := agent.Handler(req)
if err != nil {
return Transaction{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return Transaction{}, err
}
var transaction Transaction
err = sonic.Unmarshal(body, &transaction)
if err != nil {
return Transaction{}, err
}
return transaction, nil
}