Framework/Spot/DatabaseAPI.pm untested

filter: Statementstmt 0.0% 0 / 232 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 14 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 348 CC 33 SCAR 27.4
CC
33
Cov
0%
get_first_tick
42.0
ohlc_start_end
20.0
ohlc_daily_list
20.0
CRAP 15.6
1 package Quant::Framework::Spot::DatabaseAPI;
2  
3 =head1 NAME
4  
5 Quant::Framework::Spot::DatabaseAPI
6  
7 =head1 DESCRIPTION
8  
9 The API class which we can query feed database.
10  
11 This class acts as a facade to the functions available in the DB. That is to say that that actual API is expressed by the functions in the DB.
12  
13 Each function available here has a function with same name inside the db.
14  
15 If any of the functions fail due to any reason it will cause an exception thrown straight from DBI layer.
16  
17 =cut
18  
19 use Moose;
20 use DateTime;
21 use Date::Utility;
22 use Quant::Framework::Spot::Tick;
23 use Quant::Framework::Spot::OHLC;
24  
25 has db_handle => (
26 is => 'ro',
27 required => 1,
28 );
29  
30 =head2 default_prefix
31  
32 The prefix used to create name of the table `feed.tick` which will contain spot, timestamp and underlying columns.
33  
34 =cut
35  
36 has default_prefix => (
37 is => 'ro',
38 default => 'feed.',
39 );
40  
41 =head2 dbh
42  
43 Return database handle. If db_handle is a normal reference, it will be used directly.
44 If it is a code-ref, it will be invoked to get the database handle.
45  
46 =cut
47  
48 sub dbh {
49 my $self = shift;
50  
51 if (ref($self->db_handle) eq 'CODE') {
52 return $self->db_handle->();
53 }
54  
55 return $self->db_handle;
56 }
57  
58 =head2 underlying
59  
60 The underlying symbol for which this API will fetch data
61  
62 =cut
63  
64 has underlying => (
65 is => 'ro',
66 isa => 'Str',
67 required => 1,
68 );
69  
70 =head2 invert_values
71  
72 If this argument is set, all tick and OHLC data will have their value inverted. This is useful when we have EURUSD feeds information but
73 want to have data for USDEUR underlying.
74  
75 =cut
76  
77 has 'invert_values' => (
78 is => 'ro',
79 );
80  
81 =head2 use_official_ohlc
82  
83 In case there are official and non-official OHLC values for an underlying, this flag specifies which type of data we want
84  
85 =cut
86  
87 has use_official_ohlc => (
88 is => 'ro',
89 );
90  
91 =head2 tick_at_for_interval
92  
93 Returns ticks in the given interval.
94  
95 =cut
96  
97 sub tick_at_for_interval {
98 my $self = shift;
99 my $args = shift;
100  
101 my $start_time = $args->{start_date}->datetime_yyyymmdd_hhmmss;
102 my $end_time = $args->{end_date}->datetime_yyyymmdd_hhmmss;
103 my $interval = $args->{interval_in_seconds};
104  
105 my $statement = $self->dbh->prepare_cached('SELECT * FROM tick_at_for_interval($1, $2, $3, $4)', {}, 3);
106 $statement->bind_param(1, $self->underlying);
107 $statement->bind_param(2, $start_time);
108 $statement->bind_param(3, $end_time);
109 $statement->bind_param(4, $interval);
110  
111 return $self->_query_ticks($statement);
112 }
113  
114 =head1 METHODS
115  
116 =head2 ticks_start_end
117  
118 get ticks from feed db filtered by
119 - start_time, end_time - All ticks between <start_time> and <end_time>
120  
121 Returns
122 ArrayRef[Quant::Framework::Spot::Tick]
123  
124 =cut
125  
126 sub ticks_start_end {
127 my $self = shift;
128 my $args = shift;
129  
130 my $start_time;
131 my $end_time;
132 $start_time = Date::Utility->new($args->{start_time})->datetime_yyyymmdd_hhmmss
133 if ($args->{start_time});
134  
135 $end_time = Date::Utility->new($args->{end_time})->datetime_yyyymmdd_hhmmss
136 if ($args->{end_time});
137  
138 my $statement = $self->dbh->prepare_cached('SELECT * FROM ticks_start_end($1, $2, $3)', {}, 3);
139 $statement->bind_param(1, $self->underlying);
140 $statement->bind_param(2, $start_time);
141 $statement->bind_param(3, $end_time);
142  
143 return $self->_query_ticks($statement);
144 }
145  
146 =head2 get_first_tick
147  
148 Find the first tick which breaches a barrier
149  
150 =cut
151  
152 sub get_first_tick {
153 my ($self, %args) = @_;
154  
155 my $underlying = $args{underlying};
156 my $system_symbol = $args{system_symbol};
157 my $pipsize = $args{pip_size};
158 my $start_time = Date::Utility->new($args{start_time})->db_timestamp;
159 my $end_time = Date::Utility->new($args{end_time} // time)->db_timestamp;
160 my @sql_args = ($system_symbol, $start_time, $end_time);
161 my $sql =
162 'SELECT EXTRACT(epoch FROM ts) AS epoch, spot FROM ' . ($self->default_prefix // '') . 'tick WHERE underlying = $1 AND ts >= $2 AND ts <= $3';
163  
164 my $next = 4;
165 my @barriers;
166 if ($args{higher}) {
167 push @barriers, "spot > \$$next";
168 push @sql_args, $args{higher} - $pipsize / 2;
169 $next++;
170 }
171 if ($args{lower}) {
172 push @barriers, "spot < \$$next";
173 push @sql_args, $args{lower} + $pipsize / 2;
174 $next++;
175 }
176 unless (@barriers) {
177 die "At least one of higher or lower must be specified";
178 }
179 $sql .= " AND (" . join(" OR ", @barriers) . q[) ORDER BY ts ASC LIMIT 1];
180  
181 my $statement = $self->dbh->prepare_cached($sql, {}, 3);
182 foreach my $which_param (1 .. scalar @sql_args) {
183  
184 # There has to be a more reasonable standard way to do this.
185 $statement->bind_param($which_param, $sql_args[$which_param - 1]);
186 }
187 my $tick;
188 if (my ($epoch, $quote) = $self->dbh->selectrow_array($statement)) {
189 $tick = Quant::Framework::Spot::Tick->new({
190 symbol => $underlying,
191 epoch => $epoch,
192 quote => $quote,
193 });
194 }
195  
196 $tick->invert_values if ($tick and $self->invert_values);
197  
198 return $tick;
199 }
200  
201 =head2 ticks_start_limit
202  
203 get ticks from feed db filtered by
204 - start_time, limit - <limit> number of ticks starting from <start_time>
205  
206 Returns
207 ArrayRef[Quant::Framework::Spot::Tick]
208  
209 =cut
210  
211 sub ticks_start_limit {
212 my $self = shift;
213 my $args = shift;
214  
215 my $start_time;
216 $start_time = Date::Utility->new($args->{start_time})->datetime_yyyymmdd_hhmmss
217 if ($args->{start_time});
218  
219 my $statement = $self->dbh->prepare_cached('SELECT * FROM ticks_start_limit($1, $2, $3)', {}, 3);
220 $statement->bind_param(1, $self->underlying);
221 $statement->bind_param(2, $start_time);
222 $statement->bind_param(3, $args->{limit});
223  
224 my $ticks = $self->_query_ticks($statement);
225  
226 # It would probably be more efficient to do this at the db level, but
227 # I don't have that luxury at present.
228 if ($args->{end_time}) {
229 my $end_epoch = Date::Utility->new($args->{end_time})->epoch;
230 $ticks = [grep { $_->epoch <= $end_epoch } @{$ticks}];
231 }
232  
233 return $ticks;
234 }
235  
236 =head2 ticks_end_limit
237  
238 get ticks from feed db filtered by
239 - end_time, limit - <limit> number ticks before <end_time>
240  
241 Returns
242 ArrayRef[Quant::Framework::Spot::Tick]
243  
244 =cut
245  
246 sub ticks_end_limit {
247 my $self = shift;
248 my $args = shift;
249  
250 my $end_time;
251 $end_time = Date::Utility->new($args->{end_time})->datetime_yyyymmdd_hhmmss
252 if ($args->{end_time});
253  
254 my $statement = $self->dbh->prepare_cached('SELECT * FROM ticks_end_limit($1, $2, $3)', {}, 3);
255 $statement->bind_param(1, $self->underlying);
256 $statement->bind_param(2, $end_time);
257 $statement->bind_param(3, $args->{limit});
258  
259 return $self->_query_ticks($statement);
260 }
261  
262 =head2 tick_at
263  
264 get a valid tick at time given or not a valid tick before a given time. Accept argument
265 - end_time - Time at which we want the tick
266 - allow_inconsistent - if this is passed then we get the last available tick, we do not care if its a valid ick or not.
267  
268 Returns
269 Quant::Framework::Spot::Tick
270  
271 =cut
272  
273 sub tick_at {
274 my $self = shift;
275 my $args = shift;
276 my $tick;
277  
278 return unless ($args->{end_time});
279 my $end_time = Date::Utility->new($args->{end_time});
280  
281 my $sql =
282 ($args->{allow_inconsistent})
283 ? 'SELECT * FROM tick_at_or_before($1, $2::TIMESTAMP)'
284 : 'SELECT * FROM consistent_tick_at_or_before($1, $2::TIMESTAMP)';
285 my $statement = $self->dbh->prepare_cached($sql, {}, 3);
286 $statement->bind_param(1, $self->underlying);
287 $statement->bind_param(2, $end_time->db_timestamp);
288  
289 return $self->_query_single_tick($statement);
290 }
291  
292 =head2 tick_after
293  
294 get tick from feed db after the time given.
295 - start_time - the first tick after <start_time>
296  
297 Returns
298 ArrayRef[Quant::Framework::Spot::Tick]
299  
300 =cut
301  
302 sub tick_after {
303 my $self = shift;
304 my $time = shift;
305 return unless ($time);
306  
307 $time = Date::Utility->new($time);
308  
309 my $statement = $self->dbh->prepare_cached('SELECT * FROM tick_after($1, $2)', {}, 3);
310 $statement->bind_param(1, $self->underlying);
311 $statement->bind_param(2, $time->datetime_yyyymmdd_hhmmss);
312  
313 return $self->_query_single_tick($statement);
314 }
315  
316 =head2 ticks_start_end_with_limit_for_charting
317  
318 get ticks from feed db filtered by
319 - start_time, end_time, limit - all ticks between <start_time> and <end_time> and limit to <limit> entries.
320 This method is appropriate for charting applications where a limited number of prices are going to be displayed.
321  
322 Returns
323 ArrayRef[Quant::Framework::Spot::Tick]
324  
325 =cut
326  
327 sub ticks_start_end_with_limit_for_charting {
328 my $self = shift;
329 my $args = shift;
330  
331 my $start_time;
332 my $end_time;
333 $start_time = Date::Utility->new($args->{start_time})->datetime_yyyymmdd_hhmmss
334 if ($args->{start_time});
335 $end_time = Date::Utility->new($args->{end_time})->datetime_yyyymmdd_hhmmss
336 if ($args->{end_time});
337  
338 my $statement = $self->dbh->prepare_cached('SELECT * FROM ticks_start_end_with_limit_for_charting($1, $2, $3, $4)', {}, 3);
339 $statement->bind_param(1, $self->underlying);
340 $statement->bind_param(2, $start_time);
341 $statement->bind_param(3, $end_time);
342 $statement->bind_param(4, $args->{limit});
343  
344 return $self->_query_ticks($statement);
345 }
346  
347 =head2 $self->ohlc_start_end(\%args)
348  
349 This method returns reference to the list of OHLC for the specified period.
350 Accepts following arguments:
351  
352 =over 4
353  
354 =item B<start_time>
355  
356 Compute OHLC starting from the specified time. Note, that if I<start_time> is
357 not at the beginning of the unit used by the source table (minutes, hour, or
358 days depending on I<aggregation_period>) it will be aligned to the start of the
359 next unit. But timestamp of the returned OHLC may be pointing to earlier moment
360 of time, e.g. for weekly and monthly OHLC it will point to the start of week or
361 month, even though actual OHLC value may be computed from the middle of week or
362 month.
363  
364 =item B<end_time>
365  
366 Compute OHLC till specified time. Note, that it will be aligned so timestamp
367 would be multiple of I<aggregation_period>.
368  
369 =item B<aggregation_period>
370  
371 Compute OHLCs for periods of the specified duration.
372  
373 =over 4
374  
375 =item *
376  
377 if period is less than a minute, then feed.tick table is used a the source
378  
379 =item *
380  
381 if period is from one minute and less than an hour, then feed.ohlc_minutely is
382 used as source. Using period that is not multiple of a minute is not wise as
383 returned data may not make much sense.
384  
385 =item *
386  
387 if period is one hour or more, but less than a day, then feed.ohlc_hourly is
388 used as source of data. Don't use intervals that not multiple of an hour.
389  
390 =item *
391  
392 if period is a day or more, then ohlc_daily is used as the source of data.
393 Don't use intervals that are not multiple of a day. If number of days is 7 then
394 I<end_time> will be aligned to the end of the week, and all intevals will start
395 at the start of the week (first interval may not actually start at the start of
396 the week, although timestamp in OHLC will indicate that it is). If number of
397 days is 30 then I<end_time> will be aligned to the end of the month and all
398 intervals will start at the start of the month (except maybe the first one).
399  
400 =back
401  
402 =back
403  
404 If interval is multiple of a day, than method will use official daily OHLC if
405 underlying has daily OHLC. It will never set I<official> property or returned
406 OHLC objects though.
407  
408 Method returns reference to a list of
409 L<Quant::Framework::Spot::OHLC>
410  
411 =cut
412  
413 sub ohlc_start_end {
414 my $self = shift;
415 my $args = shift;
416  
417 my $start_time;
418 my $end_time;
419 $start_time = Date::Utility->new($args->{start_time})->datetime_yyyymmdd_hhmmss
420 if ($args->{start_time});
421 $end_time = Date::Utility->new($args->{end_time})->datetime_yyyymmdd_hhmmss
422 if ($args->{end_time});
423  
424 my $statement = $self->dbh->prepare_cached('SELECT * FROM ohlc_start_end($1, $2, $3, $4, $5)', {}, 3);
425 $statement->bind_param(1, $self->underlying);
426 $statement->bind_param(2, $args->{aggregation_period});
427 $statement->bind_param(3, $start_time);
428 $statement->bind_param(4, $end_time);
429 $statement->bind_param(5, $self->use_official_ohlc ? 'TRUE' : 'FALSE');
430  
431 return $self->_query_ohlc($statement);
432 }
433  
434 =head2 $self->ohlc_daily_list(\%args)
435  
436 This method returns reference to list of daily OHLC for the specified period.
437 First and last OHLC maybe computed for the part of the day using ticks in
438 feed.tick table and not precomputed daily OHLC, so these two are non-official
439 OHLC. The rest of OHLCs may be official, but I<official> attribute won't be set
440 on them. Method accepts the following parameters:
441  
442 =over 4
443  
444 =item B<start_time>
445  
446 Compute OHLCs starting from the specified time
447  
448 =item B<end_time>
449  
450 Compute OHLCs till the specified moment of time
451  
452 =back
453  
454 Method returns reference to a list of L<Quant::Framework::Spot::OHLC> objects
455  
456 =cut
457  
458 sub ohlc_daily_list {
459 my $self = shift;
460 my $args = shift;
461  
462 my $start_time;
463 my $end_time;
464 $start_time = Date::Utility->new($args->{start_time})->datetime_yyyymmdd_hhmmss
465 if ($args->{start_time});
466 $end_time = Date::Utility->new($args->{end_time})->datetime_yyyymmdd_hhmmss
467 if ($args->{end_time});
468  
469 my $statement = $self->dbh->prepare_cached('SELECT * FROM ohlc_daily_list($1, $2, $3, $4)', {}, 3);
470 $statement->bind_param(1, $self->underlying);
471 $statement->bind_param(2, $start_time);
472 $statement->bind_param(3, $end_time);
473 $statement->bind_param(4, $self->use_official_ohlc ? 'TRUE' : 'FALSE');
474  
475 return $self->_query_ohlc($statement);
476 }
477  
478 =head2 ohlc_start_end_with_limit_for_charting
479  
480 Returns OHLC in the given start/end period
481  
482 =cut
483  
484 sub ohlc_start_end_with_limit_for_charting {
485 my $self = shift;
486 my $args = shift;
487  
488 my $start_time;
489 my $end_time;
490 $start_time = Date::Utility->new($args->{start_time})->datetime_yyyymmdd_hhmmss
491 if ($args->{start_time});
492 $end_time = Date::Utility->new($args->{end_time})->datetime_yyyymmdd_hhmmss
493 if ($args->{end_time});
494  
495 my $statement = $self->dbh->prepare_cached('SELECT * FROM ohlc_start_end_with_limit_for_charting ($1, $2, $3, $4, $5, $6)', {}, 3);
496 $statement->bind_param(1, $self->underlying);
497 $statement->bind_param(2, $args->{aggregation_period});
498 $statement->bind_param(3, $start_time);
499 $statement->bind_param(4, $end_time);
500 $statement->bind_param(5, $self->use_official_ohlc ? 'TRUE' : 'FALSE');
501 $statement->bind_param(6, $args->{limit});
502  
503 return $self->_query_ohlc($statement);
504 }
505  
506 =head2 ohlc_daily_until_now_for_charting
507  
508 Returns daily OHLC values for the period starting from given date till today.
509  
510 =cut
511  
512 sub ohlc_daily_until_now_for_charting {
513 my ($self, $args) = @_;
514 my $limit = $args->{limit};
515  
516 my $query_ohlc = {
517 limit => $limit,
518 aggregation_period => 86400
519 };
520  
521 #estimate begin time and end time(crazy stuff)
522 my $now = DateTime->now();
523 $now->add(days => 1);
524 $query_ohlc->{end_time} = $now->ymd('-') . ' ' . $now->hms;
525 $now->subtract(days => ($limit + 1));
526 $query_ohlc->{start_time} = $now->ymd('-') . ' ' . $now->hms;
527  
528 return $self->ohlc_start_end_with_limit_for_charting($query_ohlc);
529 }
530  
531 sub _query_ticks {
532 my $self = shift;
533 my $statement = shift;
534  
535 my $symbol = $self->underlying;
536  
537 my @ticks;
538 if ($statement->execute()) {
539 my ($epoch, $quote, $bid, $ask);
540 $statement->bind_col(1, \$epoch);
541 $statement->bind_col(2, \$quote);
542 $statement->bind_col(3, undef);
543 $statement->bind_col(4, \$bid);
544 $statement->bind_col(5, \$ask);
545  
546 while ($statement->fetch()) {
547 my $tick_compiled = Quant::Framework::Spot::Tick->new({
548 symbol => $symbol,
549 epoch => $epoch,
550 quote => $quote,
551 bid => $bid,
552 ask => $ask,
553 });
554 $tick_compiled->invert_values if ($self->invert_values);
555 push @ticks, $tick_compiled;
556 }
557 }
558  
559 return \@ticks;
560 }
561  
562 sub _query_single_tick {
563 my $self = shift;
564 my $statement = shift;
565 my $tick_compiled;
566 if ($statement->execute()) {
567 my ($epoch, $quote, $bid, $ask);
568 $statement->bind_col(1, \$epoch);
569 $statement->bind_col(2, \$quote);
570 $statement->bind_col(3, undef);
571 $statement->bind_col(4, \$bid);
572 $statement->bind_col(5, \$ask);
573  
574 # At least one db function (tick_at_or_before) returns a data type
575 # instead of a table, which means fetch will always get 1 row result
576 # but all fields are null. So we check whether the epoch returned is
577 # anything truish before assuming we got good data back.
578 if ($statement->fetch() and $epoch) {
579 $tick_compiled = Quant::Framework::Spot::Tick->new({
580 symbol => $self->underlying,
581 epoch => $epoch,
582 quote => $quote,
583 bid => $bid,
584 ask => $ask,
585 });
586 }
587 }
588  
589 $tick_compiled->invert_values
590 if ($tick_compiled and $self->invert_values);
591 return $tick_compiled;
592 }
593  
594 sub _query_ohlc {
595 my $self = shift;
596 my $statement = shift;
597  
598 my @ohlc_data;
599 if ($statement->execute()) {
600 my ($epoch, $open, $high, $low, $close);
601 $statement->bind_col(1, \$epoch);
602 $statement->bind_col(2, \$open);
603 $statement->bind_col(3, \$high);
604 $statement->bind_col(4, \$low);
605 $statement->bind_col(5, \$close);
606  
607 while ($statement->fetch()) {
608 my $ohlc_compiled = Quant::Framework::Spot::OHLC->new({
609 epoch => $epoch,
610 open => $open,
611 high => $high,
612 low => $low,
613 close => $close,
614 });
615 $ohlc_compiled->invert_values if ($self->invert_values);
616 push @ohlc_data, $ohlc_compiled;
617 }
618 }
619  
620 return \@ohlc_data;
621 }
622  
623 no Moose;
624 __PACKAGE__->meta->make_immutable;
625  
626 1;