Posted by Just Another Lousy Programmer on February 20, 2012 (01:08AM)
Hey Jeffry -
I don't blame you for being confused, it took quite a while for me to figure out how to retrieve TK information with Python. I have done this, but I have to warn you, this code is UGLY. It does the job, but I have made no attempt to clean it up at all. Eventually I plan to make it pythonic, but the code that I'm posting here is just what I hacked together to get the basics working. That said, this should work for you:
import sys
import string
from restkit import OAuthFilter, request # http reading
import oauth2 # oauth2 framework
import simplejson as json # json reader
import dateutil.parser as dateparse # date processing
from operator import itemgetter # list processing
import csv # csv file processing
############################# tkquery.py #############################
# Routines for retrieving stock quotes from TradeKing
# urls for various queries
# balances': 'https://api.tradeking.com/v1/accounts/38547111/balances.json'
# history': 'https://api.tradeking.com/v1/accounts/38547111/history.json'
# holdings': 'https://api.tradeking.com/v1/accounts/38547111/holdings.json'
# orders': 'https://api.tradeking.com/v1/accounts/38547111/orders.json'
# chain': 'https://api.tradeking.com/v1/market/chain.json'
# stockquote': 'https://api.tradeking.com/v1/market/quotes.json'
# optionquote': 'https://api.tradeking.com/v1/market/quotes.json'
# watchlists': 'https://api.tradeking.com/v1/accounts/38547111/watchlist.json'
#
# urls that will be needed if we want to authenticate other people
# request access : 'http://developers.tradeking.com/oauth/request_token'
# access token : 'http://developers.tradeking.com/oauth/access_token'
# authorization : 'http://developers.tradeking.com/oauth/authorize'
# details of some of the JSON fields
# factor
# contract size for an option
# sectype
# CS = common stock
# BOND = bonds
# OPT = options
# accounttype gives long or short
# 3 or 5 = short
# 1 = long
# 2 = long margin
# purchase price
# for holdings, its average price per share
#
# this whole thing needs to be abstracted to a class
def tk_query(queryurl, returntype='json'):
# key and secret granted by service provider for this consumer application
CONSUMER_KEY = 'CONSUMERKEY'
CONSUMER_SECRET = 'CONSUMERSECRET'
OAUTH_TOKEN_KEY = 'OAUTHTOKENKEY'
OAUTH_TOKEN_SECRET = 'OAUTHTOKENSECRET'
MEMBER_NUMBER = MEMBERNUMBER
# set up an OAuth Consumer
myconsumer = oauth2.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
# manually update the access token/secret.
mytoken = oauth2.Token(key=OAUTH_TOKEN_KEY, secret=OAUTH_TOKEN_SECRET)
# make an oauth request
auth = OAuthFilter('*', consumer=myconsumer, token=mytoken,
method = oauth2.SignatureMethod_HMAC_SHA1())
# get the response and return it
queryresp = request(queryurl, 'GET', filters=[auth])
if returntype == 'json':
queryresult = json.loads(queryresp.body_string())
else:
queryresult = queryresp.body_string()
return queryresult
# LIST OF STOCKS
# modified so that stocks are ALWAYS returned in a list!
# located in query['response']['quotes']['instrumentquote']
def query_quote(s='F', returntype='json'):
query = tk_query(
''.join(['https://api.tradeking.com/v1/market/quotes.json',
'?symbols=', s, '&delayed=true']), returntype)
if query_error(query) is None:
query = reformat_quote_query(query)
return query
else:
return IOError
# LIST OF OPTIONS
def query_chain(s='F', qexpiration='ALL', qrange='ALL_THE_MONEY',
returntype='json'):
return tk_query(''.join(['https://api.tradeking.com/v1/market/chains.json',
'?underlying=', s, '&type=PUT&expiration=',
qexpiration, '&range=', qrange]),
returntype)
# SINGLE OPTION
def query_oquote(qunderlying='F',qexpiration='2011-06-24',
qtype='CALL',qstrike='280.0'):
return tk_query(''.join(['https://api.tradeking.com/v1/market/quotes.json',
'?underlying=',qunderlying,'&expiration=',qexpiration,'&type=',qtype,
'&strike=',qstrike,'&delayed=true']))
# WATCHLIST
def query_watchlist():
return tk_query('https://api.tradeking.com/v1/watchlists.json')
# CURRENT BALANCES
def query_balance(returntype='json'):
return tk_query('https://api.tradeking.com/v1/accounts/38547111/balances.json',
returntype)
# TRADING HISTORY
def query_history(qrange='all', qtransactions='trade', returntype='json'):
return tk_query(''.join(['https://api.tradeking.com/v1/accounts/38547111/history.json?range=',
qrange,'&transactions=',
qtransactions]),returntype)
# CURRENT HOLDINGS
def query_holdings(returntype='json'):
return tk_query('https://api.tradeking.com/v1/accounts/38547111/holdings.json',
returntype)
# OPEN ORDERS
def query_orders(returntype='json'):
return tk_query('https://api.tradeking.com/v1/accounts/38547111/orders.json',
returntype)
# if there is an error in the tkread, we'll get a return dictionary
# containing: query{'response':{'type':'Error'}}
def query_error(query):
if 'type' in query['response']:
return IOError
else:
pass