- Python v2.7+
- Pip
pip install upstox
| class Session: | |
| __init__(api_key) | |
| set_api_secret(api_secret) | |
| set_redirect_uri(redirect_uri) | |
| set_code(code) | |
| get_login_url(self) | |
| retrieve_access_token(self) | |
| class Upstox: | |
| _on_data(ws, message, data_type, continue_flag) | |
| _on_error (ws, error) | |
| _on_close (ws) | |
| __init__(api_key, access_token) | |
| get_socket_params() | |
| start_websocket(run_in_background=False) | |
| set_on_order_update(event_handler) | |
| set_on_quote_update(event_handler) | |
| set_on_trade_update(event_handler) | |
| set_on_disconnect(event_handler) | |
| set_on_error(event_handler) | |
| get_profile() | |
| get_balance() | |
| get_holdings() | |
| get_positions() | |
| get_trade_book() | |
| get_order_history(order_id=None) | |
| get_trades(order_id) | |
| logout() | |
| get_exchanges() | |
| get_instrument_by_symbol(exchange, symbol) | |
| search_instruments(exchange, symbol) | |
| get_instrument_by_token(exchange, token) | |
| get_master_contract(exchange) | |
| get_live_feed(instrument, live_feed_type) | |
| get_ohlc(instrument, interval, start_date, end_date, download_as_csv = False) | |
| subscribe(instrument, live_feed_type) | |
| unsubscribe(instrument, live_feed_type) | |
| place_order(transaction_type, instrument, quantity, order_type, | |
| product_type, price = None, trigger_price = None, | |
| disclosed_quantity = None, duration = None, stop_loss = None, | |
| square_off = None, trailing_ticks = None) | |
| modify_order(order_id, quantity = None, order_type = None, price = None, | |
| trigger_price = None, disclosed_quantity = None, duration = None) | |
| cancel_order(order_id) | |
| cancel_all_orders(self) | |
| api_call_helper(name, http_method, params, data) | |
| api_call(url, http_method, data) | |
| from upstox_api.api import Session | |
| upstoxSession = Session('api key here') | |
| upstoxSession.set_redirect_uri('redirwect url here') | |
| upstoxSession.set_api_secret('api secret here') | |
| print (upstoxSession.get_login_url()) | |
| upstoxSession.set_code('access code here') | |
| access_token = upstoxSession.retrieve_access_token() | |
| print ('Received access_token: %s' % access_token) |
| from upstox_api.api import Upstox, datetime, OHLCInterval, TransactionType, OrderType, ProductType, DurationType, \ | |
| LiveFeedType | |
| config = { | |
| 'apiKey': '', | |
| 'accessToken': '' | |
| } | |
| # Create the UpstoxAPI object bound to your API key | |
| upstoxAPI = Upstox(config['apiKey'], config['accessToken']) | |
| upstoxAPI.get_master_contract('MCX_FO') | |
| # Scrip details | |
| fut_exchange = "MCX_FO" | |
| fut_contract = "CRUDEOILM18JULFUT" | |
| SCRIP = upstoxAPI.get_instrument_by_symbol(fut_exchange, fut_contract) | |
| LTP_MINIMA = 0 | |
| LTP_MAXIMA = 0 | |
| LTP_SET_INTERVAL = 60 * 1000 | |
| FIRST_FEED_TIMESTAMP = None | |
| IS_MAX_MIN_SET = False | |
| def event_handler_quote_update(message): | |
| global FIRST_FEED_TIMESTAMP, LTP_MINIMA, LTP_MAXIMA, IS_MAX_MIN_SET, LTP_SET_INTERVAL | |
| if (FIRST_FEED_TIMESTAMP is None): | |
| FIRST_FEED_TIMESTAMP = float(message["timestamp"]) | |
| LTP_MINIMA = message["ltp"] | |
| LTP_MAXIMA = message["ltp"] | |
| print "Initial Attributes" | |
| print "Minimum LTP is: %f" % (LTP_MINIMA) | |
| print "Maximum LTP is: %f" % (LTP_MAXIMA) | |
| print "Detecting the maxima and minima during the next " + str(LTP_SET_INTERVAL/1000) + "s" | |
| detectionInterval = FIRST_FEED_TIMESTAMP + LTP_SET_INTERVAL | |
| if (int(message["timestamp"]) > detectionInterval and not IS_MAX_MIN_SET): | |
| IS_MAX_MIN_SET = True | |
| print "Final Attributes: After the detection interval" | |
| print "Minimum LTP is: %f" % (LTP_MINIMA) | |
| print "Maximum LTP is: %f" % (LTP_MAXIMA) | |
| elif int(message["timestamp"]) < detectionInterval: | |
| if message["ltp"] < LTP_MINIMA: | |
| LTP_MINIMA = message["ltp"] | |
| elif message["ltp"] > LTP_MAXIMA: | |
| LTP_MAXIMA = message["ltp"] | |
| else: | |
| print message["ltp"], LTP_MINIMA, LTP_MAXIMA | |
| if message["ltp"] < LTP_MINIMA: | |
| print "Buy Signal Generated" | |
| print "Current Ltp: " + str(message["ltp"]) | |
| print "Ltp Minima: " + str(LTP_MINIMA) | |
| placeOrder(TransactionType.Buy) | |
| elif message["ltp"] > LTP_MAXIMA: | |
| print "Sell Signal Generated" | |
| print "Current Ltp: " + str(message["ltp"]) | |
| print "Ltp Maxima: " + str(LTP_MAXIMA) | |
| placeOrder(TransactionType.Sell) | |
| def event_handler_order_update(message): | |
| print "Order Update:" + str(datetime.now()) | |
| print message | |
| def event_handler_trade_update(message): | |
| print "Trade Update:" + str(datetime.now()) | |
| print message | |
| def event_handler_error(err): | |
| print "ERROR" + str(datetime.now()) | |
| print err | |
| def event_handler_socket_disconnect(): | |
| print "SOCKET DISCONNECTED" + str(datetime.now()) | |
| def placeOrder(side): | |
| upstoxAPI.place_order( | |
| side, # transaction_type | |
| SCRIP, # instrument | |
| 1, # quantity | |
| OrderType.Market, # order_type | |
| ProductType.Intraday, # product_type | |
| 0.0, # price | |
| None, # trigger_price | |
| 0, # disclosed_quantity | |
| DurationType.DAY, # duration | |
| None, # stop_loss | |
| None, # square_off | |
| None # trailing_ticks | |
| ) | |
| def socket_connect(): | |
| print "Adding Socket Listeners" | |
| upstoxAPI.set_on_quote_update(event_handler_quote_update) | |
| # upstoxAPI.set_on_order_update(event_handler_order_update) | |
| # upstoxAPI.set_on_trade_update(event_handler_trade_update) | |
| upstoxAPI.set_on_error(event_handler_error) | |
| upstoxAPI.set_on_disconnect(event_handler_socket_disconnect) | |
| print "Suscribing to: " + SCRIP[4] | |
| print SCRIP | |
| upstoxAPI.unsubscribe(SCRIP, LiveFeedType.LTP) | |
| upstoxAPI.subscribe(SCRIP, LiveFeedType.LTP) | |
| print "Connecting to Socket" | |
| upstoxAPI.start_websocket(False) | |
| socket_connect() |
| from upstox_api.api import Upstox, datetime, OHLCInterval, TransactionType, OrderType, ProductType, DurationType | |
| config = { | |
| 'startDate_yesterday': '02/07/2018', | |
| 'endDate_yesterday': '02/07/2018', | |
| 'startDate_today': '03/07/2018', | |
| 'endDate_today': '03/07/2018', | |
| 'apiKey': '', | |
| 'accessToken': '' | |
| } | |
| # Create the UpstoxAPI object bound to your API key | |
| upstoxAPI = Upstox(config['apiKey'], config['accessToken']) | |
| # get master contract for NSE EQ | |
| upstoxAPI.get_master_contract('NSE_EQ') | |
| # create an array of Nifty50 scrips | |
| nifty50 = ( | |
| "ACC", | |
| "ADANIPORTS", "AMBUJACEM", "ASIANPAINT", | |
| "AUROPHARMA", "AXISBANK", "BAJAJ-AUTO", "BANKBARODA", | |
| "BPCL", "BHARTIARTL", "INFRATEL", "BOSCHLTD", | |
| "CIPLA", "COALINDIA", "DRREDDY", "EICHERMOT", | |
| "GAIL", "HCLTECH", "HDFCBANK", "HEROMOTOCO", | |
| "HINDALCO", "HINDUNILVR", "HDFC", "ITC", "ICICIBANK", | |
| "IBULHSGFIN", "IOC", "INDUSINDBK", "INFY", "KOTAKBANK", | |
| "LT", "LUPIN", "M&M", "MARUTI", "NTPC", "ONGC", | |
| "POWERGRID", "RELIANCE", "SBIN", "SUNPHARMA", | |
| "TCS", "TATAMTRDVR", "TATAMOTORS", "TATAPOWER", | |
| "TATASTEEL", "TECHM", "ULTRACEMCO", "VEDL", | |
| "WIPRO", "YESBANK", "ZEEL" | |
| ) | |
| OHLCData_yesterday = {} | |
| OHLCData_today = {} | |
| scripsMaster = {} | |
| def fetchOHLC (_scrip, _startDate, _endDate, _interval): | |
| start_time = datetime.strptime(_startDate, '%d/%m/%Y').date() | |
| end_time = datetime.strptime(_endDate, '%d/%m/%Y').date() | |
| return upstoxAPI.get_ohlc(_scrip, _interval, start_time, end_time) | |
| def placeOrder(symbol, side): | |
| scrip = scripsMaster[symbol] | |
| upstoxAPI.place_order( | |
| side, # transaction_type | |
| scrip, # instrument | |
| 1, # quantity | |
| OrderType.Market, # order_type | |
| ProductType.Intraday, # product_type | |
| 0.0, # price | |
| None, # trigger_price | |
| 0, # disclosed_quantity | |
| DurationType.DAY, # duration | |
| None, # stop_loss | |
| None, # square_off | |
| None # trailing_ticks | |
| ) | |
| for symbol in nifty50: | |
| scrip = upstoxAPI.get_instrument_by_symbol('NSE_EQ', symbol) | |
| scripsMaster[symbol] = scrip | |
| print "Fetching OHLC for: " + scrip[4] | |
| _yesterday = fetchOHLC( | |
| scrip, | |
| config['startDate_yesterday'], | |
| config['endDate_yesterday'], | |
| '1DAY' | |
| ) | |
| OHLCData_yesterday[symbol] = _yesterday[0]['close'] | |
| _today = fetchOHLC( | |
| scrip, | |
| config['startDate_today'], | |
| config['endDate_today'], | |
| '30MINUTE' | |
| ) | |
| OHLCData_today[symbol] = _today[0]['close'] | |
| # print OHLCData_today | |
| # print OHLCData_yesterday | |
| # Check for a gap-up/gap-down of 1% | |
| for symbol in OHLCData_yesterday.keys(): | |
| _today = OHLCData_today[symbol] | |
| _yesterday = OHLCData_yesterday[symbol] | |
| _gapPercent = (_today - _yesterday) * 100 /_yesterday | |
| if (_gapPercent > 1): | |
| print ("Sell signal: ", symbol, _gapPercent) | |
| placeOrder(symbol, TransactionType.Sell) | |
| elif (_gapPercent < -1): | |
| print ("Buy signal: ", symbol, _gapPercent) | |
| placeOrder(symbol, TransactionType.Buy) |
| OHLCInterval. | |
| Minute_1 = '1MINUTE' | |
| Minute_5 = '5MINUTE' | |
| Minute_10 = '10MINUTE' | |
| Minute_30 = '30MINUTE' | |
| Minute_60 = '60MINUTE' | |
| Day_1 = '1DAY' | |
| Week_1 = '1WEEK' | |
| Month_1 = '1MONTH' | |
| TransactionType. | |
| Buy = 'B' | |
| Sell = 'S' | |
| OrderType. | |
| Market = 'M' | |
| Limit = 'L' | |
| StopLossLimit = 'SL' | |
| StopLossMarket = 'SL-M' | |
| ProductType. | |
| Intraday = 'I' | |
| Delivery = 'D' | |
| CoverOrder = 'CO' | |
| OneCancelsOther = 'OCO' | |
| DurationType. | |
| DAY = 'DAY' | |
| IOC = 'IOC' | |
| LiveFeedType. | |
| LTP = 'LTP' | |
| Full = 'Full' |