Logging & Debugging

Reliable logging is one of the core components of the ByNinja Trading Bot architecture. Every important action inside the system is recorded, structured, and forwarded in real time through the Telegram integration. This allows traders to monitor the bot remotely, detect issues instantly, and debug complex trading scenarios without direct server access.

The logging system is designed around three main goals:

  • Real-time monitoring
  • Detailed error diagnostics
  • Remote observability through Telegram

Unlike basic console-only implementations, the ByNinja infrastructure combines rotating file logs, console output, TCP forwarding, and Telegram delivery into a unified monitoring pipeline.


Log Structure

The bot uses a centralized logging architecture built on top of Python's logging module.

Each log message follows a standardized structure:

2026-05-19 14:32:11 - TradingBot - INFO - Opened BUY position BTCUSDT

The formatter includes:

  • Timestamp
  • Logger name
  • Severity level
  • Human-readable message

Example formatter configuration:

'%(asctime)s - %(name)s - %(levelname)s - %(message)s'

This structure makes logs easy to:

  • Search
  • Parse
  • Filter
  • Analyze
  • Forward to external systems

The system uses multiple logging levels:

LevelPurpose
DEBUGInternal execution flow
INFOTrading actions and status updates
WARNINGSuspicious or unexpected behavior
ERRORRecoverable failures
CRITICALFatal system issues

Rotating File Logs

The logger automatically stores logs into rotating files using RotatingFileHandler.

Features include:

  • Automatic log persistence
  • File size limits
  • Historical backups
  • UTF-8 encoding support

Configuration:

RotatingFileHandler(
    filename=self._log_file,
    maxBytes=250*1024*1024,
    backupCount=5,
    encoding='utf-8'
)

This prevents uncontrolled log growth while preserving historical debugging data.

The system keeps:

  • Current active log
  • Up to 5 archived log files
  • 250 MB per file

This approach is especially important for long-running trading systems operating continuously 24/7.


Real-Time Telegram Logging

One of the key features of the ByNinja infrastructure is that trading bot logs are automatically forwarded into the Telegram bot in real time.

The architecture works like this:

Trading Bot
    ↓
Python Logger
    ↓
TCP Log Handler
    ↓
TCP Client
    ↓
Telegram TCP Server
    ↓
Telegram Bot
    ↓
Telegram Chat

Every important event generated by the trading bot can instantly appear inside the private Telegram channel or chat.

Examples:

✅ Position opened
📈 Take profit executed
⚠️ API rate limit warning
❌ Binance order rejected
🛑 Emergency shutdown triggered

This gives the operator immediate visibility into the system without SSH access or server monitoring tools.

The forwarding mechanism is implemented through a custom TCP logging handler:

tcp_handler = TCPLogHandler(tcp_manager)
logger.addHandler(tcp_handler)

The Telegram server receives messages through TCP and forwards them directly to the Telegram Bot API.

This effectively transforms Telegram into a real-time remote monitoring dashboard for the trading engine.


Debug Workflow

The debugging workflow is designed for fast issue isolation and recovery.

Step 1 — Detect the Problem

Most issues are immediately visible through Telegram notifications.

Example:

❌ Error starting TCP client: Connection refused

or:

⚠️ Unknown message type

Because logs are delivered in real time, problems can often be detected within seconds.

Step 2 — Inspect Detailed Logs

When deeper investigation is required, developers can inspect:

  • trading.log
  • telegram_tcp.log
  • trading_tcp.log

The logs provide chronological execution traces for:

  • Strategy decisions
  • Order execution
  • TCP communication
  • Telegram interactions
  • Persistence operations
  • Shutdown events

Step 3 — Reproduce the Scenario

The DEBUG level can be enabled to capture:

  • Internal state transitions
  • TCP message flow
  • Command execution
  • Thread lifecycle
  • Persistence operations

This allows developers to reproduce difficult edge cases and race conditions.

Step 4 — Trace the Failure Chain

Because every subsystem uses centralized logging, it becomes possible to reconstruct the exact sequence of events leading to a failure.

Example chain:

Signal generated
→ Order request sent
→ Binance API timeout
→ Retry triggered
→ Risk manager warning
→ Position recovery activated

This is especially useful in asynchronous multi-threaded systems where issues may originate far from the visible failure point.


Error Tracing

The logging system is heavily focused on structured error tracing.

All critical operations are wrapped in try/except blocks with explicit error reporting:

except Exception as e:
    logger.error(f"❌ Critical error: {e}")

This ensures that unexpected failures never silently disappear.

The system traces errors across multiple layers:

LayerExample Errors
Binance APIOrder rejection, timeout
TCP LayerConnection loss
Telegram BotAPI failures
PersistenceFile corruption
Strategy EngineInvalid signals
ThreadingDeadlocks or crashes

Pro Tip: Use a Code Editor

For a much better experience editing configuration files, we recommend using a professional code editor like Visual Studio Code.

Download VS Code ↗

Graceful Shutdown Logging

The bot also logs shutdown and recovery operations.

Example:

🛑 Shutdown signal received...
✅ PersistentMap stopped
💾 Forcing save to disk...

This is extremely important in trading environments because it confirms that:

  • Positions were saved
  • Threads stopped correctly
  • Pending operations completed
  • Persistence flushed successfully

Remote Operations Through Telegram

The Telegram integration is not limited to passive logs.

The same infrastructure also supports remote command execution.

Examples:

/starttrading
/stoptrading
/getstatus
/getstats
/buy BTCUSDT
/sell ETHUSDT

This creates a fully remote operational workflow:

  • Receive alerts in Telegram
  • Analyze logs
  • Send recovery commands
  • Monitor execution results

All without direct server access.


Production-Oriented Monitoring Architecture

The overall logging architecture combines several production-grade practices:

  • Centralized logging
  • Structured formatting
  • Rotating log files
  • Real-time remote notifications
  • Multi-thread-safe logging
  • TCP log streaming
  • Graceful shutdown tracing
  • Remote operational control

This transforms the logging subsystem from a simple debugging utility into a complete monitoring and operational infrastructure for automated crypto trading.