-
Notifications
You must be signed in to change notification settings - Fork 0
/
portfolio.go
79 lines (68 loc) · 1.99 KB
/
portfolio.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
package kalshi
import (
"context"
"encoding/json"
"fmt"
"log"
"math"
"strings"
"github.com/fsctl/go-kalshi/swagger"
)
// PortfolioItem is a single set of contracts on a given market represented
// by Ticker.
type PortfolioItem struct {
Ticker string
Contracts int64
Side MarketSide
}
// Portfolio stores an array of all PortfolioItems in the user's portfolio.
type Portfolio struct {
Items []PortfolioItem
}
// Print() prints all elements of the portfolio.
func (p *Portfolio) Print() {
fmt.Printf("Portfolio:\n")
for _, item := range p.Items {
fmt.Printf(" %s (%s): %d contracts\n", item.Ticker, item.Side.String(), item.Contracts)
}
if len(p.Items) == 0 {
fmt.Printf(" (none)\n")
}
}
// GetPortfolio returns the portfolio of the user associated with the KalshiClient instance.
func (kc *KalshiClient) GetPortfolio(ctx context.Context) (*Portfolio, error) {
p := Portfolio{
Items: make([]PortfolioItem, 0),
}
// construct url
url := fmt.Sprintf("%s/users/%s/positions", BaseURLV1, kc.authToken.UserId)
// perform request
reqBody := strings.NewReader("")
res, data := kc.doAuthenticatedRequest("GET", url, reqBody)
if res.StatusCode != 200 {
return nil, fmt.Errorf("error: getportfolio response not 200 (it's %d)", res.StatusCode)
}
// deserialize json
var userGetMarketPositionsResponse swagger.UserGetMarketPositionsResponse
if err := json.Unmarshal(data, &userGetMarketPositionsResponse); err != nil {
log.Fatalf("Error: failed to unmarshal: %v", err)
}
for _, marketPosition := range userGetMarketPositionsResponse.MarketPositions {
if marketPosition.Position != 0 {
marketId := marketPosition.MarketId
ticker := kc.GetMarketTicker(ctx, marketId)
position := marketPosition.Position
portfolioItem := PortfolioItem{
Ticker: ticker,
Contracts: int64(math.Abs(float64(position))),
}
if position < 0 {
portfolioItem.Side = No
} else {
portfolioItem.Side = Yes
}
p.Items = append(p.Items, portfolioItem)
}
}
return &p, nil
}