Hi
I am running on windows using an IB workstation with R talking to it.
It all seems to work, but I find that when running my own callback (code
attached):
1. I have to make sure I start a clean (new) command windows or
something goes wrong with the allocation of a transaction id via
reqIds (Ok I just work around by opening a new command prompt and
2. (big problem) I don't always get the prices back so the algorithms
don't always work. For example this is the output of that code:
[1] "Existing Position: JBH " "18.51"
[3] "MYR " "3.65"
[5] "Spread " "14.86"
2 -1 2103 Market data farm connection is broken:aufarm
[1] "I HAVE TRADED AT AVERAGE CLOSING SHORT. SELL"
[2] "52"
[3] "JBH. BUY"
[4] "280"
[5] "MYR"
[1] "Time" "2011-01-31 15:34:02.373"
[1] "LEI " NA
[3] "WOR " NA
[5] "Spread " NA
[7] "The boundaries are 4.46697721920205" "lower 2.44602278079795"
[9] " mean is 3.4565"
[1] "QBE " NA
[3] "AMP " NA
[5] "Spread " NA
[7] "The boundaries are 13.3779288310757" "lower 12.2030711689243"
[9] " mean is 12.7905"
[1] "QBE " NA
[3] "AXA " NA
[5] "Spread " NA
[7] "The boundaries are 12.1631661762672" "lower 11.1048338237328"
[9] " mean is 11.634"
I'm getting the prices for JBH and MYR but not for the other stocks.
The boundary/mean figures are hard coded in my function but were
obtained in a previous IB call but that was a different call
reqHistoricalData where as this is reqMktData. My perl code to manage
that part of the exercise is attached.
One thing I have noticed is that if I get my trader work station to show
the price and stop and restart my trading.R code I do get a price. Does
anyone else have experience of reqMktData not showing prices if they are
not live on the TWS?
--
Stephen Choularton Ph.D., FIoD
# 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_1 <- FALSE
closed_1 <- FALSE
traded_2 <- FALSE
closed_2 <- FALSE
traded_3 <- FALSE
closed_3 <- FALSE
traded_4 <- FALSE
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())))
Last_1_1 <- as.numeric(eWrapper$.Data$data[[1]][,5])
Last_1_2 <- as.numeric(eWrapper$.Data$data[[2]][,5])
Spread_1 <- Last_1_1 - Last_1_2
print(c('LEI ',Last_1_1, 'WOR ', Last_1_2, 'Spread ', Spread_1,
'The boundaries are 4.46697721920205', 'lower 2.44602278079795',' mean is
3.4565'))
Last_2_1 <- as.numeric(eWrapper$.Data$data[[3]][,5])
Last_2_2 <- as.numeric(eWrapper$.Data$data[[4]][,5])
Spread_2 <- Last_2_1 - Last_2_2
print(c('QBE ',Last_2_1, 'AMP ', Last_2_2, 'Spread ', Spread_2,
'The boundaries are 13.3779288310757', 'lower 12.2030711689243',' mean is
12.7905'))
Last_3_1 <- as.numeric(eWrapper$.Data$data[[5]][,5])
Last_3_2 <- as.numeric(eWrapper$.Data$data[[6]][,5])
Spread_3 <- Last_3_1 - Last_3_2
print(c('QBE ',Last_3_1, 'AXA ', Last_3_2, 'Spread ', Spread_3,
'The boundaries are 12.1631661762672', 'lower 11.1048338237328',' mean is
11.634'))
Last_4_1 <- as.numeric(eWrapper$.Data$data[[7]][,5])
Last_4_2 <- as.numeric(eWrapper$.Data$data[[8]][,5])
Spread_4 <- Last_4_1 - Last_4_2
print(c('Existing Position: JBH ',Last_4_1, 'MYR ', Last_4_2,
'Spread ', Spread_4))
# trade logic here
# first any potentially new positions from watchlist
if(!traded_1 && !is.na(Spread_1) && Spread_1 < 4.46697721920205
&& Spread_1 > 0) {
num_shares <- 1000 / Last_1_1
num_shares <- as(num_shares,'integer')
print(c('1000',Last_1_1, num_shares))
placeOrder(twsCon, twsContract('', 'LEI', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares, 'MKT'))
num_shares2 <- 1000 / Last_1_2
num_shares2 <- as(num_shares2,'integer')
print(c('1000',Last_1_2, num_shares2))
placeOrder(twsCon, twsContract('', 'WOR', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares2, 'MKT'))
traded_1 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED SHORT.
SELL',num_shares, 'LEI. BUY', num_shares2, 'WOR')
Spread_dealt_at_1 <- Spread_1
num_shares_1_1 <- num_shares
num_shares_1_2 <- num_shares2
}
if(traded_1 && !closed_1 && !is.na(Spread_1) && Spread_1 >
(Spread_dealt_at_1 * 1.05) && Spread_1 > 0) {
placeOrder(twsCon, twsContract('', 'LEI', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares_1_1, 'MKT'))
placeOrder(twsCon, twsContract('', 'WOR', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares_1_2, 'MKT'))
closed_1 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE CLOSED A SHORT.
BUY',num_shares_1_1, 'LEI. SELL', num_shares_1_2, 'WOR')
}
if(!traded_1 && !closed_1 && !is.na(Spread_1) && Spread_1 <
3.4565 && Spread_1 > 0) {
placeOrder(twsCon, twsContract('', 'LEI', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares_1_1, 'MKT'))
placeOrder(twsCon, twsContract('', 'WOR', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares_1_2, 'MKT'))
traded_1 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING
SHORT. SELL', '', 'LEI. BUY', '', 'WOR')
}
if(!traded_2 && !is.na(Spread_2) && Spread_2 > 12.2030711689243
&& Spread_2 > 0) {
num_shares <- 1000 / Last_2_1
num_shares <- as(num_shares,'integer')
print(c('1000',Last_2_1, num_shares))
placeOrder(twsCon, twsContract('', 'QBE', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares, 'MKT'))
num_shares2 <- 1000 / Last_2_2
num_shares2 <- as(num_shares2,'integer')
print(c('1000',Last_2_2, num_shares2))
placeOrder(twsCon, twsContract('', 'AMP', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares2, 'MKT'))
traded_2 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED LONG. BUY', num_shares,
'QBE. SELL', num_shares2, 'AMP')
Spread_dealt_at_2 <- Spread_2
num_shares_2_1 <- num_shares
num_shares_2_2 <- num_shares2
}
if(traded_2 && !closed_2 && !is.na(Spread_2) && Spread_2 <
(Spread_dealt_at_2 / 1.05 ) && Spread_2 > 0) {
placeOrder(twsCon, twsContract('', 'QBE', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares_2_1, 'MKT'))
placeOrder(twsCon, twsContract('', 'AMP', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares_2_2, 'MKT'))
closed_2 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE CLOSED A LONG.
SELL',num_shares_2_1, 'QBE. BUY', num_shares_2_2, 'AMP')
}
if(!traded_2 && !closed_2 && !is.na(Spread_2) && Spread_2 >
12.7905 && Spread_2 > 0) {
placeOrder(twsCon, twsContract('', 'QBE', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares_2_1, 'MKT'))
placeOrder(twsCon, twsContract('', 'AMP', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares_2_2, 'MKT'))
traded_2 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING
LONG. BUY', '', 'QBE. SELL', '', 'AMP')
}
if(!traded_3 && !is.na(Spread_3) && Spread_3 > 11.1048338237328
&& Spread_3 > 0) {
num_shares <- 1000 / Last_3_1
num_shares <- as(num_shares,'integer')
print(c('1000',Last_3_1, num_shares))
placeOrder(twsCon, twsContract('', 'QBE', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares, 'MKT'))
num_shares2 <- 1000 / Last_3_2
num_shares2 <- as(num_shares2,'integer')
print(c('1000',Last_3_2, num_shares2))
placeOrder(twsCon, twsContract('', 'AXA', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares2, 'MKT'))
traded_3 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED LONG. BUY', num_shares,
'QBE. SELL', num_shares2, 'AXA')
Spread_dealt_at_3 <- Spread_3
num_shares_3_1 <- num_shares
num_shares_3_2 <- num_shares2
}
if(traded_3 && !closed_3 && !is.na(Spread_3) && Spread_3 <
(Spread_dealt_at_3 / 1.05 ) && Spread_3 > 0) {
placeOrder(twsCon, twsContract('', 'QBE', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares_3_1, 'MKT'))
placeOrder(twsCon, twsContract('', 'AXA', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares_3_2, 'MKT'))
closed_3 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE CLOSED A LONG.
SELL',num_shares_3_1, 'QBE. BUY', num_shares_3_2, 'AXA')
}
if(!traded_3 && !closed_3 && !is.na(Spread_3) && Spread_3 >
11.634 && Spread_3 > 0) {
placeOrder(twsCon, twsContract('', 'QBE', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', num_shares_3_1, 'MKT'))
placeOrder(twsCon, twsContract('', 'AXA', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', num_shares_3_2, 'MKT'))
traded_3 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING
LONG. BUY', '', 'QBE. SELL', '', 'AXA')
}
# then in relation to open positions closing rules for any
stops and crossings of the moving average
if(!traded_4 && !is.na(Spread_4) && Spread_4 > (15.55 * 1.05)
&& Spread_4 > 0) {
placeOrder(twsCon, twsContract('', 'JBH', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', 52, 'MKT'))
placeOrder(twsCon, twsContract('', 'MYR', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', 280, 'MKT'))
traded_4 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED CLOSING STOP LOSS
SHORT. SELL', '52', 'JBH. BUY', '280', 'MYR')
}
if(!traded_4 && !is.na(Spread_4) && Spread_4 < 15.034 &&
Spread_4 > 0) {
placeOrder(twsCon, twsContract('', 'JBH', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'BUY', 52, 'MKT'))
placeOrder(twsCon, twsContract('', 'MYR', 'CFD',
'SNFE', '', '', '', 'AUD', '','','',NULL,NULL,0), twsOrder(reqIds(twsCon),
'SELL', 280, 'MKT'))
traded_4 <- TRUE
print(c('I HAVE TRADED'))
ihavetraded <- c('I HAVE TRADED AT AVERAGE CLOSING
SHORT. SELL', '52', 'JBH. BUY', '280', 'MYR')
};
}
}
con = twsConnect(99)
reqMktData(con, list(twsEquity('LEI', 'ASX', 'AUD'),twsEquity('WOR', 'ASX',
'AUD'),twsEquity('QBE', 'ASX', 'AUD'),twsEquity('AMP', 'ASX',
'AUD'),twsEquity('QBE', 'ASX', 'AUD'),twsEquity('AXA', 'ASX',
'AUD'),twsEquity('JBH', 'ASX', 'AUD'),twsEquity('MYR', 'ASX', 'AUD')),
eventWrapper=eWrapper.data(8), CALLBACK=CO_INT_N_REV)
closeAllConnections()
# 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;
_______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should
go.