Building An Algorithmic Trading Bot With Binance and Telegram Integration
Building An Algorithmic Trading Bot With Binance and Telegram Integration
This project presents the design and deployment of an automated cryptocurrency trading bot
aimed at streamlining short-position futures trading on the Binance platform. The bot is hosted
on a cloud-based infrastructure using AWS EC2 t2.micro, which ensures 24/7 operation with
minimal resource consumption. The core trading logic is driven by a combination of technical
indicators—namely, the Supertrend indicator and Exponential Moving Averages (EMA)—to
detect high-probability short-entry signals in volatile cryptocurrency markets.
The trading bot is developed using Python and utilizes the ccxt library to interface with the
Binance Futures API. It automatically calculates entry and exit points, places short orders, and
manages open positions with configurable stop-loss and take-profit settings. To ensure that
trades are executed under defined risk parameters, the bot allows users to specify leverage, risk
amount per trade, and exit strategies—including time-based exits and trend reversals.
A key feature of the system is its integration with Telegram, offering a user-friendly interface
through which the administrator can remotely control and configure the bot in real time. The
Telegram bot supports commands such as /start, /stop, /balance, /summary, and /status, along
with interactive configuration updates for strategy parameters like EMA values, ATR
multipliers, SL/TP percentages, and more.
This project not only reduces manual effort and emotional bias in trading but also enhances
speed, accuracy, and consistency. By leveraging automation and cloud computing, it delivers a
powerful solution for individual traders looking to scale and optimize their cryptocurrency
trading strategies.
LIST OF TABLES
TABLE 5.1: Database Design Format for File Storage
LIST OF ABBREVIATIONS
API - Application Programming Interface
UI - User Interface
UX - User Experience
CHAPTER 1
INTRODUCTION:
1.1Overview
Manual cryptocurrency trading demands constant attention, emotional discipline, and advanced
technical knowledge, making it prone to inconsistent and error-prone decisions. Traders often
struggle with reacting to rapid market changes and maintaining discipline in high-volatility
environments, which can lead to missed opportunities or financial losses.
This project addresses these challenges by introducing an automated trading bot designed to
operate on Binance Futures. The bot applies a predefined strategy based on technical indicators
to identify trade opportunities and manages positions using configurable stop-loss, take-profit,
and time-based exit rules. Integration with Telegram provides a real-time control interface for
starting, stopping, and configuring the bot remotely. Deployed on an AWS EC2 t2.micro
instance, it ensures 24x7 availability with minimal resource usage.
Frontend Technologies
While the project does not use a traditional GUI, it employs a conversational frontend through
Telegram:
● Telegram Bot (via Telethon): Acts as the user-facing interface to send commands like
/start, /stop, and view real-time alerts and updates.
● Interactive Menus: Admin can update parameters such as stop-loss, take-profit, and
leverage via Telegram inline buttons.
● Real-Time Notifications: Ensures that the user receives immediate feedback on trade
entries, exits, and errors.
Blockchain Technologies
Although this project does not directly interact with a blockchain, it operates within the
cryptocurrency ecosystem and uses trading APIs built around blockchain-based assets:
● Binance Futures API (via CCXT): Connects with the Binance exchange, enabling real-
time cryptocurrency trading operations.
● Crypto Trading Protocols: Interacts with tokenized markets, fetching live prices and
placing orders on blockchain-based assets.
● Environment Variables (via dotenv): Stores sensitive API keys and configuration details
securely without hardcoding.
● Local Configuration (config.json): Manages runtime settings such as SL, TP, leverage,
and coin lists, enabling flexibility and persistence.
● Secure Cloud Hosting (AWS EC2 t2.micro): Ensures 24x7 uptime in a controlled and
secure server environment.
● Logging: Tracks activity, trades, and errors for debugging and performance review
without exposing sensitive information.
The bot uses a combination of technical indicators—Supertrend and dual EMAs—to detect
bearish signals for short trades. Once a valid signal is found, it calculates position size based on
available balance and places a market order automatically. This ensures fast and consistent trade
execution without manual intervention. The strategy logic is designed to avoid overtrading by
allowing only one trade per symbol at a time and skipping trades during trend reversals. This
automation helps traders capture opportunities 24x7 while reducing human error and fatigue.
The bot is integrated with Telegram, allowing the administrator to fully control and monitor its
behavior. Using simple commands like `/start`, `/stop`, `/balance`, `/status`, and `/summary`,
users can operate the bot remotely. It also supports inline button menus to change configuration
settings such as SL, TP, leverage, and timeframe without editing files manually. All alerts, trade
updates, and errors are pushed instantly to the Telegram chat, making it a lightweight and
efficient frontend for bot control.
3. Strategy Configuration and Flexibility
The trading strategy is highly customizable via a configuration file or Telegram commands.
Users can adjust parameters like EMA lengths, ATR multiplier, timeframe, SL/TP percentages,
and trade duration. The bot reads this configuration at runtime and dynamically applies it,
enabling fine-tuning without redeployment. This level of flexibility allows the trader to optimize
the strategy based on market conditions, asset volatility, and individual risk tolerance. Changes
take effect instantly and are confirmed back to the user through Telegram.
The bot uses the `dotenv` package to load sensitive Binance API credentials securely from an
environment file. This approach keeps API keys hidden from the source code and version control
systems. Only authenticated Telegram users (by ID) can send commands to the bot, preventing
unauthorized access. Error handling routines also ensure that invalid keys or connectivity issues
are reported clearly. These practices minimize the risk of account compromise and ensure that all
interactions with Binance are secure and controlled.
Trades are exited automatically using multiple conditions, including fixed Take-Profit (TP),
Stop-Loss (SL), and time-based exits (e.g., after 2 minutes). The bot also checks for Supertrend
reversals and can close positions when a bullish signal is detected. These layered exit strategies
help preserve profits, limit losses, and avoid bad trades during volatile or consolidating markets.
Exit reasons are clearly logged and sent to Telegram so that the user understands why a trade
closed, increasing transparency and trust in the system.
6. Cloud-Based Deployment (AWS EC2)
The bot is designed for lightweight operation and is fully compatible with AWS EC2 t2.micro
instances, which are often free-tier eligible. This ensures 24x7 availability with minimal cost.
The system runs in a headless, non-GUI environment using background processes and
asynchronous tasks to efficiently handle multiple coins and Telegram commands. This
deployment model reduces downtime, ensures scalability, and removes the need for local servers
or VPS setups. It also enables remote access from anywhere with a Telegram connection.
Every trade is logged with detailed information, including entry and exit time, coin pair, price,
PnL percentage, and duration. Logs are stored in a structured CSV format that can be exported
for performance analysis or tax reporting. The bot also provides real-time trade summaries and
daily performance snapshots via the `/summary` command. These reports help the user evaluate
the effectiveness of the strategy over time and make informed decisions about tuning or pausing
the bot.
Cryptocurrency trading offers immense opportunities due to its volatility and 24/7 market
availability, but it also introduces significant challenges for retail traders. Manual trading
requires constant vigilance, fast execution, and sound technical analysis, which can be mentally
exhausting and error-prone. Traders often miss profitable entries or hold losing positions due to
emotions, lack of discipline, or technical limitations. This project aims to solve these challenges
by building an automated trading system that integrates technical indicators, real-time decision-
making, and remote control via Telegram. The following problems highlight the inefficiencies
and limitations faced in manual and semi-automated crypto trading.
Cryptocurrency markets operate continuously, with price swings occurring at any time of day.
Manual traders cannot monitor the market 24x7, leading to missed trade opportunities or delayed
exits. This creates a major disadvantage in volatile markets where timely entries and exits are
critical. The inability to react instantly often results in poor trade execution, losses, or reduced
profits. Automating trade monitoring and execution allows for round-the-clock responsiveness,
capturing opportunities even during non-trading hours without human intervention.
Manual order placement takes time—from recognizing the signal, logging into the exchange, to
calculating position size and submitting the order. This delay can cause traders to miss optimal
entry or exit points, especially in fast-moving markets. Even a few seconds can impact
profitability. The proposed bot eliminates this delay by instantly identifying signals and placing
trades programmatically using the Binance Futures API. This results in faster execution and
better alignment with the defined strategy.
4. Strategy Inconsistency
Even skilled traders often fail to follow their strategies consistently due to distractions, lack of
focus, or changing market sentiment. They might skip trades, adjust risk mid-session, or second-
guess their plans. Such inconsistencies dilute the effectiveness of any trading strategy. An
automated system enforces strategy rules with precision. It checks every selected symbol at fixed
intervals, enters trades only on verified signals, and exits based on predefined rules—ensuring
consistent, repeatable behavior across all trades.
Many traders fail to apply proper risk management—either over-leveraging trades or neglecting
to set appropriate stop-loss/take-profit levels. This exposes their accounts to significant
drawdowns. Calculating optimal trade size manually is also error-prone, especially with
fluctuating balances. The proposed bot includes built-in risk management features: dynamic
USDT-based position sizing, fixed leverage, SL/TP percentages, and trade duration limits. These
features help control exposure and protect the trading capital, even when the user is not actively
monitoring the system.
6. Limited Remote Control
Most manual or semi-automated bots lack flexible remote access. Users need to log into
platforms or edit files to make changes, which isn’t practical in real-time scenarios. Moreover,
there’s limited visibility into ongoing trades or bot status. This project solves the issue by
integrating Telegram as a remote interface. Admins can start/stop trading, adjust configurations,
check balance, and get performance summaries—all via chat commands. This enhances usability
and real-time control, even from mobile devices.
Without structured logging, it’s hard for traders to track their trade performance, understand
what worked, and identify areas of improvement. Manual logs are time-consuming and error-
prone. Many bots don’t provide easy access to trade history. The proposed bot maintains a CSV
log for each trade, recording key details like symbol, entry/exit price, time, PnL, and duration.
This log can be exported or analyzed, allowing traders to evaluate strategy effectiveness,
maintain records, and generate reports with minimal effort.
To address the challenges of manual trading in cryptocurrency markets, this project proposes a
fully automated, cloud-deployed trading bot integrated with Telegram for real-time interaction.
The system is built using Python and key libraries like `ccxt` for exchange connectivity and
`telethon` for Telegram control. The bot applies a robust trading strategy using Supertrend and
EMA indicators to identify shorting opportunities on Binance Futures. It handles trade execution,
risk management, exit logic, and user interaction autonomously. The following points describe
the key components of the proposed solution that overcome the limitations of manual or semi-
automated trading.
The bot continuously monitors selected cryptocurrency pairs using technical analysis and
automatically places trades based on valid short-entry signals. This eliminates the need for
manual signal recognition and reduces latency in execution. Orders are placed using precise
market data and predefined conditions, ensuring consistent and accurate performance. This
automation allows for timely reactions to market events and avoids errors that often occur during
manual entries. By removing human intervention from the execution process, the system ensures
discipline, speed, and reliability in every trade.
The bot is deployed on a lightweight and cost-effective AWS EC2 t2.micro instance, enabling
uninterrupted 24/7 operation. Cloud hosting ensures constant uptime, automatic restart on crash,
and access from anywhere in the world. This setup is ideal for cryptocurrency markets, which
operate around the clock. Users do not need to maintain local hardware or keep their systems
running. The EC2 instance hosts the bot as a background service that continuously scans for
signals and manages trades autonomously, ensuring maximum trading opportunity coverage.
The system includes a Telegram bot that allows real-time control, configuration, and monitoring.
Users can issue commands like `/start`, `/stop`, `/balance`, `/summary`, and configure
SL/TP/leverage via interactive menus. All trade alerts, errors, and status updates are sent directly
to Telegram. This makes the bot easy to use and accessible from any device, without requiring a
user interface or direct access to the server. Telegram also ensures a secure communication
channel between the user and the bot through admin-only access control.
To protect trading capital, the bot includes risk management features such as USDT-based
position sizing, configurable leverage, and clearly defined stop-loss and take-profit parameters.
Users can specify how much of their balance they want to risk per trade. The bot dynamically
calculates the appropriate quantity based on live prices and available margin. It also supports
trade exit based on maximum duration and strategy reversals. These features ensure that risk
exposure remains controlled and in line with the user’s financial goals.
6. Configurable Strategy Parameters
All trading parameters—such as EMA lengths, Supertrend settings, SL/TP percentages, leverage,
and timeframes—can be adjusted without restarting the bot. Changes can be made through
Telegram or directly in the `config.json` file. This makes the bot highly adaptable to different
market conditions or trading styles. Strategy tuning becomes efficient and seamless, and users
can experiment with settings to optimize performance. Configurations are applied in real time
and logged, allowing the user to maintain control over how the bot behaves.
Every trade executed by the bot is logged into a structured CSV file with key details: entry/exit
time, symbol, entry/exit price, trade result (PnL), leverage, and duration. Users can export this
log through a Telegram command (`/export`). This feature enables transparent tracking of bot
performance, simplifies record keeping, and supports data-driven improvements. It also allows
for audit trails, debugging, and retrospective performance analysis—making the trading bot not
just a tool for execution but also for learning and optimization.
1.6 Objectives
The primary objective of this project is to develop a fully automated, cloud-hosted trading bot
capable of executing short positions on Binance Futures using technical strategies. The system is
designed to minimize manual intervention, enhance decision-making accuracy, and maintain
consistent performance in volatile crypto markets. It provides a user-friendly interface via
Telegram and includes smart risk management and logging features to support long-term trading
sustainability. The following points elaborate on the specific goals this project aims to achieve.
One of the core objectives is to automate the process of identifying, entering, and exiting short
trades on Binance Futures. By using a combination of Supertrend and EMA indicators, the bot
detects bearish trends and acts upon them instantly. This eliminates the delay and error-prone
nature of manual trading and allows trades to be executed based on precise logic. Automated
trading ensures that strategies are followed consistently, without emotional interference, making
it suitable for traders looking for scalability and discipline.
The project aims to create a convenient and intuitive interface for the user through Telegram.
Instead of using complex dashboards or editing config files manually, the user can start/stop the
bot, modify settings, view performance summaries, and receive trade alerts—all from a
Telegram chat. This feature ensures that the trader can manage the bot from anywhere, on any
device, without logging into the server or needing technical expertise. It adds accessibility and
user-friendliness to the system.
A vital objective is to provide strong, customizable risk controls for each trade. The bot allows
the user to set fixed leverage, define stop-loss and take-profit percentages, and determine the
trade size based on available balance. It also includes a maximum trade duration to exit trades
that linger too long. These features help manage downside risk and prevent overexposure. By
enforcing these rules programmatically, the bot protects the trading account from major losses
and promotes long-term sustainability.
Another key goal is to maintain uninterrupted trading capability around the clock using a cloud
server. The bot is designed to run on AWS EC2 t2.micro, a cost-effective and reliable instance
type. This deployment ensures the bot is always online to monitor signals and execute trades—
even when the user is offline. Hosting the bot on the cloud also allows it to recover from
unexpected failures, reboot automatically, and remain independent of local system resources,
making it ideal for full-time trading automation.
To support continuous evaluation and improvement, the bot logs all executed trades in a
structured format. Each trade includes data like symbol, entry/exit prices, timestamps, PnL
percentage, and trade duration. The system also supports exporting this log via Telegram,
making it accessible and useful for reporting or backtesting. This objective ensures that users
have complete visibility into the bot’s performance and can make data-driven decisions about
configuration adjustments or strategy refinements.
This project aims to build a fully automated, cloud-deployed trading bot for executing short
positions on Binance Futures using technical analysis. The bot is designed to monitor real-time
market data, identify trade signals using Supertrend and EMA indicators, and execute trades
programmatically with defined risk parameters. Hosted on AWS EC2 (t2.micro), it ensures
round-the-clock availability without the need for physical infrastructure or constant human
supervision.
The bot incorporates a secure and dynamic configuration system, allowing users to set leverage,
stop-loss, take-profit, and capital allocation parameters. All interactions with the bot are handled
through a Telegram interface, offering remote access for command execution, performance
summaries, and strategy updates.
The scope is limited to executing short-side trades using a single-strategy setup. Future
enhancements like long-position support, portfolio balancing, backtesting modules, or multi-user
capability are outside the current scope but are identified as potential future work. The system is
built for individual traders or developers looking to automate their strategies with real-time
control and accountability.
CHAPTER 2:
LITERATURE SURVEY:
2.1 Existing Solutions
The cryptocurrency trading space has seen rapid innovation with the emergence of automated
trading platforms. Solutions such as 3Commas, Cryptohopper, Pionex, and TradeSanta offer
retail traders tools for automating strategies, managing portfolios, and executing trades 24x7.
While convenient, these platforms often restrict access to advanced customizations, charge
recurring fees, and limit transparency in trade execution logic. Most require separate integrations
for signal generation and execution, creating a fragmented user experience. On the other hand,
manual trading or semi-automated bots offer flexibility but lack speed, scalability, and emotional
consistency. Thus, existing solutions fail to deliver a seamless, fully customizable, cloud-
deployable system that empowers traders with total control over strategies, risk, and execution.
TradingView is a widely used charting and technical analysis platform that allows users to
design and test trading strategies using Pine Script. While it offers powerful visualization tools
and can trigger alerts, it does not support direct order execution on exchanges. Users often rely
on webhook-based integrations with third-party bots to bridge this gap. This limits execution
speed and introduces dependencies on external services.
3Commas is a commercial platform offering prebuilt trading bots, copy trading, and strategy
automation. It connects with major exchanges like Binance, KuCoin, and Coinbase. However, its
free tier is limited, and advanced features like trailing bots and multi-pair support come with a
subscription cost. Custom logic implementation is restricted to platform-supported strategies,
making it less flexible for developers or technical traders who want granular control.
Pionex is a crypto exchange that comes with built-in grid and DCA bots. While it eliminates
third-party dependencies, it offers minimal customization and supports only pre-defined
strategies. The platform is suitable for passive traders but is not designed for developers or users
who want to define and deploy custom technical indicators or exit logic like Supertrend reversal
or time-bound exits.
Manual trading via the Binance mobile or web app is still widely practiced. It gives users full
control over trades but demands constant attention, fast reactions, and strong discipline. Manual
trading is prone to errors, emotions, and missed opportunities, especially in fast-moving markets.
It also lacks automated risk controls, trade logs, or performance tracking.
Strategy Limited Moderate Requires coding Very Limited Full (Manual) Full (Supertrend + EMA)
Customization
Real-Time Web Interface Web Interface No direct control Limited Manual Telegram Bot Commands
Control
Deployment Cloud (Paid) Cloud (Paid) Depends on bot Built-in Local Device AWS EC2 t2.micro
Cost Subscription Subscription Varies Free Free Free/Open-source
Automation LevelHigh High Low to Medium High None Fully Automated
Technical Limited Set Limited Set Custom (Pine) None Manual Supertrend + EMA
Indicators
Risk ManagementBasic Basic External Logic Basic Manual Custom SL/TP + USDT
Risk
Trade Logging Partial Partial External Tools No Manual CSV Logging +
Summary
Remote No No No No No Yes (via Telegram)
Configuration
Research Gap
Despite the availability of various crypto trading automation tools, a significant gap exists in
solutions that offer full customizability, affordability, strategy-level transparency, and real-time
control. Many platforms are either commercial, limited in flexibility, or lack the ability to
program complex exit conditions and personalized risk models. Moreover, integration with
intuitive communication interfaces like Telegram is uncommon in open-source bots. This project
identifies and addresses those gaps by proposing a fully programmable, strategy-driven, real-
time controllable system hosted on the cloud. Below are specific areas where current research
and implementations fall short:
1. Lack of Real-Time Configurable Interfaces
Most existing bots require users to modify code or configuration files and restart the system to
apply changes. This process is not only inefficient but also impractical for real-time trading in
fast markets. There is a research gap in bots that support real-time configuration through
accessible platforms like Telegram, enabling users to adjust SL/TP, leverage, or risk exposure on
the fly. The proposed system addresses this by allowing dynamic updates through Telegram bot
commands, reducing downtime and manual intervention.
Platforms like 3Commas and Cryptohopper allow limited indicator combinations and rely on
GUI-based strategies or pre-defined templates. They do not support user-defined logic such as
combining Supertrend with dual EMA crossovers or incorporating time-based exit conditions.
This limits their usefulness for technically proficient users or researchers. The proposed bot fills
this gap by being fully programmable in Python, giving traders the ability to implement, test, and
deploy highly specific strategies without commercial constraints.
While many bots offer basic risk tools like stop-loss and take-profit, they often lack personalized
risk profiling per trade based on dynamic balance calculations. Most do not allow defining risk in
absolute USDT values, nor do they offer trade duration-based exits or reversal signal exits. This
creates a gap for users seeking sophisticated risk management frameworks. The proposed bot
introduces user-defined USDT risk per trade, fixed leverage, SL/TP percentages, and trade
timers—ensuring precise control over capital exposure.
Another major gap in existing solutions is the lack of transparent, exportable trade history logs.
Many bots display results on dashboards but do not maintain structured CSV logs for
independent analysis or audit. Researchers and advanced users require full visibility into the
bot’s decisions for debugging, backtesting, and reporting. The proposed system logs every trade
with key metrics like entry/exit time, price, PnL, duration, and exit reason—and provides a
Telegram command to export the entire trade history.
Platforms like TradingView allow signal generation through custom indicators but require
separate third-party services to execute trades via webhooks or APIs. This fragmented setup
introduces delays and risks in execution. There is a clear research gap in integrated bots that both
generate signals and execute trades within the same system. The proposed bot runs strategy
logic, monitors market data, and places orders instantly through the Binance API—all in one
unified, fully integrated Python system.
Despite the increasing availability of cloud computing services like AWS, most open-source bots
are still built for local deployment and are not optimized for lightweight, always-on cloud
execution. There is a lack of research into deploying cost-effective bots (e.g., on AWS EC2
t2.micro) that offer reliability, remote access, and continuous uptime. The proposed bot is
explicitly designed for this environment—running asynchronously with minimal resource usage
and full remote operability.
CHAPTER 3:
System Analysis
3.1 Introduction
This stage identifies the functional needs of the system, such as trade execution logic, risk
management, and Telegram-based control. It ensures that the bot meets user expectations for
automation, reliability, and configurability.
2. Feasibility Study
The project’s cloud-based model using AWS EC2 is examined for technical, operational, and
economic feasibility. It confirms that a t2.micro instance can support asynchronous trade logic
with low operational costs.
System analysis includes reviewing potential risks such as API key leakage, failed trade
execution, and downtime. Secure storage with .env files and proper exception handling are part
of the mitigation strategy.
The architecture is evaluated for future upgrades, such as long trade support, multi-user
management, and strategy expansion. The use of modular Python code supports long-term
scalability and easier maintenance.
Analysis Model
The analysis model outlines the logical flow and core components of the trading bot system. It
includes signal generation using Supertrend and EMA indicators, decision-making logic for short
trades, and integration with Binance Futures via API. It also incorporates Telegram command
handling, risk management configurations, and trade logging, ensuring a fully automated, event-
driven trading process.
1. Planning: In this phase, system requirements are gathered, objectives are set, and
constraints are identified. Detailed planning ensures the next stages are executed
effectively.
2. Risk Analysis: Possible risks such as technical challenges, cost overruns, or performance
issues are analyzed. Mitigation strategies are prepared, which makes this model
particularly effective for high-risk projects.
3. Engineering: This is the core development phase, where the actual coding, testing, and
implementation occur. Prototypes may be developed for user validation.
4. Evaluation: Stakeholders review the deliverables, provide feedback, and decide whether
to continue with the next spiral or revisit earlier phases.
Fig:3.2.1 SPIRAL MODEL
Advantages
● Beginner-friendly interfaces
Disadvantages
The proposed system is a fully automated Binance Futures trading bot deployed on AWS EC2. It
executes short trades based on Supertrend and EMA indicators, supports real-time Telegram
control, and offers dynamic risk management, trade logging, and cloud-based reliability—all
designed to simplify, secure, and optimize crypto trading.
2. Telegram-Based Control
Start, stop, and configure trades remotely via Telegram commands and menus.
The system is designed to provide secure, decentralized file storage and management with
blockchain-backed access control and auditability. The following functional requirements outline
the core capabilities grouped by system modules
1. File Management
● Batch Operations
Supports group actions such as deleting, downloading, or moving multiple files
simultaneously.
● Key Management
Encryption keys are generated client-side and stored securely by the user or via secure
key vaults.
● Algorithm Support
Allows switching between encryption standards (e.g., AES-256, RSA-2048) based on
user preference or file sensitivity.
● Decryption Logs
All decryption events are logged and stored on the blockchain for traceability and user
accountability.
3. Blockchain Integration
4. User Interface
5. Administrative Functions
● Analytics Dashboard
Admins get a visual overview of system usage: storage consumption,
uploads/downloads, active users, etc.
The non-functional requirements define the quality attributes of the system including its
performance, security, reliability, usability, and scalability. These attributes ensure the system
remains robust, secure, efficient, and user-friendly under varying operating conditions.
1. Performance
● The platform must support file upload and download speeds comparable to traditional
cloud services like Google Drive or Dropbox.
● The system must maintain real-time responsiveness even with up to 1,000 concurrent
users.
● It should be capable of processing and transferring files up to 1 GB efficiently without
timeouts or failure.
● The user interface (UI) must respond in less than 3 seconds under normal load conditions
to ensure seamless experience.
2. Security
● All data must be encrypted using AES-256, one of the most secure encryption standards.
● Users retain full control over encryption keys, with no server-side key storage unless
explicitly configured.
● The system must be hardened against the OWASP Top 10 security vulnerabilities,
including XSS, CSRF, and SQL injection.
3. Reliability
● The system aims for a 99.9% uptime SLA, ensuring high availability for end-users.
● Files are stored redundantly across multiple IPFS nodes to prevent data loss.
● A comprehensive backup and disaster recovery plan is in place for system resilience.
● The system must gracefully tolerate individual IPFS node or network failures without
impacting the end-user experience.
4. Usability
● The platform features a user-friendly dashboard that is intuitive and requires minimal
training.
● Accessibility support must comply with WCAG 2.1 AA standards for users with
disabilities.
5. Scalability
● The system supports horizontal scaling using containerized services (e.g., Docker,
Kubernetes).
● Load balancers are implemented to distribute traffic and maintain high system
availability during peak usage.
The User Interface Component is implemented using the Telegram Bot API, integrated via the
Python telethon library. It enables interactive communication with the user through command-
based and menu-driven inputs. Administrators can send commands such as /start, /stop, /balance,
and /set to manage the bot’s behavior. Inline keyboards are used to update strategy parameters
like SL, TP, and leverage without accessing the backend. This component ensures secure,
intuitive, and mobile-accessible control, making the bot user-friendly and easily manageable
from anywhere.
The mobile interface is delivered entirely via the Telegram app, providing seamless control over
the trading bot from any smartphone. It supports real-time commands, configuration, and
notifications. The mobile-first approach ensures high accessibility, low latency, and a user-
friendly experience without needing a dedicated app or web portal.
Key Features:
1. Real-Time Commands – Send /start, /stop, /balance, etc., instantly via mobile.
2. Inline Configuration – Adjust SL, TP, and leverage through tap-based menus.
3. Push Notifications – Get alerts for trade entries, exits, errors, and daily summaries.
4. Cross-Platform – Works on Android, iOS, and Telegram Desktop.
The Application Layer handles the business logic of the trading bot. It processes strategy rules,
validates trade signals using Supertrend and EMA, calculates risk-based position sizing, and
communicates with the Binance Futures API. It ensures that all trading decisions and actions
follow predefined logic with high precision and reliability.
The API Gateway Component acts as the central point for communication between the trading
bot and external services such as Binance Futures and Telegram. It handles all RESTful and
WebSocket API interactions, ensuring data is securely fetched, processed, and returned in real
time. This component enables seamless integration, isolation of business logic, and efficient
error handling across modules.
Key Functions:
1. Binance API Integration – Sends trade orders, retrieves market data, and monitors
account positions.
2. Telegram Command Handling – Listens to user inputs and routes commands to the
application layer.
3. Rate Limiting & Error Handling – Manages retries and Binance’s API rate limits.
4. Secure API Communication – Uses environment variables to protect sensitive
credentials.
5. Data Parsing and Forwarding – Converts raw API responses into usable formats for
trading logic.
The Authentication Component is responsible for verifying the identity of users interacting
with the bot and ensuring secure access to both the trading system and third-party APIs. Its
primary function is to protect the trading environment from unauthorized control, especially
since operations like placing orders, adjusting parameters, or accessing balances carry financial
risk.
In this system, authentication is enforced through Telegram User ID filtering. Only the
authorized admin (pre-configured in the .env file) can execute sensitive commands such as /start,
/stop, or /set. All other requests are ignored or flagged. For external APIs, Binance API and
Secret Keys are stored securely using the dotenv configuration, ensuring they’re not exposed in
the code.
Authentication Methods:
● Telegram User Validation: Allows command access only from approved Telegram ID.
● API Key Protection: Binance credentials are securely loaded from environment
variables.
The Business Logic Layer drives the decision-making engine of the bot. It interprets signals from
technical indicators, applies risk management rules, and determines trade actions like entry, exit,
and stop-loss handling, ensuring all trades align with the configured strategy logic.
The File Manager Component manages persistent data storage and retrieval within the bot. It
handles the creation, updating, and maintenance of trade logs in CSV format, recording key
metrics such as entry time, exit time, symbol, PnL, and trade duration. This component ensures
data integrity and enables users to retrieve past performance using Telegram commands like
/export, supporting analysis, auditing, and continuous improvement of trading strategies.
The Algo Service Component is the core logic engine responsible for processing live market
data and executing trades based on predefined technical strategies. It uses Supertrend and EMA
indicators to generate short-trade signals. Upon signal confirmation, it calculates position size
based on user-defined USDT risk, places orders, and applies SL/TP and time-based exits. It
continuously monitors market movements and manages active positions in real time, ensuring
every trade adheres to the configured strategy.
Key Functions:
1. Strategy Execution (Supertrend + EMA)
The Audit Service Component is responsible for maintaining transparency and accountability by
logging all trade activities and system events. It records critical actions such as order placements,
trade exits, configuration changes, errors, and warnings. These logs are stored in structured CSV
format for future review. This component ensures traceability, aids in debugging, and allows
users to assess bot performance and behavior over time with downloadable summaries via
Telegram commands.
The Data Layer manages all data interactions within the system, including reading market
prices, storing trade records, and retrieving configuration parameters. It ensures smooth data
flow between the strategy logic and storage components. This layer supports CSV-based logging
and secure handling of environment variables for sensitive API keys and user credentials.
3.5.5.1 Blockchain Network Component
1. Blockchain Integration
Integrates with public or private blockchains to store key trade data, enhancing trust and
traceability.
Deploys smart contracts to automate trading rules, validate execution conditions, and ensure
logic consistency independent of centralized servers.
3. Transaction Management
Handles the creation, signing, and submission of blockchain transactions to log system events or
trades, ensuring integrity and non-repudiation of data records.
This component enhances data integrity and supports future scalability in decentralized trading
environments
The proposed automated trading bot system is composed of multiple interdependent modules,
each designed to handle specific functions that contribute to the overall performance and
reliability of the bot. These modules work together to deliver seamless strategy execution, real-
time control, secure data handling, and efficient trade management. Every module is designed
with scalability, modularity, and reusability in mind, making the system robust and maintainable
for long-term use.
Key Modules:
3. Risk Management Module – Calculates SL, TP, leverage, and position size.
4. Order Execution Module – Interfaces with Binance API for placing/canceling orders.
5. Data Logging Module – Records trade data to CSV for analysis and export.
7. Audit and Security Module – Logs actions and protects API credentials.
SYSTEM SPECIFICATIONS
Functional requirements define the specific operations and tasks the system must perform to
fulfill user needs. These requirements are critical for guiding development and ensuring the bot
performs expected functions effectively. The proposed automated trading bot integrates real-time
market analysis, decision-making logic, and communication interfaces, offering users an
intelligent, responsive, and secure trading assistant.
Non-functional requirements define the quality attributes, system constraints, and performance
expectations of the trading bot. The system must ensure high availability, running 24/7 on an
AWS EC2 t2.micro instance with minimal resource usage. It should maintain security by using
environment variables to protect sensitive data such as API keys and user credentials. The bot
must be scalable and modular, allowing easy future upgrades. Reliability is critical—the bot
must handle API failures gracefully with proper error logging and retry logic. Additionally, the
system should be user-friendly, providing responsive, real-time Telegram feedback for all
operations and configuration changes
1. Availability
The bot must remain active 24/7 to respond to market movements at any time. It should be
continuously deployed on an AWS EC2 t2.micro instance, ensuring uninterrupted operation with
minimal downtime, even during low-resource availability periods.
2. Security
Sensitive credentials like Binance API keys and Telegram user IDs must be stored securely using
environment variables (.env files). Only authorized users should be able to access trading
features via Telegram, protecting the system from unauthorized control or financial loss.
3. Scalability
4. Reliability
The bot must execute trades and handle errors consistently. It should include retry mechanisms
for API timeouts or failures, and log any exceptions for debugging and reliability monitoring.
5. Usability
The Telegram-based interface must offer simple commands and real-time feedback. All critical
actions (e.g., /start, /stop, /set, /status) should return clear responses to guide the user without
technical confusion.
6. Performance Efficiency
The system should operate efficiently within the limited resources of a t2.micro instance. All
background processes, such as data fetching, trade monitoring, and logging, should be handled
asynchronously to ensure non-blocking performance.
7. Maintainability
Code should be clean, modular, and well-documented, allowing developers to quickly identify
and update specific modules (e.g., strategy logic, Telegram handlers, or logging functions)
without affecting the entire system.
4.3 Software Requirements
The software requirements define the necessary tools, libraries, and environments essential for
developing, deploying, and running the automated cryptocurrency trading bot system effectively.
These components ensure compatibility, stability, and optimal performance across different
modules of the bot.
1. Operating System
● Ubuntu 20.04 LTS (preferred for EC2 deployment) or any Linux-based OS.
2. Programming Language
● Python 3.10+
● Core development language used for all backend logic, Telegram interface, and API
integrations.
4. Development Environment
5. Deployment Platform
SYSTEM DESIGN
5.1 Introduction
System design is the blueprint that defines how the components of the automated trading bot
interact and function together. It converts the functional requirements into structured modules,
ensuring clarity, scalability, and maintainability. The trading bot is architected using a layered
design—separating presentation, business logic, application services, and data handling. This
modular approach enables clean communication between the Telegram interface, trading strategy
engine, risk control mechanisms, and Binance API interactions. System design also includes
diagrams such as data flow, sequence, and class models that illustrate how user commands,
market signals, and trade responses are processed and tracked through asynchronous event-
driven operations.
Although this trading bot does not use a traditional relational database (like MySQL or
PostgreSQL), it employs a lightweight file-based logging system (CSV) to persist trade data.
This design ensures portability, simplicity, and ease of access, especially when deployed on a
minimal-resource instance like AWS EC2 t2.micro.
The bot records all executed trades in a structured .csv file, allowing easy export, review, and
analysis. Typical columns include:
● Trade ID
● Symbol
● Entry Time
● Exit Time
● Entry Price
● Exit Price
● PNL (Profit/Loss)
● Leverage Used
● USDT Risked
This flat-file storage is efficient and human-readable, suitable for single-user bots.
System-level configurations such as API keys, leverage, SL/TP %, and allowed Telegram user
IDs are stored in a .env file using the python-dotenv library. Runtime adjustments (e.g., strategy
tuning) are temporarily stored in memory and updated via Telegram inline commands.
This hybrid approach balances security, simplicity, and customizability, ideal for a lightweight,
event-driven bot system.
Table 5.1: Audit Events
usedFor String Purpose of the key (API key storage, file encryption, etc.)
IMPLEMENTATION
System Security
System security refers to the protection of computing systems and the data they handle from
unauthorized access, modification, or destruction. It involves implementing layers of defenses
across hardware, software, networks, and user protocols. Strong system security ensures
confidentiality, integrity, and availability of information. Key practices include access control,
encryption, firewalls, regular updates, and monitoring. With rising cyber threats, securing
systems has become essential in all sectors. Proper policies, user awareness, and technical
safeguards collectively form the foundation of effective security measures.
Key Points
src/
├── bot/
├── core/
│ ├── trader.py # Main trade loop, symbol scanning, active trade logic
├── exchange/
├── config/
│ ├── settings.py # Load/save JSON config, update runtime parameters
├── utils/
6.6 Screenshots:
11. NIST. (2001). Advanced Encryption Standard (AES). FIPS Pub 197
Appendix A:
Config.json:
{
"binance": {
"api_key": "f101d2750f70be4894df3a013dd1fffebd4a0909735321b22214536497c1c556",
"api_secret": "84a3108200f1d7d43297365f8882f3f293eb721a193e823cb99bd3a8dbe5137f"
},
"selected_coins": [
"BTC/USDT",
"ETH/USDT",
"BNB/USDT",
"SOL/USDT",
"XRP/USDT"
],
"parameters": {
"atr": 10,
"multiplier": 3,
"ema1": 200,
"ema2": 365,
"tp": 0.5,
"sl": 0.5,
"exitmin": 2,
"use_exitmin": true,
"timeframe": "1m",
"margin_mode": "cross",
"leverage": 2
}
}
Appendix B:
import asyncio
import logging
import pandas as pd
import numpy as np
import platform
import json
# Configure logging
logging.basicConfig(
level=logging.INFO,
handlers=[logging.StreamHandler()],
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
TELEGRAM_TOKEN = "7992435639:AAGqtJphKPiVhQGYJqhj-kfPVK6-x0YCUMs"
CHAT_ID = "1151193863"
LEVERAGE = 2
def load_binance_config():
try:
with open('config.json', 'r') as f:
config = json.load(f)
return binance_config
except Exception as e:
binance_config = load_binance_config()
exchange = ccxt.binance({
'apiKey': binance_config['api_key'],
'secret': binance_config['api_secret'],
'enableRateLimit': True,
})
exchange.set_sandbox_mode(True)
application = Application.builder().token(TELEGRAM_TOKEN).build()
bot = application.bot
def load_config():
return json.load(f)
# Global variables
checked_symbols_state = {}
is_running = False
active_trade = None
valid_symbols = set()
trade_history = []
session_start_balance = 0.0
config = load_config()
multiplier = params.get("multiplier", 3)
stop_loss_pct = params.get("sl", 2)
exit_minutes = params.get("exitmin", 2)
margin_mode = "cross"
def init_from_config():
config = load_config()
multiplier = params.get("multiplier", 3)
stop_loss_pct = params.get("sl", 2)
exit_minutes = params.get("exitmin", 2)
def get_selected_coins():
config = load_config()
def save_config(config):
json.dump(config, f, indent=4)
def get_main_menu():
return InlineKeyboardMarkup([
[InlineKeyboardButton("
callback_data='stop_bot')],
✅ 🛑
Start Bot", callback_data='start_bot'), InlineKeyboardButton(" Stop Bot",
[InlineKeyboardButton("
callback_data='status')],
💰 Balance", callback_data='balance'), InlineKeyboardButton(" 📡 Status",
[InlineKeyboardButton("
callback_data='trades')],
⚙️ Config", callback_data='config'), InlineKeyboardButton(" 📊 Trades",
[InlineKeyboardButton("
callback_data='help')],
🔧 Settings", callback_data='settings'), InlineKeyboardButton("🆘 Help",
])
def get_config_menu():
config = load_config()
return InlineKeyboardMarkup([
def get_settings_menu():
config = load_config()
return InlineKeyboardMarkup([
[InlineKeyboardButton(f" ⏳
callback_data='set_use_exitmin')],
ExitMin: {'On' if params.get('use_exitmin', True) else 'Off'}",
])
def get_exitmin_menu():
return InlineKeyboardMarkup([
[InlineKeyboardButton("on", callback_data='set_exitmin_on'),
InlineKeyboardButton("off", callback_data='set_exitmin_off')],
])
def get_timeframe_menu():
return InlineKeyboardMarkup([
[InlineKeyboardButton("1m", callback_data='set_timeframe_1m'),
InlineKeyboardButton("15m", callback_data='set_timeframe_15m')],
[InlineKeyboardButton("30m", callback_data='set_timeframe_30m'),
InlineKeyboardButton("1h", callback_data='set_timeframe_1h')],
])
def get_leverage_menu():
return InlineKeyboardMarkup([
[InlineKeyboardButton("1x", callback_data='set_leverage_1'),
InlineKeyboardButton("2x", callback_data='set_leverage_2'),
InlineKeyboardButton("3x", callback_data='set_leverage_3'),
InlineKeyboardButton("4x", callback_data='set_leverage_4'),
InlineKeyboardButton("5x", callback_data='set_leverage_5')],
[InlineKeyboardButton("6x", callback_data='set_leverage_6'),
InlineKeyboardButton("7x", callback_data='set_leverage_7'),
InlineKeyboardButton("8x", callback_data='set_leverage_8'),
InlineKeyboardButton("9x", callback_data='set_leverage_9'),
InlineKeyboardButton("10x", callback_data='set_leverage_10')],
])
if update.message.text == "/menu":
elif update.message.text not in ["/start", "/stop", "/balance", "/status", "/showconfig", "/set", "/help"]:
else:
query = update.callback_query
await query.answer()
data = query.data
if data == 'start_bot':
new_markup = get_config_menu()
new_markup = get_settings_menu()
elif data.startswith('set_'):
config = load_config()
if param == 'use_exitmin':
params['use_exitmin'] = True
config['parameters'] = params
save_config(config)
global use_exitmin
use_exitmin = True
params['use_exitmin'] = False
config['parameters'] = params
save_config(config)
use_exitmin = False
amount = float(pos['contracts'])
await send_signal(f" 🔔 Closed short position for {active_trade}: {amount} contracts on bot stop")
else:
except Exception as e:
active_trade = None
stop_message = f"""
🚫 BOT DEACTIVATED 🚫
📊 Session Report:
└─ Trades: {len(trade_history)}
⚙️ Leverage: {LEVERAGE}x
📅 Date: {datetime.now().strftime("%Y-%m-%d")}
"""
await reset_global_states()
if update.callback_query:
query = update.callback_query
else:
await send_signal(stop_message)
logging.info("Bot stopped.")
else:
if update.callback_query:
else:
try:
await sync_time()
message = f"""
💰 ACCOUNT STATUS 💰
📈 Current Balance:
├─ USDT: {usdt_balance:.2f}
⚙️ Settings:
├─ Timeframe: {timeframe}
├─ Leverage: {LEVERAGE}x
├─ Take-Profit: {take_profit_pct}%
└─ Stop-Loss: {stop_loss_pct}%
📊 Open Positions:
📅 Date: {datetime.now().strftime("%Y-%m-%d")}
"""
if update.callback_query:
query = update.callback_query
else:
except ccxt.AuthenticationError as e:
if update.callback_query:
query = update.callback_query
else:
except Exception as e:
message = "Sorry, I couldn't fetch your balance at the moment. Please check your API credentials."
if update.callback_query:
query = update.callback_query
else:
status_message = f"""
⏰ Timeframe: {timeframe}
📅 Date: {datetime.now().strftime("%Y-%m-%d")}
"""
if update.callback_query:
query = update.callback_query
"""
if update.callback_query:
query = update.callback_query
else:
checked_symbols_state = {}
active_trade = None
is_running = False
def has_active_trade():
global active_trade
try:
await sync_time()
if not ohlcv:
raise ValueError(f"No data returned for {symbol}")
return df
except Exception as e:
await asyncio.sleep(retry_delay)
else:
return pd.DataFrame()
alpha = 2 / (length + 1)
ema = prices.copy()
ema[:smoothing_period] = initial_sma[:smoothing_period]
except Exception as e:
try:
await sync_time()
await exchange.set_margin_mode('cross', symbol)
max_retries = 3
retry_delay = 1
try:
adjusted_amount = round(amount, 3)
return order
except ccxt.BaseError as e:
await send_signal(f" ❌ Margin insufficient for {symbol}, reducing position size and retrying...")
await asyncio.sleep(retry_delay)
continue
logging.warning(f"
1}/{max_retries}). Retrying...")
❗ PERCENT_PRICE filter error for {symbol} (attempt {attempt +
await asyncio.sleep(retry_delay)
continue
else:
raise e
try:
if best_bid:
limit_price = best_bid * 0.999
adjusted_amount = round(amount, 3)
return order
else:
return None
return None
except Exception as e:
return None
try:
await sync_time()
return order
except Exception as e:
return None
try:
await sync_time()
balance = await exchange.fetch_balance()
except ccxt.AuthenticationError as e:
raise
except Exception as e:
await asyncio.sleep(delay)
else:
return 0.0
trade_start_time = datetime.now(timezone.utc)
try:
current_price = ticker['last']
open_position = None
await asyncio.sleep(wait_time)
global valid_symbols
try:
await sync_time()
valid_symbols = set(markets.keys())
config = load_config()
config['selected_coins'] = selected_coins
save_config(config)
except Exception as e:
valid_symbols = set(get_selected_coins())
try:
await load_valid_symbols()
while True:
if is_running:
await wait_for_next_candle()
if has_active_trade():
finally:
await exchange.close()
await application.updater.stop()
await application.stop()
await application.shutdown()
logging.info("Bot resources cleaned up.")
if __name__ == "__main__":
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(start())
except Exception as e: