Skip to main content

TradingAPI SDK - Python Client for accessing TradingAPI and Streaming Market Data

Description

TradingAPI is a complete SDK that allows you to build a trading and investment platform which includes executing orders in real time, streaming live trade and order data (Using Websockets) and more.

Installation

pip install -r requirements.txt
 
pip install --upgrade mStock-TradingApi-B

It is recommended to update 'pip' and setuptools to the latest version if you are facing any issues during installation

pip install -U pip setuptools

[!NOTE] The package can be used with the name tradingapi_b


### API Usage

```python
import logging
from tradingapi_b.mconnect import *

logging.basicConfig(level=logging.DEBUG)

#Object for MConnect API
mconnect_obj=MConnectB()

#Login
login_response=mconnect_obj.login("<user_id>","<password>")

#Generate access token by calling generate session
gen_response=mconnect_obj.generate_session("<API_Key>","<request_token_here>","<otp>")

#Place Order
try:
    porder_resp=mconnect_obj.place_order(_variety="NORMAL",_trading_symbol="ACC-EQ",_symboltoken="22",_exchange="NSE",_transactiontype="BUY",_ordertype="MARKET",_quantity="20",_producttype="DELIVERY",_price="0",_triggerprice="0",_squareoff="0",_stoploss="0",_trailingStopLoss="",_disclosedquantity="0",_duration="DAY",_ordertag="")
    
    logging.info("Order placed. ID is: {}".format(porder_resp["data"]["order_id"]))

except Exception as e:
    logging.info("Order placement failed: {}".format(e.message))
#Modify Order
mconnect_obj.modify_order("NORMAL","order_id","MARKET","DELIVERY","DAY","0","10","SBIN-EQ","3045","NSE","780")

#Cancel Order
mconnect_obj.cancel_order("NORMAL","order_id")

#Cancel All orders
mconnect_obj.cancel_all()

#Get Order Details
mconnect_obj.get_order_details("order_id")

#Fetch all orders
mconnect_obj.get_order_book()

#Get Net position for logged in user
mconnect_obj.get_net_position()

#Calculate Order Margin
mconnect_obj.calculate_order_margin("DELIVERY","BUY","5","2250","NSE","ACC","22","0")

#Fetch all holdings
mconnect_obj.get_holdings()

#Get Historical Chart
mconnect_obj.get_historical_chart("NSE","11536","ONE_HOUR","01-02-2025","07-02-2025")

#Get Market Quote
mconnect_obj.get_market_quote("OHLC",{"NSE": ["3045"],"BSE": ["500410"]})

#Get Instrument Master
mconnect_obj.get_instruments()

#Get fund Summary
mconnect_obj.get_fund_summary()

#Get Trade History
mconnect_obj.get_trade_history("2025-01-15","02-02-2025")

#Convert Position
mconnect_obj.convert_position("NSE","3787","DELIVERY","INTRADAY","WIPRO-EQ","WIPRO","","","","","","", "","","","","","","BUY", 1,"DAY")

#Loser Gainer
mconnect_obj.loser_gainer("1","13","1","G")

#Create Basket
mconnect_obj.create_basket("Test Basket","Test Basket Description")

#Fetch Basket
mconnect_obj.fetch_basket()

#Rename Basket
mconnect_obj.rename_basket("New Basket Name","basket_id")

#Delete Basket
mconnect_obj.delete_basket("basket_id")

#Calculate Basket
mconnect_obj.calculate_basket("0","C","0","E","0","11915","LMT","Test Basket","I","DAY","1","A","B","1","19.02","269","NSE")

#Get Trade Book
mconnect_obj.get_trade_book()

#Get Intraday Chart
mconnect_obj.get_intraday_chart("1","22","ONE_MINUTE")

#Get Option Chain Master
mconnect_obj.get_option_chain_master("5")

#Get Option Chain Data
mconnect_obj.get_option_chain_data("2","1432996200","22")

#Logout
mconnect_obj.logout()

Websocket Usage

from tradingapi_b.mticker import *
import logging

logging.basicConfig(level=logging.DEBUG)

#Testing Web Socket or MTicker
m_ticker=MTicker("<API_KEY>","<ACCESS_TOKEN>","<WEB_SOCKET_URL>")


def on_ticks(ws, ticks):
    # Callback to receive ticks.
    logging.info("Ticks: {}".format(ticks))

def on_order_update(ws,data):
    #Callback to receive Order Updates
    logging.info("On Order Updates Packet received : {}".format(data))

def on_trade_update(ws,data):
    #Callback to receive Trade Updates
    logging.info("On Trade Updates Packet received : {}".format(data))

def on_connect(ws, response):
    # Callback on successful connect.
    m_ticker.send_login_after_connect()
    # Subscribe to a list of instrument_tokens 
    ws.subscribe("NSE",[5633])
    print("Connected to socket and logged in successfully")

def on_close(ws, code, reason):
    # On connection close stop the event loop.
    # Reconnection will not happen after executing `ws.stop()`
    ws.stop()

# Assign the callbacks.
m_ticker.on_ticks = on_ticks
m_ticker.on_connect = on_connect
m_ticker.on_close = on_close
m_ticker.on_order_update=on_order_update
m_ticker.on_trade_update=on_trade_update

# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
m_ticker.connect()


logging.info('Now Closing Web socket connection')

m_ticker.close()

logging.info('Testing complete')

Running Unit Tests

This requires having pytest library pre installed. You can install the same via pip:

pip install pytest

Navigate to the unit directory and run the connect_test.py file using pytest

cd unit
pytest connect_test.py

Support

For issues, please open an issue on GitHub.

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a new branch (feature-xyz)
  3. Commit your changes
  4. Push the branch and create a pull request

Metadata

Release files for mStock-TradingApi-B 1.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mStock-TradingApi-B 1.0.5
File Size Uploaded Provenance Actions
mstock_tradingapi_b-1.0.5.tar.gz 17.8 kB Without provenance Details for mstock_tradingapi_b-1.0.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mStock-TradingApi-B 1.0.5
File Interpreter ABI Platform Actions
mstock_tradingapi_b-1.0.5-py3-none-any.whl Python 3 none any Details for mstock_tradingapi_b-1.0.5-py3-none-any.whl

Total release size: 37.3 kB

Release files / mstock_tradingapi_b-1.0.5.tar.gz

Download URL mstock_tradingapi_b-1.0.5.tar.gz
Size 17.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f01f2339ea866c7eee09fe7e8c2c8567f599d686e63a92cb9c18cf3dae92a178
BLAKE2b-256 checksum
How to use checksums
933b59e5f10417b1e4da3fc767826094f59d2851d53b0c44d3dccdd20646c2d6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.9

Release files / mstock_tradingapi_b-1.0.5-py3-none-any.whl

Download URL mstock_tradingapi_b-1.0.5-py3-none-any.whl
Size 19.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b62e44cfc8e8dd393e2749c7cff0f6fe6eb1cb67c6a504eafa114e28eb10e9d9
BLAKE2b-256 checksum
How to use checksums
43ca7c92d52217f89bcb52475d657a184fcfffe665e9cafd3483af9bb202c41f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.9

Security for mStock-TradingApi-B 1.0.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page