| setGooglePortfolioHoldings(username,password,portfolioId,tickerId,action,shares,price,comission)
|
function success = setGooglePortfolioHoldings(username,password,portfolioId,tickerId,action,shares,price,comission)
% setGooglePortfolioHoldings trades virtual stock holdings
% in the given Google Finance Portfolio.
% See accompanying example (googlePortfolioHoldingsExample.m) on how it can
% be used.
if nargin < 8
display('requires 7 parameters! setPortfolioHoldings.m');
return;
end
%import java stuff.
import java.io.*;
import java.net.*;
import java.lang.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
%get token from google.
[authorized, aToken]=connectAndAuthorize(username, password, 'finance');
if (~authorized)
result=-1;
return;
end
%get current date.
now = Date();
now.setTime(now.getTime());
df = SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
time=df.format(now);
time=time.replace(' ', 'T');
%create entry for transaction.
event=['<entry xmlns=''http://www.w3.org/2005/Atom'' ' ...
'xmlns:gf=''http://schemas.google.com/finance/2007'' '...
'xmlns:gd=''http://schemas.google.com/g/2005''>'...
'<gf:transactionData date=''',char(time),'.000', ...
''' shares=''', num2str(shares), ''' type=''', action, '''> <gf:commission> '...
'<gd:money amount=''',num2str(comission),''' currencyCode=''USD''/> '...
'</gf:commission> <gf:price>'...
'<gd:money amount=''', num2str(price), ''' currencyCode=''USD''/> '...
'</gf:price> </gf:transactionData> </entry>'];
%try to post entry to portfolio on Google Finance.
MAXITER=3;
success=false;
try
% try to create new event
safeguard=0;
while (~success && safeguard<MAXITER)
safeguard=safeguard+1;
%get the portfolio info
geturlString = ['http://finance.google.com/finance/feeds/default/portfolios/',num2str(portfolioId),'/positions/',tickerId,'/transactions/'];
url = URL( geturlString );
con = url.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestMethod( 'POST' );
con.setDoOutput( true );
con.setDoInput( true );
con.setRequestProperty('content-type','application/atom+xml;charset=UTF-8');
% stuff the Authorization request header
con.setRequestProperty('Authorization',String('GoogleLogin ').concat(aToken));
ps = PrintStream(con.getOutputStream());
ps.print(event);
ps.close();
is = con.getInputStream();
if (con.getResponseCode()~=201)
display(sprintf('transaction failed, http code: %d',con.getResponseCode()));
con.disconnect();
success = false;
return;
else
%display(sprintf('transaction complete, http code: %d',con.getResponseCode()));
success=true;
%continue;
end
end
catch ME
disp(ME.message);
disp(['from line: ' num2str(ME.stack.line)]);
success = false;
return;
end
|
|