Debian Codegraph @

lib/Finance/Quote/TwelveData.pm

raw
1 #!/usr/bin/perl -w
2 # vi: set ts=2 sw=2 noai ic showmode showmatch:
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 # 02110-1301, USA
17
18 package Finance::Quote::TwelveData;
19 use strict;
20
21
22 use constant DEBUG => $ENV{DEBUG};
23 use if DEBUG, 'Smart::Comments';
24
25 use JSON qw( decode_json );
26 use HTTP::Request::Common;
27 use Text::Template;
28 use DateTime::Format::Strptime qw( strptime strftime );
29
30 our $VERSION = '1.71'; # VERSION
31
32 my $URL = Text::Template->new(TYPE => 'STRING', SOURCE => 'https://api.twelvedata.com/quote?symbol={$symbol}&apikey={$token}');
33 my $THROTTLE = 1.05 * 60.0/8.0; # 5% more than maximum seconds / request for free tier
34 my $AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36';
35
36 our $DISPLAY = 'TwelveData';
37 our $FEATURES = {'API_KEY' => 'registered user API key'};
38 our @LABELS = qw/symbol name exchange currency isodate currency open high low close last/;
39 our $METHODHASH = {subroutine => \&twelvedata,
40 display => $DISPLAY,
41 labels => \@LABELS,
42 features => $FEATURES};
43
44 sub methodinfo {
45 return (
46 twelvedata => $METHODHASH,
47 usa => $METHODHASH,
48 nyse => $METHODHASH,
49 nasdaq => $METHODHASH,
50 );
51 }
52
53 sub methods {
54 my %m = methodinfo(); return map {$_ => $m{$_}{subroutine} } keys %m;
55 }
56
57 sub labels {
58 my %m = methodinfo(); return map {$_ => [@{$m{$_}{labels}}] } keys %m;
59 }
60
61 sub parameters {
62 return ('API_KEY');
63 }
64
65
66 sub twelvedata {
67 my $quoter = shift;
68
69 my @stocks = @_;
70 my $quantity = @stocks;
71 my ( %info, $reply, $url, $code, $desc, $body, $mark );
72 my $ua = $quoter->user_agent();
73 my $agent = $ua->agent();
74 $ua->agent($AGENT);
75
76 my $token = exists $quoter->{module_specific_data}->{twelvedata}->{API_KEY} ?
77 $quoter->{module_specific_data}->{twelvedata}->{API_KEY} :
78 $ENV{"TWELVEDATA_API_KEY"};
79
80 foreach my $symbol (@stocks) {
81
82 if ( !defined $token ) {
83 $info{ $symbol, 'success' } = 0;
84 $info{ $symbol, 'errormsg' } =
85 'TwelveData API_KEY not defined. Get an API key at https://twelvedata.com';
86 next;
87 }
88
89 # Rate limit - first time through loop, mark is negative
90 $mark -= time();
91 ### TwelveData Mark: $mark
92 sleep($mark) if $mark > 0;
93 $mark = time() + $THROTTLE;
94
95 $url = $URL->fill_in(HASH => {symbol => $symbol, token => $token});
96 $reply = $ua->request(GET $url);
97
98 ### url: $url
99 ### reply: $reply
100
101 $code = $reply->code;
102 $desc = HTTP::Status::status_message($code);
103 $body = $reply->content;
104
105 if ($code != 200) {
106 $info{ $symbol, 'success' } = 0;
107 $info{ $symbol, 'errormsg' } = $desc;
108 next;
109 }
110
111 my $quote;
112 eval {$quote = JSON::decode_json $body};
113 if ($@) {
114 $info{ $symbol, 'success' } = 0;
115 $info{ $symbol, 'errormsg' } = $@;
116 next;
117 }
118
119 if (exists $quote->{'status'} and $quote->{'status'} eq 'error') {
120 $info{ $symbol, 'success' } = 0;
121 $info{ $symbol, 'errormsg' } = $quote->{'message'};
122 next;
123 }
124
125 if (not exists $quote->{'symbol'} or $quote->{'symbol'} ne $symbol) {
126 $info{ $symbol, 'success' } = 0;
127 $info{ $symbol, 'errormsg' } = "TwevleData return and unexpected json result";
128 next;
129 }
130
131 $info{ $symbol, 'success' } = 1;
132 $info{ $symbol, 'symbol' } = $symbol;
133 $info{ $symbol, 'name'} = $quote->{'name'} if $quote->{'name'};
134 $info{ $symbol, 'exchange'} = $quote->{'exchange'} if $quote->{'exchange'};
135 $info{ $symbol, 'currency'} = $quote->{'currency'} if $quote->{'currency'};
136 $info{ $symbol, 'open' } = $quote->{'open'} if $quote->{'open'};
137 $info{ $symbol, 'high' } = $quote->{'high'} if $quote->{'high'};
138 $info{ $symbol, 'low' } = $quote->{'low'} if $quote->{'low'};
139 $info{ $symbol, 'close' } = $quote->{'close'} if $quote->{'close'};
140 $info{ $symbol, 'last' } = $quote->{'close'} if $quote->{'close'};
141 $info{ $symbol, 'volume' } = $quote->{'volume'} if $quote->{'volume'};
142 $info{ $symbol, 'method' } = 'twelvedata';
143
144 my $time = strptime('%s', int($quote->{'timestamp'}));
145 my $isodate = strftime('%F', $time);
146 $quoter->store_date( \%info, $symbol, { isodate => $isodate } );
147 }
148
149 $ua->agent($agent);
150
151 return wantarray() ? %info : \%info;
152 }
153 1;
154
155 =head1 NAME
156
157 Finance::Quote::TwelveData - Obtain quotes from https://twelvedata.com
158
159 =head1 SYNOPSIS
160
161 use Finance::Quote;
162
163 $q = Finance::Quote->new('TwelveData', twelvedata => {API_KEY => 'your-twelvedata-api-key'});
164
165 %info = $q->fetch('twelvedata', 'IBM', 'AAPL');
166
167 =head1 DESCRIPTION
168
169 This module fetches information from https://twelvedata.com.
170
171 This module is loaded by default on a Finance::Quote object. It's
172 also possible to load it explicitly by placing "TwelveData" in the argument
173 list to Finance::Quote->new().
174
175 This module provides the "twelvedata" fetch method.
176
177 =head1 API_KEY
178
179 https://twelvedata.com requires users to register and obtain an API key, which
180 is a secret value written in hexidecimal.
181
182 The API key may be set by either providing a module specific hash to
183 Finance::Quote->new as in the above example, or by setting the environment
184 variable TWELVEDATA_API_KEY.
185
186 =head2 FREE KEY LIMITS
187
188 The TwelveData free key limits usage to:
189
190 =over
191
192 =item 800 queries per day
193
194 =item 8 queries per minute
195
196 =back
197
198 =head1 LABELS RETURNED
199
200 The following labels may be returned by Finance::Quote::TwelveData :
201 symbol name exchange currency isodate currency open high low close last
202
203 =cut