-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
402 lines (360 loc) ยท 13.6 KB
/
Copy pathmain.go
File metadata and controls
402 lines (360 loc) ยท 13.6 KB
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
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/carvalab/openbymadata"
)
func main() {
fmt.Println("๐๏ธ OpenBYMAData Go Library - Complete Example")
fmt.Println(strings.Repeat("=", 60))
fmt.Println("๐ Features: Individual ticker lookups, 5-minute caching, batch operations")
fmt.Println()
// Create client with caching enabled (default)
client := openbymadata.NewClient(&openbymadata.ClientOptions{
Timeout: 15 * time.Second,
RetryAttempts: 3,
EnableCache: true, // Default: true
})
defer client.Close()
ctx := context.Background()
// =============================================================================
// 1. Market Status & Basic Info
// =============================================================================
fmt.Println("๐ 1. Market Status & Info")
fmt.Println(strings.Repeat("-", 30))
isWorking, err := client.IsWorkingDay(ctx)
if err != nil {
log.Printf("Error checking market status: %v", err)
} else {
status := "๐ด CLOSED"
if isWorking {
status = "๐ข OPEN"
}
fmt.Printf("Market Status: %s\n", status)
}
indices, err := client.GetIndices(ctx)
if err != nil {
log.Printf("Error getting indices: %v", err)
} else {
fmt.Printf("Market Indices (%d):\n", len(indices))
for i, index := range indices {
if i >= 3 { // Show first 3
break
}
changeSymbol := "๐"
if index.Change < 0 {
changeSymbol = "๐"
}
fmt.Printf(" %s %s: %.2f (%.2f%%)\n",
changeSymbol, index.Symbol, index.Last, index.Change)
}
}
// =============================================================================
// 2. Individual Ticker Lookups (NEW!)
// =============================================================================
fmt.Println("\n๐ฐ 2. Individual Ticker Lookups")
fmt.Println(strings.Repeat("-", 35))
// Get specific CEDEAR (US stock)
fmt.Println("๐บ๐ธ CEDEARs:")
startTime := time.Now()
aapl, err := client.GetCedear(ctx, "AAPL")
if err != nil {
fmt.Printf(" โ AAPL: %v\n", err)
} else {
duration := time.Since(startTime)
fmt.Printf(" ๐ AAPL: $%.2f (%.2f%%) [%v]\n",
aapl.Last, aapl.Change, duration)
fmt.Printf(" Volume: %d | Last Update: %s\n",
aapl.Volume, aapl.DateTime.Format("15:04:05"))
}
// Get specific Argentine stock
fmt.Println("๐ฆ๐ท Argentine Leading Equity:")
ggal, err := client.GetBluechip(ctx, "GGAL")
if err != nil {
fmt.Printf(" โ GGAL: %v\n", err)
} else {
fmt.Printf(" ๐ฆ GGAL: $%.2f (%.2f%%)\n", ggal.Last, ggal.Change)
}
// Universal search (don't need to know security type)
fmt.Println("๐ Universal Search:")
symbols := []string{"BMA", "TSLA", "UNKNOWN"}
for _, symbol := range symbols {
security, err := client.GetSecurity(ctx, symbol)
if err != nil {
fmt.Printf(" โ %s: Not found\n", symbol)
} else {
changeIcon := "๐"
if security.Change < 0 {
changeIcon = "๐"
}
fmt.Printf(" %s %s: $%.2f (%.2f%%)\n",
changeIcon, symbol, security.Last, security.Change)
}
}
// =============================================================================
// 3. Batch Operations (Efficient!)
// =============================================================================
fmt.Println("\n๐ฆ 3. Batch Operations")
fmt.Println(strings.Repeat("-", 25))
// Get multiple tickers efficiently (shares cache)
watchlist := []string{"AAPL", "MSFT", "GOOGL", "TSLA", "META", "GGAL"}
startTime = time.Now()
securities, err := client.GetMultipleSecurities(ctx, watchlist)
duration := time.Since(startTime)
if err != nil {
log.Printf("Error getting multiple securities: %v", err)
} else {
fmt.Printf("๐ผ Portfolio (%d/%d securities) [%v]:\n",
len(securities), len(watchlist), duration)
totalValue := 0.0
for _, symbol := range watchlist {
if security, found := securities[symbol]; found {
changeIcon := "๐ข"
if security.Change < 0 {
changeIcon = "๐ด"
}
fmt.Printf(" %s %-6s: $%-10.2f %+6.2f%%\n",
changeIcon, symbol, security.Last, security.Change)
totalValue += security.Last
} else {
fmt.Printf(" โ %-6s: Not found\n", symbol)
}
}
fmt.Printf(" ๐ฐ Total Portfolio Value: $%.2f\n", totalValue)
}
// =============================================================================
// 4. Collection Data (Traditional approach)
// =============================================================================
fmt.Println("\n๐ 4. Collection Data (API endpoints: leading-equity, general-equity, cedears)")
fmt.Println(strings.Repeat("-", 80))
// Leading Equity (blue chips) - cached call
bluechips, err := client.GetBluechips(ctx)
if err != nil {
log.Printf("Error getting leading equity: %v", err)
} else {
fmt.Printf("๐ Leading Equity (%d securities from 'leading-equity' endpoint):\n", len(bluechips))
for i, security := range bluechips {
if i >= 3 { // Show first 3
fmt.Printf(" ... and %d more\n", len(bluechips)-3)
break
}
changeIcon := "๐ข"
if security.Change < 0 {
changeIcon = "๐ด"
}
fmt.Printf(" %s %s: $%.2f (%.2f%%) | Vol: %d\n",
changeIcon, security.Symbol, security.Last, security.Change, security.Volume)
}
}
// CEDEARs - cached call
cedears, err := client.GetCedears(ctx)
if err != nil {
log.Printf("Error getting CEDEARs: %v", err)
} else {
fmt.Printf("\n๐ CEDEARs (%d securities from 'cedears' endpoint):\n", len(cedears))
for i, cedear := range cedears {
if i >= 3 { // Show first 3
fmt.Printf(" ... and %d more\n", len(cedears)-3)
break
}
changeIcon := "๐ข"
if cedear.Change < 0 {
changeIcon = "๐ด"
}
fmt.Printf(" %s %s: $%.2f (%.2f%%)\n",
changeIcon, cedear.Symbol, cedear.Last, cedear.Change)
}
}
// General Equity (galpones) - cached call
galpones, err := client.GetGalpones(ctx)
if err != nil {
log.Printf("Error getting general equity: %v", err)
} else {
fmt.Printf("\n๐ข General Equity (%d securities from 'general-equity' endpoint):\n", len(galpones))
for i, galpone := range galpones {
if i >= 3 { // Show first 3
fmt.Printf(" ... and %d more\n", len(galpones)-3)
break
}
changeIcon := "๐ข"
if galpone.Change < 0 {
changeIcon = "๐ด"
}
fmt.Printf(" %s %s: $%.2f (%.2f%%)\n",
changeIcon, galpone.Symbol, galpone.Last, galpone.Change)
}
}
// =============================================================================
// 5. Fixed Income & Derivatives
// =============================================================================
fmt.Println("\n๐๏ธ 5. Fixed Income & Derivatives")
fmt.Println(strings.Repeat("-", 35))
bonds, err := client.GetBonds(ctx)
if err != nil {
log.Printf("Error getting bonds: %v", err)
} else {
fmt.Printf("๐ Government Bonds: %d instruments\n", len(bonds))
if len(bonds) > 0 {
fmt.Printf(" Example: %s - $%.2f\n", bonds[0].Symbol, bonds[0].Last)
}
}
options, err := client.GetOptions(ctx)
if err != nil {
log.Printf("Error getting options: %v", err)
} else {
fmt.Printf("๐ Options: %d contracts\n", len(options))
}
futures, err := client.GetFutures(ctx)
if err != nil {
log.Printf("Error getting futures: %v", err)
} else {
fmt.Printf("๐ฎ Futures: %d contracts\n", len(futures))
}
// =============================================================================
// 6. Cache Performance Demo
// =============================================================================
fmt.Println("\nโก 6. Cache Performance (5-minute automatic caching)")
fmt.Println(strings.Repeat("-", 55))
// Show cache information
cacheInfo := client.GetCacheInfo()
fmt.Printf("๐๏ธ Cache Status:\n")
for category, info := range cacheInfo {
infoMap := info.(map[string]interface{})
fmt.Printf(" %-12s: %v items, age %v, fresh: %v\n",
category, infoMap["count"], infoMap["age"], infoMap["fresh"])
}
// Demonstrate cache speed
fmt.Printf("\n๐ Cache Speed Test:\n")
// Get AAPL again (should be from cache)
fmt.Printf(" Getting AAPL again (cached)... ")
startTime = time.Now()
_, err = client.GetCedear(ctx, "AAPL")
cachedDuration := time.Since(startTime)
fmt.Printf("%v (lightning fast!)\n", cachedDuration)
// =============================================================================
// 7. Historical Data (Chart Data)
// =============================================================================
fmt.Println("\n๐ 7. Historical Data (Chart Data)")
fmt.Println(strings.Repeat("-", 35))
now := time.Now()
threeMonthsAgo := now.AddDate(0, -3, 0)
marketTime, err := client.GetMarketTime(ctx)
if err != nil {
log.Printf("Error getting market time: %v", err)
} else {
fmt.Printf("๐ Market opens at %s, closes at %s (%s)\n",
marketTime.OpeningText, marketTime.ClosingText, marketTime.Timezone)
}
quote, err := client.GetCurrentQuote(ctx, "GGAL", openbymadata.Settlement48HS)
if err != nil {
fmt.Printf("๐ฒ Current quote for GGAL: %v\n", err)
} else {
fmt.Printf("๐ฒ GGAL (48HS): last $%.2f, bid $%.2f, ask $%.2f\n",
quote.Last, quote.Bid, quote.Ask)
}
profile, err := client.GetEquityProfile(ctx, "ALUA")
if err != nil {
fmt.Printf("๐ข ALUA equity profile: %v\n", err)
} else {
fmt.Printf("๐ข ALUA equity profile fields: %d\n", len(profile.Fields))
}
directors, err := client.GetCompanyManagement(ctx, "ALUA")
if err != nil {
fmt.Printf("๐ฅ ALUA management: %v\n", err)
} else {
fmt.Printf("๐ฅ ALUA management entries: %d\n", len(directors))
}
intraday, err := client.GetIntradayHistory(ctx, "GGAL", openbymadata.Resolution5Min, threeMonthsAgo, now)
if err != nil {
log.Printf("Error getting intraday data: %v", err)
} else {
fmt.Printf("โฑ๏ธ GGAL 5-minute bars (last 3 months): %d points\n", len(intraday.Time))
}
// Get historical data for SPY (S&P 500 ETF) - last 30 days
fmt.Printf("๐ Historical Data for SPY (last 30 days):\n")
historyData, err := client.GetHistoryLastDays(ctx, "SPY", 30)
if err != nil {
log.Printf("Error getting historical data: %v", err)
} else {
fmt.Printf(" Retrieved %d data points:\n", len(historyData.Time))
if len(historyData.Time) >= 3 {
// Show first, middle, and last data points
for i, dataIndex := range []int{0, len(historyData.Time) / 2, len(historyData.Time) - 1} {
date := historyData.Time[dataIndex].Format("2006-01-02")
position := []string{"First", "Middle", "Latest"}[i]
fmt.Printf(" %s (%s): Open=$%.2f High=$%.2f Low=$%.2f Close=$%.2f Vol=%d\n",
position, date, historyData.Open[dataIndex], historyData.High[dataIndex],
historyData.Low[dataIndex], historyData.Close[dataIndex], historyData.Volume[dataIndex])
}
}
}
// Get custom date range historical data (weekly data)
fmt.Printf("\n๐
Custom Date Range (Weekly data - last 3 months):\n")
weeklyData, err := client.GetHistory(ctx, "AAPL", openbymadata.ResolutionWeekly, threeMonthsAgo, now)
if err != nil {
log.Printf("Error getting weekly data: %v", err)
} else {
fmt.Printf(" AAPL Weekly Data - %d weeks retrieved\n", len(weeklyData.Time))
if len(weeklyData.Time) > 0 {
lastIndex := len(weeklyData.Time) - 1
latestDate := weeklyData.Time[lastIndex].Format("2006-01-02")
fmt.Printf(" Latest week (%s): Close=$%.2f\n", latestDate, weeklyData.Close[lastIndex])
}
}
// OHLCV is the historical-data shape returned by GetHistoryLastDays / GetHistory.
// =============================================================================
// 8. News & Financial Data
// =============================================================================
fmt.Println("\n๐ฐ 8. News & Financial Data")
fmt.Println(strings.Repeat("-", 30))
news, err := client.GetNews(ctx)
if err != nil {
log.Printf("Error getting news: %v", err)
} else {
fmt.Printf("๐ฐ Latest News (%d items):\n", len(news))
for i, newsItem := range news {
if i >= 2 { // Show first 2
break
}
fmt.Printf(" ๐ %s\n", newsItem.Titulo)
fmt.Printf(" Date: %s\n", newsItem.Fecha.Format("2006-01-02 15:04"))
}
}
// Get income statement for a company
if len(bluechips) > 0 {
ticker := bluechips[0].Symbol
statements, err := client.GetIncomeStatement(ctx, ticker)
if err != nil {
fmt.Printf("๐ Income statements for %s: Error - %v\n", ticker, err)
} else {
fmt.Printf("๐ Income statements for %s: %d records\n", ticker, len(statements))
}
}
// =============================================================================
// Summary
// =============================================================================
fmt.Println("\n๐ Example Complete!")
fmt.Println(strings.Repeat("=", 60))
fmt.Println("โจ Features Demonstrated:")
fmt.Println(" โข Individual ticker lookups (GetCedear, GetBluechip, GetSecurity)")
fmt.Println(" โข Efficient batch operations (GetMultipleSecurities)")
fmt.Println(" โข Historical data & charting (GetHistory, GetHistoryLastDays)")
fmt.Println(" โข 5-minute automatic caching (reduces API calls by 95%)")
fmt.Println(" โข API endpoint mapping:")
fmt.Println(" - GetBluechips() โ 'leading-equity' endpoint")
fmt.Println(" - GetGalpones() โ 'general-equity' endpoint")
fmt.Println(" - GetCedears() โ 'cedears' endpoint")
fmt.Println(" - GetHistory() โ 'chart/historical-series/history' endpoint")
fmt.Println(" โข Full market data coverage (equities, bonds, derivatives)")
fmt.Println(" โข Real-time market news and financial data")
fmt.Println(" โข Thread-safe concurrent operations")
fmt.Println(" โข Comprehensive error handling")
fmt.Println("\n๐ Production Ready:")
fmt.Println(" โข Context-aware operations")
fmt.Println(" โข Built-in retry logic")
fmt.Println(" โข Strongly-typed data structures")
fmt.Println(" โข Zero external dependencies")
}