Trading Bot Integration
Complete trading bot implementations for automated cryptocurrency trading using Vedicquant cosmic signals.
🚀 Overview
Automate your trading with cosmic intelligence! This section covers:
- Multi-Exchange Support: Binance, Bybit, Kraken integration
- Risk Management: Position sizing and portfolio protection
- Real-time P&L Tracking: Live profit/loss monitoring
- Vedic Phase Filtering: Trade only during favorable cosmic periods
📦 Exchange Support
Binance Integration
- Spot and futures trading
- OCO (One-Cancels-Other) orders
- Advanced order types
- Testnet support for safe development
Bybit Integration
- Derivatives trading
- Perpetual contracts
- Advanced risk management
- High-frequency trading support
Multi-Exchange Architecture
- Unified trading interface
- Portfolio diversification
- Cross-exchange arbitrage opportunities
- Centralized risk management
🎯 Quick Start
Basic Trading Bot Structure
python
from vedicquant_client import VedicquantSSEClient
import ccxt
class CosmicTradingBot(VedicquantSSEClient):
def __init__(self, exchange_config):
super().__init__(api_key='free-week-demo123')
# Initialize exchange
self.exchange = ccxt.binance({
'apiKey': exchange_config['api_key'],
'secret': exchange_config['secret'],
'sandbox': True, # Use testnet for safety
'enableRateLimit': True
})
# Trading parameters
self.risk_per_trade = 0.02 # 2% risk per trade
self.max_positions = 5
self.allowed_symbols = ['BTC', 'ETH', 'SOL', 'ADA']
self.favorable_phases = ['Amrita', 'Shubha', 'Labha']
def default_signal_handler(self, signal_data):
if signal_data.get('event_type') == 'new_signal':
if self.should_trade_signal(signal_data):
self.execute_trade(signal_data)
def should_trade_signal(self, signal):
# Signal validation logic
symbol = signal.get('symbol')
strength = signal.get('signal_strength')
phase = signal.get('phase_name', '')
# Check symbol allowlist
if symbol not in self.allowed_symbols:
return False
# Check signal strength
if strength != 'strong':
return False
# Check Vedic phase
if not any(phase_name in phase for phase_name in self.favorable_phases):
self.logger.info(f"⚠️ Unfavorable phase: {phase}")
return False
# Check position limits
if len(self.get_open_positions()) >= self.max_positions:
return False
return True
def execute_trade(self, signal):
try:
symbol = f"{signal['symbol']}/USDT"
signal_type = signal['signal_type']
# Calculate position size based on risk
position_size = self.calculate_position_size(signal)
if signal_type == 'BUY':
order = self.exchange.create_market_buy_order(symbol, position_size)
else:
order = self.exchange.create_market_sell_order(symbol, position_size)
self.logger.info(f"✅ Order executed: {symbol} {signal_type}")
# Set stop loss and take profit
self.set_exit_orders(signal, order)
except Exception as e:
self.logger.error(f"❌ Trade execution failed: {e}")
def calculate_position_size(self, signal):
# Risk-based position sizing
portfolio_value = self.get_portfolio_value()
risk_amount = portfolio_value * self.risk_per_trade
entry_price = signal['price_at_signal']
stop_price = signal['stop_loss_price']
price_risk = abs(entry_price - stop_price) / entry_price
position_value = risk_amount / price_risk if price_risk > 0 else 0
return position_value / entry_price
def set_exit_orders(self, signal, entry_order):
# Set stop loss and take profit orders
try:
symbol = f"{signal['symbol']}/USDT"
amount = entry_order['amount']
# Stop loss order
stop_order = self.exchange.create_stop_market_order(
symbol,
'sell' if signal['signal_type'] == 'BUY' else 'buy',
amount,
signal['stop_loss_price']
)
# Take profit order
profit_order = self.exchange.create_limit_order(
symbol,
'sell' if signal['signal_type'] == 'BUY' else 'buy',
amount,
signal['target_price']
)
self.logger.info(f"✅ Exit orders set for {symbol}")
except Exception as e:
self.logger.error(f"❌ Failed to set exit orders: {e}")
# Usage
exchange_config = {
'api_key': 'your_binance_api_key',
'secret': 'your_binance_secret'
}
bot = CosmicTradingBot(exchange_config)
bot.start()
🛡️ Risk Management
Position Sizing
python
def calculate_position_size(self, signal, portfolio_value, risk_percentage=0.02):
"""
Calculate position size based on:
- Total portfolio value
- Risk percentage per trade
- Distance to stop loss
"""
risk_amount = portfolio_value * risk_percentage
entry_price = signal['price_at_signal']
stop_price = signal['stop_loss_price']
# Price risk as percentage
price_risk = abs(entry_price - stop_price) / entry_price
# Position value that risks only the specified amount
position_value = risk_amount / price_risk if price_risk > 0 else 0
# Convert to position size in base currency
return position_value / entry_price
Portfolio Limits
python
class RiskManager:
def __init__(self):
self.max_positions = 5
self.max_portfolio_risk = 0.10 # 10% total portfolio risk
self.max_single_position = 0.05 # 5% per position
def can_open_position(self, signal, current_positions):
# Check position count limit
if len(current_positions) >= self.max_positions:
return False, "Maximum positions reached"
# Check portfolio concentration
total_risk = sum(pos['risk_amount'] for pos in current_positions.values())
if total_risk >= self.max_portfolio_risk:
return False, "Portfolio risk limit exceeded"
return True, "Position approved"
Vedic Phase Filtering
python
class VedicFilter:
def __init__(self):
self.favorable_phases = {
'Amrita': 1.0, # Best - take full position
'Shubha': 0.8, # Very good - reduce position by 20%
'Labha': 0.6, # Good - reduce position by 40%
'Chara': 0.0, # Neutral - no trading
'Kala': 0.0, # Dangerous - no trading
'Roga': 0.0, # Disease - no trading
'Udvega': 0.0 # Anxiety - no trading
}
def get_position_multiplier(self, phase_name):
"""Get position size multiplier based on Vedic phase"""
for phase, multiplier in self.favorable_phases.items():
if phase in phase_name:
return multiplier
return 0.0 # Unknown phase - no trading
def should_trade_in_phase(self, phase_name):
"""Check if trading is allowed in current phase"""
return self.get_position_multiplier(phase_name) > 0
📋 Available Examples
From your migrated documentation:
binance_bot.py
- Complete Binance trading implementationbybit_bot.py
- Bybit derivatives tradingREADME.md
- Original trading documentation
🎯 Features
- 🔄 Real-time Trading: Instant signal execution
- 🛡️ Risk Management: Advanced position sizing
- 📊 Performance Tracking: P&L monitoring
- 🌙 Cosmic Intelligence: Vedic phase filtering
- 🔄 Auto-reconnection: Robust connection handling
🔧 Development Setup
Environment Variables
bash
# Exchange API credentials
BINANCE_API_KEY=your_api_key
BINANCE_SECRET=your_secret
BYBIT_API_KEY=your_api_key
BYBIT_SECRET=your_secret
# Vedicquant
VEDICQUANT_API_KEY=free-week-demo123
# Trading parameters
RISK_PER_TRADE=0.02
MAX_POSITIONS=5
USE_TESTNET=true
Dependencies
bash
pip install ccxt requests python-dotenv pandas numpy
🚨 Safety First
Always Start with Testnet
- Use exchange testnet/sandbox environments
- Test with small amounts
- Validate signal processing logic
- Monitor bot performance
Risk Controls
- Never risk more than you can afford to lose
- Start with very small position sizes
- Use stop losses on every trade
- Monitor bot performance continuously
🎯 Best Practices
- Gradual Scaling: Start small and increase size slowly
- Diversification: Don't put all capital in one strategy
- Monitoring: Track all trades and performance metrics
- Vedic Respect: Honor the cosmic timing wisdom
Ready to automate cosmic trading! 🌙✨