Python client for DAS Trader Pro CMD API
Project description
DAS Trader Python API Client
Complete Python client for the DAS Trader Pro CMD API that enables automated trading, real-time order management, position tracking, and market data streaming.
🚀 Key Features
Core Trading Capabilities
- Complete Trading: Send, modify, and cancel orders (Market, Limit, Stop, Peg, etc.)
- Real-Time Market Data: Level 1, Level 2, and Time & Sales streaming
- Position Management: Automatic position tracking and real-time P&L
- Historical Data: Access to daily and minute charts
- Specific Order Queries: Get pending orders and executed orders separately
Enhanced Features
- Production-Grade Logging: Structured logging with rotation and masking
- Connection Resilience: Circuit breaker pattern with exponential backoff
- Configuration Management: Environment variables and JSON config support
- Enhanced Error Handling: Categorized exceptions with recovery guidance
- Multi-Format Parsing: Handles various DAS response formats
- Automatic Reconnection: Robust connection handling with auto-reconnect
- Native Asyncio: High performance with concurrent operations
- Type Safety: Fully typed for better IDE support
📋 Requirements
- Python 3.8+
- DAS Trader Pro with CMD API enabled
- Valid DAS Trader account
⚡ Quick Installation
git clone https://github.com/jefrnc/das-bridge.git
cd das-bridge
pip install -e .
Optional Dependencies
# For notifications
pip install aiohttp
# For data analysis
pip install numpy pandas matplotlib
# For Windows desktop notifications
pip install win10toast # Windows only
# For configuration management
pip install python-dotenv
🔧 Configuration
1. Environment Variables
cp .env.example .env
# Edit .env with your credentials
2. Basic Configuration
# .env
DAS_HOST=localhost
DAS_PORT=9910
DAS_USERNAME=your_das_username
DAS_PASSWORD=your_das_password
DAS_ACCOUNT=your_das_account
🎯 Basic Usage
import asyncio
from das_trader import DASTraderClient, OrderSide, OrderType, MarketDataLevel
async def main():
# Create client
client = DASTraderClient(host="localhost", port=9910)
try:
# Connect to DAS Trader
await client.connect("your_username", "your_password", "your_account")
# Get buying power
bp = await client.get_buying_power()
print(f"Buying Power: ${bp['buying_power']:,.2f}")
# Subscribe to market data
await client.subscribe_quote("AAPL", MarketDataLevel.LEVEL1)
# Get quote
quote = await client.get_quote("AAPL")
print(f"AAPL: Bid ${quote.bid} | Ask ${quote.ask} | Last ${quote.last}")
# Send order
order_id = await client.send_order(
symbol="AAPL",
side=OrderSide.BUY,
quantity=100,
order_type=OrderType.LIMIT,
price=150.00
)
print(f"Order sent: {order_id}")
# Check positions
positions = client.get_positions()
for pos in positions:
if not pos.is_flat():
print(f"{pos.symbol}: {pos.quantity} shares, "
f"P&L: ${pos.unrealized_pnl:.2f}")
finally:
await client.disconnect()
if __name__ == "__main__":
asyncio.run(main())
🔥 Enhanced Capabilities
Advanced Order Management
# Get specific order types
pending_orders = await client.get_pending_orders()
executed_orders = await client.get_executed_orders()
# Enhanced market data
level1_data = await client.get_level1_data("AAPL")
montage_data = await client.get_montage_data("AAPL")
# Robust buying power (handles multi-line responses)
bp_data = await client.get_buying_power()
Production-Ready Features
# Enhanced logging with rotation
from das_trader.enhanced_logger import EnhancedDASLogger
logger = EnhancedDASLogger(
account_id="TRADER123",
log_dir="logs/production",
max_log_size=50*1024*1024 # 50MB rotation
)
# Connection resilience
from das_trader.connection_resilience import ConnectionResilientManager
resilient_mgr = ConnectionResilientManager(
client.connection,
max_reconnect_attempts=5,
health_check_interval=60.0
)
# Configuration management
from das_trader.config_manager import load_das_config
config = load_das_config("config.json")
client = DASTraderClient(**config.get_client_config())
📊 Supported Order Types
# Market Order
await client.send_order("AAPL", OrderSide.BUY, 100, OrderType.MARKET)
# Limit Order
await client.send_order("AAPL", OrderSide.BUY, 100, OrderType.LIMIT, price=150.00)
# Stop Loss
await client.send_order("AAPL", OrderSide.SELL, 100, OrderType.STOP, stop_price=145.00)
# Stop Limit
await client.send_order("AAPL", OrderSide.SELL, 100, OrderType.STOP_LIMIT,
price=148.00, stop_price=145.00)
# Trailing Stop
await client.send_order("AAPL", OrderSide.SELL, 100, OrderType.TRAILING_STOP,
trail_amount=2.00)
📈 Callbacks and Events
# Order callbacks
def on_order_filled(order):
print(f"Order filled: {order.symbol}")
def on_order_rejected(order):
print(f"Order rejected: {order.symbol}")
client.orders.register_callback("order_filled", on_order_filled)
client.orders.register_callback("order_rejected", on_order_rejected)
# Position callbacks
def on_position_update(position):
print(f"Position updated: {position.symbol} P&L: ${position.unrealized_pnl:.2f}")
client.positions.register_callback("position_updated", on_position_update)
# Market data callbacks
def on_quote_update(quote):
print(f"{quote.symbol}: ${quote.last}")
client.market_data.register_callback("quote_update", on_quote_update)
🤖 Advanced Examples
Basic Trading Bot
# See examples/trading_bot.py
python examples/trading_bot.py
Portfolio Monitor
# See examples/portfolio_monitor.py
python examples/portfolio_monitor.py
Market Data Streaming
# See examples/market_data_streaming.py
python examples/market_data_streaming.py
🛡️ Risk Management
# Configuration in config.example.py
MAX_POSITION_SIZE = 1000
MAX_ORDER_VALUE = 50000.0
STOP_LOSS_PERCENT = 0.02 # 2%
TAKE_PROFIT_PERCENT = 0.04 # 4%
# Paper Trading Mode
PAPER_TRADING_MODE = True
PAPER_TRADING_INITIAL_BALANCE = 100000.0
📚 API Documentation
Main Classes
DASTraderClient: Main client for interacting with DAS TraderOrderManager: Order management and status trackingPositionManager: Position tracking and P&LMarketDataManager: Market data streaming and cachingConnectionManager: TCP connection handling and reconnectionNotificationManager: Multi-platform notification system
Main Enums
OrderType: MARKET, LIMIT, STOP, STOP_LIMIT, PEG, TRAILING_STOPOrderSide: BUY, SELL, SHORT, COVEROrderStatus: PENDING, NEW, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTEDTimeInForce: DAY, GTC, IOC, FOK, MOO, MOCMarketDataLevel: LEVEL1, LEVEL2, TIME_SALES
🧪 Testing
# Run tests
pytest tests/ -v
# With coverage
pytest tests/ --cov=das_trader --cov-report=html
🔐 Security
- Never commit credentials in code
- Use environment variables for sensitive configuration
- The
.envfile is in.gitignore - Consider using paper trading mode for testing
📝 Logging
import logging
logging.basicConfig(level=logging.INFO)
# The client includes detailed logging:
# - Connections and authentication
# - Sent and received orders
# - Market data streaming
# - Errors and reconnections
🤝 Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a branch for your feature (
git checkout -b feature/new-feature) - Commit your changes (
git commit -am 'Add new feature') - Push to the branch (
git push origin feature/new-feature) - Open a Pull Request
📄 License
This project is under the MIT License - see the LICENSE file for details.
⚠️ Disclaimer
This software is for educational and development purposes. Automated trading carries significant financial risks. Use at your own risk and always consider:
- Thorough testing in paper trading mode
- Proper risk management
- Constant position monitoring
- Compliance with local regulations
🔗 Related Projects
- das-api-examples: Practical examples and tests for the DAS Trader Pro CMD API
- Direct TCP connection tests
- API feature verification
- Configuration guides and troubleshooting
📚 Useful Links
📞 Support
To report bugs or request features:
- Open an Issue
- Check the documentation
- Consult the examples
Developed with ❤️ for the algorithmic trading community
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 das_bridge-1.0.0.tar.gz.
File metadata
- Download URL: das_bridge-1.0.0.tar.gz
- Upload date:
- Size: 67.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.8.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
971c0146514316d29114edbd18ab57160b5a6f0a43e83b53e2cc2f7bc28a5eb4
|
|
| MD5 |
d5fc6573a27d1793001186dced97adb3
|
|
| BLAKE2b-256 |
62a71092078e36bfbb2e15cdbbe936cd3ae99a4879e0eee1f9652554df26ec37
|
File details
Details for the file das_bridge-1.0.0-py3-none-any.whl.
File metadata
- Download URL: das_bridge-1.0.0-py3-none-any.whl
- Upload date:
- Size: 65.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.8.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
213ba75e5e6f37d9bc8dd235f73eeec9c03ced5766c83a45900a054d460207b8
|
|
| MD5 |
5b7a0d65d19c8c77c71fa6049fd17b52
|
|
| BLAKE2b-256 |
cc018bcb2e070ba86e1275fdd63e466cd1fbbadce236ecba31a8a6b3b4202c4c
|