Package: utradeconnect
uTrade ConnectPython SDKuTrade Connectencompasses a suite ofREST-like APIsdesigned to expose a broad
spectrum of functionalities crucial for the development of a comprehensiveinvestment  and trading platform. These capabilities include thereal-time execution of orders,efficient management of user portfolios,streaming of live market data via WebSockets,
and other features—all seamlessly accessible through a concise andwell-structured  HTTP API collection.uTrade(c) 2023. All rights reserved. Licensed under the MIT License.InstallationThere are two methods to installuTrade Connect:Using pip:uTrade Connectis available on PyPI and can be installed using pip. Ensure you have Python 3.8 or above and internet access. Run the following command in your terminal:pipinstallutradeconnectUsing the provided shell script:Alternatively, you can use therunPackage.shshell script provided in the project's root directory. This script creates a Python wheel for the project and installs it. To use this method, navigate to the project's root directory in your terminal and run the following command:shrunPackage.shAfter installation, check theconfig.inifile in the project's root directory and ensure you add theroot url, keepsourceasWEBAPI, anddisable_sslastrue.UsageThere are two methods to configure base parameters foruTrade Connect:Using config.ini:configure an .ini file named asconfig.iniin your application's working directory, the sample content is as below:[user]source=WEBAPI[SSL]disable_ssl=True[root_url]root="Provided Url"broadcastMode=FullPassing root url, disable_ssl while creatinguTrade ConnectObjectconnect_object=UtradeConnect(apiKey=<your_api_key>,secretKey=<your_secret_key>,source=<source>,root=<provided_url>,debug=<debug_mode_boolean>,disable_ssl=<boolean>)Create uTrade Connect ObjectAPI Credentials and ConfigAPI_KEY = "YOUR_API_KEY_HERE"
  API_SECRET = "YOUR_API_SECRET_HERE"
  source = "WEBAPI"
  BASE_URL = "Provided Url"To securely manage your API credentials, it is recommended to use a.envfile in your projectuTradeConnectInstantiate aUtradeConnectobject by specifying your APIappKey,secretKey,source,root[optional] as parameters when employing market APIs.Conversely, ifinteractive APIsare preferred, furnish the requisite credentials for interactive functionality.utradeConnect=UtradeConnect(api_key=API_KEY,secretKey=API_SECRET,source=source,root=BASE_URL)API UsageLogin ( API authentication )To initiate API authentication, invoke the login service, which will provide a token for continued access to various services throughout the session.Marketdata Loginresponse=utradeConnect.marketdata_login()Interactive LoginThe acquisition of anaccess tokenismandatory for client interactive login.For Client Interactive loginresponse=utradeConnect.interactive_login(accessToken)Subscribe SymbolTo commence a subscription to a specific symbol, employ the marketdata API.
This API facilitates the retrieval of a Subscribe Response object, which
encapsulates relevant tick data, including metrics such as Last Traded Price (LTP),
Open, High, and other pertinent information, depending on the subscribed event typeCandleData event:1505Index event:1512MarketDepth event:1502Market event:1507OpenInterest event:1510TouchLine event:1501instruments=[{"exchangeSegment":1,"exchangeInstrumentID":22},{"exchangeSegment":1,"exchangeInstrumentID":2885},]response=utradeConnect.send_subscription(instruments=instruments,eventCode=1501)QuotesThe Quote service furnishes details pertaining to Asks, Bids and other pertinent informationinstruments=[{"exchangeSegment":1,"exchangeInstrumentID":22},{"exchangeSegment":1,"exchangeInstrumentID":2885},]response=utradeConnect.get_quote(instruments=instruments,eventCode=1501,publishFormat="JSON")Place Order RequestTo execute an order, leverage theInteractive API. The resulting response will include anAppOrderId.response=utradeConnect.place_order(exchangeSegment="NSECM",exchangeInstrumentID=2885,productType="MIS",orderType="LIMIT",orderSide="BUY",timeInForce="DAY",disclosedQuantity=0,orderQuantity=10,limitPrice=300,stopPrice=0,orderUniqueIdentifier="123abc",clientID="C1",)Cancel Order RequestTo cancel an order, leverage theInteractive API. The resulting response will include anAppOrderId.response=utradeConnect.place_order(appOrderID=OrderIDclientID="C1",)Refer to thePython client postman documentationfor the complete list of supported methods.WebSocket usageMarket WebSocketTransmission of events, includingTouchLine,MarketData,CandleData,OpenInterest,
andIndex, occurs through the socket. To capture these events, implementation of
theUtradeAPIMarketdataEventsinterface is required. The relevant events will
be received through the methods that are specifically overridden within this
interface.Connecting toMarketdata socket# Authenticate to obtain an authorization token if you are not currently logged in.
    response = utradeConnect.marketdata_login()
    # Store the token and userid
    set_marketDataToken = response['result']['token']
    set_muserID = response['result']['userID']
    socketInstance = MDSocket_io(set_marketDataToken, set_muserID, base_url, broadcast_mode )Callback forConnectiondef on_connect():
        print('Market Data Socket connected successfully!')

        # Subscribe to instruments
        response = utradeConnect.send_subscription(Instruments, 1501)
        print("Subscription response: ", response)Callback forDisconnectiondef on_disconnect(data):
     print('Market Data Socket disconnected!')Callback foroverridden methods# Callback on receiving message
def on_message(data):
   print('I received a message!')

# Callback for Touchline message with code 1501 FULL
def on_message1501_json_full(data):
    print('I received a 1501 Touchline message!' , data)

# Callback for Market depth message with code 1502 FULL
def on_message1502_json_full(data):
    print('I received a 1502 Market depth message!' , data)

# Callback for Candle data message with code 1505 FULL
def on_message1505_json_full(data):
    print('I received a 1505 Candle data message!' , data)

# Callback for MarketStatus data message with code 1507 FULL
def on_message1507_json_full(data):
    print('I received a 1507 MarketStatus data message!' , data)

# Callback for Open interest message with code 1510 FULL
def on_message1510_json_full(data):
    print('I received a 1510 Open interest message!' , data)

# Callback for LTP message with code 1512 FULL
def on_message1512_json_full(data):
    print('I received a 1512 Level1,LTP message!' , data)

# Callback for Instrument Property Change message with code 1105 FULL 
def on_message1105_json_full(data):
    print('I received a 1105, Instrument Property Change Event message!' , data)Order WebSocketTransmission of events, includingOrder,Trade Conversion,Position,
andTrade, occurs through the socket. To capture these events, implementation of
theUtradeAPIOrderdataEventsinterface is required. The relevant events will
be received through the methods that are specifically overridden within this
interface.Connecting toInteractive socket# Authenticate to obtain an authorization token if you are not currently logged in.
    response = utradeConnect.interactive_login(ACCESS_TOKEN)
    # Store the token and userid
    set_interactiveToken = response['result']['token']
    set_iuserID = response['result']['userID']
    socketInstance = OrderSocket_io(set_interactiveToken, set_iuserID, base_url)Callback forConnectiondef on_connect():
        print('Interactive socket connected successfully!')Callback forDisconnectiondef on_disconnect(data):
     print('Interactive Socket disconnected!')Callback foroverridden methods# Callback for receiving message
def on_message():
    print('I received a message!')

# Callback for joined event
def on_joined(data):
    print('Interactive socket joined successfully!' , data)


# Callback for error
def on_error(data):
    print('Interactive socket error!' , data)


# Callback for order
def on_order(data):
    print("Order placed!" , data)


# Callback for trade
def on_trade(data):
    print("Trade Received!" , data)


# Callback for position
def on_position(data):
    print("Position Retrieved!" , data)


# Callback for trade conversion event
def on_tradeconversion(data):
    print("Trade Conversion Received!" , data)ExamplesExample CodeExample code demonstrating how to use the uTrade API can be found in theutrade-python-api-sdkexample directory.runMarketExample.py: Examples of all the API calls for Interactive as well as Marketdata APIs.runOrderExample.py: Examples of all the API calls for Interactive as well as Marketdata APIs.runOrderSocketExample.py: Interactive Socket Streaming Example.runMarketSocketExample.py: Marketdata Socket Streaming Example.