Skip to content

Instantly share code, notes, and snippets.

@svishi
Created June 30, 2017 10:30
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save svishi/ba0ee4e08f1e2364addfe76c5b2ef7d7 to your computer and use it in GitHub Desktop.
Save svishi/ba0ee4e08f1e2364addfe76c5b2ef7d7 to your computer and use it in GitHub Desktop.
Python SDK - Sample Code - Interactive API
from upstox_api.api import *
from datetime import datetime
from pprint import pprint
import os, sys
from tempfile import gettempdir
try: input = raw_input
except NameError: pass
u = None
s = None
break_symbol = '@'
profile = None
def main():
global s, u
logged_in = False
print('Welcome to Upstox API!\n')
print('This is an interactive Python connector to help you understand how to get connected quickly')
print('The source code for this connector is publicly available')
print('To get started, please create an app on the Developer Console (developer.upstox.com)')
print('Once you have created an app, keep your app credentials handy\n')
stored_api_key = read_key_from_settings('api_key')
stored_access_token = read_key_from_settings('access_token')
if stored_access_token is not None and stored_api_key is not None:
print('You already have a stored access token: [%s] paired with API key [%s]' % (stored_access_token, stored_api_key))
print('Do you want to use the above credentials?')
selection = input('Type N for no, any key for yes: ')
if selection.lower() != 'n':
try:
u = Upstox(stored_api_key, stored_access_token)
logged_in = True
except requests.HTTPError as e:
print('Sorry, there was an error [%s]. Let''s start over\n\n' % e)
if logged_in is False:
stored_api_key = read_key_from_settings('api_key')
if stored_api_key is not None:
api_key = input('What is your app''s API key [%s]: ' % stored_api_key)
if api_key == '':
api_key = stored_api_key
else:
api_key = input('What is your app''s API key: ')
write_key_to_settings('api_key', api_key)
stored_api_secret = read_key_from_settings('api_secret')
if stored_api_secret is not None:
api_secret = input('What is your app''s API secret [%s]: ' % stored_api_secret)
if api_secret == '':
api_secret = stored_api_secret
else:
api_secret = input('What is your app''s API secret: ')
write_key_to_settings('api_secret', api_secret)
stored_redirect_uri = read_key_from_settings('redirect_uri')
if stored_redirect_uri is not None:
redirect_uri = input('What is your app''s redirect_uri [%s]: ' % stored_redirect_uri)
if redirect_uri == '':
redirect_uri = stored_redirect_uri
else:
redirect_uri = input('What is your app''s redirect_uri: ')
write_key_to_settings('redirect_uri', redirect_uri)
s = Session(api_key)
s.set_redirect_uri(redirect_uri)
s.set_api_secret(api_secret)
print('\n')
print('Great! Now paste the following URL on your browser and type the code that you get in return')
print('URL: %s\n' % s.get_login_url())
input('Press the enter key to continue\n')
code = input('What is the code you got from the browser: ')
s.set_code(code)
try:
access_token = s.retrieve_access_token()
except SystemError as se:
print('Uh oh, there seems to be something wrong. Error: [%s]' % se)
return
write_key_to_settings('access_token', access_token)
u = Upstox(api_key, access_token)
clear_screen()
show_home_screen()
def show_home_screen():
global s, u
global profile
print('\n*** Welcome to Upstox API ***\n\n')
print('1. Get Profile\n')
print('2. Get Balance\n')
print('3. Get Positions\n')
print('4. Get Holdings\n')
print('5. Get Order History\n')
print('6. Get LTP Quote\n')
print('7. Get Full Quote\n')
print('8. Show socket example\n')
print('9. Quit\n')
selection = input('Select your option: \n')
try:
int(selection)
except:
clear_screen()
show_home_screen()
selection = int(selection)
clear_screen()
if selection == 1:
load_profile()
pprint(profile)
elif selection == 2:
pprint(u.get_balance())
elif selection == 3:
pprint(u.get_positions())
elif selection == 4:
pprint(u.get_holdings())
elif selection == 5:
pprint(u.get_order_history())
elif selection == 6:
product = select_product()
if product is not None:
pprint(u.get_live_feed(product, LiveFeedType.LTP))
elif selection == 7:
product = select_product()
if product is not None:
pprint(u.get_live_feed(product, LiveFeedType.Full))
elif selection == 8:
socket_example()
elif selection == 9:
sys.exit(0)
show_home_screen();
def load_profile():
global profile
# load user profile to variable
profile = u.get_profile()
def select_product():
global u
exchange = select_exchange()
product = None
clear_screen()
while exchange is not None:
u.get_master_contract(exchange)
product = find_product(exchange)
clear_screen()
if product is not None:
break
exchange = select_exchange()
return product
def find_product(exchange):
found_product = False
result = None
while not found_product:
query = input('Type the symbol that you are looking for. Type %s to go back: ' % break_symbol)
if query.lower() == break_symbol:
found_product = True
result = None
break
results = u.search_instruments(exchange, query)
if len(results) == 0:
print('No results found for [%s] in [%s] \n\n' % (query, exchange))
break
else:
for index, result in enumerate(results):
if index > 9:
break
print ('%d. %s' % (index, result.symbol))
selection = input('Please make your selection. Type %s to go back: ' % break_symbol)
if query.lower() == break_symbol:
found_product = False
result = None
break
try:
selection = int(selection)
except ValueError:
found_product = False
result = None
break
if 0 <= selection <= 9 and len(results) >= selection + 1:
found_product = True
result = results[selection]
break
found_product = False
return result
def select_exchange():
global profile
if profile is None:
load_profile()
back_to_home_screen = False
valid_exchange_selected = False
while not valid_exchange_selected:
print('** Live quote streaming example **\n')
for index, item in enumerate(profile[u'exchanges_enabled']):
print ('%d. %s' % (index + 1, item))
print ('9. Back')
print('\n')
selection = input('Select exchange: ')
try:
selection = int(selection)
except ValueError:
break
if selection == 9:
valid_exchange_selected = True
back_to_home_screen = True
break
selected_index = selection - 1
if 0 <= selected_index < len(profile[u'exchanges_enabled']):
valid_exchange_selected = True
break
if back_to_home_screen:
return None
return profile[u'exchanges_enabled'][selected_index]
def socket_example():
print('Press Ctrl+C to return to the main screen\n')
u.set_on_quote_update(event_handler_quote_update)
u.get_master_contract('NSE_EQ')
try:
u.subscribe(u.get_instrument_by_symbol('NSE_EQ', 'TATASTEEL'), LiveFeedType.Full)
except:
pass
try:
u.subscribe(u.get_instrument_by_symbol('NSE_EQ', 'RELIANCE'), LiveFeedType.LTP)
except:
pass
u.start_websocket(False)
def event_handler_quote_update(message):
pprint("Quote Update: %s" % str(message))
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def write_key_to_settings(key, value):
filename = os.path.join(gettempdir(), 'interactive_api.json')
try:
file = open(filename, 'r')
except IOError:
data = {"api_key" : "", "api_secret" : "", "redirect_uri" : "", "access_token" : ""}
with open(filename, 'w') as output_file:
json.dump(data, output_file)
file = open(filename, 'r')
try:
data = json.load(file)
except:
data = {}
data[key] = value
with open(filename, 'w') as output_file:
json.dump(data, output_file)
def read_key_from_settings(key):
filename = os.path.join(gettempdir(), 'interactive_api.json')
try:
file = open(filename, 'r')
except IOError:
file = open(filename, 'w')
file = open(filename, 'r')
try:
data = json.load(file)
return data[key]
except:
pass
return None
if __name__ == "__main__":
main()
@RaMb00
Copy link

RaMb00 commented Oct 31, 2017

I am new to API and Python stuff. I copied ur command to my IDE. Where do I need to paste Key and secret code in ur command lines.

@balajigopalakrishnan
Copy link

replace your key & token in the below lines of code.
stored_api_key = read_key_from_settings('api_key')
stored_access_token = read_key_from_settings('access_token')

@ravisreepadhi
Copy link

from upstox_api.api import *
ModuleNotFoundError: No module named 'upstox_api'

@manishgupta-ind
Copy link

Hi I am new to Python or algo trading. I learnt that python is the best language to code strategy for automatic trading. Can any senior person suggest me any simple book/ pdf/ youtube video/ website to learn python for writing trading strategy for beginners.

@pun2et
Copy link

pun2et commented Mar 3, 2019

@svishi

this is awesome implementation.
Cheers ..............

@pun2et
Copy link

pun2et commented Mar 3, 2019

@svishi

is there anything like this for Zerodha?
very much required. Upstox production API facing hell lot of issue..

@tandonkunal
Copy link

@pun2et
Bro you saying upstox better than zerodha ?
I am about to start with algos give your honest feedback for both if you can! thanks !

@ramkumarrammohan
Copy link

@svishi In the above example, 'socket_example' is not working as expected. After I gave all credentials and entered input as '8'.
It seems after input it's getting into the event loop and stuck there itself. Noting is coming in console even i have tried in market hours. What could be the possibilities?

@amitag123
Copy link

@svishi In the above example, 'socket_example' is not working as expected. After I gave all credentials and entered input as '8'.
It seems after input it's getting into the event loop and stuck there itself. Noting is coming in console even i have tried in market hours. What could be the possibilities?

Have you install websocket. You need to type the following codes
C:\Python>pip install websocket-client==0.40.0

@manishgupta-ind
Copy link

When I run this code in Pycharm I get following error:
Traceback (most recent call last):
File "C:/Users/manis/PycharmProjects/ManishExcelling/venv/ExcellingTrade2/01MyFirstAlgo.py", line 310, in
main()
File "C:/Users/manis/PycharmProjects/ManishExcelling/venv/ExcellingTrade2/01MyFirstAlgo.py", line 40, in main
u = Upstox(stored_api_key, stored_access_token)
File "C:\Users\manis\PycharmProjects\ManishExcelling\venv\lib\site-packages\upstox_api\api.py", line 290, in init
profile = self.api_call_helper('profile', PyCurlVerbs.GET, None, None)
File "C:\Users\manis\PycharmProjects\ManishExcelling\venv\lib\site-packages\upstox_api\api.py", line 853, in api_call_helper
response = self.api_call(url, http_method, data)
File "C:\Users\manis\PycharmProjects\ManishExcelling\venv\lib\site-packages\upstox_api\api.py", line 871, in api_call
"authorization": "Bearer " + self.access_token}
TypeError: must be str, not dict

@manishgupta-ind
Copy link

When I run this line "u = Upstox ('your_api_key', access_token)", I get following errors:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 290, in init
profile = self.api_call_helper('profile', PyCurlVerbs.GET, None, None)
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 853, in api_call_helper
response = self.api_call(url, http_method, data)
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 871, in api_call
"authorization": "Bearer " + self.access_token}
TypeError: must be str, not dict

Can someone help me please.

@Dineshel
Copy link

When I run this code in Pycharm I get following error:
Traceback (most recent call last):
File "C:/Users/manis/PycharmProjects/ManishExcelling/venv/ExcellingTrade2/01MyFirstAlgo.py", line 310, in
main()
File "C:/Users/manis/PycharmProjects/ManishExcelling/venv/ExcellingTrade2/01MyFirstAlgo.py", line 40, in main
u = Upstox(stored_api_key, stored_access_token)
File "C:\Users\manis\PycharmProjects\ManishExcelling\venv\lib\site-packages\upstox_api\api.py", line 290, in init
profile = self.api_call_helper('profile', PyCurlVerbs.GET, None, None)
File "C:\Users\manis\PycharmProjects\ManishExcelling\venv\lib\site-packages\upstox_api\api.py", line 853, in api_call_helper
response = self.api_call(url, http_method, data)
File "C:\Users\manis\PycharmProjects\ManishExcelling\venv\lib\site-packages\upstox_api\api.py", line 871, in api_call
"authorization": "Bearer " + self.access_token}
TypeError: must be str, not dict

@Dineshel
Copy link

same problem kindly help me to solve this error

@Dineshel
Copy link

When I run this line "u = Upstox ('your_api_key', access_token)", I get following errors:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 290, in init
profile = self.api_call_helper('profile', PyCurlVerbs.GET, None, None)
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 853, in api_call_helper
response = self.api_call(url, http_method, data)
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 871, in api_call
"authorization": "Bearer " + self.access_token}
TypeError: must be str, not dict

Can someone help me please.

sir/madam, if you got the solution pls post it

@manishgupta-ind
Copy link

When I run this line "u = Upstox ('your_api_key', access_token)", I get following errors:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 290, in init
profile = self.api_call_helper('profile', PyCurlVerbs.GET, None, None)
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 853, in api_call_helper
response = self.api_call(url, http_method, data)
File "C:\Users\manis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\upstox_api\api.py", line 871, in api_call
"authorization": "Bearer " + self.access_token}
TypeError: must be str, not dict
Can someone help me please.

sir/madam, if you got the solution pls post it

Just insert this code prior to mentioned line and it should solve the problem:
access_token = access_token['access_token']

@Dineshel
Copy link

Dineshel commented Jun 20, 2020 via email

@Dineshel
Copy link

Hi I am new to Python or algo trading. I learnt that python is the best language to code strategy for automatic trading. Can any senior person suggest me any simple book/ pdf/ youtube video/ website to learn python for writing trading strategy for beginners.

now i am begginer , you are senior. are you completed your automation??, and pls suggest me to how to do that??

pls suggest youtube /books etc...

@manishgupta-ind
Copy link

Hi I am new to Python or algo trading. I learnt that python is the best language to code strategy for automatic trading. Can any senior person suggest me any simple book/ pdf/ youtube video/ website to learn python for writing trading strategy for beginners.

now i am begginer , you are senior. are you completed your automation??, and pls suggest me to how to do that??

pls suggest youtube /books etc...

I am still learning. Lol!!! I completed college 16 years ago and I do not have IT background so learning a programming language is so boring now. I am learning it from various youtube channels as well as following 2 websites: https://www.tutorialspoint.com/python/index.htm, https://www.guru99.com/python-tutorials.html. I also use google sometimes to find new resources for python if required.

@recklessgod
Copy link

Hi, not getting API key. I am chatting with Upstox agent and get a reply is that it is temporarily discontinued. Please let me know

@megha457
Copy link

megha457 commented Jul 6, 2021

Hi,
I ran this code and gave API key, secret, and redirect URL as inputs.
this was the next step:
Great! Now paste the following URL on your browser and type the code that you get in return
URL: https://api.upstox.com/index/dialog/authorize?apiKey=VsuqNVm0dCaKk8JIUgUZ29S9nNeVqYYQ4r7TOs0o&redirect_uri=https%3A%2F%2Fup.algomojo.com%2Fxl-connect%2Fam%2Flogin-response%3Fid%3DJQ1760&response_type=code

When I click on the URL, it takes me to my upstox account's dashboard, there is no code given

What should I do?
Can someone please help

@srujanmhase
Copy link

For creating a session object what should the redirect uri be? I just want to access the data in a python script not manage any users in an OAuth environment?

@bikashdaga
Copy link

Hi, I am Beginner in Python and learning my Pythons basics from the Scaler Topics - https://www.scaler.com/topics/python/. Their tutorials helped me a lot and they are easy to understand. Sometimes I also used different Resources available on the web too.

@yung78956
Copy link

Hey I am Still Learning as I am beginner to Python Programming Language. To Learn Online I follow Various Articles and You tube Videos. Majorly i am Liking this website content as it's in very easy To Understand https://wiingy.com/learn/python/python-tutorial/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment