-
Notifications
You must be signed in to change notification settings - Fork 0
/
brmarket.go
135 lines (118 loc) · 2.19 KB
/
brmarket.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
package brmarket
import (
"encoding/json"
"errors"
"io"
"net/http"
)
type IndexType int
const (
IBOV IndexType = iota
IBXX
IBXL
IBRA
IGCX
ITAG
IGNM
IGCT
IDIV
MLCX
IVBX
ICO2
ISEE
ICON
IEEX
IFNC
IMOB
INDX
IMAT
UTIL
IFIX
BDRX
)
// Response type for B3 API
type B3IndexInfo struct {
BizSts bizSts `json:"BizSts"`
Index index `json:"Index"`
UnderlyingList []underlyingList `json:"UnderlyingList"`
Msg msg `json:"Msg"`
}
type bizSts struct {
Cd string `json:"cd"`
}
type index struct {
Symbol string `json:"symbol"`
Description string `json:"description"`
}
type underlyingList struct {
IndexTheoreticalQty float64 `json:"indexTheoreticalQty"`
IndxCmpnPctg float64 `json:"indxCmpnPctg"`
Symb string `json:"symb"`
Desc string `json:"desc"`
}
type msg struct {
DtTm string `json:"dtTm"`
}
// Errors
var (
// ErrIndexNotFound is used for all indexes not supported
ErrIndexNotFound = errors.New("index not found")
)
func (i IndexType) String() string {
return [...]string{
"IBOV",
"IBXX",
"IBXL",
"IBRA",
"IGCX",
"ITAG",
"IGNM",
"IGCT",
"IDIV",
"MLCX",
"IVBX",
"ICO2",
"ISEE",
"ICON",
"IEEX",
"IFNC",
"IMOB",
"INDX",
"IMAT",
"UTIL",
"IFIX",
"BDRX",
}[i]
}
func IndexFromString(input string) (*IndexType, error) {
for i := IBOV; i <= BDRX; i++ {
if i.String() == input {
return &i, nil
}
}
return nil, ErrIndexNotFound
}
// Return shares for reach index, only Brazilian indexes allowed.
// Example: GetSharesForIndex("IBOV") or GetSharesForIndex(brmarket.IBOV.String())
func GetSharesForIndex(index string) (B3IndexInfo, error) {
idx, indexErr := IndexFromString(index)
if indexErr != nil {
return B3IndexInfo{}, indexErr
}
URL := "https://cotacao.b3.com.br/mds/api/v1/IndexComposition/" + idx.String()
resp, err := http.Get(URL)
if err != nil {
return B3IndexInfo{}, err
}
defer resp.Body.Close()
//Read the response body
data, err := io.ReadAll(resp.Body)
if err != nil {
return B3IndexInfo{}, err
}
var info B3IndexInfo
if err := json.Unmarshal(data, &info); err != nil {
return info, err
}
return info, nil
}