Alice Blue Python SDK
A comprehensive guide to integrating Alice Blue's official Python SDK into your trading applications. Learn how to authenticate, place orders, fetch market data, and stream real-time ticks with WebSocket.

What you can build with Alice Blue SDK
The Alice Blue Python SDK provides comprehensive access to trading infrastructure with automatic WebSocket handling.
Session Management
Authenticate using API key, password, and 2FA (year of birth) for secure access.
Order Placement
Place Market, Limit, Stop-Loss, Cover Orders, and Bracket Orders with ease.
Basket Orders
Buy or sell multiple securities simultaneously with basket order support.
Master Contracts
Access instrument data across NSE, BSE, NFO, MCX, and CDS exchanges.
WebSocket Streaming
Subscribe to real-time tick data with multiple feed types (Market Data, Compact, SnapQuote).
Market Status
Get live market status messages and exchange notifications.
Installation
Install the required packages using pip. Make sure you have Python 3.x installed.
# Install Alice Blue SDK
pip install alice_blue
# Force upgrade existing installation
pip uninstall alice_blue
pip --no-cache-dir install --upgrade alice_blue
# Required dependencies (installed automatically)
pip install websocket_client
pip install requests
pip install bs4alice_blueOfficial Alice Blue SDK
websocket_clientWebSocket support for live data
requestsHTTP library for API calls
bs4BeautifulSoup for HTML parsing
Authentication & Session
Get an access token (valid for 24 hours) and create the AliceBlue object to start trading.
from alice_blue import *
import logging
logging.basicConfig(level=logging.DEBUG)
# Get access token (valid for 24 hours)
access_token = AliceBlue.login_and_get_access_token(
username='your_username',
password='your_password',
twoFA='1990', # Year of birth
api_secret='your_api_secret',
app_id='your_app_id'
)
# Create AliceBlue object
alice = AliceBlue(
username='your_username',
password='your_password',
access_token=access_token
)
# Check connectivity
print(alice.get_balance()) # Get balance / margin limits
print(alice.get_profile()) # Get profile
print(alice.get_daywise_positions()) # Get daywise positions
print(alice.get_netwise_positions()) # Get netwise positions
print(alice.get_holding_positions()) # Get holding positionsGetting API Credentials: Login to Alice Blue developer console, click 'Create App', enter App Name and Redirect URI as https://ant.aliceblueonline.com/plugin/callback. Copy the App ID and API Secret.
Master Contracts & Instruments
Load master contracts to search for instruments by symbol, token, or FNO parameters.
# Download master contracts for specific exchanges
alice = AliceBlue(
username='username',
password='password',
access_token=access_token,
master_contracts_to_download=['NSE', 'BSE'] # Faster loading
)
# Get instrument by symbol
tatasteel = alice.get_instrument_by_symbol('NSE', 'TATASTEEL')
reliance = alice.get_instrument_by_symbol('NSE', 'RELIANCE')
nifty50 = alice.get_instrument_by_symbol('NSE', 'Nifty 50')
banknifty = alice.get_instrument_by_symbol('NSE', 'Nifty Bank')
# Get instrument by token (useful for BSE)
ongc_bse = alice.get_instrument_by_token('BSE', 500312)
# Get FNO instruments
import datetime
bn_fut = alice.get_instrument_for_fno(
symbol='BANKNIFTY',
expiry_date=datetime.date(2024, 6, 27),
is_fut=True,
strike=None,
is_CE=False
)
bn_call = alice.get_instrument_for_fno(
symbol='BANKNIFTY',
expiry_date=datetime.date(2024, 6, 27),
is_fut=False,
strike=50000,
is_CE=True
)
# Search instruments by name
all_sensex = alice.search_instruments('BSE', 'SENSEX')
print(all_sensex)
# Search multiple instruments
symbols = ['BANKNIFTY', 'NIFTY', 'INFY', 'BHEL']
all_scripts = alice.search_instruments('NFO', symbols)Placing Orders
Execute Market, Limit, Stop-Loss, Cover Orders, and Bracket Orders programmatically.
# Market Order - Delivery
alice.place_order(
transaction_type=TransactionType.Buy,
instrument=alice.get_instrument_by_symbol('NSE', 'INFY'),
quantity=1,
order_type=OrderType.Market,
product_type=ProductType.Delivery,
price=0.0,
trigger_price=None,
stop_loss=None,
square_off=None,
trailing_sl=None,
is_amo=False
)
# Limit Order - Intraday
alice.place_order(
transaction_type=TransactionType.Buy,
instrument=alice.get_instrument_by_symbol('NSE', 'INFY'),
quantity=1,
order_type=OrderType.Limit,
product_type=ProductType.Intraday,
price=1500.0,
trigger_price=None,
stop_loss=None,
square_off=None,
trailing_sl=None,
is_amo=False
)
# Cover Order with Stop Loss
alice.place_order(
transaction_type=TransactionType.Buy,
instrument=alice.get_instrument_by_symbol('NSE', 'INFY'),
quantity=1,
order_type=OrderType.Market,
product_type=ProductType.CoverOrder,
price=0.0,
trigger_price=1450.0, # Stop loss trigger price
stop_loss=None,
square_off=None,
trailing_sl=None,
is_amo=False
)
# Bracket Order with Target and Stop Loss
alice.place_order(
transaction_type=TransactionType.Buy,
instrument=alice.get_instrument_by_symbol('NSE', 'INFY'),
quantity=1,
order_type=OrderType.Limit,
product_type=ProductType.BracketOrder,
price=1500.0,
trigger_price=None,
stop_loss=1480.0, # Stop loss price
square_off=1550.0, # Target price
trailing_sl=None,
is_amo=False
)Basket Orders & Order Management
Place multiple orders simultaneously and manage your order book.
# Place basket order - buy/sell multiple securities at once
order1 = {
"instrument": alice.get_instrument_by_symbol('NSE', 'INFY'),
"order_type": OrderType.Market,
"quantity": 1,
"transaction_type": TransactionType.Buy,
"product_type": ProductType.Delivery
}
order2 = {
"instrument": alice.get_instrument_by_symbol('NSE', 'SBIN'),
"order_type": OrderType.Limit,
"quantity": 2,
"price": 600.0,
"transaction_type": TransactionType.Sell,
"product_type": ProductType.Intraday
}
orders = [order1, order2]
print(alice.place_basket_order(orders))
# Cancel an order
alice.cancel_order('170713000075481')
# Get order history
print(alice.get_order_history('170713000075481')) # Specific order
print(alice.get_order_history()) # All orders
# Get trade book
print(alice.get_trade_book())WebSocket Streaming
Subscribe to real-time market data with multiple feed types. Limit: 250 instruments.
Live Feed Subscription
from alice_blue import *
from time import sleep
socket_opened = False
def event_handler_quote_update(message):
print(f"Quote update: {message}")
def open_callback():
global socket_opened
socket_opened = True
# Start WebSocket connection
alice.start_websocket(
subscribe_callback=event_handler_quote_update,
socket_open_callback=open_callback,
run_in_background=True
)
# Wait for connection to open
while not socket_opened:
pass
# Subscribe to live feed
# Available feed types:
# - LiveFeedType.MARKET_DATA
# - LiveFeedType.COMPACT
# - LiveFeedType.SNAPQUOTE
# - LiveFeedType.FULL_SNAPQUOTE
alice.subscribe(
alice.get_instrument_by_symbol('NSE', 'ONGC'),
LiveFeedType.MARKET_DATA
)
# Subscribe to multiple instruments
alice.subscribe(
[
alice.get_instrument_by_symbol('NSE', 'TATASTEEL'),
alice.get_instrument_by_symbol('NSE', 'ACC')
],
LiveFeedType.MARKET_DATA
)
sleep(10)
# Unsubscribe from feed
alice.unsubscribe(
alice.get_instrument_by_symbol('NSE', 'TATASTEEL'),
LiveFeedType.MARKET_DATA
)
# Get all subscriptions
print(alice.get_all_subscriptions())Market Status & Exchange Messages
from alice_blue import *
from time import sleep
socket_opened = False
def market_status_messages(message):
print(f"Market status: {message}")
def exchange_messages(message):
print(f"Exchange messages: {message}")
def open_callback():
global socket_opened
socket_opened = True
# Start WebSocket with market status callbacks
alice.start_websocket(
market_status_messages_callback=market_status_messages,
exchange_messages_callback=exchange_messages,
socket_open_callback=open_callback,
run_in_background=True
)
while not socket_opened:
pass
# Subscribe to market status and exchange messages
alice.subscribe_market_status_messages()
alice.subscribe_exchange_messages()
sleep(10)
# Get messages directly
print(alice.get_market_status_messages())
print(alice.get_exchange_messages())Order Types Reference
Available enums for order properties in Alice Blue SDK.
TransactionType
TransactionType.BuyTransactionType.Sell
OrderType
OrderType.MarketOrderType.LimitOrderType.StopLossLimitOrderType.StopLossMarket
ProductType
ProductType.IntradayProductType.DeliveryProductType.CoverOrderProductType.BracketOrder
Supported Exchanges & Instruments
Trade across multiple exchanges and instrument types using the Alice Blue SDK.
Prerequisites
Alice Blue Trading Account
Active trading account with Alice Blue
API Access
Contact Alice Blue to enable API trading
Python 3.x
Compatible Python installation
Developer Console App
Create app in developer console for App ID & Secret
Ready to start building?
Get your API credentials from Alice Blue and start integrating today.