#!/usr/bin/perl --
#
#
# Stock Data Tracker Angelos Karageorgiou angelos@iqs.gr July 2001
#  Perl rocks!
#
#
###############################################################################
#
# Please create a system DSN which points to AseTicker.mdb  called "ticker"
#                        one which points to AseHistory.mdb called "AseHistory"
#                        one which points to AseEquity.mdb  called "AseEquity"
#
################################################################################

use Win32::GUI;
use Win32::ODBC;	# for ODBC  install with "ppm install DBI" for activestate perl
use Socket;


$WshShell = $WScript->CreateObject("WScript.Shell");

$File = GUI::GetOpenFileName(
        -owner => $W,
        -directory => "C:\\Tradetrek",
        -title => "Load Stocks and limits File",
        -file => $File,
    );



if ( ( ! defined ( $File) ) || ( $File =~ /^$/) ){
	wprint ("No File Specified Exiting");
	exit(1);
}




$SIG{PIPE} = \&catch_zap;   # oh well just in case something breaks

###### Constants #########
$host='panther.iqs.gr';	# target host
$port=9000;		# target port


$SEP="\t";		# Field Separator
$ENDDAY=15;		# go home at 3 o clock
$SLEEP=15;		# seconds to sleep between iterations 
$HOME="\\tradetrek\\logs";# where log files go
$NUMSTOCKS=390;		# above this point we should consider that we have all the stocks for closing the day
$CLOSESLEEP=60;		# seconds to sleep for closings
$SPACER=" ";	# spaces :-)

$oldsymbol="";

($sec, $min, $hour, $mday, $mon,$year,$wday, $yday, $isdst) =
        localtime(time());

$today=sprintf("%04d-%02d-%02d",1900+$year,$mon+1,$mday);



%SUP1={};
%SUP2={};
%RES1={};
%RES2={};
#
#   Get the IPOS
#
readgalan();


#################################################################
##############                                  #################
##############       Process the big picture    #################
##############                                  #################
#################################################################



$DSN="ticker";
if (!($dbticker = new Win32::ODBC($DSN) ) ){
       wprint("Error connecting to $DSN");
       wprint("Error: " . Win32::ODBC::Error());
       exit;
}

$prevRun=sprintf("%02d:%02d:%02d",$hour,$min,$sec);
sleep 1;

#
#  Main  Processing Loop 
#
while ( $hour < $ENDDAY ) { # all day until 3 oclock

	# Prepare file,times etc.

	($sec, $min, $hour, $mday, $mon,$year,$wday, $yday, $isdst) =
        	localtime(time());


	$now=sprintf("%02d:%02d:%02d",$hour,$min,$sec);

	queryTicker($prevRun,$now,$filename);

	$prevRun=$now;

	sleep $SLEEP; #seconds

} 

$dbticker->Close();	#done with the Ticker
1;


################################################################
#########    Query the Ticker mdb file     #####################
################################################################

sub queryTicker{
my $prevRun=shift;
my $now=shift;
my $filename=shift;
my $sqlTicker;

#       Get the info from ODBC

$sqlTicker="SELECT 	
	TimeStamp,
	Symbol,
	LastSaleType,
	Last,
	Volume,
	TotalVolume,
	Bid,
	BidSize,
	Ask,
	AskSize
		FROM ticker
	WHERE 
		TimeStamp > #$prevRun#
	and
		TimeStamp <= #$now#
	ORDER BY TimeStamp, SYMBOL";
	

#wprint($sqlTicker);
	
	if ($dbticker->Sql($sqlTicker)){
	        wprint ("SQL failed.\n");
        	wprint ("Error: " . $dbticker->Error());
	       $dbticker->Close();
        	exit;
	}

$count=0;
undef %seenData;

$text = "                                   Time: ".  $now . "\n\n";
while($dbticker->FetchRow()){
	$count++;
	undef %tData;

	%tData = $dbticker->DataHash();
	if ( $seenData{$tData{"Symbol"}} ) {
		next;
	} else {
		$seenData{$tData{"Symbol"}}
	}

	checkTickerdata($count);
}

if ( $count < 0 ) {
        wprint("No Ticker Data found for period $prevRun \- $now");
} else {
	wprint($text);
}



}  # end query Ticker




#########       Output the Ticker Data                ###########################

sub checkTickerdata{
my $count=shift;
	# stupid stpupid stupid, they have a special value for the date
	($date,$now)=split(" ",$tData{"TimeStamp"});	
#	print $now	 		. $SEP ;
#	print $tData{"Symbol"} 		. $SEP ;
#	print $tData{"LastSaleType"} 	. $SEP ;
#	print $tData{"Last"} 		. $SEP ;
#	print $tData{"Volume"} 		. $SEP ;
#	print $tData{"TotalVolume"} 	. $SEP ;
#	print $tData{"Bid"} 		. $SEP ;
#	print $tData{"BidSize"}		. $SEP ;
#	print $tData{"Ask"} 		. $SEP ;
#	print $tData{"AskSize"}		. "\n" ;
	print "\n";

#$text=$now . " " . $tData{'Symbol'} . " " . $tData{'Last'} ." " . $tData{'Volume'};
#wprint($text);



	$price=$tData{"Last"} ;

	$compup=$price*0.99;
	$compdown=$price*1.01;

	$symbol=$tData{"Symbol"};

	if ( $oldsymbol =~ /^$symbol$/ ) {
		next;
	}

#	$text.=$symbol . " " . "SUP1=$SUP1{$symbol} SUP2=$SUP2{$symbol} RES1=$RES1{$symbol} RES2=$RES2{$symbol}";
	$text.=$symbol;


	if ( $compup >= $SUP2{$symbol} ) {
		$text.=sprintf("%s %s at %5.2f is a STRONG SELL $$$$$$$$$$\n",$SPACER,$symbol,$price);
		$oldsymbol=$symbol;
		next;
	}
	if ( $compup >= $SUP1{$symbol} ) {
		$text.=sprintf("%s %s at %5.2f is a       SELL   $$$$$$$$$$$ \n",$SPACER,$symbol,$price);
		$oldsymbol=$symbol;
		next;
	}

	if ( $compdown < $RES1{$symbol} ) {
		$text.=sprintf("%s %s at %5.2f is a        BUY\n",$SPACER,$symbol,$price);
		$oldsymbol=$symbol;
		next;
	}
	if ( $compdown < $RES2{$symbol} ) {
		$text.=sprintf("%s %s at %5.2f is a STRONG BUY\n",$SPACER,$symbol,$price);
		$oldsymbol=$symbol;
		next;
	}

}



#
# Pipe signal catcher
# 
sub catch_pipe {
            my $signame = shift;
            die "Somebody sent me a SIG$signame";
}





sub readgalan {
open(FILE,"<$File")|| die "Cannot read data";
$count=0;
while(<FILE>){
	$count++;
	if ( $count < 2 ) {
		next;
	}
	chomp($_);
	($symbol,$sup1,$res1,$sup2,$res2)=split("	",$_);
	$SUP1{$symbol}=$sup1;
	$SUP2{$symbol}=$sup2;
	$RES1{$symbol}=$res1;
	$RES2{$symbol}=$res2;
   }

close(FILE);
wprint("Loaded $count Symbols\n\nI am now going to the background");
}


sub wprint(){
#	$WScript->Echo (join(" ",@_));
	$WshShell->Popup(join(" ",@_),20,"Stock Alert",1+48);
};