Skip to content

Running and Testing Your Bot

Development Workflow

flowchart TD
    A[Develop Bot] --> B[Run in Simulator]
    B --> C{Evaluate Performance}
    C -->|Good Results| D[Ready for Use]
    C -->|Issues Found| E[Debug & Refine]
    E --> A

    style A fill:#d4f1f9,stroke:#333
    style B fill:#d4f1f9,stroke:#333
    style C fill:#ffe6cc,stroke:#333
    style D fill:#d5e8d4,stroke:#333
    style E fill:#f8cecc,stroke:#333

Running Your Bot

To run your bot, create a main script that instantiates your bot class and calls the run() method:

from my_bot import MyBot

if __name__ == "__main__":
    # Replace with your actual credentials and room ID
    username = "your_username"
    password = "your_password"
    room_id = 123  # From the trading session URL

    # Create and run the bot
    bot = MyBot(username, password, room_id)
    bot.run()

Running Process

sequenceDiagram
    participant Main as Main Script
    participant Bot as TraderionBot
    participant Client as TraderionClient
    participant Server as Traderion Server

    Main->>Bot: Create bot instance
    Bot->>Client: Create client instance
    Client->>Server: Authenticate
    Client->>Server: Fetch initial data
    Main->>Bot: Call run()

    Bot->>+Client: Start polling thread
    Bot->>+Bot: Start event processing thread
    Bot->>+Bot: Start logging thread

    loop While session is active
        Client->>Server: Poll for updates
        Server-->>Client: Return updates
        Client->>Bot: Add events to queue
        Bot->>Bot: Process events

        alt Room is playing
            Bot->>Bot: Execute main_loop()
        end
    end

Testing with the Dashboard

The Traderion dashboard provides valuable insights for testing and debugging your bot. Here's how to use it effectively:

Test Dashboard Example

Run the test dashboard to verify your dashboard setup:

python -m traderion.examples.test_dashboard

Debugging with the Dashboard

  1. Monitor Real-time Data:
  2. Check position updates
  3. Verify market price changes
  4. Track bot status and actions

  5. Analyze Event History:

  6. Review market events
  7. Check bot activity logs
  8. Monitor performance metrics

  9. Use Custom Panels:

  10. Add strategy-specific data
  11. Track key indicators
  12. Monitor decision-making process

Dashboard Logging

Combine dashboard updates with logging for comprehensive debugging:

def on_market_price_change(self, old_prices, new_prices):
    if self.dashboard:
        self.dashboard.update_core_data('market_prices', new_prices)
        self.dashboard.add_market_event('Price Change', 
            f"From {old_prices} to {new_prices}")
    logger.info(f"Price changed from {old_prices} to {new_prices}")

Testing Approaches

1. Direct Testing

Test your bot implementation directly in the Traderion simulator:

from my_bot import MyBot

if __name__ == "__main__":
    bot = MyBot('username', 'password', room_id=123)
    bot.run()

2. Strategy Testing

Test individual strategies before integrating them into your bot:

from traderion.bot import TraderionBot
from traderion.strategies.ema import CrossingEMAs

class TestBot(TraderionBot):
    def __init__(self, username, password, room_id):
        super().__init__(username, password, room_id)
        # Test a specific strategy with different parameters
        self.strategy = CrossingEMAs(self.api, {
            'target_amount': 10000,
            'small_ema_period': 5,
            'big_ema_period': 20
        })

    def on_market_price_change(self, old_prices, new_prices):
        # Forward event to strategy
        self.strategy.on_price_curve_change([price for (_, price) in self.api.get_price_curve()])

    def main_loop(self):
        # Execute strategy logic
        self.strategy.run()

Debugging Techniques

Logging

Implement comprehensive logging to track your bot's decisions and actions:

import logging
import time

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='bot.log'
)
logger = logging.getLogger('my_bot')

class MyBot(TraderionBot):
    def on_market_price_change(self, old_prices, new_prices):
        logger.info(f"Price changed from {old_prices} to {new_prices}")
        # Your logic here

    def log_info(self):
        while True:
            position = self.api.get_position()
            logger.info(f"Current position: {position['amount']} @ {position['rate']}")
            logger.info(f"PnL: {position['pnl']}")
            time.sleep(5)

Error Handling

Implement robust error handling to prevent crashes:

try:
    # Risky operation (e.g., API call)
    self.api.hit_price(direction, amount, price)
except TradingError as e:
    logger.error(f"Trading error: {e}")
    # Handle trading-specific error
except Exception as e:
    logger.error(f"Unexpected error: {e}")
    # Implement fallback behavior

Performance Evaluation

Track key performance metrics to evaluate your bot's effectiveness:

graph TD
    A[Performance Metrics] --> B[Profitability]
    A --> C[Risk Management]
    A --> D[Execution Quality]

    B --> B1[Total P&L]
    B --> B2[Return on Capital]
    B --> B3[Win Rate]

    C --> C1[Maximum Drawdown]
    C --> C2[Position Limit Utilization]
    C --> C3[Risk-Adjusted Return]

    style A fill:#f5f5f5,stroke:#333,stroke-width:2px
    style B fill:#d5e8d4,stroke:#333
    style C fill:#ffe6cc,stroke:#333
    style D fill:#d4f1f9,stroke:#333

Next Steps