Bot Architecture

Interactive System & Multi-Process Architecture

Click any component to inspect its internal logic, or simulate data packets traveling across the TCP layer.

ByNinja Trading Bot

TCP Client Process
ByNinjaTradingBot CoreMain Engine
TCPClientManagerSocket Client
Background QueueSend / Receive Threads

Thread-safe non-blocking queue

Functions:
Sends system logs, trade alerts & metrics
Receives remote trading control commands

TCP/IP Connection

Port: Configurable Socket
Trading Logs & Status Updates
TCP SOCKET
Control Commands

Telegram-TCP Server

TCP Server Process
TCPServerManagerServer Daemon
TelegramBot CoreBot API Engine
Command HandlerAsync Router
Functions:
Routes incoming TCP logs to Telegram API
Routes Telegram user commands back to socket

Telegram Bot API

HTTPS Cloud

Official Telegram REST API & webhook cloud gateway

Telegram Chat Interface

Trader UI
/starttrading|/stopbuying|/getstatus
Interactive

ByNinjaTradingBot Core

Trading Application (Python Process 1)Core Strategy Engine

Main execution engine responsible for continuous market monitoring, exchange WebSocket integration, EMA strategy calculation, and risk management.

Real-time Exchange API Order Placement
Non-blocking Market Analysis Loop
Automated Position & Risk Controls

System Overview

The ByNinja Trading platform is built as a distributed multi-process system that separates trading execution from user interaction.

The architecture consists of two independent applications:

  • Trading Bot — responsible for market analysis, strategy execution, risk management, and order processing.
  • Telegram Control Server — responsible for notifications, remote control, and command handling through Telegram.

Both services communicate through a lightweight custom TCP layer, allowing them to run independently while remaining synchronized in real time.

This separation improves stability, scalability, and fault isolation. Even if the Telegram service becomes unavailable, the trading engine can continue operating without interruption.


Process Architecture

The system uses a process-oriented design where each component has a dedicated responsibility.

Trading Process

The trading process manages:

  • Exchange API integration
  • Market monitoring
  • Strategy execution
  • Risk management
  • Position handling
  • Internal logging

The trading engine runs continuously and exposes remote control commands through the TCP client connection.

Telegram Process

The Telegram process handles:

  • Telegram Bot API communication
  • User command processing
  • Notifications and alerts
  • TCP server management

This process acts as a bridge between the user and the trading engine.

Independent Runtime

Both applications are launched separately and operate as independent processes:

Code
python3 -c "from trading.main import main; main()"
Code
python3 -c "from telegram.main import main; main()"

Because both services are isolated, each process can be restarted, updated, or debugged independently without affecting the other subsystem.


TCP Communication

The communication layer is based on a custom TCP protocol designed for low overhead and real-time interaction.

Communication Flow

Interactive Command Flow Pipeline

Sequential command propagation from Telegram User to Trading Engine

Telegram UserUser Interface

Trader Command Input

Active Command01
Telegram BotAPI Integration

Bot API Command Processor

02
TCP ServerGateway Layer

Command Gateway Listener

03
Trading Bot TCP ClientTransport Layer

Socket Transport Handler

04
Trading EngineApplication Layer

Core Strategy Execution

05

The reverse flow is used for logs, alerts, and status updates.

Message Structure

All messages are transferred in JSON format with a fixed-length header:

Code
{
    "tag": "command",
    "message": "starttrading",
    "timestamp": 1750000000
}

Supported Features

The TCP layer includes:

  • Automatic reconnection logic
  • Background send/receive workers
  • Thread-safe message queues
  • Graceful shutdown handling
  • Message routing by type
  • Persistent connection monitoring

Command System

The architecture supports remote commands such as:

  • Start / stop trading
  • Enable or disable buying
  • Enable or disable selling
  • Force buy / sell actions
  • Statistics retrieval
  • System status monitoring

Commands can be global or symbol-specific.


Multi-Process Design

The platform follows a multi-process architecture instead of a monolithic design.

Advantages

Isolation

A failure in the Telegram subsystem does not stop trading operations.

Scalability

Each service can be deployed on different machines or containers in the future.

Maintainability

The codebase is separated into logical components with clear responsibilities.

Reliability

TCP reconnection and background workers help maintain stable communication even during temporary network failures.

Concurrent Execution

Trading operations, Telegram polling, TCP communication, and logging all run concurrently using dedicated threads.


Internal Concurrency Model

Inside each process, the system uses multithreading for asynchronous operations.

Trading Application Threads

  • Trading execution thread
  • TCP communication thread
  • Log forwarding thread
  • Background monitoring workers

Telegram Application Threads

  • Telegram polling thread
  • TCP server thread
  • Message forwarding workers

This design ensures that network operations never block the trading engine itself.