-
Notifications
You must be signed in to change notification settings - Fork 1
/
currency.go
558 lines (455 loc) · 14.4 KB
/
currency.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
// particular currency exchange rates
//
// public func: NewCurrency
// types: NBPCurrency, Rate
// NBPCurrency methods:
// CurrencyRaw, CurrencyByDate, CurrencyLast, CurrencyToday,
// GetRateCurrent, GetRateToday, GetRateByDate,
// GetPrettyOutput, GetCSVOutput, GetRawOutput
package nbpapi
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"text/tabwriter"
"time"
)
// NewCurrency - function creates new currency type
func NewCurrency(tableType string) *NBPCurrency {
cli := &http.Client{
Timeout: time.Second * 10,
}
r := &NBPCurrency{
tableType: tableType,
Client: cli,
}
return r
}
/*
CurrencyRaw - function downloads data in json or xml form
Function returns error or nil
Parameters:
date - date in the format: 'YYYY-MM-DD' (ISO 8601 standard),
or a range of dates in the format: 'YYYY-MM-DD:YYYY-MM-DD' or 'today'
(rate for today) or 'current' - current table / rate (last published)
last - as an alternative to date, the last <n> tables/rates
can be retrieved
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
format - 'json' or 'xml'
*/
func (c *NBPCurrency) CurrencyRaw(code, date string, last int, format string) error {
var err error
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return err
}
url := c.getCurrencyAddress(c.tableType, date, last, code)
c.result, err = c.getData(url, format)
if err != nil {
return err
}
return err
}
/*
CurrencyByDate - function downloads and writes data to exchange (exchangeC) slice,
raw data (json) still available in result field
Function returns error or nil
Parameters:
date - date in the format: 'YYYY-MM-DD' (ISO 8601 standard),
or a range of dates in the format: 'YYYY-MM-DD:YYYY-MM-DD' or 'today'
(rate for today) or 'current' - current table / rate (last published)
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
*/
func (c *NBPCurrency) CurrencyByDate(code, date string) error {
var err error
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return err
}
url := c.getCurrencyAddress(c.tableType, date, 0, code)
c.result, err = c.getData(url, "json")
if err != nil {
return err
}
if c.tableType != "C" {
err = json.Unmarshal(c.result, &c.Exchange)
} else {
err = json.Unmarshal(c.result, &c.ExchangeC)
}
if err != nil {
return err
}
return err
}
/*
CurrencyLast - function downloads and writes data to exchange (exchangeC) slice,
raw data (json) still available in result field
Function returns error or nil
Parameters:
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
last - as an alternative to date, the last <n> tables/rates
can be retrieved
*/
func (c *NBPCurrency) CurrencyLast(code string, last int) error {
var err error
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return err
}
url := c.getCurrencyAddress(c.tableType, "", last, code)
c.result, err = c.getData(url, "json")
if err != nil {
return err
}
if c.tableType != "C" {
err = json.Unmarshal(c.result, &c.Exchange)
} else {
err = json.Unmarshal(c.result, &c.ExchangeC)
}
if err != nil {
return err
}
return err
}
/*
CurrencyToday - function downloads and writes data to exchange (exchangeC) slice,
raw data (json) still available in result field
Function returns error or nil
Parameters:
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
*/
func (c *NBPCurrency) CurrencyToday(code string) error {
var err error
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return err
}
url := c.getCurrencyAddress(c.tableType, "today", 0, code)
c.result, err = c.getData(url, "json")
if err != nil {
return err
}
if c.tableType != "C" {
err = json.Unmarshal(c.result, &c.Exchange)
} else {
err = json.Unmarshal(c.result, &c.ExchangeC)
}
if err != nil {
return err
}
return err
}
/*
GetRateCurrent - function downloads current currency exchange rate
and return Rate struct (or error)
Parameters:
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
*/
func (c *NBPCurrency) GetRateCurrent(code string) (Rate, error) {
var err error
var rate Rate
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return rate, err
}
url := c.getCurrencyAddress(c.tableType, "current", 0, code)
c.result, err = c.getData(url, "json")
if err != nil {
return rate, err
}
if c.tableType != "C" {
err = json.Unmarshal(c.result, &c.Exchange)
} else {
err = json.Unmarshal(c.result, &c.ExchangeC)
}
if err != nil {
return rate, err
}
if c.tableType != "C" {
rate.No = c.Exchange.Rates[0].No
rate.EffectiveDate = c.Exchange.Rates[0].EffectiveDate
rate.Mid = c.Exchange.Rates[0].Mid
rate.Ask = 0
rate.Bid = 0
} else {
rate.No = c.ExchangeC.Rates[0].No
rate.EffectiveDate = c.ExchangeC.Rates[0].EffectiveDate
rate.Mid = 0
rate.Ask = c.ExchangeC.Rates[0].Ask
rate.Bid = c.ExchangeC.Rates[0].Bid
}
return rate, err
}
/*
GetRateToday - function downloads today's currency exchange rate
and returns Rate struct (or error)
Parameters:
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
*/
func (c *NBPCurrency) GetRateToday(code string) (Rate, error) {
var err error
var rate Rate
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return rate, err
}
url := c.getCurrencyAddress(c.tableType, "today", 0, code)
c.result, err = c.getData(url, "json")
if err != nil {
return rate, err
}
if c.tableType != "C" {
err = json.Unmarshal(c.result, &c.Exchange)
} else {
err = json.Unmarshal(c.result, &c.ExchangeC)
}
if err != nil {
return rate, err
}
if c.tableType != "C" {
rate.No = c.Exchange.Rates[0].No
rate.EffectiveDate = c.Exchange.Rates[0].EffectiveDate
rate.Mid = c.Exchange.Rates[0].Mid
rate.Ask = 0
rate.Bid = 0
} else {
rate.No = c.ExchangeC.Rates[0].No
rate.EffectiveDate = c.ExchangeC.Rates[0].EffectiveDate
rate.Mid = 0
rate.Ask = c.ExchangeC.Rates[0].Ask
rate.Bid = c.ExchangeC.Rates[0].Bid
}
return rate, err
}
/*
GetRateByDate - function downloads today's currency exchange rate
and returns slice of Rate struct (or error)
Parameters:
code - ISO 4217 currency code, depending on the type of the
table available currencies may vary
date - date in the format: 'YYYY-MM-DD' (ISO 8601 standard),
or a range of dates in the format: 'YYYY-MM-DD:YYYY-MM-DD' or 'today'
(rate for today) or 'current' - current table / rate (last published)
*/
func (c *NBPCurrency) GetRateByDate(code, date string) ([]Rate, error) {
var err error
var rates []Rate
var rate Rate
err = checkCurrencyCode(c.tableType, code)
if err != nil {
return nil, err
}
url := c.getCurrencyAddress(c.tableType, date, 0, code)
c.result, err = c.getData(url, "json")
if err != nil {
return nil, err
}
if c.tableType != "C" {
err = json.Unmarshal(c.result, &c.Exchange)
} else {
err = json.Unmarshal(c.result, &c.ExchangeC)
}
if err != nil {
return nil, err
}
if c.tableType != "C" {
for _, item := range c.Exchange.Rates {
rate.No = item.No
rate.EffectiveDate = item.EffectiveDate
rate.Mid = item.Mid
rate.Ask = 0
rate.Bid = 0
rates = append(rates, rate)
}
} else {
for _, item := range c.ExchangeC.Rates {
rate.No = item.No
rate.EffectiveDate = item.EffectiveDate
rate.Mid = 0
rate.Ask = item.Ask
rate.Bid = item.Bid
rates = append(rates, rate)
}
}
return rates, err
}
/*
CreatePrettyOutput - function returns exchange rates as formatted table
depending on the tableType field:
for type A and B tables a column with an average rate is printed,
for type C two columns: buy price and sell price
Parameters:
lang - 'en' or 'pl'
*/
func (c *NBPCurrency) CreatePrettyOutput(lang string) string {
const padding = 3
var builder strings.Builder
var output string
var total, totalBuy, totalSell float64
// output language
setLang(lang)
w := tabwriter.NewWriter(&builder, 0, 0, padding, ' ', tabwriter.Debug)
if c.tableType != "C" {
output += fmt.Sprintln()
output += fmt.Sprintln(l.Get("Table type:")+"\t", c.Exchange.Table)
output += fmt.Sprintln(l.Get("Currency name:")+"\t", c.Exchange.Currency)
output += fmt.Sprintln(l.Get("Currency code:")+"\t", c.Exchange.Code)
output += fmt.Sprintln()
fmt.Fprintln(w, l.Get("TABLE \t DATE \t AVERAGE (PLN)"))
fmt.Fprintln(w, l.Get("----- \t ---- \t -------------"))
for _, currencyItem := range c.Exchange.Rates {
currencyValue := fmt.Sprintf("%.4f", currencyItem.Mid)
total += currencyItem.Mid
fmt.Fprintln(w, currencyItem.No+" \t "+currencyItem.EffectiveDate+" \t "+currencyValue)
}
if len(c.Exchange.Rates) > 1 {
avg := total / float64(len(c.Exchange.Rates))
fmt.Fprintln(w)
fmt.Fprintln(w, l.Get("The average exchange rate (from downloaded): "), fmt.Sprintf("%.4f", avg))
fmt.Fprintln(w)
}
} else {
output += fmt.Sprintln()
output += fmt.Sprintln(l.Get("Table type:")+"\t", c.ExchangeC.Table)
output += fmt.Sprintln(l.Get("Currency name:")+"\t", c.ExchangeC.Currency)
output += fmt.Sprintln(l.Get("Currency code:")+"\t", c.ExchangeC.Code)
output += fmt.Sprintln()
fmt.Fprintln(w, l.Get("TABLE \t DATE \t BUY (PLN) \t SELL (PLN) "))
fmt.Fprintln(w, l.Get("----- \t ---- \t --------- \t ---------- "))
for _, currencyItem := range c.ExchangeC.Rates {
currencyValueBid := fmt.Sprintf("%.4f", currencyItem.Bid)
currencyValueAsk := fmt.Sprintf("%.4f", currencyItem.Ask)
totalBuy += currencyItem.Bid
totalSell += currencyItem.Ask
fmt.Fprintln(w, currencyItem.No+" \t "+currencyItem.EffectiveDate+" \t "+currencyValueBid+" \t "+currencyValueAsk)
}
if len(c.ExchangeC.Rates) > 1 {
avgBuy := totalBuy / float64(len(c.ExchangeC.Rates))
avgSell := totalSell / float64(len(c.ExchangeC.Rates))
fmt.Fprintln(w)
fmt.Fprintln(w, l.Get("Buy: the average exchange rate (from downloaded): "), fmt.Sprintf("%.4f", avgBuy))
fmt.Fprintln(w, l.Get("Sell: the average exchange rate (from downloaded): "), fmt.Sprintf("%.4f", avgSell))
fmt.Fprintln(w)
}
}
w.Flush()
return output + builder.String()
}
/*
CreateCSVOutput - function returns currency rates,
in the form of CSV (data separated by a comma), depending on the
tableType field: for type A and B tables a column with an average
rate is printed, for type C two columns: buy price and sell price
Parameters:
lang - 'en' or 'pl'
*/
func (c *NBPCurrency) CreateCSVOutput(lang string) string {
var output string = ""
// output language
setLang(lang)
if c.tableType != "C" {
output += fmt.Sprintln(l.Get("TABLE,DATE,AVERAGE (PLN)"))
for _, currencyItem := range c.Exchange.Rates {
currencyValue := fmt.Sprintf("%.4f", currencyItem.Mid)
output += fmt.Sprintln(currencyItem.No + "," + currencyItem.EffectiveDate + "," + currencyValue)
}
} else {
output += fmt.Sprintln(l.Get("TABLE,DATE,BUY (PLN),SELL (PLN)"))
for _, currencyItem := range c.ExchangeC.Rates {
currencyValueBid := fmt.Sprintf("%.4f", currencyItem.Bid)
currencyValueAsk := fmt.Sprintf("%.4f", currencyItem.Ask)
output += fmt.Sprintln(currencyItem.No + "," + currencyItem.EffectiveDate + "," + currencyValueBid + "," + currencyValueAsk)
}
}
return output
}
// CreateRawOutput - function print just result of request (json or xml)
func (c *NBPCurrency) CreateRawOutput() string {
return string(c.result)
}
// SetTableType - the function allows to set the supported type of exchange rate table
func (c *NBPCurrency) SetTableType(tableType string) error {
if c.tableType == tableType {
return nil
}
err := checkTableType(tableType)
if err != nil {
return err
}
// data cleaning
c.clearData()
c.tableType = tableType
return nil
}
/* getData - function that retrieves data from the NBP website
and returns them in the form of JSON / XML (or error), based on
the arguments provided:
url - NBP web api address
format - 'json' or 'xml'
*/
func (c *NBPCurrency) getData(url, format string) ([]byte, error) {
c.clearData()
return fetchData(c.Client, url, format)
}
// clearData - function clears data
func (c *NBPCurrency) clearData() {
c.result = nil
c.Exchange = exchangeCurrency{}
c.ExchangeC = exchangeCurrencyC{}
}
// --------------------- Private func ---------------------------------
// getCurrencyAddress - function builds download address depending on previously
// verified input parameters (--table, --date or --last, --code)
func (c *NBPCurrency) getCurrencyAddress(tableType, date string, last int, code string) string {
var address string
if last != 0 {
address = queryCurrencyLast(tableType, strconv.Itoa(last), code)
} else if date == "today" {
address = queryCurrencyToday(tableType, code)
} else if date == "current" {
address = queryCurrencyCurrent(tableType, code)
} else if len(date) == 10 {
address = queryCurrencyDate(tableType, date, code)
} else if len(date) == 21 {
address = queryCurrencyRange(tableType, date, code)
}
return address
}
// queryCurrencyLast - returns query: last <number> currency exchange
// rates in json/xml form, or error
func queryCurrencyLast(tableType, last, currency string) string {
return fmt.Sprintf("%s/rates/%s/%s/last/%s/", baseAddressCurrency, tableType, currency, last)
}
// queryCurrencyToday - returns query: today's currency exchange rate
func queryCurrencyToday(tableType, currency string) string {
return fmt.Sprintf("%s/rates/%s/%s/today/", baseAddressCurrency, tableType, currency)
}
// queryCurrencyCurrent - returns query: current exchange rate for
// particular currency (last published price)
func queryCurrencyCurrent(tableType, currency string) string {
return fmt.Sprintf("%s/rates/%s/%s/", baseAddressCurrency, tableType, currency)
}
// queryCurrencyDay - returns query: exchange rate for particular currency
// on the given date (YYYY-MM-DD)
func queryCurrencyDate(tableType, date, currency string) string {
return fmt.Sprintf("%s/rates/%s/%s/%s/", baseAddressCurrency, tableType, currency, date)
}
// queryCurrencyRange - returns query: exchange rate for particular currency
// within the given date range (RRRR-MM-DD:RRRR-MM-DD)
func queryCurrencyRange(tableType, date, currency string) string {
var startDate string
var stopDate string
temp := strings.Split(date, ":")
startDate = temp[0]
stopDate = temp[1]
address := fmt.Sprintf("%s/rates/%s/%s/%s/%s/", baseAddressCurrency, tableType, currency, startDate, stopDate)
return address
}