No project description provided
Project description
NSE Socket Client
A professional Python client library for the NSE Socket server with WebSocket and REST API support for real-time market data streaming and order management.
Features
- Real-time Market Data: WebSocket-based streaming for live market data
- Order Management: Place, cancel, and track trading orders
- Historical Data: Access historical market data with advanced filtering
- Admin Controls: Broadcast management for administrators
- Professional Logging: Comprehensive logging with customizable levels
- Auto-reconnection: Robust connection handling with automatic reconnection
- Heartbeat Support: Built-in ping/pong for connection health monitoring
- Multiple Symbol Support: Subscribe to multiple instruments simultaneously
- Clean API: Simple, intuitive interface for complex operations
Installation
pip install nse-socket-client
Quick Start
Basic Usage
from nse_socket_client import NSEClient
# Create client with authentication
client = NSEClient("ws://localhost:8080", "http://localhost:3000")
# Authenticate with username
if client.authenticate("your_username"):
# Set up data handler
def handle_market_data(data):
symbol = data["symbol"]
price_data = data["data"]
print(f"{symbol}: Price=${price_data['close']:.2f}, Volume={price_data['volume']:,}")
client.on_ticks = handle_market_data
# Connect and subscribe to multiple symbols
symbols = ["NIFTY", "RELIANCE", "TCS", "HDFC"]
if client.connect_and_subscribe(symbols):
print("🚀 Streaming market data... Press Ctrl+C to stop")
client.run() # Blocks until stopped
Using Existing Token
from nse_socket_client import NSEClient
# Create client with existing JWT token
client = NSEClient("ws://localhost:8080", "http://localhost:3000", token="your_jwt_token")
# Set up event handlers
client.on_ticks = lambda data: print(f"Received: {data}")
client.on_connect = lambda: print("Connected!")
client.on_disconnect = lambda: print("Disconnected!")
# Connect and start streaming
if client.connect_and_subscribe(["NIFTY", "INDIGO"]):
client.run()
Order Management
# Place a market order
order = client.place_order(
symbol="RELIANCE",
side="buy",
order_type="market",
quantity=10
)
# Place a limit order
limit_order = client.place_order(
symbol="TCS",
side="sell",
order_type="limit",
quantity=5,
price=3500.00
)
# Get all orders
orders = client.get_orders()
print(f"Total orders: {len(orders)}")
# Cancel an order
if order:
success = client.cancel_order(order["id"])
print(f"Order cancelled: {success}")
Historical Data
# Get recent historical data
historical_data = client.get_historical_data("NIFTY", limit=100)
# Get data for specific date range
from datetime import date
data = client.get_historical_data(
"RELIANCE",
from_date="2024-01-01",
to_date="2024-01-31",
limit=500
)
# Get daily data
daily_data = client.get_historical_data(
"TCS",
time_period="day",
limit=30
)
# Get available symbols
symbols = client.get_available_symbols()
print(f"Available symbols: {len(symbols)}")
Advanced Features
# Batch subscribe to many symbols
symbols = ["NIFTY", "BANKNIFTY", "RELIANCE", "TCS", "HDFC", "ICICIBANK"]
results = client.subscribe_batch(symbols, batch_size=10)
# Configure heartbeat
client.set_heartbeat_config(enabled=True, interval=25, timeout=10)
# Set custom log level
client.set_log_level("DEBUG")
# Check connection status
if client.is_connected():
print(f"Connected with {client.get_subscription_count()} active subscriptions")
# Get heartbeat status
heartbeat_info = client.get_heartbeat_status()
print(f"Heartbeat: {heartbeat_info}")
Admin Features
For users with admin privileges:
# Start data broadcasting
client.start_broadcast()
# Check broadcast status
status = client.get_broadcast_status()
print(f"Broadcast state: {status['state']}")
# Pause/Resume broadcasting
client.pause_broadcast()
client.resume_broadcast()
# Stop broadcasting
client.stop_broadcast()
Configuration
WebSocket Configuration
client = NSEClient(
ws_uri="ws://localhost:8080",
api_uri="http://localhost:3000",
token="your_token"
)
# Configure auto-reconnection
client.auto_reconnect = True
client.reconnect_interval = 5
client.max_reconnect_attempts = 10
# Configure heartbeat
client.heartbeat_enabled = True
client.heartbeat_interval = 25
client.ping_timeout = 10
Event Handlers
def on_market_data(data):
"""Handle incoming market data"""
print(f"Market Data: {data}")
def on_connection():
"""Handle connection established"""
print("WebSocket connected")
def on_disconnection():
"""Handle connection lost"""
print("WebSocket disconnected")
def on_error(error):
"""Handle errors"""
print(f"Error: {error}")
def on_order_update(order):
"""Handle order updates"""
print(f"Order Update: {order}")
# Assign handlers
client.on_ticks = on_market_data
client.on_connect = on_connection
client.on_disconnect = on_disconnection
client.on_error = on_error
client.on_order_update = on_order_update
Error Handling
from nse_socket_client import (
NSESocketError,
AuthenticationError,
ConnectionError,
SubscriptionError,
HistoricalDataError,
AdminError
)
try:
client = NSEClient("ws://localhost:8080", "http://localhost:3000")
client.authenticate("username")
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except ConnectionError as e:
print(f"Connection failed: {e}")
except NSESocketError as e:
print(f"NSE Socket error: {e}")
API Reference
NSEClient Class
Constructor
NSEClient(ws_uri, api_uri, token=None)
Authentication
authenticate(username)- Authenticate with usernameget_token(username)- Get JWT token
Connection Management
ws_connect()- Connect to WebSocketws_disconnect()- Disconnect from WebSocketis_connected()- Check connection statushealth_check()- Check API server health
Subscription Management
subscribe_feed(symbol)- Subscribe to single symbolsubscribe_multiple(symbols)- Subscribe to multiple symbolssubscribe_batch(symbols, batch_size)- Batch subscribeunsubscribe_feed(symbol)- Unsubscribe from symbolconnect_and_subscribe(symbols)- Connect and subscribe in one call
Order Management
place_order(symbol, side, order_type, quantity, price, stop_price)cancel_order(order_id)get_orders(symbol, status)get_order(order_id)
Historical Data
get_historical_data(symbol, limit, from_date, to_date, time_period)get_historical_summary()get_available_symbols()
Requirements
- Python 3.7+
- requests >= 2.25.0
- websocket-client >= 1.0.0
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file nse-socket-client-0.7.tar.gz.
File metadata
- Download URL: nse-socket-client-0.7.tar.gz
- Upload date:
- Size: 15.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0014a1aa60730311983beea20f670c5a20208d2f5819d66650ab6b2cb6da63e1
|
|
| MD5 |
ac0d3b90ee12f46874951f8c915adf25
|
|
| BLAKE2b-256 |
dc2e4ab2571bb604a3cd22f260346fe9f56a6d9ca9d60cc8eee192dce685cc63
|
File details
Details for the file nse_socket_client-0.7-py3-none-any.whl.
File metadata
- Download URL: nse_socket_client-0.7-py3-none-any.whl
- Upload date:
- Size: 13.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8bcdc0576bd01b09be9878475369031a1ce7973ca2e6cadfd26f0006c6287ce9
|
|
| MD5 |
7e46f240298a755526b0b1dd6f10ea38
|
|
| BLAKE2b-256 |
713d076dd60eabb40a2a9cb698cf0376198ff1301e7944c9040b00cb6dbf0964
|