App/financeta/gui.pm

filter: Statementstmt 94.7% 36 / 38 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 13 / 13 Podpod n/a totaltotal 96.0% 49 / 51 CC 1 SCAR 0.2
CC
1
Cov
95%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« App/financeta/gui/tradereport.pm ↑ Summary
1 package App::financeta::gui;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use 5.10.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 our $VERSION = '0.16';
7 $VERSION = eval $VERSION;
8 1 ▶use App::financeta::mo;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use App::financeta::utils qw(dumper log_filter get_icon_path get_file_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Log::Any '$log', filter => \&App::financeta::utils::log_filter;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use File::HomeDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use File::Path ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 if ($^O !~ /win32/i) {
18 eval {
19 require POE;
20 require POE::Kernel;
21 POE::Kernel->import({loop => 'Prima'});
22 require POE::Session;
23 } or die "Unable to load POE::Loop::Prima";
24 }
25 0 ▶use Prima qw(
Subroutine BEGIN: called CC=1 SCAR=2.6
26 Application Buttons MsgBox Calendar ComboBox Notebooks
27 Widget::ScrollWidget DetailedList Dialog::ColorDialog
28 Dialog::FileDialog Dialog::FindDialog ScrollBar
29 Dialog::PrintDialog Dialog::ImageDialog Dialog::FontDialog
30 sys::GUIException Utils
31 0 );
32 use Prima::Utils ();
33 use Capture::Tiny ();
34 use PDL::Lite;
35 use PDL::IO::Misc;
36 use PDL::NiceSlice;
37 use PDL::Graphics::Gnuplot;
38 use App::financeta::gui::security_wizard;
39 use App::financeta::gui::progress_bar;
40 use App::financeta::gui::editor;
41 use App::financeta::gui::tradereport;
42 use App::financeta::indicators;
43 use App::financeta::data;
44 use Scalar::Util qw(blessed);
45 use Browser::Open ();
46 use YAML::Any ();
47 use JSON::XS qw(encode_json);
48 use Template;
49  
50 $PDL::doubleformat = "%0.6lf";
51 $| = 1;
52 has debug => 0;
53 has timezone => 'America/New_York';
54 has brand => __PACKAGE__;
55 has main => (builder => '_build_main');
56 has tmpdir => ( default => sub {
57 my $dir = $ENV{TEMP} || $ENV{TMP} || $ENV{APPDATA} if $^O =~ /Win32|Cygwin/i;
58 $dir //= $ENV{TMPDIR} || File::Spec->tmpdir;
59 $dir //= '/tmp' unless $^O =~ /Win32|Cygwin/i;
60 $dir = File::Spec->catdir($dir, $ENV{USER} || getlogin(), 'financeta');
61 File::Path::make_path($dir) unless -d $dir;
62 return $dir;
63 });
64 has datadir => ( default => sub {
65 my $dir = $ENV{DATADIR} || File::Spec->catfile(File::HomeDir->my_home, '.financeta');
66 File::Path::make_path($dir) unless -d $dir;
67 return $dir;
68 });
69 has plot_engine => 'highcharts';
70 has current => {};
71 has indicator => (builder => '_build_indicator');
72 has tab_was_closed => 0;
73 has editors => {};
74 has tradereports => {};
75 has list_sources => ['yahoo', 'gemini'];
76 has list_sources_pretty => ['Yahoo! Finance', 'Gemini Crypto Exchange'];
77 has list_sources_urls => ['https://finance.yahoo.com', 'https://docs.gemini.com/rest-api/?python#symbols'];
78  
79 sub _build_indicator {
80 my $self = shift;
81 return App::financeta::indicators->new(debug => $self->debug,
82 plot_engine => $self->plot_engine);
83 }
84  
85 sub _build_editor {
86 my $self = shift;
87 my $name = shift || '';
88 $name =~ s/tab_//g if length $name;
89 return App::financeta::gui::editor->new(debug => $self->debug,
90 parent => $self, brand => $self->brand . " Rules Editor for $name");
91 }
92  
93 sub _build_tradereport {
94 my $self = shift;
95 my $name = shift || '';
96 $name =~ s/tab_//g if length $name;
97 return App::financeta::gui::tradereport->new(debug => $self->debug,
98 parent => $self, brand => $self->brand . " Trade Report for $name");
99 }
100  
101 sub icon {
102 my $icon_path = get_icon_path(__PACKAGE__);
103 return (defined $icon_path) ? Prima::Icon->load($icon_path) : undef;
104 }
105  
106 sub _build_main {
107 my $self = shift;
108 my $mw = Prima::MainWindow->new(
109 name => 'main',
110 text => $self->brand,
111 size => [800, 600],
112 centered => 1,
113 menuItems => $self->_menu_items,
114 # force border styles for consistency
115 borderIcons => bi::All,
116 borderStyle => bs::Sizeable,
117 windowState => ws::Normal,
118 icon => $self->icon,
119 #ownerIcon => 0,
120 # origin
121 left => 10,
122 top => 0,
123 );
124 $mw->maximize;
125 $log->debug("Creating main window");
126 return $mw;
127 }
128  
129 sub _menu_items {
130 my $self = shift;
131 $log->debug("Creating menu items");
132 my $help_menu = [
133 '~Help' => [
134 [
135 'help_viewer', 'Documentation', 'F1', kb::F1,
136 sub {
137 my $url = 'https://vikasnkumar.github.io/financeta/';
138 $log->info("Opening $url in your default browser.");
139 my $ok = Browser::Open::open_browser($url, 1);
140 if (not defined $ok) {
141 message("Error finding a browser to open $url");
142 $log->warn("Error finding a default browser to open $url");
143 } elsif ($ok != 0) {
144 message("Error opening $url");
145 $log->warn("Error opening $url in default browser");
146 }
147 }, $self,
148 ],
149 ],
150 ];
151 my $security_menu = [
152 '~Security' => [
153 [
154 'security_new', '~New', 'Ctrl+N', '^N',
155 sub {
156 my ($win, $item) = @_;
157 ## as of Prima 1.58 .data was renamed to .options
158 my $gui = $win->menu->options($item);
159 unless (ref $gui eq __PACKAGE__) {
160 $log->error("Invalid gui object passed to menu item $item");
161 return;
162 }
163 if ($gui->security_wizard($win)) {
164 my $bar = App::financeta::gui::progress_bar->new(owner => $win, title => 'Downloading...');
165 # download security data
166 my ($data, $symbol, $csv) = $gui->download_data($bar);
167 if (defined $data) {
168 $gui->display_data($win, $data);
169 my ($info, $tname) = $gui->get_tab_info($win);
170 if ($info and $csv) {
171 $info->{csv} = $csv;
172 $gui->set_tab_info($win, $info);
173 }
174 my $type = $gui->current->{plot_type} || 'OHLC';
175 $gui->plot_data($win, $data, $symbol, $type);
176 $gui->enable_menu_options($win);
177 }
178 $bar->close if $bar;
179 }
180 },
181 $self,
182 ],
183 [
184 'security_open', '~Open', 'Ctrl+O', '^O',
185 sub {
186 my ($win, $item) = @_;
187 my $gui = $win->menu->options($item);
188 unless (ref $gui eq __PACKAGE__) {
189 $log->error("Invalid gui object passed to menu item $item");
190 return;
191 }
192 $gui->load_new_tab($win);
193 },
194 $self,
195 ],
196 [
197 '-security_save', '~Save', 'Ctrl+S', '^S',
198 sub {
199 my ($win, $item) = @_;
200 my $gui = $win->menu->options($item);
201 unless (ref $gui eq __PACKAGE__) {
202 $log->error("Invalid gui object passed to menu item $item");
203 return;
204 }
205 $gui->save_current_tab($win, 0);
206 },
207 $self,
208 ],
209 [
210 '-security_saveas', 'Save As', '', '',
211 sub {
212 my ($win, $item) = @_;
213 my $gui = $win->menu->options($item);
214 unless (ref $gui eq __PACKAGE__) {
215 $log->error("Invalid gui object passed to menu item $item");
216 return;
217 }
218 $gui->save_current_tab($win, 1);
219 },
220 $self,
221 ],
222 [
223 '-security_close', '~Close', 'Ctrl+W', '^W',
224 sub {
225 my ($win, $item) = @_;
226 my $gui = $win->menu->options($item);
227 unless (ref $gui eq __PACKAGE__) {
228 $log->error("Invalid gui object passed to menu item $item");
229 return;
230 }
231 $gui->close_current_tab($win);
232 },
233 $self,
234 ],
235 [
236 'app_exit', 'E~xit', 'Ctrl+Q', '^Q',
237 sub {
238 my ($win, $item) = @_;
239 my $gui = $win->menu->options($item);
240 unless (ref $gui eq __PACKAGE__) {
241 $log->error("Invalid gui object passed to menu item $item");
242 return;
243 }
244 $gui->close_all($win);
245 },
246 $self,
247 ],
248 ],
249 ];
250 my $plot_menu = [
251 '~Plot' => [
252 [
253 '-*plot_ohlc', 'OHLC', '', '',
254 sub {
255 my ($win, $item) = @_;
256 my $gui = $win->menu->options($item);
257 unless (ref $gui eq __PACKAGE__) {
258 $log->error("Invalid gui object passed to menu item $item");
259 return;
260 }
261 my ($data, $symbol, $indicators, $h, $bs) = $gui->get_tab_data($win);
262 $gui->plot_data($win, $data, $symbol, 'OHLC', $indicators, $bs);
263 $win->menu->check('plot_ohlc');
264 $win->menu->uncheck('plot_ohlcv');
265 $win->menu->uncheck('plot_close');
266 $win->menu->uncheck('plot_closev');
267 $win->menu->uncheck('plot_cdl');
268 $win->menu->uncheck('plot_cdlv');
269 },
270 $self,
271 ],
272 [
273 '-plot_ohlcv', 'OHLC & Volume', '', '',
274 sub {
275 my ($win, $item) = @_;
276 my $gui = $win->menu->options($item);
277 unless (ref $gui eq __PACKAGE__) {
278 $log->error("Invalid gui object passed to menu item $item");
279 return;
280 }
281 my ($data, $symbol, $indicators, $h, $bs) = $gui->get_tab_data($win);
282 $gui->plot_data($win, $data, $symbol, 'OHLCV', $indicators, $bs);
283 $win->menu->check('plot_ohlcv');
284 $win->menu->uncheck('plot_ohlc');
285 $win->menu->uncheck('plot_close');
286 $win->menu->uncheck('plot_closev');
287 $win->menu->uncheck('plot_cdl');
288 $win->menu->uncheck('plot_cdlv');
289 },
290 $self,
291 ],
292 [
293 '-plot_close', 'Close Price', '', '',
294 sub {
295 my ($win, $item) = @_;
296 my $gui = $win->menu->options($item);
297 unless (ref $gui eq __PACKAGE__) {
298 $log->error("Invalid gui object passed to menu item $item");
299 return;
300 }
301 my ($data, $symbol, $indicators, $h, $bs) = $gui->get_tab_data($win);
302 $gui->plot_data($win, $data, $symbol, 'CLOSE', $indicators, $bs);
303 $win->menu->check('plot_close');
304 $win->menu->uncheck('plot_ohlc');
305 $win->menu->uncheck('plot_ohlcv');
306 $win->menu->uncheck('plot_closev');
307 $win->menu->uncheck('plot_cdl');
308 $win->menu->uncheck('plot_cdlv');
309 },
310 $self,
311 ],
312 [
313 '-plot_closev', 'Close Price & Volume', '', '',
314 sub {
315 my ($win, $item) = @_;
316 my $gui = $win->menu->options($item);
317 unless (ref $gui eq __PACKAGE__) {
318 $log->error("Invalid gui object passed to menu item $item");
319 return;
320 }
321 my ($data, $symbol, $indicators, $h, $bs) = $gui->get_tab_data($win);
322 $gui->plot_data($win, $data, $symbol, 'CLOSEV', $indicators, $bs);
323 $win->menu->check('plot_closev');
324 $win->menu->uncheck('plot_ohlc');
325 $win->menu->uncheck('plot_ohlcv');
326 $win->menu->uncheck('plot_close');
327 $win->menu->uncheck('plot_cdl');
328 $win->menu->uncheck('plot_cdlv');
329 },
330 $self,
331 ],
332 [
333 '-plot_cdl', 'Candlesticks', '', '',
334 sub {
335 my ($win, $item) = @_;
336 my $gui = $win->menu->options($item);
337 unless (ref $gui eq __PACKAGE__) {
338 $log->error("Invalid gui object passed to menu item $item");
339 return;
340 }
341 my ($data, $symbol, $indicators, $h, $bs) = $gui->get_tab_data($win);
342 $gui->plot_data($win, $data, $symbol, 'CANDLE', $indicators, $bs);
343 $win->menu->check('plot_cdl');
344 $win->menu->uncheck('plot_ohlc');
345 $win->menu->uncheck('plot_ohlcv');
346 $win->menu->uncheck('plot_close');
347 $win->menu->uncheck('plot_closev');
348 $win->menu->uncheck('plot_cdlv');
349 },
350 $self,
351 ],
352 [
353 '-plot_cdlv', 'Candlesticks & Volume', '', '',
354 sub {
355 my ($win, $item) = @_;
356 my $gui = $win->menu->options($item);
357 unless (ref $gui eq __PACKAGE__) {
358 $log->error("Invalid gui object passed to menu item $item");
359 return;
360 }
361 my ($data, $symbol, $indicators, $h, $bs) = $gui->get_tab_data($win);
362 $gui->plot_data($win, $data, $symbol, 'CANDLEV', $indicators, $bs);
363 $win->menu->check('plot_cdlv');
364 $win->menu->uncheck('plot_ohlc');
365 $win->menu->uncheck('plot_ohlcv');
366 $win->menu->uncheck('plot_close');
367 $win->menu->uncheck('plot_closev');
368 $win->menu->uncheck('plot_cdl');
369 },
370 $self,
371 ],
372 [
373 sprintf('-%splot_using_highcharts', ($self->plot_engine eq 'highcharts') ? '*' : ''),
374 'Use HighCharts', '', '',
375 sub {
376 my ($win, $item) = @_;
377 $win->menu->check('plot_using_highcharts');
378 $win->menu->uncheck('plot_using_gnuplot');
379 my $gui = $win->menu->options($item);
380 unless (ref $gui eq __PACKAGE__) {
381 $log->error("Invalid gui object passed to menu item $item");
382 return;
383 }
384 $gui->plot_engine('highcharts');
385 $gui->indicator->plot_engine('highcharts');
386 $log->info("Changing plot engine to " . $self->plot_engine);
387 my $pwin = $win->{plot};
388 $pwin->close if $pwin;
389 },
390 $self,
391 ],
392 [
393 sprintf('-%splot_using_gnuplot', ($self->plot_engine eq 'gnuplot') ? '*' : ''),
394 'Use Gnuplot', '', '',
395 sub {
396 my ($win, $item) = @_;
397 $win->menu->check('plot_using_gnuplot');
398 $win->menu->uncheck('plot_using_highcharts');
399 my $gui = $win->menu->options($item);
400 unless (ref $gui eq __PACKAGE__) {
401 $log->error("Invalid gui object passed to menu item $item");
402 return;
403 }
404 $gui->plot_engine('gnuplot');
405 $gui->indicator->plot_engine('gnuplot');
406 $log->info("Changing plot engine to " . $self->plot_engine);
407 },
408 $self,
409 ],
410 ],
411 ];
412 my $analysis_menu = [
413 '~Analysis' => [
414 [
415 '-add_indicator', 'Add Indicator', 'Ctrl+I', '^I',
416 sub {
417 my ($win, $item) = @_;
418 my $gui = $win->menu->options($item);
419 unless (ref $gui eq __PACKAGE__) {
420 $log->error("Invalid gui object passed to menu item $item");
421 return;
422 }
423 my ($data, $symbol, $indicators) = $gui->get_tab_data($win);
424 # ok add an indicator which also plots it
425 if ($gui->add_indicator($win, $data, $symbol)) {
426 $win->menu->remove_indicator->enabled(1);
427 }
428 },
429 $self,
430 ],
431 [
432 '-remove_indicator', 'Remove Indicator', 'Ctrl+Shift+I', '^#I',
433 sub {
434 my ($win, $item) = @_;
435 my $gui = $win->menu->options($item);
436 unless (ref $gui eq __PACKAGE__) {
437 $log->error("Invalid gui object passed to menu item $item");
438 return;
439 }
440 # ok remove the indicator and update the plots and
441 # display tables
442 $gui->remove_indicator($win);
443 },
444 $self,
445 ],
446 [
447 '-edit_rules', '~Edit Rules', 'Ctrl+E', '^E',
448 sub {
449 my ($win, $item) = @_;
450 my $gui = $win->menu->options($item);
451 unless (ref $gui eq __PACKAGE__) {
452 $log->error("Invalid gui object passed to menu item $item");
453 return;
454 }
455 my ($info, $tabname) = $self->get_tab_info($win);
456 $self->open_editor($win, $info->{rules}, $tabname);
457 },
458 $self,
459 ],
460 [
461 '-execute_rules', 'Execute ~Rules', 'Ctrl+R', '^R',
462 sub {
463 my ($win, $item) = @_;
464 my $gui = $win->menu->options($item);
465 unless (ref $gui eq __PACKAGE__) {
466 $log->error("Invalid gui object passed to menu item $item");
467 return;
468 }
469 my ($info, $tabname) = $self->get_tab_info($win);
470 $self->execute_rules_no_editor($win, $tabname, $info->{rules});
471 $win->menu->trade_report->enabled(1);
472 },
473 $self,
474 ],
475 [
476 '-trade_report', 'Trade Report', '', '',
477 sub {
478 my ($win, $item) = @_;
479 my $gui = $win->menu->options($item);
480 unless (ref $gui eq __PACKAGE__) {
481 $log->error("Invalid gui object passed to menu item $item");
482 return;
483 }
484 my ($info, $tabname) = $self->get_tab_info($win);
485 my $buysells = $self->get_tab_buysells_for_name($win, $tabname);
486 $self->open_tradereport($win, $tabname, $buysells);
487 },
488 $self,
489 ],
490 ],
491 ];
492 return [ $security_menu, $plot_menu, $analysis_menu, $help_menu ];
493 }
494  
495 sub close_all {
496 my ($self, $win) = @_;
497 my $pwin = $win->{plot};
498 $pwin->close if $pwin;
499 $log->info("Closing all open windows");
500 $win->close if $win;
501 $::application->close;
502 }
503  
504 sub run {
505 my $self = shift;
506 $self->main->show;
507 $self->disable_menu_options; # to be safe
508 my $stack_sub = sub {
509 my $sig = shift;
510 my $stackdump = Carp::longmess();
511 $log->error("Signal caught: SIG$sig\n$stackdump\n");
512 Prima::Utils::post(sub {
513 if ($::application) {
514 my $choice = Prima::MsgBox::signal_dialog('Error',
515 "Signal caught: SIG$sig", $stackdump);
516 if ($choice == mb::Abort) {
517 $log->error("Exiting the application");
518 exit;
519 } else {
520 $log->error("Not exiting the application");
521 }
522 }
523 });
524 };
525 # Prima::sys::GUIException takes care of __DIE__
526 local $SIG{SEGV} = $stack_sub;
527 local $SIG{INT} = $stack_sub;
528 local $SIG{QUIT} = $stack_sub;
529 local $SIG{TERM} = $stack_sub;
530 local $SIG{HUP} = $stack_sub;
531 run Prima;
532 }
533  
534 sub security_wizard {
535 my ($self, $win) = @_;
536 my $wiz = App::financeta::gui::security_wizard->new(owner => $win, gui => $self);
537 return ($wiz->run() == mb::Ok) ? 1 : undef;
538 }
539  
540 sub remove_indicator($) {
541 my ($self, $win) = @_;
542 my $result = $self->remove_indicator_wizard($win);
543 if ($result and ref $result eq 'HASH') {
544 $log->debug("Removing indicator: ", dumper($result));
545 # we know here the name of the indicator, the index of the indicator and
546 # the columns in the data to remove.
547 # let's do that.
548 my ($data, $symbol, $indicators, $headers) = $self->get_tab_data_by_name($win, $result->{tab});
549 return unless $headers;
550 my $total_cols = $data->dim(1);
551 my @ncols = (0 .. $total_cols - 1); # get a list of column numbers
552 my @nhdrs = (@$headers);
553 return unless $result->{columns};
554 my @cols2rem = @{$result->{columns}};
555 foreach my $c (@cols2rem) {
556 $ncols[$c] = undef;
557 $nhdrs[$c] = undef;
558 }
559 @nhdrs = grep { defined $_ } @nhdrs;
560 @ncols = grep { defined $_ } @ncols;
561 $log->debug("New Headers: ", dumper(\@nhdrs));
562 $log->debug("Remaining columns: ", dumper(\@ncols));
563 my $ndata = $data->dice('X', \@ncols);
564 my $nindics = [];
565 if ($indicators) {
566 my $index = $result->{indicator_index};
567 for (0 .. scalar(@$indicators) - 1) {
568 next if $_ == $index;
569 push @$nindics, $indicators->[$_];
570 }
571 }
572 if ($self->set_tab_data_by_name($win, $result->{tab}, $ndata, $symbol, $nindics, \@nhdrs)) {
573 $log->debug("Successfully set data");
574 $self->display_data($win, $ndata, $symbol);
575 my ($adata, $asymbol, $aindicators, $ahdr, $abysl) = $self->get_tab_data($win);
576 my $type = $self->current->{plot_type} || 'OHLC';
577 $self->plot_data($win, $adata, $asymbol, $type, $aindicators, $abysl);
578 # disable remove indicator if there are no indicators left
579 unless (scalar @$aindicators) {
580 #$self->main->menu->remove_indicator->enabled(0);
581 }
582 }
583 }
584 }
585  
586 sub remove_indicator_wizard {
587 my ($self, $win) = @_;
588 my $w = Prima::Dialog->new(
589 name => 'rem_ind_wizard',
590 centered => 1,
591 origin => [200, 200],
592 size => [640, 280],
593 text => 'Remove Indicator Wizard',
594 icon => $self->icon,
595 visible => 1,
596 taskListed => 0,
597 onExecute => sub {
598 my $dlg = shift;
599 $dlg->cbox_tabs->List->focusedItem(-1);
600 $dlg->cbox_inds->List->focusedItem(-1);
601 $dlg->btn_cancel->enabled(1);
602 $dlg->btn_ok->enabled(0);
603 },
604 );
605 $w->owner($win) if defined $win;
606 my %tabs = $self->get_tab_names($win);
607 $log->debug("Current tabs: ", dumper(\%tabs));
608 my $result = {};
609 $w->insert(Label => name => 'label_tabs',
610 text => 'Select Security',
611 font => { style => fs::Bold, height => 16 },
612 alignment => ta::Left,
613 autoHeight => 1,
614 autoWidth => 1,
615 origin => [20, 240],
616 hint => 'This is a list of already open tabs',
617 hintVisible => 1,
618 );
619 $w->insert(ComboBox =>
620 name => 'cbox_tabs',
621 style => cs::DropDownList,
622 height => 30,
623 width => 360,
624 hScroll => 0,
625 multiSelect => 0,
626 multiColumn => 0,
627 dragable => 0,
628 focusedItem => -1,
629 font => { height => 14 },
630 items => ['', keys %tabs],
631 origin => [180, 240],
632 onChange => sub {
633 my $cbox = shift;
634 my $owner = $cbox->owner;
635 my $lbox = $cbox->List;
636 my $index = $lbox->focusedItem;
637 my $txt = $lbox->get_item_text($index);
638 if (defined $txt and length $txt) {
639 my $indicators = $self->get_tab_indicators($owner->owner, $txt);
640 my @inds = ();
641 if ($indicators) {
642 foreach (@$indicators) {
643 push @inds, $_->{indicator}->{func};
644 }
645 }
646 $log->debug("Current indicators for tab $txt: ", dumper(\@inds));
647 if (scalar @inds) {
648 $owner->cbox_inds->items(\@inds);
649 $owner->btn_ok->enabled(1);
650 } else {
651 $owner->cbox_inds->items([]);
652 $owner->btn_ok->enabled(0);
653 }
654 $result->{tab} = $txt;
655 } else {
656 $owner->cbox_inds->items([]);
657 $owner->cbox_inds->focusedItem(-1);
658 $owner->cbox_inds->text('');
659 $owner->btn_ok->enabled(0);
660 delete $result->{tab};
661 }
662 },
663 );
664 $w->cbox_tabs->text('');
665 $w->insert(Label => name => 'label_inds',
666 text => 'Select Indicator',
667 font => { style => fs::Bold, height => 16 },
668 alignment => ta::Left,
669 autoHeight => 1,
670 autoWidth => 1,
671 origin => [20, 200],
672 hint => 'These indicators are already present in the selected tab',
673 hintVisible => 1,
674 );
675 $w->insert(ComboBox =>
676 name => 'cbox_inds',
677 style => cs::DropDownList,
678 height => 30,
679 width => 360,
680 hScroll => 0,
681 font => { height => 14 },
682 multiSelect => 0,
683 multiColumn => 0,
684 dragable => 0,
685 focusedItem => -1,
686 text => '',
687 items => [],
688 origin => [180, 200],
689 onChange => sub {
690 my $cbox = shift;
691 my $owner = $cbox->owner;
692 my $lbox = $cbox->List;
693 my $index = $lbox->focusedItem;
694 my $txt = $lbox->get_item_text($index);
695 if (defined $txt) {
696 $owner->btn_ok->enabled(1);
697 $result->{indicator} = $txt;
698 $result->{indicator_index} = $index;
699 } else {
700 $owner->btn_ok->enabled(0);
701 $cbox->items([]);
702 $cbox->focusedItem(-1);
703 $cbox->text('');
704 delete $result->{indicator};
705 delete $result->{indicator_index};
706 }
707 },
708 );
709 $w->insert(
710 Button => name => 'btn_cancel',
711 text => 'Cancel',
712 autoHeight => 1,
713 autoWidth => 1,
714 origin => [ 20, 20 ],
715 modalResult => mb::Cancel,
716 default => 0,
717 enabled => 1,
718 font => { height => 16, style => fs::Bold },
719 onClick => sub {
720 $result = {};
721 },
722 );
723 $w->insert(
724 Button => name => 'btn_ok',
725 text => 'OK',
726 autoHeight => 1,
727 autoWidth => 1,
728 origin => [ 150, 20 ],
729 modalResult => mb::Ok,
730 default => 1,
731 enabled => 0,
732 font => { height => 16, style => fs::Bold },
733 onClick => sub {
734 my $btn = shift;
735 my $owner = $btn->owner;
736 my $indicators = $self->get_tab_indicators($owner->owner, $result->{tab});
737 my @inds = ();
738 if ($indicators) {
739 my $iref = $indicators->[$result->{indicator_index}]->{indicator};
740 if ($iref->{func} eq $result->{indicator}) {
741 $result->{columns} = $indicators->[$result->{indicator_index}]->{columns};
742 } else {
743 $log->warn("Cannot find the columns to remove");
744 }
745 } else {
746 $log->warn("Invalid indicators for tab: ", $result->{tab});
747 }
748 $log->debug("Result: ", dumper($result));
749 },
750 );
751 my $res = $w->execute();
752 $w->end_modal;
753 return ($res == mb::Ok) ? $result : undef;
754 }
755  
756 sub run_and_display_indicator {
757 my ($self, $win, $data, $symbol, $indicators) = @_;
758 return unless $win;
759 if (defined $data and defined $symbol and defined $indicators and
760 ref $indicators eq 'ARRAY') {
761 my $icount = scalar @$indicators;
762 foreach my $iref (@$indicators) {
763 $log->debug("Trying to run indicator for :", dumper($iref));
764 my $output;
765 if (exists $iref->{params} and exists $iref->{params}->{CompareWith}) {
766 # ok this is a security.
767 # we need to download the data for this and store it
768 my $bar = App::financeta::gui::progress_bar->new(owner => $win, title => 'Downloading...');
769 my $current = $self->current;
770 $iref->{params}->{CompareWith} =~ s/\s//g;
771 $current->{symbol} = $iref->{params}->{CompareWith};
772 my $tz = $self->timezone;
773 unless ($current->{start_date}) {
774 my $sd = $data->at(0, 0); # time in 0th column
775 my $dt = DateTime->from_epoch(epoch => $sd, time_zone => $tz);
776 $current->{start_date} = $dt;
777 }
778 unless ($current->{end_date}) {
779 my $ed = $data->at($data->dim(0) - 1, 0); # time in 0th column
780 my $dt = DateTime->from_epoch(epoch => $ed, time_zone => $tz);
781 $current->{end_date} = $dt;
782 }
783 my ($data2, $symbol2, $csv2) = $self->download_data($bar, $current);
784 $bar->close if $bar;
785 return unless (defined $data2 and defined $symbol2);
786 $log->debug("Successfully downloaded data for $symbol2");
787 $iref->{params}->{CompareWith} = $symbol2;
788 $output = $self->indicator->execute_ohlcv($data, $iref, $data2);
789 } else {
790 $output = $self->indicator->execute_ohlcv($data, $iref);
791 }
792 unless (defined $output) {
793 message_box('Indicator Error',
794 "Unable to run the indicator on data.",
795 mb::Ok | mb::Error);
796 return;
797 }
798 my ($next_data) = $self->display_data($win, $data, $symbol, $iref, $output);
799 $icount--;
800 $data = $next_data if $icount > 0;
801 }
802 return 1;
803 }
804 return 0;
805 }
806  
807 sub add_indicator($$$) {
808 my ($self, $win, $data, $symbol) = @_;
809 if ($self->add_indicator_wizard($win)) {
810 my $iref = $self->current->{indicator};
811 if ($self->run_and_display_indicator($win, $data, $symbol, [$iref])) {
812 my ($ndata, $nsymbol, $indicators, $ndhr, $nbs) = $self->get_tab_data($win);
813 my $type = $self->current->{plot_type} || 'OHLC';
814 $self->plot_data($win, $ndata, $nsymbol, $type, $indicators, $nbs);
815 return 1;
816 }
817 }
818 return 0;
819 }
820  
821 sub indicator_parameter_wizard {
822 my ($self, $gbox, $fn_name, $grp, $params) = @_;
823 if ($gbox) {
824 # remove the current parameter screen
825 my @widgets = $gbox->get_widgets;
826 if (@widgets) {
827 map { $_->close() } @widgets;
828 }
829 } else {
830 return;
831 }
832 # if all are defined create the parameter screen
833 if (defined $fn_name and defined $grp and defined $params) {
834 $gbox->text("$fn_name Parameters");
835 my @origin = $gbox->origin;
836 my @size = $gbox->size;
837 $log->debug("Gbox: Origin: @origin Size: @size");
838 my $num = scalar @$params;
839 my $sz_x = $size[0] / 2; # label and value
840 my $sz_y = $size[1] / ($num + 1);
841 my $count = 0;
842 $self->current->{indicator}->{params} = {};
843 # if no params just write that
844 unless (scalar @$params) {
845 $gbox->insert('Label',
846 text => "There are no parameters to configure.",
847 name => "label_$grp\_noparams",
848 alignment => ta::Left,
849 autoHeight => 1,
850 autoWidth => 1,
851 origin => [$origin[0] + 10,
852 $origin[1] + $count * $sz_y - 40],
853 font => {height => 16},
854 );
855 }
856 foreach my $p (reverse @$params) {
857 next unless ref $p eq 'ARRAY';
858 my $hkey = $p->[0];
859 my $label = $p->[1];
860 my $type = $p->[2];
861 my $typeclass = blessed($type) if $type;
862 my $value = $p->[3];
863 if (defined $type and $type eq 'ARRAY' and ref $value eq 'ARRAY') {
864 # use ComboBox
865 $self->current->{indicator}->{params}->{$hkey} = $value->[0];
866 $self->current->{indicator}->{params}->{$hkey . '_index'} = 0;
867 $gbox->insert(Label => text => $label,
868 name => "label_$grp\_$count",
869 alignment => ta::Left,
870 autoHeight => 1,
871 autoWidth => 1,
872 origin => [$origin[0] + 10,
873 $origin[1] + $count * $sz_y - 40],
874 font => {height => 13},
875 );
876 $gbox->insert(ComboBox => style => cs::DropDownList,
877 name => "cbox_$grp\_$count",
878 height => 30,
879 width => $sz_x - 50,
880 autoHeight => 1,
881 font => { height => 16 },
882 hScroll => 0,
883 multiSelect => 0,
884 multiColumn => 0,
885 dragable => 0,
886 focusedItem => -1,
887 items => $value,
888 autoTab => 1,
889 origin => [$origin[0] + 10 + $sz_x,
890 $origin[1] + $count * $sz_y - 40],
891 onChange => sub {
892 my $cbox = shift;
893 my $lbox = $cbox->List;
894 my $index = $lbox->focusedItem;
895 $self->current->{indicator}->{params}->{$hkey} = $lbox->get_item_text($index);
896 $self->current->{indicator}->{params}->{$hkey . '_index'} = $index;
897 },
898 );
899 } elsif (defined $typeclass and $typeclass eq 'PDL::Type') {
900 # use InputLine for all numbers
901 $self->current->{indicator}->{params}->{$hkey} = $value;
902 $gbox->insert(Label => text => $label,
903 name => "label_$grp\_$count",
904 alignment => ta::Left,
905 autoHeight => 1,
906 autoWidth => 1,
907 origin => [$origin[0] + 10,
908 $origin[1] + $count * $sz_y - 40],
909 font => {height => 13},
910 );
911 $gbox->insert(InputLine => name => "input_$grp\_$count",
912 alignment => ta::Left,
913 autoHeight => 1,
914 width => $sz_x - 50,
915 autoTab => 1,
916 maxLen => 20,
917 origin => [$origin[0] + 10 + $sz_x,
918 $origin[1] + $count * $sz_y - 40],
919 text => $value,
920 font => {height => 16},
921 onChange => sub {
922 my $il = shift;
923 my $val = undef;
924 my $txt = $il->text;
925 return unless length $txt;
926 if ($type->symbol eq 'PDL_B') {
927 # byte buffer
928 $val = $txt;
929 } elsif ($type->symbol eq 'PDL_F' or $type->symbol eq 'PDL_D') {
930 # is a real number
931 if ($txt =~ /^(\d+\.?\d*)|(\.\d+)$/) {
932 $val = sprintf "%0.04f", $txt;
933 } else {
934 message_box('Parameter Error',
935 "$label has to be a real number",
936 mb::Ok | mb::Error);
937 return;
938 }
939 } else {
940 # is an integer form
941 if ($txt =~ /^([+-]?\d+)$/) {
942 $val = sprintf "%d", $txt;
943 } else {
944 message_box('Parameter Error',
945 "$label has to be an integer",
946 mb::Ok | mb::Error);
947 return;
948 }
949 }
950 $self->current->{indicator}->{params}->{$hkey} = $val;
951 },
952 );
953 } elsif (defined $type and $type eq 'PDL') {
954 # use InputLine for all numbers
955 $self->current->{indicator}->{params}->{$hkey} = $value;
956 $self->current->{indicator}->{params}->{$hkey . '_pdl'} = 1;
957 $gbox->insert(Label => text => $label,
958 name => "label_$grp\_$count",
959 alignment => ta::Left,
960 autoHeight => 1,
961 autoWidth => 1,
962 origin => [$origin[0] + 10,
963 $origin[1] + $count * $sz_y - 40],
964 font => {height => 13},
965 hint => 'This should be a comma-separated list of integers',
966 );
967 $gbox->insert(InputLine => name => "input_$grp\_$count",
968 alignment => ta::Left,
969 autoHeight => 1,
970 width => $sz_x - 50,
971 autoTab => 1,
972 maxLen => 256,
973 origin => [$origin[0] + 10 + $sz_x,
974 $origin[1] + $count * $sz_y - 40],
975 text => $value,
976 font => {height => 16},
977 onChange => sub {
978 my $il = shift;
979 my $val = undef;
980 my $txt = $il->text;
981 return unless length $txt;
982 if ($txt !~ /\d[\d,\s]*/) {
983 message_box('Parameter Error',
984 "$label has to be a comma-separated list of integers",
985 mb::Ok | mb::Error);
986 return;
987 }
988 $self->current->{indicator}->{params}->{$hkey} = $txt;
989 $self->current->{indicator}->{params}->{$hkey . '_pdl'} = 1;
990 },
991 );
992 } else {
993 # use checkbox
994 $self->current->{indicator}->{params}->{$hkey} = ($value) ? 1 : 0;
995 $gbox->insert(CheckBox => name => "chk_$grp\_$count",
996 alignment => ta::Left,
997 autoTab => 1,
998 origin => [$origin[0] + 10,
999 $origin[1] + $count * $sz_y - 40],
1000 text => $label,
1001 font => {height => 13},
1002 onCheck => sub {
1003 my $chk = shift;
1004 $self->current->{indicator}->{params}->{$hkey} =
1005 $chk->checked ? 1 : 0;
1006 },
1007 );
1008 }
1009 $count++;
1010 }
1011 } else {
1012 $gbox->text("Indicator Parameters");
1013 delete $self->current->{indicator}->{params};
1014 }
1015 }
1016  
1017 sub add_indicator_wizard {
1018 my ($self, $win) = @_;
1019 my $w = Prima::Dialog->new(
1020 name => 'add_ind_wizard',
1021 centered => 1,
1022 origin => [200, 200],
1023 size => [640, 480],
1024 text => 'Technical Analysis Indicator Wizard',
1025 icon => $self->icon,
1026 visible => 1,
1027 taskListed => 0,
1028 onExecute => sub {
1029 my $dlg = shift;
1030 $dlg->cbox_groups->List->focusedItem(-1);
1031 $dlg->cbox_funcs->List->focusedItem(-1);
1032 $dlg->btn_cancel->enabled(1);
1033 $dlg->btn_ok->enabled(0);
1034 },
1035 );
1036 $w->owner($win) if defined $win;
1037 $self->current->{indicator} = {}; # reset
1038 my @groups = $self->indicator->get_groups;
1039 $w->insert(Label => name => 'label_groups',
1040 text => 'Select Group',
1041 font => { style => fs::Bold, height => 16 },
1042 alignment => ta::Left,
1043 autoHeight => 1,
1044 autoWidth => 1,
1045 origin => [20, 440],
1046 hint => 'This is a list of indicator groups',
1047 hintVisible => 1,
1048 );
1049 $w->insert(ComboBox =>
1050 name => 'cbox_groups',
1051 style => cs::DropDownList,
1052 height => 30,
1053 width => 360,
1054 hScroll => 0,
1055 multiSelect => 0,
1056 multiColumn => 0,
1057 dragable => 0,
1058 focusedItem => -1,
1059 font => { height => 14 },
1060 items => [ '', @groups],
1061 origin => [180, 440],
1062 onChange => sub {
1063 my $cbox = shift;
1064 my $owner = $cbox->owner;
1065 my $lbox = $cbox->List;
1066 my $index = $lbox->focusedItem;
1067 my $txt = $lbox->get_item_text($index);
1068 if (defined $txt and length $txt) {
1069 my @funcs = $self->indicator->get_funcs($txt);
1070 if (scalar @funcs) {
1071 $owner->cbox_funcs->items(\@funcs);
1072 } else {
1073 $owner->cbox_funcs->items([]);
1074 }
1075 $owner->btn_ok->enabled(1);
1076 $self->current->{indicator}->{group} = $txt;
1077 } else {
1078 $owner->cbox_funcs->items([]);
1079 $owner->cbox_funcs->focusedItem(-1);
1080 $self->indicator_parameter_wizard($owner->gbox_params);
1081 $owner->cbox_funcs->text('');
1082 $owner->btn_ok->enabled(0);
1083 delete $self->current->{indicator}->{group};
1084 }
1085 },
1086 );
1087 $w->cbox_groups->text('');
1088 $w->insert(Label => name => 'label_funcs',
1089 text => 'Select Function',
1090 font => { style => fs::Bold, height => 16 },
1091 alignment => ta::Left,
1092 autoHeight => 1,
1093 autoWidth => 1,
1094 origin => [20, 400],
1095 hint => 'Each indicator group has multiple indicators it supports',
1096 hintVisible => 1,
1097 );
1098 $w->insert(ComboBox =>
1099 name => 'cbox_funcs',
1100 style => cs::DropDownList,
1101 height => 30,
1102 width => 360,
1103 hScroll => 0,
1104 font => { height => 14 },
1105 multiSelect => 0,
1106 multiColumn => 0,
1107 dragable => 0,
1108 focusedItem => -1,
1109 text => '',
1110 items => [],
1111 origin => [180, 400],
1112 onChange => sub {
1113 my $cbox = shift;
1114 my $owner = $cbox->owner;
1115 my $lbox = $cbox->List;
1116 my $index = $lbox->focusedItem;
1117 my $txt = $lbox->get_item_text($index);
1118 my $grp = $self->current->{indicator}->{group};
1119 if (defined $grp) {
1120 # $params is an array-ref
1121 my $params = $self->indicator->get_params($txt, $grp);
1122 $self->current->{indicator}->{func} = $txt;
1123 $log->debug("Params: ", dumper($params));
1124 $owner->btn_ok->enabled(1);
1125 $self->indicator_parameter_wizard($owner->gbox_params,
1126 $txt, $grp, $params);
1127 } else {
1128 $owner->btn_ok->enabled(0);
1129 $cbox->items([]);
1130 $cbox->focusedItem(-1);
1131 delete $self->current->{indicator}->{func};
1132 $self->indicator_parameter_wizard($owner->gbox_params);
1133 $cbox->text('');
1134 }
1135 },
1136 );
1137 $w->insert(
1138 Button => name => 'btn_cancel',
1139 text => 'Cancel',
1140 autoHeight => 1,
1141 autoWidth => 1,
1142 origin => [ 20, 20 ],
1143 modalResult => mb::Cancel,
1144 default => 0,
1145 enabled => 1,
1146 font => { height => 16, style => fs::Bold },
1147 onClick => sub {
1148 delete $self->current->{indicator};
1149 },
1150 );
1151 $w->insert(
1152 Button => name => 'btn_ok',
1153 text => 'OK',
1154 autoHeight => 1,
1155 autoWidth => 1,
1156 origin => [ 360, 20 ],
1157 modalResult => mb::Ok,
1158 default => 1,
1159 enabled => 0,
1160 font => { height => 16, style => fs::Bold },
1161 onClick => sub {
1162 $log->debug("Final parameters selected: ", dumper($self->current->{indicator}));
1163 },
1164 );
1165 $w->insert(
1166 Button => name => 'btn_help',
1167 text => 'Indicator Help',
1168 autoHeight => 1,
1169 autoWidth => 1,
1170 origin => [ 150, 20 ],
1171 default => 0,
1172 enabled => 1,
1173 font => { height => 16, style => fs::Bold },
1174 onClick => sub {
1175 my $url = 'https://vikasnkumar.github.io/financeta/indicators.html';
1176 my $ok = Browser::Open::open_browser($url, 1);
1177 if (not defined $ok) {
1178 message("Error finding a browser to open $url");
1179 } elsif ($ok != 0) {
1180 message("Error opening $url");
1181 }
1182 },
1183 );
1184 $w->insert(GroupBox => name => 'gbox_params',
1185 text => 'Indicator Parameters',
1186 size => [600, 300],
1187 origin => [20, 60],
1188 font => { height => 16, style => fs::Bold },
1189 );
1190 my $res = $w->execute();
1191 $w->end_modal;
1192 return $res == mb::Ok;
1193 }
1194  
1195 sub download_data {
1196 my ($self, $pbar, $current) = @_;
1197 $pbar->update(5) if $pbar;
1198 $current = $self->current unless $current;
1199 my $src_index = $current->{source_index} // 0;
1200 my $src = @{$self->list_sources}[$src_index];
1201 my $start = $current->{start_date};
1202 my $end = $current->{end_date};
1203 my $symbol = $current->{symbol};
1204 #TODO: check symbol validity
1205 my $csv = sprintf "%s_%d_%d.csv", $symbol, $start->ymd(''), $end->ymd('');
1206 $csv = File::Spec->catfile($self->tmpdir, $csv);
1207 if (defined $current->{csv}) {
1208 $csv = $current->{csv};
1209 $log->debug("Using $csv as it was chosen");
1210 }
1211 $pbar->update(10) if $pbar;
1212 my $data;
1213 unlink $csv if $current->{force_download};
1214 unless (-e $csv) {
1215 $pbar->update(25) if $pbar;
1216 $data = App::financeta::data::ohlcv($src, $symbol, $start, $end, $csv);
1217 $pbar->update(35) if $pbar;
1218 unless (defined $data) {
1219 message_box('Error',
1220 "Failed to download $symbol data. Check if '$symbol' is correct",
1221 mb::Ok | mb::Error);
1222 unlink $csv if -e $csv;
1223 return;
1224 }
1225 wcols($data, $csv, { COLSEP => ',' });
1226 $log->info("File $csv has downloaded data for analysis for symbol $symbol");
1227 $pbar->update(75) if $pbar;
1228 } else {
1229 ## now read this back into a PDL using rcol
1230 $pbar->update(35) if $pbar;
1231 $log->info("$csv already present. loading it...");
1232 $data = rcols($csv, [], { COLSEP => ',', DEFTYPE => PDL::double});
1233 $pbar->update(75) if $pbar;
1234 }
1235 return ($data, $symbol, $csv);
1236 }
1237  
1238 sub display_data {
1239 my ($self, $win, $data, $symbol, $iref, $output) = @_;
1240 return unless defined $win and defined $data;
1241 my @tabsize = $win->size();
1242 $symbol = $self->current->{symbol} unless defined $symbol;
1243 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1244 unless (@tabs) {
1245 $win->insert('Prima::TabbedNotebook',
1246 name => 'data_tabs',
1247 size => \@tabsize,
1248 origin => [ 0, 0 ],
1249 style => tns::Simple,
1250 growMode => gm::Client,
1251 visible => 1,
1252 onChange => sub {
1253 my ($w, $oldidx, $newidx) = @_;
1254 my $owner = $w->owner;
1255 $log->debug("Tab changed from $oldidx to $newidx");
1256 return if ($oldidx == $newidx and !$self->tab_was_closed);
1257 $self->tab_was_closed(0);
1258 # ok find the detailed-list object and use it
1259 my ($data, $symbol, $indicators, $h, $bs) = $self->_get_tab_data($w, $newidx);
1260 my $type = $self->current->{plot_type} || 'OHLC';
1261 $self->plot_data($owner, $data, $symbol, $type, $indicators, $bs);
1262 },
1263 );
1264 }
1265 my $nt = $win->data_tabs;
1266 my $nt_tabs = $nt->tabs;
1267 # create unique tab-names
1268 if (scalar @$nt_tabs) {
1269 my %tabnames = map { $_ => 1 } @$nt_tabs;
1270 $log->debug("$symbol tab already exists") if exists $tabnames{$symbol};
1271 $log->debug("$symbol tab will be added") if not exists $tabnames{$symbol};
1272 $nt->tabs([@$nt_tabs, $symbol]) if not exists $tabnames{$symbol};
1273 } else {
1274 $log->debug("$symbol tab will be added");
1275 $nt->tabs([$symbol]);
1276 }
1277 my $pc = $nt->pageCount;
1278 $log->debug("TabCount: $pc");
1279 my $pageno = $pc;
1280 # find the existing tab with the same symbol info and remove the widget
1281 # there and get that page number
1282 # default headers
1283 my $headers = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'];
1284 my $existing_indicators = [];
1285 my ($info, $buysells);
1286 for my $idx (0 .. $pc) {
1287 my @wids = $nt->widgets_from_page($idx);
1288 next unless @wids;
1289 my @dls = grep { $_->name eq "tab_$symbol" } @wids;
1290 if (@dls) {
1291 foreach (@dls) {
1292 $log->debug("Found existing " . $_->name . " at $idx");
1293 $headers = $_->headers if defined $_->headers;
1294 push @$existing_indicators, @{$_->{-indicators}} if exists $_->{-indicators};
1295 $info = $_->{-info} if exists $_->{-info};
1296 $buysells = $_->{-buysells} if exists $_->{-buysells};
1297 $nt->delete_widget($_);
1298 }
1299 $pageno = $idx;
1300 last;
1301 }
1302 }
1303 # handle the current indicator first
1304 if ($output and scalar @$output) {
1305 my @cols = ();
1306 foreach my $a (@$output) {
1307 # add the DetailedList column number
1308 push @cols, scalar(@$headers);
1309 # add the header
1310 push @$headers, $a->[0];
1311 # splice the indicator PDL into $data
1312 $data = $data->glue(1, $a->[1]) if ref $a->[1] eq 'PDL';
1313 }
1314 # add the current indicator to the bottom of the list
1315 push @$existing_indicators, {indicator => $iref, data => $output, columns => \@cols};
1316 }
1317 $log->debug("Data dimension: ", dumper([$data->dims]));
1318 $log->debug("Updated headers: ", dumper($headers));
1319 my $items;
1320 if (defined $buysells and ref $buysells eq 'HASH' and
1321 defined $buysells->{buys} and
1322 defined $buysells->{sells}) {
1323 my $buys = $buysells->{buys};
1324 my $sells = $buysells->{sells};
1325 if (ref $buys eq 'PDL' and ref $sells eq 'PDL') {
1326 my $ldata = $data->copy;
1327 $ldata = $ldata->glue(1, $buys);
1328 $ldata = $ldata->glue(1, $sells);
1329 push @$headers, 'Buys', 'Sells' unless grep {/Buys|Sells/} @$headers;
1330 $items = $ldata->transpose->unpdl;
1331 } else {
1332 $log->warn("Buy-sells object is corrupt. Not using.");
1333 $items = $data->transpose->unpdl;
1334 }
1335 } else {
1336 $items = $data->transpose->unpdl;
1337 }
1338 my $tz = $self->timezone;
1339 # reformat
1340 foreach my $arr (@$items) {
1341 my $dt = DateTime->from_epoch(epoch => $arr->[0], time_zone => $tz)->datetime(' ');
1342 $arr->[0] = $dt;
1343 for (my $i = 1; $i < scalar @$arr; ++$i) {
1344 $arr->[$i] = '' if $arr->[$i] =~ /BAD/i;
1345 }
1346 }
1347 $tabsize[0] *= 0.98;
1348 $tabsize[1] *= 0.96;
1349 my $dl = $nt->insert_to_page($pageno, 'DetailedList',
1350 name => "tab_$symbol",
1351 pack => { expand => 1, fill => 'both' },
1352 items => $items,
1353 origin => [ 10, 10 ],
1354 headers => $headers,
1355 hScroll => 1,
1356 growMode => gm::Client | gm::GrowHiX | gm::GrowHiY,
1357 columns => scalar @$headers,
1358 onSort => sub {
1359 my ($p, $col, $dir) = @_;
1360 return if $col != 1;
1361 if ($dir) {
1362 $p->{items} = [
1363 sort {$$a[$col] <=> $$b[$col]}
1364 @{$self->{items}}
1365 ];
1366 } else {
1367 $p->{items} = [
1368 sort {$$b[$col] <=> $$a[$col]}
1369 @{$self->{items}}
1370 ];
1371 }
1372 $p->clear_event;
1373 },
1374 title => $symbol,
1375 titleSpace => 30,
1376 size => \@tabsize,
1377 visible => 1,
1378 );
1379 $nt->pageIndex($pageno);
1380 $dl->{-pdl} = $data;
1381 $dl->{-symbol} = $symbol;
1382 $dl->{-indicators} = $existing_indicators if defined $existing_indicators;
1383 $dl->{-info} = $info || {};
1384 $dl->{-buysells} = $buysells if defined $buysells;
1385 return wantarray ? ($data) : 1;
1386 }
1387  
1388 sub enable_menu_options {
1389 my $self = shift;
1390 my $win = shift || $self->main;
1391 # enable the menu option now that we have something open
1392 $win->menu->security_save->enabled(1);
1393 $win->menu->security_saveas->enabled(1);
1394 $win->menu->security_close->enabled(1);
1395 $win->menu->plot_ohlc->enabled(1);
1396 $win->menu->plot_ohlcv->enabled(1);
1397 $win->menu->plot_close->enabled(1);
1398 $win->menu->plot_closev->enabled(1);
1399 $win->menu->plot_cdl->enabled(1);
1400 $win->menu->plot_cdlv->enabled(1);
1401 $win->menu->plot_using_highcharts->enabled(1);
1402 $win->menu->plot_using_gnuplot->enabled(1);
1403 $win->menu->add_indicator->enabled(1);
1404 $win->menu->edit_rules->enabled(1);
1405 $win->menu->execute_rules->enabled(1);
1406 # $win->menu->trade_report->enabled(1);
1407 }
1408  
1409 sub disable_menu_options {
1410 my $self = shift;
1411 my $win = $self->main;
1412 # disable the menu option now that we have nothing open
1413 $win->menu->security_save->enabled(0);
1414 $win->menu->security_saveas->enabled(0);
1415 $win->menu->security_close->enabled(0);
1416 $win->menu->plot_ohlc->enabled(0);
1417 $win->menu->plot_ohlcv->enabled(0);
1418 $win->menu->plot_close->enabled(0);
1419 $win->menu->plot_closev->enabled(0);
1420 $win->menu->plot_cdl->enabled(0);
1421 $win->menu->plot_cdlv->enabled(0);
1422 $win->menu->plot_using_highcharts->enabled(0);
1423 $win->menu->plot_using_gnuplot->enabled(0);
1424 $win->menu->add_indicator->enabled(0);
1425 $win->menu->remove_indicator->enabled(0);
1426 $win->menu->edit_rules->enabled(0);
1427 $win->menu->execute_rules->enabled(0);
1428 $win->menu->trade_report->enabled(0);
1429 }
1430  
1431 #rudimentary
1432 sub get_model {
1433 my ($self, $data, $symbol, $indicators) = @_;
1434 if (defined $data and defined $symbol) {
1435 my $sd = $data->at(0, 0);
1436 my $ed = $data->at($data->dim(0) - 1, 0);
1437 my $tz = $self->timezone;
1438 my %saved = (
1439 start_date => $sd,
1440 end_date => $ed,
1441 symbol => $symbol,
1442 );
1443 if ($indicators and ref $indicators eq 'ARRAY') {
1444 my $arr = [];
1445 foreach (@$indicators) {
1446 push @$arr, $_->{indicator};
1447 }
1448 $saved{indicators} = $arr;
1449 } elsif ($indicators and ref $indicators eq 'HASH') {
1450 $saved{indicators} = [$indicators->{indicator}];
1451 }
1452 return wantarray ? %saved : \%saved;
1453 }
1454 }
1455  
1456 #rudimentary
1457 sub save_current_tab {
1458 my ($self, $win, $save_as, $name) = @_;
1459 return unless $win;
1460 my ($data, $symbol, $indicators) = (defined $name) ?
1461 $self->get_tab_data_by_name($win, $name) :
1462 $self->get_tab_data($win);
1463 # in save-as mode do not get historical file name
1464 my ($info, $tname) = (defined $name) ?
1465 $self->get_tab_info_by_name($win, $name) :
1466 $self->get_tab_info($win);
1467 my $saved = $self->get_model($data, $symbol, $indicators);
1468 return unless $saved;
1469 my $tz = $self->timezone;
1470 $saved->{saved_at} = DateTime->now(time_zone => $tz)->iso8601();
1471 $log->debug("Saving the model: ", dumper($saved));
1472 my $mfile;
1473 if ($info and $info->{filename} and not $save_as) {
1474 $mfile = $info->{filename};
1475 $log->info(sprintf "Saving tab %s to %s", ($name ? $name : ''), $mfile);
1476 } else {
1477 my $dlg = Prima::Dialog::SaveDialog->new(
1478 fileName => "$symbol.yml",
1479 filter => [
1480 ['financeta files' => '*.yml'],
1481 ['All files' => '*'],
1482 ],
1483 filterIndex => 0,
1484 multiSelect => 0,
1485 overwritePrompt => 1,
1486 pathMustExist => 1,
1487 directory => $self->datadir,
1488 );
1489 $mfile = $dlg->fileName if $dlg->execute;
1490 if ($mfile) {
1491 if ($^O !~ /Win32/) {
1492 $mfile = File::Spec->catfile($self->datadir, $mfile) unless ($mfile =~ /^\//);
1493 } else {
1494 $mfile .= '.yml' unless $mfile =~ /\.yml$/; #windows is weird
1495 }
1496 $name //= $tname // '';
1497 $log->info("Saving tab $name to $mfile");
1498 } else {
1499 $name //= $tname // '';
1500 $log->warn("Saving the tab $name was canceled.");
1501 return;
1502 }
1503 }
1504 if ($info and defined $info->{rules}) {
1505 $saved->{rules} = $info->{rules};
1506 } else {
1507 if (exists $self->editors->{$tname}) {
1508 $saved->{rules} = $self->editors->{$tname}->get_text;
1509 }
1510 }
1511 $saved->{old_filename} = $info->{old_filename} if defined $info and defined $info->{old_filename};
1512 $saved->{csv} = $info->{csv} if defined $info and defined $info->{csv};
1513 if ($mfile) {
1514 $saved->{filename} = $mfile;
1515 $log->debug("You have selected $mfile to save the tab info into.");
1516 YAML::Any::DumpFile($mfile, $saved) or message("Unable to save to $mfile");
1517 $self->set_tab_info($win, $saved);
1518 1;
1519 } else {
1520 $log->warn("Saving the tab was canceled.");
1521 }
1522 }
1523  
1524 #rudimentary
1525 sub load_new_tab {
1526 my ($self, $win) = @_;
1527 return unless $win;
1528 my $dlg = Prima::Dialog::OpenDialog->new(
1529 filter => [
1530 ['financeta files' => '*.yml'],
1531 ['All files' => '*'],
1532 ],
1533 filterIndex => 0,
1534 fileMustExist => 1,
1535 multiSelect => 0,
1536 directory => $self->datadir,
1537 );
1538 my $mfile = $dlg->fileName if $dlg->execute;
1539 $log->info("requesting file $mfile to be opened");
1540 return unless $mfile;
1541 return unless -e $mfile;
1542 my $saved = YAML::Any::LoadFile($mfile);
1543 return unless $saved;
1544 my $tz = $self->timezone;
1545 my $current = {
1546 start_date => DateTime->from_epoch(epoch => $saved->{start_date}, time_zone => $tz),
1547 end_date => DateTime->from_epoch(epoch => $saved->{end_date}, time_zone => $tz),
1548 symbol => $saved->{symbol},
1549 force_download => 0,
1550 };
1551 $current->{csv} = $saved->{csv} if defined $saved->{csv};
1552 my $bar = App::financeta::gui::progress_bar->new(owner => $win, title => 'Loading...');
1553 my ($data, $symbol, $csv) = $self->download_data($bar, $current);
1554 $log->debug("Loading the data into tab");
1555 $saved->{csv} = $csv if defined $csv;
1556 # overwrite the filename for saving
1557 if (defined $saved->{filename} and $mfile ne $saved->{filename}) {
1558 $saved->{old_filename} = $saved->{filename};
1559 }
1560 $saved->{filename} = $mfile;
1561 $self->display_data($win, $data, $symbol);
1562 $self->enable_menu_options($win);
1563 $self->set_tab_info($win, $saved);
1564 $log->debug("Running the indicators and updating tab");
1565 $bar->close if $bar;
1566 if ($self->run_and_display_indicator($win, $data, $symbol,
1567 $saved->{indicators})) {
1568 # this is specially done
1569 $win->menu->remove_indicator->enabled(1);
1570 }
1571 my ($adata, $asym, $aind, $ahdr, $abysl) = $self->get_tab_data($win);
1572 my $type = $self->current->{plot_type} || 'OHLC';
1573 $self->plot_data($win, $adata, $asym, $type, $aind, $abysl);
1574 }
1575  
1576 sub close_current_tab {
1577 my ($self, $win) = @_;
1578 return unless $win;
1579 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1580 return unless @tabs;
1581 my $nt = $win->data_tabs;
1582 my $idx = $nt->pageIndex;
1583 if ($nt->pageCount == 1) {
1584 foreach my $e (keys %{$self->editors}) {
1585 my $ed = $self->editors->{$e};
1586 $ed->close;
1587 }
1588 $self->editors({});
1589 foreach my $t (keys %{$self->tradereports}) {
1590 my $trw = $self->tradereports->{$t};
1591 $trw->close;
1592 }
1593 $self->tradereports({});
1594 if ($win->{plot}) {
1595 $win->{plot}->close();
1596 }
1597 $nt->close;
1598 $self->disable_menu_options;
1599 } else {
1600 $self->tab_was_closed(1);
1601 # find corresponding editors and close them
1602 my @wids = $win->data_tabs->widgets_from_page($idx);
1603 if (@wids) {
1604 my ($dl) = grep { $_->name =~ /^tab_/i } @wids;
1605 if ($dl and exists $self->editors->{$dl->name}) {
1606 $log->debug("Closing the rules editor for " . $dl->name);
1607 $self->editors->{$dl->name}->close;
1608 delete $self->editors->{$dl->name};
1609 }
1610 if ($dl and exists $self->tradereports->{$dl->name}) {
1611 $log->debug("Closing the trade report for " . $dl->name);
1612 $self->tradereports->{$dl->name}->close;
1613 delete $self->tradereports->{$dl->name};
1614 }
1615 }
1616 $nt->delete_page($idx);
1617 $nt->pageIndex($idx >= $nt->pageCount ?
1618 $nt->pageCount - 1 : $idx);
1619 }
1620 }
1621  
1622 sub _get_tab_data {
1623 my ($self, $nb, $idx) = @_;
1624 my @nt = $nb->widgets_from_page($idx);
1625 return unless @nt;
1626 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1627 if ($dl) {
1628 $log->debug("Found " . $dl->name);
1629 return ($dl->{-pdl}, $dl->{-symbol}, $dl->{-indicators},
1630 [$dl->headers],
1631 $dl->{-buysells});
1632 }
1633 }
1634  
1635 sub get_tab_data {
1636 my ($self, $win) = @_;
1637 return unless $win;
1638 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1639 return unless @tabs;
1640 my $idx = $win->data_tabs->pageIndex;
1641 return $self->_get_tab_data($win->data_tabs, $idx);
1642 }
1643  
1644 sub get_tab_data_by_name($$) {
1645 my ($self, $win, $name) = @_;
1646 return unless $win;
1647 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1648 return unless @tabs;
1649 my $pc = $win->data_tabs->pageCount - 1;
1650 return unless $pc >= 0;
1651 $log->debug("Looking for $name");
1652 for my $idx (0 .. $pc) {
1653 my @nt = $win->data_tabs->widgets_from_page($idx);
1654 next unless @nt;
1655 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1656 if ($dl and ($dl->{-symbol} eq $name) or ($dl->name eq $name)) {
1657 $log->debug("Found $name on page $idx");
1658 return ($dl->{-pdl},
1659 $dl->{-symbol},
1660 $dl->{-indicators},
1661 [$dl->headers],
1662 $dl->{-buysells});
1663 }
1664 }
1665 return undef;
1666 }
1667  
1668 sub get_tab_info {
1669 my ($self, $win) = @_;
1670 return unless $win;
1671 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1672 return unless @tabs;
1673 my $idx = $win->data_tabs->pageIndex;
1674 my @nt = $win->data_tabs->widgets_from_page($idx);
1675 return unless @nt;
1676 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1677 if ($dl) {
1678 $log->debug("Getting info for " . $dl->name);
1679 return wantarray ? ($dl->{-info}, $dl->name) : $dl->{-info};
1680 }
1681 }
1682  
1683 sub set_tab_info($$) {
1684 my ($self, $win, $info) = @_;
1685 return unless $win;
1686 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1687 return unless @tabs;
1688 my $idx = $win->data_tabs->pageIndex;
1689 my @nt = $win->data_tabs->widgets_from_page($idx);
1690 return unless @nt;
1691 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1692 if ($dl) {
1693 $log->debug("Setting info for " . $dl->name);
1694 $dl->{-info} = $info;
1695 return 1;
1696 }
1697 }
1698  
1699 sub set_tab_data_by_name($$) {
1700 my ($self, $win, $name, $p, $s, $ind, $hdr) = @_;
1701 return unless $win;
1702 return unless $name;
1703 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1704 return unless @tabs;
1705 my $pc = $win->data_tabs->pageCount - 1;
1706 return unless $pc >= 0;
1707 my $found;
1708 for my $idx (0 .. $pc) {
1709 my @nt = $win->data_tabs->widgets_from_page($idx);
1710 next unless @nt;
1711 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1712 if ($dl and $dl->{-symbol} eq $name) {
1713 $log->debug("Found $name on page $idx");
1714 $dl->{-pdl} = $p;
1715 $dl->{-indicators}= $ind;
1716 $dl->headers($hdr);
1717 return 1;
1718 }
1719 }
1720 }
1721  
1722 sub get_tab_info_by_name {
1723 my ($self, $win, $name) = @_;
1724 return unless $win;
1725 return unless $name;
1726 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1727 return unless @tabs;
1728 my $pc = $win->data_tabs->pageCount - 1;
1729 return unless $pc >= 0;
1730 for my $idx (0 .. $pc) {
1731 my @nt = $win->data_tabs->widgets_from_page($idx);
1732 next unless @nt;
1733 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1734 if ($dl and $dl->name eq $name) {
1735 $log->debug("Getting info for " . $dl->name);
1736 return wantarray ? ($dl->{-info}, $dl->name) : $dl->{-info};
1737 }
1738 }
1739 }
1740  
1741 sub set_tab_info_by_name {
1742 my ($self, $win, $name, $info) = @_;
1743 return unless $win;
1744 return unless $name;
1745 return unless $info;
1746 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1747 return unless @tabs;
1748 my $pc = $win->data_tabs->pageCount - 1;
1749 return unless $pc >= 0;
1750 for my $idx (0 .. $pc) {
1751 my @nt = $win->data_tabs->widgets_from_page($idx);
1752 next unless @nt;
1753 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1754 if ($dl and $dl->name eq $name) {
1755 $log->debug("Setting info for " . $dl->name);
1756 $dl->{-info} = $info;
1757 return 1;
1758 }
1759 }
1760 }
1761  
1762 sub set_tab_buysells_by_name {
1763 my ($self, $win, $name, $buysells) = @_;
1764 return unless $win;
1765 return unless $name;
1766 return unless $buysells;
1767 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1768 return unless @tabs;
1769 my $pc = $win->data_tabs->pageCount - 1;
1770 return unless $pc >= 0;
1771 for my $idx (0 .. $pc) {
1772 my @nt = $win->data_tabs->widgets_from_page($idx);
1773 next unless @nt;
1774 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1775 if ($dl and $dl->name eq $name) {
1776 $log->debug("Setting buy-sells for " . $dl->name);
1777 $dl->{-buysells} = $buysells;
1778 return 1;
1779 }
1780 }
1781 }
1782  
1783 sub get_tab_buysells_for_name {
1784 my ($self, $win, $name) = @_;
1785 return unless $win;
1786 return unless $name;
1787 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1788 return unless @tabs;
1789 my $pc = $win->data_tabs->pageCount - 1;
1790 return unless $pc >= 0;
1791 for my $idx (0 .. $pc) {
1792 my @nt = $win->data_tabs->widgets_from_page($idx);
1793 next unless @nt;
1794 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1795 if ($dl and $dl->name eq $name) {
1796 $log->debug("Getting buy-sells for " . $dl->name);
1797 return wantarray ? ($dl->{-buysells}, $dl->name) : $dl->{-buysells};
1798 }
1799 }
1800 }
1801  
1802 sub get_tab_names($) {
1803 my ($self, $win) = @_;
1804 return unless $win;
1805 my @tabs = grep { $_->name =~ /data_tabs/ } $win->get_widgets();
1806 return unless @tabs;
1807 my $pc = $win->data_tabs->pageCount - 1;
1808 return unless $pc >= 0;
1809 my %names = ();
1810 for my $idx (0 .. $pc) {
1811 my @nt = $win->data_tabs->widgets_from_page($idx);
1812 next unless @nt;
1813 my ($dl) = grep { $_->name =~ /^tab_/i } @nt;
1814 $names{$dl->{-symbol}} = $dl->name if ($dl);
1815 }
1816 return wantarray ? %names : \%names;
1817 }
1818  
1819 sub get_tab_indicators {
1820 my ($self, $win, $txt) = @_;
1821 my ($data, $sym, $indicators, $headers) = $self->get_tab_data_by_name($win, $txt);
1822 return $indicators;
1823 }
1824  
1825 sub open_editor {
1826 my ($self, $win, $rules, $tabname, $hidden) = @_;
1827 # update the editor window with rules
1828 # once the editor window saves something update the parent tab's rules
1829 # object
1830 my $editor = $self->editors->{$tabname} || $self->_build_editor($tabname);
1831 unless (defined $editor) {
1832 $log->error("Unable to create the editor window.");
1833 return;
1834 }
1835 # find the list of indicators and the variable names
1836 my $indicators = $self->get_tab_indicators($win, $tabname) || [];
1837 my @vars = qw(open high low close);
1838 foreach (@$indicators) {
1839 my $iref = $_->{indicator};
1840 my $idata = $_->{data};
1841 next unless defined $idata;
1842 foreach (@$idata) {
1843 push @vars, $_->[3];
1844 }
1845 }
1846 my @varcomm = map { "### \$$_" } @vars;
1847 my $varstr = join ("\n", @varcomm);
1848 my $autogen = <<"AUTOGEN";
1849 ### START OF AUTOGENERATED CODE - DO NOT EDIT
1850 ### The list of variables that you can use is below:
1851 $varstr
1852 ### END OF AUTOGENERATED CODE
1853 AUTOGEN
1854 $log->debug("New Auto comment block:\n$autogen");
1855 if (defined $rules and length $rules) {
1856 if ($rules =~ /(.*###\sEND\sOF\sAUTOGENERATED\sCODE\s+)(.*)/s) {
1857 $log->debug("Old Auto comment block:\n$1");
1858 $log->debug("User block:\n$2");
1859 $rules = $autogen . "\n" . $2;
1860 } else {
1861 $rules = $autogen . "\n" . $rules;
1862 }
1863 } else {
1864 $rules = $autogen . "\n";
1865 }
1866 if ($editor->update_editor($rules, $tabname, \@vars, $hidden)) {
1867 }
1868 $self->editors->{$tabname} = $editor;
1869 }
1870  
1871 sub save_editor {
1872 my ($self, $txt, $tabname, $is_closing) = @_;
1873 unless (defined $tabname) {
1874 $log->error("Tab-name not retrieved. not sure which tab to save it for.");
1875 return;
1876 }
1877 # ok we have a tab for which we need to save info
1878 my $info = $self->get_tab_info_by_name($self->main, $tabname);
1879 $info->{rules} = $txt if $info;
1880 $log->debug("Retrieved info - ", dumper($info), " for tab($tabname)") if $info;
1881 $log->warn("Unable to retrieve info for $tabname") unless $info;
1882 if ($self->set_tab_info_by_name($self->main, $tabname, $info)) {
1883 $log->debug("Saving tab($tabname) info to file");
1884 my $rc = $self->save_current_tab($self->main, 0, $tabname);
1885 $log->warn("Unable to save information for $tabname") unless $rc;
1886 } else {
1887 $log->warn("Unable to save editor rules for tab $tabname");
1888 }
1889 delete $self->editors->{$tabname} if $is_closing;
1890 }
1891  
1892 sub close_editor {
1893 my ($self, $tabname) = @_;
1894 delete $self->editors->{$tabname} if defined $tabname;
1895 }
1896  
1897 sub open_tradereport {
1898 my ($self, $win, $tabname, $buysells) = @_;
1899 return unless defined $buysells;
1900 my $trw = $self->tradereports->{$tabname} || $self->_build_tradereport($tabname);
1901 unless (defined $trw) {
1902 $log->error("Unable to create the trade report window.");
1903 return;
1904 }
1905 $trw->update($tabname, $buysells);
1906 $self->tradereports->{$tabname} = $trw;
1907 }
1908  
1909 sub close_tradereport {
1910 my ($self, $tabname) = @_;
1911 delete $self->tradereports->{$tabname} if defined $tabname;
1912 }
1913  
1914 sub execute_rules_no_editor {
1915 my ($self, $win, $tabname, $code_txt) = @_;
1916 return unless ($win and $tabname and $code_txt);
1917 return unless length $code_txt;
1918 $self->open_editor($win, $code_txt, $tabname, 1);
1919 my $editor = $self->editors->{$tabname};
1920 $editor->execute($editor->get_text);
1921 }
1922  
1923 sub execute_rules {
1924 my ($self, $tabname, $coderef, $win_in) = @_;
1925 if (defined $tabname) {
1926 return unless ref $coderef eq 'CODE';
1927 # ok now we have the code ready.
1928 # let's make sure the variables needed by the code
1929 # are in the same order as the code expects them to be in
1930 # then we invoke the code, and retrieve the buy-sell results
1931 # and update the display
1932 my $win = $win_in || $self->main;
1933 # find the list of indicators and the variable names
1934 my ($data, $sym, $indicators, $headers) =
1935 $self->get_tab_data_by_name($win, $tabname);
1936 my @var_pdls = ();
1937 $indicators = [] unless defined $indicators;
1938 push @var_pdls, $data(, (1)); # open
1939 push @var_pdls, $data(, (2)); # high
1940 push @var_pdls, $data(, (3)); # low
1941 push @var_pdls, $data(, (4)); # close
1942 foreach (@$indicators) {
1943 my $iref = $_->{indicator};
1944 my $idata = $_->{data};
1945 next unless defined $idata;
1946 foreach (@$idata) {
1947 push @var_pdls, $_->[1]; # this is the PDL
1948 }
1949 }
1950 my $buysells = &$coderef(@var_pdls); # invoke the rules sub
1951 if (defined $buysells and ref $buysells eq 'HASH') {
1952 $log->debug("Retrieved buy-sells successfully from code-ref");
1953 $buysells = $self->indicator->calculate_pnl($data(, (0)), $data(, (4)), $buysells);
1954 if ($buysells) {
1955 $log->debug("Done applying P&L calcs to buy-sells");
1956 if ($self->set_tab_buysells_by_name($win, $tabname, $buysells)) {
1957 $log->debug("Successully set buy-sells for tab $tabname\n");
1958 }
1959 $log->debug("BUYS: ", $buysells->{buys});
1960 $log->debug("SELLS: ", $buysells->{sells});
1961 $log->debug("Longs PnL: ", $buysells->{longs_pnl});
1962 $log->debug("Shorts PnL: ", $buysells->{shorts_pnl});
1963 $log->debug("Runtime P&L: ", $buysells->{rtpnl});
1964 } else {
1965 $log->warn("Failed to calculate P&L on executed rules");
1966 }
1967 # this $data should not change theoretically
1968 $self->display_data($win, $data, $sym);
1969 my ($adata, $asym, $aind, $ahdr, $abysl) = $self->get_tab_data_by_name($win, $tabname);
1970 my $type = $self->current->{plot_type} || 'OHLC';
1971 $self->plot_data($win, $adata, $asym, $type, $aind, $abysl);
1972 $self->main->menu->trade_report->enabled(1);
1973 $self->open_tradereport($win, $tabname, $abysl);
1974 } else {
1975 $log->warn("Unable to execute rules strategy code-ref");
1976 return;
1977 }
1978 } else {
1979 $log->warn("Code for non-existent tab $tabname was being executed");
1980 }
1981 }
1982  
1983 sub plot_data {
1984 my $self = shift;
1985 if (lc($self->plot_engine) eq 'gnuplot') {
1986 $log->info("Using Gnuplot to do plotting");
1987 $log->info("PDL::Graphics::Gnuplot $PDL::Graphics::Gnuplot::VERSION is being used");
1988 return $self->plot_data_gnuplot(@_);
1989 } elsif (lc($self->plot_engine) eq 'highcharts') {
1990 $log->info("Using HighCharts to do plotting");
1991 return $self->plot_data_highcharts(@_);
1992 }
1993 $log->warn($self->plot_engine . " is not supported yet.");
1994 }
1995  
1996 sub plot_data_gnuplot {
1997 my ($self, $win, $data, $symbol, $type, $indicators, $buysell) = @_;
1998 return unless defined $data;
1999 # use the x11 term by default first
2000 my $term = 'x11';
2001 # if the wxt term is there use that instead since it is just better
2002 # if the aqua term is there use that if wxt isn't there
2003 if ($^O =~ /Darwin/i) {
2004 Capture::Tiny::capture {
2005 my @terms = PDL::Graphics::Gnuplot::terminfo();
2006 $term = 'aqua' if (grep {/aqua/} @terms) > 0;
2007 $term = 'wxt' if (grep {/wxt/} @terms) > 0;
2008 $term = 'qt' if (grep {/qt/} @terms) > 0;
2009 };
2010 } elsif ($^O =~ /Win32|Cygwin/i) {
2011 Capture::Tiny::capture {
2012 my @terms = PDL::Graphics::Gnuplot::terminfo();
2013 $term = 'windows' if (grep {/windows/} @terms) > 0;
2014 $term = 'wxt' if (grep {/wxt/} @terms) > 0;
2015 $term = 'qt' if (grep {/qt/} @terms) > 0;
2016 # on Cygwin it may be x11
2017 };
2018 }
2019 $log->debug("Using term $term");
2020 my $pwin = $win->{plot} || gpwin($term, size => [1024, 768, 'px']);
2021 $win->{plot} = $pwin;
2022 $symbol = $self->current->{symbol} unless defined $symbol;
2023 $type = $self->current->{plot_type} unless defined $type;
2024 my @general_plot = ();
2025 my @volume_plot = ();
2026 my @addon_plot = ();
2027 my @candle_plot = ();
2028 $self->indicator->color_idx(0); # reset color index
2029 if (defined $indicators and scalar @$indicators) {
2030 # ok now create a list of indicators to plot
2031 foreach (@$indicators) {
2032 my $iref = $_->{indicator};
2033 my $idata = $_->{data};
2034 my $iplot = $self->indicator->get_plot_args($data(,(0)), $idata, $iref);
2035 next unless $iplot;
2036 if (ref $iplot eq 'ARRAY') {
2037 push @general_plot, @$iplot if scalar @$iplot;
2038 } elsif (ref $iplot eq 'HASH') {
2039 my $iplot_gen = $iplot->{general};
2040 push @general_plot, @$iplot_gen if $iplot_gen and scalar @$iplot_gen;
2041 my $iplot_vol = $iplot->{volume};
2042 push @volume_plot, @$iplot_vol if $iplot_vol and scalar @$iplot_vol;
2043 my $iplot_addon = $iplot->{additional};
2044 push @addon_plot, @$iplot_addon if $iplot_addon and scalar @$iplot_addon;
2045 my $iplot_cdl = $iplot->{candle};
2046 push @candle_plot, @$iplot_cdl if $iplot_cdl and scalar @$iplot_cdl;
2047 } else {
2048 $log->warn('Unable to handle plot arguments in ' . ref($iplot) . ' form!');
2049 }
2050 }
2051 }
2052 if (defined $buysell and ref $buysell eq 'HASH' and
2053 defined $buysell->{buys} and defined $buysell->{sells}) {
2054 my $buys = $buysell->{buys};
2055 my $sells = $buysell->{sells};
2056 my $rtpnl = $buysell->{rtpnl};
2057 if (ref $buys eq 'PDL' and ref $sells eq 'PDL') {
2058 my $bsplot = $self->indicator->get_plot_args_buysell(
2059 $data(,(0)), $buys, $sells, $rtpnl);
2060 if (defined $bsplot and ref $bsplot eq 'ARRAY') {
2061 push @general_plot, @$bsplot if scalar @$bsplot;
2062 } elsif (ref $bsplot eq 'HASH') {
2063 my $bsplot_gen = $bsplot->{general};
2064 if ($bsplot_gen) {
2065 push @general_plot, @$bsplot_gen if scalar @$bsplot_gen;
2066 }
2067 my $bsplot_addon = $bsplot->{additional};
2068 if (ref $bsplot_addon eq 'ARRAY' and scalar (@$bsplot_addon)) {
2069 push @addon_plot, @$bsplot_addon;
2070 }
2071 }
2072 } else {
2073 $log->warn("Unable to plot invalid buy-sell data");
2074 }
2075 }
2076 $pwin->reset();
2077 # use multiplot
2078 $pwin->multiplot();
2079 my %binmode = ();
2080 if ($^O !~ /Win32/ and $Alien::Gnuplot::version < 4.6) {
2081 $log->debug("Binary mode is set to 0 due to gnuplot $Alien::Gnuplot::version");
2082 $binmode{binary} = 0;
2083 }
2084 if ($type eq 'OHLC') {
2085 my %addon_gen = ();
2086 if (@addon_plot) {
2087 $addon_gen{size} = ["1, 0.7"];
2088 $addon_gen{origin} = [0, 0.3];
2089 $addon_gen{bmargin} = 0;
2090 $addon_gen{lmargin} = 9;
2091 $addon_gen{rmargin} = 2;
2092 }
2093 $pwin->plot({
2094 %binmode,
2095 object => '1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb "black" behind',
2096 title => ["$symbol Open-High-Low-Close", textcolor => 'rgb "white"'],
2097 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2098 border => 'linecolor rgbcolor "white"',
2099 xlabel => ['Date', textcolor => 'rgb "yellow"'],
2100 ylabel => ['Price', textcolor => 'rgb "yellow"'],
2101 xdata => 'time',
2102 xtics => {format => '%Y-%m-%d', rotate => -90, textcolor => 'orange', },
2103 ytics => {textcolor => 'orange'},
2104 label => [1, $self->brand, textcolor => 'rgb "cyan"', at => "graph 0.90,0.03"],
2105 %addon_gen,
2106 },
2107 {
2108 with => 'financebars',
2109 linecolor => 'white',
2110 legend => 'Price',
2111 },
2112 $data(,(0)), $data(,(1)), $data(,(2)), $data(,(3)), $data(,(4)),
2113 @general_plot,
2114 );
2115 if (@addon_plot) {
2116 $pwin->plot({
2117 %binmode,
2118 object => '1',
2119 title => '',
2120 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2121 border => 'linecolor rgbcolor "white"',
2122 ylabel => '',
2123 xlabel => '',
2124 xtics => '',
2125 ytics => {textcolor => 'orange'},
2126 bmargin => 0,
2127 tmargin => 0,
2128 lmargin => 9,
2129 rmargin => 2,
2130 size => ["1,0.3"], #bug in P:G:G
2131 origin => [0, 0],
2132 label => [1, "", at => "graph 0.90,0.03"],
2133 },
2134 @addon_plot,
2135 );
2136 }
2137 } elsif ($type eq 'OHLCV') {
2138 my %addon_gen = ();
2139 my %addon_vol = ();
2140 if (@addon_plot) {
2141 $addon_gen{size} = ["1, 0.6"]; #bug in P:G:G
2142 $addon_gen{origin} = [0, 0.4];
2143 $addon_vol{size} = ["1, 0.2"]; #bug in P:G:G
2144 $addon_vol{origin} = [0, 0];
2145 } else {
2146 $addon_gen{size} = ["1, 0.7"]; #bug in P:G:G
2147 $addon_gen{origin} = [0, 0.3];
2148 $addon_vol{size} = ["1, 0.3"]; #bug in P:G:G
2149 $addon_vol{origin} = [0, 0];
2150 $addon_vol{object} = '1'; # needed as otherwise the addon plot does it
2151 }
2152 $pwin->plot({
2153 %binmode,
2154 object => '1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb "black" behind',
2155 xlabel => ['Date', textcolor => 'rgb "yellow"'],
2156 ylabel => ['Price', textcolor => 'rgb "yellow"'],
2157 title => ["$symbol Price & Volume", textcolor => "rgb 'white'"],
2158 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2159 border => 'linecolor rgbcolor "white"',
2160 xdata => 'time',
2161 xtics => {format => '%Y-%m-%d', rotate => -90, textcolor => 'orange', },
2162 ytics => {textcolor => 'orange'},
2163 bmargin => 0,
2164 lmargin => 9,
2165 rmargin => 2,
2166 %addon_gen,
2167 label => [1, $self->brand, textcolor => 'rgb "cyan"', at => "graph 0.90,0.03"],
2168 },
2169 {
2170 with => 'financebars',
2171 linecolor => 'white',
2172 legend => 'Price',
2173 },
2174 $data(,(0)), $data(,(1)), $data(,(2)), $data(,(3)), $data(,(4)),
2175 @general_plot,
2176 );
2177 if (@addon_plot) {
2178 $pwin->plot({
2179 %binmode,
2180 object => '1',
2181 title => '',
2182 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2183 border => 'linecolor rgbcolor "white"',
2184 ylabel => '',
2185 xlabel => '',
2186 xtics => '',
2187 ytics => {textcolor => 'orange'},
2188 bmargin => 0,
2189 tmargin => 0,
2190 lmargin => 9,
2191 rmargin => 2,
2192 size => ["1,0.2"], #bug in P:G:G
2193 origin => [0, 0.2],
2194 label => [1, "", at => "graph 0.90,0.03"],
2195 },
2196 @addon_plot,
2197 );
2198 }
2199 $pwin->plot({
2200 %binmode,
2201 title => '',
2202 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2203 border => 'linecolor rgbcolor "white"',
2204 ylabel => ['Volume (in 1M)', textcolor => 'rgb "yellow"'],
2205 xlabel => '',
2206 xtics => '',
2207 ytics => {textcolor => 'orange'},
2208 bmargin => 0,
2209 tmargin => 0,
2210 lmargin => 9,
2211 rmargin => 2,
2212 %addon_vol,
2213 label => [1, "", at => "graph 0.90,0.03"],
2214 },
2215 {
2216 with => 'impulses',
2217 legend => 'Volume',
2218 linecolor => 'cyan',
2219 },
2220 $data(,(0)), $data(,(5)) / 1e6,
2221 @volume_plot,
2222 );
2223 } elsif ($type eq 'CANDLE') {
2224 my %addon_gen = ();
2225 if (@addon_plot) {
2226 $addon_gen{size} = ["1, 0.7"];
2227 $addon_gen{origin} = [0, 0.3];
2228 $addon_gen{bmargin} = 0;
2229 $addon_gen{lmargin} = 9;
2230 $addon_gen{rmargin} = 2;
2231 }
2232 # use candlesticks feature of Gnuplot
2233 $pwin->plot({
2234 %binmode,
2235 object => '1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb "black" behind',
2236 title => ["$symbol Open-High-Low-Close", textcolor => 'rgb "white"'],
2237 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2238 border => 'linecolor rgbcolor "white"',
2239 xlabel => ['Date', textcolor => 'rgb "yellow"'],
2240 ylabel => ['Price', textcolor => 'rgb "yellow"'],
2241 ytics => {textcolor => 'orange'},
2242 xdata => 'time',
2243 xtics => {format => '%Y-%m-%d', rotate => -90, textcolor => 'orange', },
2244 label => [1, $self->brand, textcolor => 'rgb "cyan"', at => "graph 0.90,0.03"],
2245 %addon_gen,
2246 },
2247 {
2248 with => 'candlesticks',
2249 linecolor => 'white',
2250 legend => 'Price',
2251 },
2252 $data(,(0)), $data(,(1)), $data(,(2)), $data(,(3)), $data(,(4)),
2253 @general_plot,
2254 @candle_plot,
2255 );
2256 if (@addon_plot) {
2257 $pwin->plot({
2258 %binmode,
2259 object => '1',
2260 title => '',
2261 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2262 border => 'linecolor rgbcolor "white"',
2263 ylabel => '',
2264 xlabel => '',
2265 xtics => '',
2266 ytics => {textcolor => 'orange'},
2267 bmargin => 0,
2268 tmargin => 0,
2269 lmargin => 9,
2270 rmargin => 2,
2271 size => ["1,0.3"], #bug in P:G:G
2272 origin => [0, 0],
2273 label => [1, "", at => "graph 0.90,0.03"],
2274 },
2275 @addon_plot,
2276 );
2277 }
2278 } elsif ($type eq 'CANDLEV') {
2279 my %addon_gen = ();
2280 my %addon_vol = ();
2281 if (@addon_plot) {
2282 $addon_gen{size} = ["1, 0.6"]; #bug in P:G:G
2283 $addon_gen{origin} = [0, 0.4];
2284 $addon_vol{size} = ["1, 0.2"]; #bug in P:G:G
2285 $addon_vol{origin} = [0, 0];
2286 } else {
2287 $addon_gen{size} = ["1, 0.7"]; #bug in P:G:G
2288 $addon_gen{origin} = [0, 0.3];
2289 $addon_vol{size} = ["1, 0.3"]; #bug in P:G:G
2290 $addon_vol{origin} = [0, 0];
2291 $addon_vol{object} = '1'; # needed as otherwise the addon plot does it
2292 }
2293 $pwin->plot({
2294 %binmode,
2295 object => '1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb "black" behind',
2296 title => ["$symbol Price & Volume", textcolor => "rgb 'white'"],
2297 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2298 border => 'linecolor rgbcolor "white"',
2299 xlabel => ['Date', textcolor => 'rgb "yellow"'],
2300 ylabel => ['Price', textcolor => 'rgb "yellow"'],
2301 xdata => 'time',
2302 ytics => {textcolor => 'orange'},
2303 xtics => {format => '%Y-%m-%d', rotate => -90, textcolor => 'orange', },
2304 tmargin => '',
2305 bmargin => 0,
2306 lmargin => 9,
2307 rmargin => 2,
2308 %addon_gen,
2309 label => [1, $self->brand, textcolor => 'rgb "cyan"', at => "graph 0.90,0.03"],
2310 },
2311 {
2312 with => 'candlesticks',
2313 linecolor => 'white',
2314 legend => 'Price',
2315 },
2316 $data(,(0)), $data(,(1)), $data(,(2)), $data(,(3)), $data(,(4)),
2317 @general_plot,
2318 @candle_plot,
2319 );
2320 if (@addon_plot) {
2321 $pwin->plot({
2322 %binmode,
2323 object => '1',
2324 title => '',
2325 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2326 border => 'linecolor rgbcolor "white"',
2327 ylabel => '',
2328 xlabel => '',
2329 xtics => '',
2330 ytics => {textcolor => 'orange'},
2331 bmargin => 0,
2332 tmargin => 0,
2333 lmargin => 9,
2334 rmargin => 2,
2335 size => ["1,0.2"], #bug in P:G:G
2336 origin => [0, 0.2],
2337 label => [1, "", at => "graph 0.90,0.03"],
2338 },
2339 @addon_plot,
2340 );
2341 }
2342 $pwin->plot({
2343 %binmode,
2344 title => '',
2345 ylabel => ['Volume (in 1M)', textcolor => 'rgb "yellow"'],
2346 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2347 border => 'linecolor rgbcolor "white"',
2348 xtics => '',
2349 xlabel => '',
2350 ytics => {textcolor => 'orange'},
2351 bmargin => 0,
2352 tmargin => 0,
2353 lmargin => 9,
2354 rmargin => 2,
2355 %addon_vol,
2356 label => [1, "", at => "graph 0.90,0.03"],
2357 },
2358 {
2359 with => 'impulses',
2360 legend => 'Volume',
2361 linecolor => 'cyan',
2362 },
2363 $data(,(0)), $data(,(5)) / 1e6,
2364 @volume_plot,
2365 );
2366 } elsif ($type eq 'CLOSEV') {
2367 my %addon_gen = ();
2368 my %addon_vol = ();
2369 if (@addon_plot) {
2370 $addon_gen{size} = ["1, 0.6"]; #bug in P:G:G
2371 $addon_gen{origin} = [0, 0.4];
2372 $addon_vol{size} = ["1, 0.2"]; #bug in P:G:G
2373 $addon_vol{origin} = [0, 0];
2374 } else {
2375 $addon_gen{size} = ["1, 0.7"]; #bug in P:G:G
2376 $addon_gen{origin} = [0, 0.3];
2377 $addon_vol{size} = ["1, 0.3"]; #bug in P:G:G
2378 $addon_vol{origin} = [0, 0];
2379 $addon_vol{object} = '1'; # needed as otherwise the addon plot does it
2380 }
2381 $pwin->plot({
2382 %binmode,
2383 object => '1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb "black" behind',
2384 title => ["$symbol Price & Volume", textcolor => "rgb 'white'"],
2385 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2386 border => 'linecolor rgbcolor "white"',
2387 ylabel => ['Close Price', textcolor => 'rgb "yellow"'],
2388 xlabel => ['Date', textcolor => 'rgb "yellow"'],
2389 xdata => 'time',
2390 xtics => {format => '%Y-%m-%d', rotate => -90, textcolor => 'orange', },
2391 ytics => {textcolor => 'orange'},
2392 bmargin => 0,
2393 lmargin => 9,
2394 rmargin => 2,
2395 %addon_gen,
2396 label => [1, $self->brand, textcolor => 'rgb "cyan"', at => "graph 0.90,0.03"],
2397 },
2398 {
2399 with => 'lines',
2400 linecolor => 'white',
2401 legend => 'Close Price',
2402 },
2403 $data(,(0)), $data(,(4)),
2404 @general_plot,
2405 );
2406 if (@addon_plot) {
2407 $pwin->plot({
2408 %binmode,
2409 object => '1',
2410 title => '',
2411 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2412 border => 'linecolor rgbcolor "white"',
2413 ylabel => '',
2414 xlabel => '',
2415 xtics => '',
2416 ytics => {textcolor => 'orange'},
2417 bmargin => 0,
2418 tmargin => 0,
2419 lmargin => 9,
2420 rmargin => 2,
2421 size => ["1,0.2"], #bug in P:G:G
2422 origin => [0, 0.2],
2423 label => [1, "", at => "graph 0.90,0.03"],
2424 },
2425 @addon_plot,
2426 );
2427 }
2428 $pwin->plot({
2429 %binmode,
2430 title => '',
2431 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2432 border => 'linecolor rgbcolor "white"',
2433 ylabel => ['Volume (in 1M)', textcolor => 'rgb "yellow"'],
2434 xlabel => '',
2435 xtics => '',
2436 ytics => {textcolor => 'orange'},
2437 bmargin => 0,
2438 tmargin => 0,
2439 lmargin => 9,
2440 rmargin => 2,
2441 %addon_vol,
2442 label => [1, "", at => "graph 0.90,0.03"],
2443 },
2444 {
2445 with => 'impulses',
2446 legend => 'Volume',
2447 linecolor => 'cyan',
2448 },
2449 $data(,(0)), $data(,(5)) / 1e6,
2450 @volume_plot,
2451 );
2452 } else {
2453 $type = 'CLOSE';
2454 my %addon_gen = ();
2455 if (@addon_plot) {
2456 $addon_gen{size} = ["1, 0.7"];
2457 $addon_gen{origin} = [0, 0.3];
2458 $addon_gen{bmargin} = 0;
2459 $addon_gen{lmargin} = 9;
2460 $addon_gen{rmargin} = 2;
2461 }
2462 $pwin->plot({
2463 %binmode,
2464 object => '1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb "black" behind',
2465 title => ["$symbol Close Price", textcolor => 'rgb "white"'],
2466 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2467 border => 'linecolor rgbcolor "white"',
2468 xlabel => ['Date', textcolor => 'rgb "yellow"'],
2469 ylabel => ['Close Price', textcolor => 'rgb "yellow"'],
2470 xdata => 'time',
2471 xtics => {format => '%Y-%m-%d', rotate => -90, textcolor => 'orange', },
2472 ytics => {textcolor => 'orange'},
2473 label => [1, $self->brand, textcolor => 'rgb "cyan"', at => "graph 0.90,0.03"],
2474 %addon_gen,
2475 },
2476 {
2477 with => 'lines',
2478 linecolor => 'white',
2479 legend => 'Close Price',
2480 },
2481 $data(,(0)), $data(,(4)),
2482 @general_plot,
2483 );
2484 if (@addon_plot) {
2485 $pwin->plot({
2486 %binmode,
2487 object => '1',
2488 title => '',
2489 key => ['on', 'outside', textcolor => 'rgb "yellow"'],
2490 border => 'linecolor rgbcolor "white"',
2491 ylabel => '',
2492 xlabel => '',
2493 xtics => '',
2494 ytics => {textcolor => 'orange'},
2495 bmargin => 0,
2496 tmargin => 0,
2497 lmargin => 9,
2498 rmargin => 2,
2499 size => ["1,0.3"], #bug in P:G:G
2500 origin => [0, 0],
2501 label => [1, "", at => "graph 0.90,0.03"],
2502 },
2503 @addon_plot,
2504 );
2505 }
2506 }
2507 $pwin->end_multi;
2508 # make the current plot type the type
2509 $self->current->{plot_type} = $type if defined $type;
2510 }
2511  
2512 sub plot_data_highcharts {
2513 my ($self, $win, $data, $symbol, $type, $indicators, $buysell) = @_;
2514 return unless defined $data;
2515 $symbol = $self->current->{symbol} unless defined $symbol;
2516 $type = $self->current->{plot_type} unless defined $type;
2517 ### for OHLC type
2518 ## timestamp: data(,(0))
2519 ## OHLC: data(, (1)), data(, (2)), data(,(3)), data(,(4))
2520 ## Volume: data(, (5))
2521 $log->debug("Symbol $symbol. Plot type $type");
2522 ### we use Template toolkit to take a template, plug data in via variables
2523 ### and auto-generate an HTML page that will then render graphics as needed
2524 ### maybe all the data should be in the HTML form for easy generation
2525 ### and the JS code has to be fixed and pre-written.
2526 ### so the JS code uses variables that are defined in the HTML data that is printed by
2527 ### the template
2528 my $ttfile = get_file_path('chart.tt');
2529 $log->info("Template file path: $ttfile");
2530 my $html = File::Spec->catfile($self->tmpdir, lc "$symbol\_$type.html");
2531 ## highcharts requires timestamp in milliseconds
2532 ## transpose the data for JSON charting
2533 my $chart_type_pretty;
2534 my @charts = ();
2535 $type //= 'OHLC';
2536 my $next_y_axis = 0;
2537 my $has_volume_chart = 0;
2538 if ($type eq 'OHLC' or $type eq 'CANDLE') {
2539 $chart_type_pretty = ($type eq 'CANDLE') ? 'Candlestick' : 'OHLC Price';
2540 my $ppdl = encode_json pdl($data(,(0)) * 1000, $data(,(1)), $data(,(2)), $data(,(3)), $data(,(4)))->transpose->unpdl;
2541 $log->debug($ppdl);
2542 push @charts, {
2543 title => $symbol,
2544 data => $ppdl,
2545 type => ($type eq 'CANDLE') ? 'candlestick' : 'ohlc',
2546 id => lc "$symbol-$type",
2547 y_axis => 0,
2548 };
2549 $next_y_axis = 1;
2550 } elsif ($type eq 'OHLCV' or $type eq 'CANDLEV') {
2551 $chart_type_pretty = ($type eq 'CANDLEV') ? 'Candlestick & Volume' : 'OHLC Price & Volume';
2552 my $ppdl = encode_json pdl($data(,(0)) * 1000, $data(,(1)), $data(,(2)), $data(,(3)), $data(,(4)))->transpose->unpdl;
2553 $log->debug($ppdl);
2554 my $vpdl = encode_json pdl($data(,(0)) * 1000, $data(,(5)))->transpose->unpdl;
2555 push @charts, {
2556 title => $symbol,
2557 data => $ppdl,
2558 type => ($type eq 'CANDLEV') ? 'candlestick' : 'ohlc',
2559 id => lc "$symbol-$type",
2560 y_axis => 0,
2561 };
2562 push @charts, {
2563 title => 'Volume',
2564 data => $vpdl,
2565 type => 'column',
2566 id => lc "$symbol-volume",
2567 y_axis => 1,
2568 };
2569 $has_volume_chart = 1;
2570 $next_y_axis = 2;
2571 } elsif ($type eq 'CLOSEV') {
2572 $chart_type_pretty = "Close Price & Volume";
2573 my $ppdl = encode_json pdl($data(,(0)) * 1000, $data(,(4)))->transpose->unpdl;
2574 my $vpdl = encode_json pdl($data(,(0)) * 1000, $data(,(5)))->transpose->unpdl;
2575 $log->debug($ppdl);
2576 push @charts, {
2577 title => $symbol,
2578 data => $ppdl,
2579 type => 'line',
2580 id => lc "$symbol-$type",
2581 y_axis => 0,
2582 };
2583 push @charts, {
2584 title => 'Volume',
2585 data => $vpdl,
2586 type => 'column',
2587 id => lc "$symbol-volume",
2588 y_axis => 1,
2589 };
2590 $has_volume_chart = 1;
2591 $next_y_axis = 2;
2592 } else {
2593 $chart_type_pretty = "Close Price";
2594 my $ppdl = encode_json pdl($data(,(0)) * 1000, $data(,(4)))->transpose->unpdl;
2595 $log->debug($ppdl);
2596 push @charts, {
2597 title => $symbol,
2598 data => $ppdl,
2599 type => 'line',
2600 id => lc "$symbol-$type",
2601 y_axis => 0,
2602 };
2603 $next_y_axis = 1;
2604 }
2605 ## add the indicators
2606 if (defined $indicators and scalar @$indicators) {
2607 $self->indicator->color_idx(0); # reset color index
2608 # ok now create a list of indicators to plot
2609 # we have to take the data and plot it into HighCharts structure
2610 foreach (@$indicators) {
2611 my $iref = $_->{indicator};
2612 my $idata = $_->{data};
2613 ## we have custom HighCharts plotting data handlers
2614 my $iplot = $self->indicator->get_plot_args($data(,(0)), $idata, $iref);
2615 next unless $iplot;
2616 if (ref $iplot eq 'ARRAY') {
2617 foreach my $ph (@$iplot) {
2618 use Data::Dumper;
2619 print Dumper($ph), "\n";
2620 $ph->{id} = lc "$symbol-$ph->{id}";
2621 $ph->{y_axis} = 0;
2622 $ph->{type} = ($ph->{impulses}) ? 'column' : 'line';
2623 push @charts, $ph;
2624 }
2625 } elsif (ref $iplot eq 'HASH') {
2626 my $iplot_gen = $iplot->{general};
2627 if (ref $iplot_gen eq 'ARRAY') {
2628 foreach my $ph (@$iplot_gen) {
2629 $ph->{type} = ($ph->{impulses}) ? 'column' : 'line';
2630 $ph->{id} = lc "$symbol-$ph->{id}";
2631 $ph->{y_axis} = 0;
2632 push @charts, $ph;
2633 }
2634 }
2635 my $iplot_vol = $iplot->{volume};
2636 if ($has_volume_chart and ref $iplot_vol eq 'ARRAY') {
2637 foreach my $ph (@$iplot_vol) {
2638 $ph->{type} = 'column';
2639 $ph->{id} = lc "$symbol-$ph->{id}";
2640 $ph->{y_axis} = 1;
2641 push @charts, $ph;
2642 }
2643 }
2644 my $iplot_addon = $iplot->{additional};
2645 if (ref $iplot_addon eq 'ARRAY') {
2646 foreach my $ph (@$iplot_addon) {
2647 $ph->{type} = ($ph->{impulses}) ? 'column' : 'line';
2648 $ph->{id} = lc "$symbol-$ph->{id}";
2649 $ph->{y_axis} = $next_y_axis;
2650 push @charts, $ph;
2651 }
2652 }
2653 if ($type =~ /CANDLE/) {
2654 my $iplot_cdl = $iplot->{candle};
2655 $log->debug("Candle: " . dumper($iplot_cdl));
2656 foreach my $ph (@$iplot_cdl) {
2657 $ph->{type} = 'column';
2658 $ph->{id} = lc "$symbol-$ph->{id}";
2659 $ph->{y_axis} = 0;
2660 push @charts, $ph;
2661 }
2662 }
2663 } else {
2664 $log->warn('Unable to handle plot arguments in ' . ref($iplot) . ' form!');
2665 }
2666 }
2667 }
2668 ## handle buys and sells
2669 ##handle runtime P&L and draw an area plot
2670 if (defined $buysell and ref $buysell eq 'HASH' and
2671 defined $buysell->{buys} and defined $buysell->{sells}) {
2672 my $buys = $buysell->{buys};
2673 my $sells = $buysell->{sells};
2674 if (ref $buys eq 'PDL' and ref $sells eq 'PDL') {
2675 my $bpdl = pdl($data(,(0)) * 1000, $buys)->transpose;
2676 my $bidx = $bpdl((1))->which;#check if !0 is true
2677 my $bpdlclean = $bpdl->dice_axis(1, $bidx);
2678 $log->debug($bpdlclean);
2679 my $bpdljs = encode_json $bpdlclean->unpdl;
2680 push @charts, {
2681 title => "Buy Signals",
2682 data => $bpdljs,
2683 type => 'line',
2684 id => lc "$symbol-buy-signals",
2685 y_axis => 0,
2686 is_signal => 1,
2687 marker_symbol => 'triangle',
2688 marker_color => 'green',
2689 };
2690 my $spdl = pdl($data(,(0)) * 1000, $sells)->transpose;
2691 my $sidx = $spdl((1))->which;#check if !0 is true
2692 my $spdlclean = $spdl->dice_axis(1, $sidx);
2693 $log->debug($spdlclean);
2694 my $spdljs = encode_json $spdlclean->unpdl;
2695 push @charts, {
2696 title => "Sell Signals",
2697 data => $spdljs,
2698 type => 'line',
2699 id => lc "$symbol-sell-signals",
2700 y_axis => 0,
2701 is_signal => 1,
2702 marker_symbol => 'triangle-down',
2703 marker_color => 'red',
2704 };
2705 } else {
2706 $log->warn("Unable to plot invalid buy-sell data");
2707 }
2708 if (ref $buysell->{rtpnl} eq 'PDL') {
2709 my $rpdl = pdl($data(, (0)) * 1000, $buysell->{rtpnl})->transpose;
2710 my $rpdljs = encode_json $rpdl->unpdl;
2711 push @charts, {
2712 title => "Runtime P&L",
2713 data => $rpdljs,
2714 type => 'area',
2715 id => lc "$symbol-runtime-pnl",
2716 y_axis => $next_y_axis + 1,
2717 };
2718 }
2719 }
2720 my %y_axes_index = ();
2721 foreach (@charts) {
2722 $y_axes_index{$_->{y_axis}}++;
2723 }
2724 my $cheight = 400;
2725 foreach (keys %y_axes_index) {
2726 $cheight += 200;
2727 }
2728 my $ttconf = {
2729 page => {
2730 title => "$chart_type_pretty plot of $symbol",
2731 close_on_idle => 1,
2732 },
2733 chart => {
2734 height => $cheight . "px",
2735 yaxes_index => [sort keys(%y_axes_index)],
2736 charts => \@charts,
2737 title => $symbol,
2738 },
2739 };
2740 my $tt = Template->new({ ABSOLUTE => 1 });
2741 my $ret = $tt->process($ttfile, $ttconf, $html, { binmode => ':utf8' });
2742 if ($ret) {
2743 my $url = "file://$html";
2744 my $ok = Browser::Open::open_browser($url, 1);
2745 if (not defined $ok) {
2746 message("Error finding a browser to open $url");
2747 $log->warn("Error finding a default browser to open $url");
2748 } elsif ($ok != 0) {
2749 message("Error opening $url");
2750 $log->warn("Error opening $url in default browser");
2751 }
2752 } else {
2753 $log->error("Failed to generate $html from $ttfile: " . $tt->error() . "\n");
2754 message("Failed to plot chart in a browser!");
2755 }
2756 # make the current plot type the type
2757 $self->current->{plot_type} = $type if defined $type;
2758 }
2759  
2760 1;
2761  
2762 __END__
« App/financeta/gui/tradereport.pm ↑ Summary