# make.pl

# each approach where the code is written like this is in its own directory and has a make.pl file so you can make the R code

# the R code is simply called trading.R

# so to run you simply go R <trading.R> out.txt (and you can view the output in out.txt

# WRONG - IT WOULD APPEAR YOU HAVE TO HAVE A FRESH PROMPT TO GET A CORRECT ID SO MAKE SURE YOU OPEN A NEW COMMAND PROMPT UP FOR IT WHEN YOU WANT TO RUN trading.R

# use strict;
# use R; # doesnt work with windows so ill
# use R.bat at the command line and put the input into r_in.txt and output into r_out.txt


# lets get my symbols
# make sure your entries are x > y in this file

my $AVERAGE_TRANSACTION_SIZE = 1000;
my $STOP_LOSS = 1.05;
my $CONNECTION_ID = 99; # connection ID have to be unique for each thing you are running and not used twice while the same R connection is open!



open (FILE, 'CO_INT_N_REV_WATCHLIST.TXT');

my @symbols;

while(<FILE>){


	chomp($_);
	if($_ !~ '#'){push(@symbols,$_);}
	

}

close FILE;

#### going to write my r_in.txt here

open (FILE, '>r_in.txt');

print FILE "

library(IBrokers)
library('quantmod')

processEach <- function(sym1,exch1,currency1, sym2,exch2,currency2)  {

	one <- reqHistoricalData(tws, twsEquity(sym1, exch=exch1, currency=currency1),duration = '6 M') 
	Sys.sleep(10)
	two <- reqHistoricalData(tws, twsEquity(sym2, exch=exch2, currency=currency2),duration = '6 M') 
	Sys.sleep(10)
	print(c('sprd->',last(one[,4]) - last(two[,4])))
	sma <- SMA(one[,4] - two[,4], n=20)
	print(c('m.ave->',last(sma)))
	spd <- one[,4] - two[,4]
	spd <- last(spd,20)
	s <- sd(spd)
	upper <- last(sma) + (2 * s)
	lower <- last(sma) - (2 * s)
	print(c('upp.s.d->', upper))
	print(c('low.s.d->', lower ))
	
}


tws <- twsConnect(15)
tws

";



foreach(@symbols) {

	
	my ($first, $second) = split ('<->', $_);
	my ($sym1,$exch1,$currency1) = split(',',$first);
	my ($sym2,$exch2,$currency2) = split(',',$second);
	print FILE "processEach('$sym1','$exch1','$currency1','$sym2','$exch2','$currency2')\n";
	
}

print FILE "\ncloseAllConnections()";

close FILE;

system('R <r_in.txt> out.txt');



open (FILE, 'out.txt');

#raw file: [1] "m.ave->" "25.1805"

#raw file: [1] "upp.s.d->"        "25.5708347913549"

#raw file: [1] "low.s.d->"        "24.7901652086451"

my @data;

while(<FILE>){

	#print "raw file: $_\n" ;
	if ($_ =~ m/processEach\('/ || ($_ =~ m/sprd/  && $_ !~ m/print.c.'sprd->/ ) || ($_ =~ m/m.ave/  && $_ !~ m/print.c..m.ave/ ) || ($_ =~ m/upp.s.d/  && $_ !~ m/print.c..upp.s.d/ ) || ($_ =~ m/low.s.d/  && $_ !~ m/print.c..low.s.d/ )){
		push(@data,$_);
		print "$_"
	}
	
	;

}

close FILE;


for(my $i = 0; $i < $#data; $i = $i + 5) {

	

}



my $traded;
my $getNprintData;
my $to_be_opened;
my $index;
my $symbols = "list(";
$data_num = 1;

my @moving_averages;

for(my $i = 0; $i < $#data; $i = $i + 5) {


	print "data $i is: $data[$i]\n";
	
	$data[$i] =~ m/processEach\('(...)','(...)','(...)','(...)','(...)','(...)'\)/;
	
	
		
	my $sym1 = $1;
	print "sym1 = $sym1\n";
	my $exch1 = $2;
	my $currency1 = $3;
	my $sym2 = $4;
	my $exch2 = $5;
	my $currency2 = $6;
	
	
	
	
	$data[$i + 1] =~ m/\[1\] \"sprd->\"\s*\"(.*)\"/;
	
	my $spread = $1;
	#print "spread = $spread\n";
	
	
	
	$data[$i + 2] =~ m/\[1\] \"m.ave->\"\s*\"(.*)\"/;
	
	my $mean = $1;
	
		
	$data[$i + 3] =~ m/\[1\] \"upp.s.d->\"\s*\"(.*)\"/;
	
	my $upper = $1;
	
		
	
	$data[$i + 4] =~ m/\[1\] \"low.s.d->\"\s*\"(.*)\"/;
	
		
	my $lower = $1;
	
	print "$sym1:$sym2 $spread > $upper || $spread < $lower :\n";
	
	if ($spread - $upper > 0|| $lower - $spread > 0){ # are they outside
	
		$symbols .= "twsEquity('$sym1', '$exch1', '$currency1'),twsEquity('$sym2', '$exch2', '$currency2'),";
	
		print "outside\n";
	
		if ($i == 0) {
			$index = 1;
		} elsif ($i % 5 == 0) {

			$index++

		}
		$traded = $traded . "\ttraded_$index <- FALSE\n\tclosed_$index <- FALSE\n";
		
		$data_num2 = $data_num + 1;

		$getNprintData = $getNprintData  . "\n\t\tLast_".$index."_1 <- as.numeric(eWrapper\$.Data\$data\[\[$data_num\]\]\[,5\])
		Last_".$index."_2 <- as.numeric(eWrapper\$.Data\$data\[\[$data_num2\]\]\[,5\])
		Spread_$index <- Last_".$index."_1 - Last_".$index."_2
		print(c('$sym1 ',Last_".$index."_1, '$sym2 ', Last_".$index."_2, 'Spread ', Spread_$index, 'The boundaries are $upper', 'lower $lower',' mean is $mean'))";
		
		$data_num++;
		$data_num++;
		
		

		# ok and now short or long
		if ($spread - $upper > 0) { #short

			# shorts
			
			$to_be_opened .= "\n\t\tif(!traded_$index && !is.na(Spread_$index) && Spread_$index < $upper && Spread_$index > 0) { 

						
			num_shares <- $AVERAGE_TRANSACTION_SIZE / Last_".$index."_1
			num_shares <- as(num_shares,'integer')
			print(c('$AVERAGE_TRANSACTION_SIZE',Last_".$index."_1, num_shares))
			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', num_shares, 'MKT'))
			num_shares2 <- $AVERAGE_TRANSACTION_SIZE / Last_".$index."_2
			num_shares2 <- as(num_shares2,'integer')
			print(c('$AVERAGE_TRANSACTION_SIZE',Last_".$index."_2, num_shares2))
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', num_shares2, 'MKT'))
			traded_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE TRADED SHORT. SELL',num_shares, '$sym1. BUY', num_shares2, '$sym2')
			Spread_dealt_at_$index <- Spread_$index
			num_shares_".$index."_1 <- num_shares
			num_shares_".$index."_2 <- num_shares2
			
			}";
			
			# and lets add the stop if we do open
			

			$to_be_opened .= "\n\t\tif(traded_$index && !closed_$index && !is.na(Spread_$index) && Spread_$index > (Spread_dealt_at_$index * $STOP_LOSS)  && Spread_$index > 0) { 


			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', num_shares_".$index."_1, 'MKT'))
			
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', num_shares_".$index."_2, 'MKT'))
			closed_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE CLOSED A  SHORT. BUY',num_shares_".$index."_1, '$sym1. SELL', num_shares_".$index."_2, '$sym2')
			}";
			
			# and lets add a close if it passes the average once we have opened
			
			
			$to_be_opened .= "\n\t\tif(!traded_$index && !closed_$index && !is.na(Spread_$index) && Spread_$index < $mean && Spread_$index > 0) { 
			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', num_shares_".$index."_1, 'MKT'))
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', num_shares_".$index."_2, 'MKT'))
			traded_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING SHORT. SELL', '$sym1_num', '$sym1. BUY', '$sym2_num', '$sym2')
					
			}";
			
			
		} elsif ($lower - $spread > 0){ # long
		
			# longs
			
					
			$to_be_opened .= "\n\t\tif(!traded_$index && !is.na(Spread_$index) && Spread_$index > $lower && Spread_$index > 0) { 
			
			 
			
			num_shares <- $AVERAGE_TRANSACTION_SIZE / Last_".$index."_1
			num_shares <- as(num_shares,'integer')
			print(c('$AVERAGE_TRANSACTION_SIZE',Last_".$index."_1, num_shares))
			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', num_shares, 'MKT'))
			num_shares2 <- $AVERAGE_TRANSACTION_SIZE / Last_".$index."_2
			num_shares2 <- as(num_shares2,'integer')
			print(c('$AVERAGE_TRANSACTION_SIZE',Last_".$index."_2, num_shares2))
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', num_shares2, 'MKT'))
			traded_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE TRADED LONG. BUY', num_shares, '$sym1. SELL', num_shares2, '$sym2')
			Spread_dealt_at_$index <- Spread_$index
			num_shares_".$index."_1 <- num_shares
			num_shares_".$index."_2 <- num_shares2
			}";
			
			# and lets add the stop if we do open
						
			
			$to_be_opened .= "\n\t\tif(traded_$index && !closed_$index && !is.na(Spread_$index) && Spread_$index < (Spread_dealt_at_$index / $STOP_LOSS )  && Spread_$index > 0) { 


			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', num_shares_".$index."_1, 'MKT'))

			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', num_shares_".$index."_2, 'MKT'))
			closed_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE CLOSED A LONG. SELL',num_shares_".$index."_1, '$sym1. BUY', num_shares_".$index."_2, '$sym2')
			}";
			
			# and lets add a close if it passes the average once we have opened
						
						
			$to_be_opened .= "\n\t\tif(!traded_$index && !closed_$index && !is.na(Spread_$index) && Spread_$index > $mean && Spread_$index > 0) { 
			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', num_shares_".$index."_1, 'MKT'))
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', num_shares_".$index."_2, 'MKT'))
			traded_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING LONG. BUY', '$sym1_num', '$sym1. SELL', '$sym2_num', '$sym2')
								
			}";
		
		
		}
		

	}
		
	
	#as(1.1,"integer")
	
	#print "these are the figures $sym1 $sym2 $spread $ma $upper $lower\n";


}	

##### ADD EXISTING POSITIONS ############

open(FILE1, 'CO_INT_N_REV_POSITIONS.TXT');
#WDC,ASX,AUD,1044,CFX,ASX,AUD,5682,LONG,7.94181	

# maybe I can just deal with them here

my $to_be_closed;

while(<FILE1>){

   print "$_";

   if ($_ gt "\n") { # don't want an empty file

	
	
	# OK lets get the data
	# this file contains thus comma seperated info
	my ($sym1, $exch1, $currency1, $sym1_num, $sym2, $exch2, $currency2, $sym2_num, $direction, $cost) = split(',',$_);
	chomp($cost);
	print "$sym1, $exch1, $currency1, $sym1_num, $sym2, $exch2, $currency2, $sym2_num, $direction, $cost\n";
	

	$index++; 
	
	$traded = $traded . "\ttraded_$index <- FALSE\n";
	
	$symbols .= "twsEquity('$sym1', '$exch1', '$currency1'),twsEquity('$sym2', '$exch2', '$currency2'),";
	$data_num2 = $data_num + 1;
	$getNprintData .= "\n\t\tLast_".$index."_1 <- as.numeric(eWrapper\$.Data\$data\[\[$data_num\]\]\[,5\])
		Last_".$index."_2 <- as.numeric(eWrapper\$.Data\$data\[\[$data_num2\]\]\[,5\])
		Spread_$index <- Last_".$index."_1 - Last_".$index."_2
		print(c('Existing Position: $sym1 ',Last_".$index."_1, '$sym2 ', Last_".$index."_2, 'Spread ', Spread_$index))";
		
	$data_num++;
	$data_num++;
	
	if ($direction =~ m/SHORT/) {
	
		print "inside short\n";
		# first a stop loss at 2% the wrong way
		$to_be_closed .= "\n\t\tif(!traded_$index && !is.na(Spread_$index) && Spread_$index > ($cost * $STOP_LOSS) && Spread_$index > 0) { 
			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', $sym1_num, 'MKT'))
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', $sym2_num, 'MKT'))
			traded_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE TRADED CLOSING STOP LOSS SHORT. SELL', '$sym1_num', '$sym1. BUY', '$sym2_num', '$sym2')

		}";
		
		# then to close if you pass the moving average
		# where is the moving average?
		# maybe I'll have to get it
		
		
		$getMA = "
		
		library(IBrokers)
		library('quantmod')
		
		processEach <- function(sym1,exch1,currency1, sym2,exch2,currency2)  {
		
			one <- reqHistoricalData(tws, twsEquity(sym1, exch=exch1, currency=currency1),duration = '6 M') 
			Sys.sleep(10)
			two <- reqHistoricalData(tws, twsEquity(sym2, exch=exch2, currency=currency2),duration = '6 M') 
			Sys.sleep(10)
			print(c('sprd->',last(one[,4]) - last(two[,4])))
			sma <- SMA(one[,4] - two[,4], n=20)
			print(c('m.ave->',last(sma)))
			spd <- one[,4] - two[,4]
			spd <- last(spd,20)
			s <- sd(spd)
			upper <- last(sma) + (2 * s)
			lower <- last(sma) - (2 * s)
			print(c('upp.s.d->', upper))
			print(c('low.s.d->', lower ))
			
		}
				
		tws <- twsConnect(15)
		tws
		
		processEach('$sym1','$exch1','$currency1','$sym2','$exch2','$currency2')
		
		closeAllConnections()
		
		";
		
	
		
		open (FILE, '>getMA.txt');
		
		print FILE $getMA;
		
		close FILE;
		
		system('R <getMA.txt> ma.txt');
		
		# OK lets get it back
		
		open (FILE, 'ma.txt');
		
		my $moving_average;
		
		while(<FILE>) {
		
			# [1] "m.ave->" "27.3955"
			if($_ =~ m/\[1\] \"m.ave->\"\s*\"(.*)\"/) {
			
				$moving_average = $1;
			
			}
		
		}
		
		close FILE;
		
		print "the moving average is $moving_average\n";
		
		
		$to_be_closed .= "\n\t\tif(!traded_$index && !is.na(Spread_$index) && Spread_$index < $moving_average && Spread_$index > 0) { 
			placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', $sym1_num, 'MKT'))
			placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', $sym2_num, 'MKT'))
			traded_$index <- TRUE
			print(c('I HAVE TRADED'))
			ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING SHORT. SELL', '$sym1_num', '$sym1. BUY', '$sym2_num', '$sym2')
		
		}";
		
	} elsif ($direction =~ m/LONG/){ # repeat but other way around
	
		print "inside long\n";
	
	
		# first a stop loss at 2% the wrong way
			$to_be_closed .= "\n\t\tif(!traded_$index && !is.na(Spread_$index) && Spread_$index < ($cost / $STOP_LOSS) && Spread_$index > 0) { 
				placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', $sym1_num, 'MKT'))
				placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', $sym2_num, 'MKT'))
				traded_$index <- TRUE
				print(c('I HAVE TRADED'))
				ihavetraded <- c('I HAVE TRADED CLOSING STOP LOSS LONG. SELL', '$sym1_num', '$sym1. BUY', '$sym2_num', '$sym2')
	
			}";
			
			# then to close if you pass the moving average
			# where is the moving average?
			# maybe I'll have to get it
			
			
			$getMA = "
			
			library(IBrokers)
			library('quantmod')
			
			processEach <- function(sym1,exch1,currency1, sym2,exch2,currency2)  {
			
				one <- reqHistoricalData(tws, twsEquity(sym1, exch=exch1, currency=currency1),duration = '6 M') 
				Sys.sleep(10)
				two <- reqHistoricalData(tws, twsEquity(sym2, exch=exch2, currency=currency2),duration = '6 M') 
				Sys.sleep(10)
				print(c('sprd->',last(one[,4]) - last(two[,4])))
				sma <- SMA(one[,4] - two[,4], n=20)
				print(c('m.ave->',last(sma)))
				spd <- one[,4] - two[,4]
				spd <- last(spd,20)
				s <- sd(spd)
				upper <- last(sma) + (2 * s)
				lower <- last(sma) - (2 * s)
				print(c('upp.s.d->', upper))
				print(c('low.s.d->', lower ))
				
			}
					
			tws <- twsConnect(15)
			tws
			
			processEach('$sym1','$exch1','$currency1','$sym2','$exch2','$currency2')
			
			closeAllConnections()
			
			";
			
		
			
			open (FILE, '>getMA.txt');
			
			print FILE $getMA;
			
			close FILE;
			
			system('R <getMA.txt> ma.txt');
			
			# OK lets get it back
			
			open (FILE, 'ma.txt');
			
			my $moving_average;
			
			while(<FILE>) {
			
				# [1] "m.ave->" "27.3955"
				if($_ =~ m/\[1\] \"m.ave->\"\s*\"(.*)\"/) {
				
					$moving_average = $1;
				
				}
			
			}
			
			close FILE;
			
			print "the moving average is $moving_average\n";
			
			
			$to_be_closed .= "\n\t\tif(!traded_$index && !is.na(Spread_$index) && Spread_$index > $moving_average && Spread_$index > 0) { 
				placeOrder(twsCon,  twsContract('', '$sym1', 'CFD', 'SNFE', '', '', '', '$currency1', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'SELL', $sym1_num, 'MKT'))
				placeOrder(twsCon,  twsContract('', '$sym2', 'CFD', 'SNFE', '', '', '', '$currency2', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon), 'BUY', $sym2_num, 'MKT'))
				traded_$index <- TRUE
				print(c('I HAVE TRADED'))
				ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING LONG. SELL', '$sym1_num', '$sym1. BUY', '$sym2_num', '$sym2')
			
		}";
	
	
	
	
	}
	

   }	

	

}

close FILE1;






# get rid of last comma

$symbols =~ s/\),$/\)/;

# OK got to write this:

my $number = $index * 2;

my $co_int_n_rev = "


\# co.txt run's like this: R <co.txt> out.txt

library(IBrokers)

CO_INT_N_REV <- function(twsCon, eWrapper, timestamp, file, playback = 1, ...) {
	
	con <- twsCon\[\[1\]\]	
$traded
	ihavetraded <- 'I HAVE NOT TRADED'
	while (TRUE) {

		socketSelect(list(con), FALSE, NULL)

		\# get data
		
		curMsg <- readBin(con, character(), 1)
		if (!is.null(timestamp)) {
			processMsg(curMsg, con, eWrapper, format(Sys.time(), timestamp), file, ...)
		} else {
			processMsg(curMsg, con, eWrapper, timestamp, file, ...)
		}

		# extract data

		Symbols <- eWrapper\$.Data\$symbols 
		print(ihavetraded)
		print(c('Time', format(Sys.time())))
$getNprintData
		
		\# trade logic here 
		     
		\# first any potentially new positions from watchlist
$to_be_opened
		
		\# then in relation to open positions closing rules for any stops and crossings of the moving average
		
$to_be_closed;

		
		
		
		
	}	
}
    
    
con = twsConnect($CONNECTION_ID)

reqMktData(con, $symbols),  eventWrapper=eWrapper.data(".$number ."), CALLBACK=CO_INT_N_REV)

closeAllConnections()

";

open(FILE, '>trading.R');

print FILE $co_int_n_rev;

close FILE;

