0% found this document useful (0 votes)
204 views86 pages

Building An Algorithmic Trading Bot With Binance and Telegram Integration

This project outlines the development of an automated cryptocurrency trading bot for Binance Futures, utilizing AWS EC2 for continuous operation and Python for implementation. The bot employs technical indicators like Supertrend and EMAs to identify short-position trading opportunities, while integrating with Telegram for real-time user control and configuration. Key features include automated trade execution, risk management, and detailed logging, aimed at enhancing trading efficiency and minimizing emotional biases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
204 views86 pages

Building An Algorithmic Trading Bot With Binance and Telegram Integration

This project outlines the development of an automated cryptocurrency trading bot for Binance Futures, utilizing AWS EC2 for continuous operation and Python for implementation. The bot employs technical indicators like Supertrend and EMAs to identify short-position trading opportunities, while integrating with Telegram for real-time user control and configuration. Key features include automated trade execution, risk management, and detailed logging, aimed at enhancing trading efficiency and minimizing emotional biases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

ABSTRACT:

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.

Keywords: Cryptocurrency, Automation, Trading, Binance, Futures, Python, Bot, Telegram,


Supertrend, Blockchain
TABLE OF CONTENTS

Chapter/Section Title Page No.


Chapter 1 Introduction
1.1 Overview 6
1.2 Technology Stack 7
1.3 Key Features 8
1.4 Problem Statement 11
1.5 Proposed Solution 13
1.6 Objectives 16
1.7 Scope of the Project 18
Chapter 2 Scope of the Project
2.1 Existing Solutions 20
2.2 Comparative 22
Analysis
2.3 Research Gap 24
Chapter 3 System Analysis
3.1 Introduction 27
3.2 Analysis Model & 28
Spiral Model
3.3 Existing System 30
Analysis
3.4 Proposed System 31
3.4.1 System Overview 31
3.4.2 Functional 32
Requirements
3.4.3 Non-Functional 34
Requirements
3.5 System Architecture 36
Architectural
Overview
3.5.2 Presentation Layer 37
3.5.3 Application Layer 39
3.5.4 Business Logic 41
Layer
3.5.5 Data Layer 43
3.6 Module Description 45
Chapter 4 System
Specifications
4.1 Functional 47
Requirement
4.2 Non-Functional 49
Requirements
4.3 Software 51
Requirements
Chapter 5 System Design
5.1 Introduction 53
5.2 Database Design 54
(CSV + .env)
5.3 Diagrams (Entity, 56
Sequence, Class)
Chapter 6 Implementation
6.1 System Security 58
6.2 Implementation 59
Architecture
6.3 Project Directory 60
Structure
6.4 Telegram Command 61
Handling
6.5 Screenshots 63
References 65
LIST OF FIGURES
Fig 3.1: Spiral Model

Fig 3.2: System Architecture Overview

Fig 3.4.1: Data Flow Architecture

Fig 5.1: Entity-Relationship Diagram

Fig 5.2: Use Case Diagram

Fig 5.3: Sequence Diagram - File Upload Flow

Fig 5.4: Sequence Diagram - File Retrieval Flow

Fig 5.5: Class Diagram

Fig 5.6: Activity Diagram

Fig 5.7: Collaboration Diagram

LIST OF TABLES
TABLE 5.1: Database Design Format for File Storage

TABLE 5.2: Database Design Format for User Preferences

TABLE 5.3: Database Design Format for Encryption Metadata

TABLE 5.4: Database Design Format for Sequence Diagrams

TABLE 5.5: Database Design Format for class diagram

TABLE 6.1:Implementation Architecture

TABLE 6.2: Security Test Results

LIST OF ABBREVIATIONS
API - Application Programming Interface

IPFS – InterPlanetary File System

DApp - Decentralized Application

Web3 - Decentralized Web

ERC-721 - Ethereum Request for Comments 721

AES - Advanced Encryption Standard

GCM - Galois/Counter Mode

CID - Content Identifier

UI - User Interface

UX - User Experience

JSON - JavaScript Object Notation

CORS - Cross-Origin Resource Sharing

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.

1.2 Technology Stack


The application employs a modern technology stack designed for scalability, security and user
experience

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.

● Symbol Management: Handles multiple crypto pairs traded on Binance’s blockchain-


backed futures market.

Storage & Security:


The bot ensures secure, persistent configuration and safe interaction with exchange APIs:

● 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.

1.3 Key Features


This automated Binance Futures trading bot integrates advanced trading strategies with real-time
control via Telegram and reliable deployment on AWS cloud infrastructure. Designed to
simplify and optimize cryptocurrency trading, it minimizes emotional bias, executes trades with
speed and precision, and supports comprehensive risk management. The bot is built using Python
with libraries like `ccxt` for Binance integration and `telethon` for Telegram automation. Below
are the standout features that make this system efficient, responsive, and user-friendly.

1. Automated Signal-Based Trading

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.

2. Real-Time Telegram Control Interface

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.

4. Safe and Secure API Key Management

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.

5. Smart Exit Mechanisms

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.

7. Detailed Trade Logging and Summary Reporting

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.

1.4 Problem Statement

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.

1. Lack of 24x7 Monitoring

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.

2. Emotion-Driven Decision Making

Human emotions—fear, greed, impatience—significantly impact trading decisions. Traders may


exit trades early due to fear or hold onto losses hoping for a reversal. Emotional reactions often
override predefined strategies, resulting in inconsistent outcomes. Emotional trading is one of the
leading causes of failure in retail trading. An automated bot follows logic without bias, adhering
strictly to risk parameters like stop-loss and take-profit. This ensures discipline, consistency, and
risk-controlled execution of trades, regardless of market pressure.
3. Delayed Order Execution

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.

5. Risk Management Challenges

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.

7. No Trade Tracking or Logging

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.

1.5 Proposed Solution

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.

1. Fully Automated Trade Execution

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.

2. 24x7 Operation on AWS EC2

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.

3. Emotionless, Rule-Based Trading


By enforcing a strict logic-based strategy, the bot eliminates emotional trading decisions. It does
not panic during dips or hesitate during spikes. It operates purely based on coded logic,
executing trades only when the entry conditions are fully met and exiting based on stop-loss,
take-profit, or strategy-defined reversal. This approach ensures psychological neutrality and
consistency, both of which are essential for long-term profitability in trading. Rule-based
execution also makes the system more predictable and easier to analyze and improve over time.

4. Integrated Telegram Interface

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.

5. Dynamic Risk Management

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.

7. Trade Logging and Reporting

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.

1. Automate Short-Position Trading

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.

2. Provide Real-Time Remote Control via Telegram

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.

3. Implement Configurable Risk Management

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.

4. Enable 24x7 Cloud-Based Trading

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.

5. Ensure Transparent Performance Logging

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.

1.7 Scope of the Project

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.

Key deliverables within the scope include:

● Integration with Binance Futures via the `ccxt` Python library


● Signal generation using EMA crossover and Supertrend indicators
● Automated entry and exit for short trades with TP/SL/duration logic
● Telegram bot integration using `telethon` for real-time control and alerts
● Logging and export of trade activity for reporting and performance tracking
● Deployment and testing on AWS EC2 t2.micro instance

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.

1. TradingView – Strategy Visualization and Alerts

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.

2. 3Commas – Commercial Trading Automation

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.

3. Cryptohopper – Cloud-Based Bot Builder


Cryptohopper is another popular cloud-based trading bot platform that offers template-driven
automation and marketplace signals. It features backtesting tools, strategy designers, and
integration with TradingView alerts. Although beginner-friendly, it lacks true programmability
and depends heavily on graphical UI and paid templates. Complex strategies using multi-
indicator logic or time-based exits are not easily supported.

4. Pionex – Exchange with Built-In Bots

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.

5. Binance App / Manual Trading

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.

2.2 Comparative Analysis


With the rising interest in algorithmic cryptocurrency trading, multiple platforms have emerged
offering automated bots and strategy integrations. Tools like 3Commas, Cryptohopper, and
TradingView have enabled semi-automation, but most fall short in offering full customizability,
cost efficiency, or truly hands-free control. These platforms often limit deep strategy control or
require subscription fees, making them less ideal for technical users seeking advanced, indicator-
driven automation. In contrast, the proposed system is an open, fully customizable, cloud-hosted
trading bot with Telegram integration, designed specifically for short-position trades using
technical strategies. Below is a comparative analysis with the most popular alternatives.

Feature / 3Commas Cryptohopper TradingView + Pionex Manual Trading Proposed System


Platform Bot

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

Key Differences of the Proposed System


● End-to-End Automation Based on Custom Strategy
Unlike template-based platforms, this bot executes trades using a fully custom Supertrend
+ EMA strategy, ensuring true indicator-level control over entries and exits.

● Full Telegram Integration for Remote Access


The bot can be controlled and configured entirely via Telegram commands and
interactive menus—eliminating the need to access the server directly.

● Cloud Deployment on Free-Tier AWS EC2


Hosted on a t2.micro EC2 instance, the bot is cost-effective and capable of 24x7 trading
without relying on paid third-party platforms.

● No Subscription or Licensing Cost


The system is developed using open-source libraries and runs independently, making it
accessible to developers and traders without recurring fees.

● Dynamic Risk Control and Smart Exit Management


Users can define SL/TP percentages, trade durations, and USDT risk per trade, which the
bot applies dynamically to each position.

● Trade Transparency and Reporting


All trades are logged in a CSV file with timestamps, profit/loss, and duration, and can be
exported via Telegram for review or audit purposes.

● Lightweight, Modular, and Developer-Friendly


The bot is coded in Python using modular architecture, making it easy to extend, debug,
or adapt to different strategies and trading pairs.

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.

2. Limited Strategy Customization in Commercial Platforms

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.

3. Inadequate Risk Management Customization

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.

4. Absence of Transparent Logging and Exportable Performance Data

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.

5. Fragmented Signal-to-Execution Workflow

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.

6. Underutilization of Cloud Resources for Personal Bots

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

System analysis involves evaluating the requirements, limitations, and opportunities of a


proposed solution. It helps identify how the automated trading bot can improve efficiency,
eliminate manual errors, and ensure reliable performance. The analysis focuses on both technical
and functional aspects of the system to ensure robust architecture and strategy implementation.
1. Requirement Evaluation

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.

3. Risk and Security Assessment

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.

4. Scalability and Maintainability

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.

Spiral Model Phases

The Spiral Model is a progressive, risk-oriented software development methodology that


combines elements of both design and prototyping. It is ideal for complex and high-risk projects
where requirements may evolve over time. The model is structured into four key phases that are
repeated in iterations or “spirals” to gradually build the final product.

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

3.3 Existing System Analysis

The existing system of manual or semi-automated cryptocurrency trading relies heavily on


human decision-making, third-party tools, or paid platforms like 3Commas and Cryptohopper.
While they offer basic automation, they lack full strategy customization, real-time control, and
transparent trade management. Users often depend on multiple tools for signal generation and
execution, leading to delays and inefficiencies.

Advantages
● Beginner-friendly interfaces

● Access to ready-made bots and templates

● Some platforms offer 24/7 automation

Disadvantages

● Limited customization and flexibility

● Expensive subscription fees

● Lack of real-time, remote configurability

● No transparent trade logs or personalized risk control

3.4 proposed system

3.4.1 System Overview

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.

Key Features of Proposed System


1. Automated Strategy Execution
Executes short trades using EMA and Supertrend logic without manual intervention.

2. Telegram-Based Control
Start, stop, and configure trades remotely via Telegram commands and menus.

3. Cloud Deployment on AWS EC2


Runs 24x7 on a lightweight, low-cost EC2 t2.micro instance.

4. Custom Risk Management


Supports SL, TP, leverage, and USDT-based position sizing.

5. Trade Logging and Reporting


Maintains detailed CSV logs and sends performance summaries to Telegram.

3.4.2 Functional Requirements

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

● Secure File Upload & Decentralized Storage


Users must be able to upload files securely; files are stored on a decentralized backend
(e.g., IPFS, Sia).

● File Categorization and Tagging


Files can be organized using tags, folders, or metadata fields for efficient retrieval.
● Version Control & History Tracking
Every file upload creates a version entry. Users can view and restore previous versions.

● Batch Operations
Supports group actions such as deleting, downloading, or moving multiple files
simultaneously.

2. Security and Encryption

● Client-Side End-to-End Encryption


Files are encrypted in the browser before upload using AES-256 or RSA, preventing
server-side decryption.

● 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

● Smart Contracts for Access Control


Smart contracts enforce file access policies such as time locks, user permissions, and
access frequency limits.
● Immutable Metadata Storage
Every file upload includes hashed metadata (filename, owner, timestamp) written
immutably to the blockchain.

● On-Chain Audit Trail


All file access, uploads, deletions, and key events are logged on-chain for transparent
auditing.

● NFT Ownership Representation


Each file can be minted as an NFT to represent digital ownership and enable file
monetization or transfer.

4. User Interface

● Responsive Cross-Platform Web App


A sleek, modern interface built with React/Vue that adapts to desktop and mobile
devices.

● Dashboard and File Manager


Centralized view to upload, search, tag, and track files with real-time activity insights.

● File Preview and Sharing


Secure file preview (e.g., PDFs, images) in-browser and sharing via secure, expiring
links.

● Customizable Profile Settings


Users can manage credentials, themes, notifications, and storage preferences from their
account.

5. Administrative Functions
● Analytics Dashboard
Admins get a visual overview of system usage: storage consumption,
uploads/downloads, active users, etc.

● Role-Based User Management


Different roles (admin, auditor, user) with permissions to manage access, audit, or
maintain the platform.

● Real-Time Audit Logs and Alerts


View and export logs for all user activities with alerts for suspicious actions (e.g., brute-
force, rapid deletions).

● Performance and Debug Tools


Admin tools to monitor backend performance, run diagnostics, and optimize system
components in real-time.

3.4.3 Non-Functional Requirements

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.

● Regular third-party security audits and penetration testing should be conducted to


maintain ongoing platform integrity.

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.

● The interface will support multi-language localization for global accessibility.

● The system must maintain a mobile-responsive design, ensuring full functionality on


smartphones and tablets.

5. Scalability

● The system supports horizontal scaling using containerized services (e.g., Docker,
Kubernetes).

● An auto-scaling infrastructure will dynamically allocate resources based on real-time user


load.

● All operations are optimized with asynchronous processing to reduce bottlenecks.

● Load balancers are implemented to distribute traffic and maintain high system
availability during peak usage.

3.5 System Architecture

3.5.1 Architectural Overview

The system architecture is designed around modular, asynchronous Python components. It


integrates Binance Futures API for trading, Telethon for Telegram communication, and runs
continuously on an AWS EC2 t2.micro instance. The architecture supports real-time trade
execution, remote control, dynamic configuration, and persistent trade logging, ensuring a
reliable, scalable, and fully automated crypto trading environment.

Figure 3.5.1: Comprehensive System Architecture Diagram

3.5.2 Presentation Layer


The Presentation Layer serves as the communication bridge between the user and the trading
system. It utilizes Telegram as the user-facing interface, allowing commands and responses in
real time. Through simple messages and inline buttons, users can start, stop, and configure the
bot remotely with ease and convenience.

3.5.2.1 User Interface Component

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.

3.5.2.2 Mobile Interface Component

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.

5. Low Data Usage – Operates efficiently even on limited internet connections.

6. Secure Access – Restricted to admin Telegram ID to prevent unauthorized usage

3.5.3 Application Layer

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.

3.5.3.1 API Gateway Component

Purpose and Functionality

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.

3.5.3.2 Authentication Component

Purpose and Functionality

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.

● Access Isolation: No open APIs or web access—everything routes through private


Telegram control.
● Command Whitelisting: Only predefined commands are accepted, reducing attack
vectors.

3.5.4 Business Logic Layer

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.

3.5.4.1 File Manager Component

Purpose and Functionality

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.

3.5.4.2 Algo Service Component

Purpose and Functionality

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)

2. Live Market Monitoring

3. Short Position Detection

4. Position Sizing Based on Risk

5. Stop-Loss and Take-Profit Management

6. Timed Exit Execution

7. Trend Reversal Detection

8. Trade Validation and Logging

3.5.4.3 Audit Service Component

Purpose and Functionality

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.

3.5.5 Data Layer

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

Purpose and Functionality

The Blockchain Network Component (optional/future-ready) is designed to enhance the


system’s transparency, security, and auditability by leveraging decentralized ledger technology.
It enables logging of critical trade actions and configurations on a blockchain, ensuring tamper-
proof records and verifiable trade history.

1. Blockchain Integration

Integrates with public or private blockchains to store key trade data, enhancing trust and
traceability.

2. Smart Contract Management

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.

3.5.5.2 IPFS Storage Component

Purpose and Functionality

The IPFS (InterPlanetary File System) Storage Component is designed to provide


decentralized, tamper-proof storage for trade logs, configuration snapshots, and audit records. It
ensures long-term availability and immutability of critical files by distributing them across a
peer-to-peer network.
Key Functions:

1. Decentralized File Storage

2. Tamper-Proof Trade Logs

3. Snapshot Backup of Configurations

4. Redundancy and High Availability

5. Immutable Record Keeping

6. Hash-Based File Retrieval

7. Reduced Central Server Dependency

This component enhances data integrity and supports future scalability in decentralized trading
environments

3.6 Module Description

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:

1. Telegram Interface Module – Handles user commands and configuration inputs.

2. Strategy Engine Module – Executes Supertrend + EMA-based trade logic.

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.

6. Configuration Module – Manages and applies user-defined strategy settings.

7. Audit and Security Module – Logs actions and protects API credentials.

8. Scheduler Module – Monitors time-based exits and daily reporting.


CHAPTER 4

SYSTEM SPECIFICATIONS

4.1 Functional Requirements

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.

Key Functional Requirements:

1. User Authentication via Telegram


Only authorized Telegram user IDs can control or configure the bot, ensuring secure
access to critical operations.

2. Start/Stop Command Handling


The bot must respond to /start and /stop commands to toggle trading operations in real
time without restarting the application.

3. Trading Signal Detection


The system should evaluate real-time market data using Supertrend and EMA indicators
to detect valid short-entry signals.

4. Trade Execution via Binance API


Upon signal confirmation, the bot should calculate order quantity and place short trades
with defined SL and TP using Binance Futures API.

5. Dynamic Risk Configuration


Users must be able to configure leverage, SL/TP percentage, and USDT risk
dynamically using Telegram commands.

6. Real-Time Trade Monitoring


The system should track open positions, close trades based on conditions (e.g.,
SL/TP/time), and log outcomes.

7. Trade Logging and Exporting


All trade activities must be logged in a structured CSV file, which can be exported via
the /export command

4.2 Non-Functional Requirements

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

The system architecture should be modular, allowing additional strategies, multi-symbol


tracking, or user extensions in the future without overhauling core functionality. This ensures
long-term adaptability as user needs evolve or trading complexity increases.

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.

● Lightweight and efficient, suitable for 24x7 cloud operation.

2. Programming Language

● Python 3.10+

● Core development language used for all backend logic, Telegram interface, and API
integrations.

3. Required Python Libraries

● ccxt – To interact with Binance Futures API.

● telethon – For Telegram Bot integration.

● asyncio – For asynchronous, non-blocking operations.

● python-dotenv – To load API keys and secure environment variables.


● pandas – For structured data handling and trade logs.

● logging – For event logging and debugging.

4. Development Environment

● Visual Studio Code / PyCharm (optional for development)

● Jupyter Notebook (optional for strategy testing)

5. Deployment Platform

● Amazon Web Services (AWS) EC2 – t2.micro instance

● Provides low-cost, reliable, always-on hosting for bot execution


CHAPTER 5

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.

5.2 Database Design

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.

a) Trade Log Structure (CSV File)

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

● Trade Duration (mins)

● PNL (Profit/Loss)

● Leverage Used

● USDT Risked

This flat-file storage is efficient and human-readable, suitable for single-user bots.

b) Configuration Storage (.env and Runtime Variables)

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

Field Type Description

id String Unique identifier for the audit event

type String Type of event (trade_start, trade_exit, config_update, etc.)

userId String Telegram user ID initiating the event

timestam String Timestamp of the event in ISO 8601 format


p

status String Status of the event (success, error, warning)

message String Description or context of the action

tradeId String Reference to associated trade log (if applicable)

ipAddress String IP address or origin identifier (optional for Telegram)


Table 5.2: User Preferences

Field Type Description

userId String Telegram user ID of the admin or user

leverage Number Default leverage configured by the user

usdtRiskPerTrade Number USDT amount to risk per trade

stopLossPercent Number Stop-loss percentage set by the user

takeProfitPercent Number Take-profit percentage set by the user

emaPeriod Number Period for EMA calculation in the strategy

atrMultiplier Number ATR multiplier used in Supertrend calculation

trailingStop Boolean Whether trailing stop is enabled or disabled

lastUpdated String Timestamp of the last update to preferences


Table 5.3: Encryption Metadata

Field Type Description

keyId String Unique ID of the encryption key

algorithm String Encryption algorithm used (e.g., AES-256, RSA)

createdOn String Timestamp when the key was generated

usedFor String Purpose of the key (API key storage, file encryption, etc.)

status String Status of the key (active, revoked, expired)

owner String Component or module that owns or manages this key

checksum String Hash or fingerprint of the key for verification


Fig:5.1 Entity-Relationship Diagram
5.4 Sequence Diagrams
5.5 class diagram
Chapter 6.1

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

● Ensures confidentiality, integrity, and availability of data.

● Implements access control to restrict unauthorized users.

● Uses encryption to protect data in transit and at rest.

● Employs firewalls and antivirus for threat detection and prevention.

● Relies on regular software updates to patch vulnerabilities.

● Incorporates audit trails and monitoring for suspicious activity.

● Requires user training to prevent social engineering attacks.

6.1 Implementation Architecture


The application is designed using an asynchronous architecture with a focus on modular
responsibilities, separating Telegram bot logic, Binance API interactions, strategy processing,
configuration management, and utility helpers into organized layers.

src/

├── bot/

│ ├── handlers.py # Telegram command & callback handlers

│ ├── interface.py # Telegram bot setup and messaging functions

│ └── menu.py # Inline keyboard UI and menus

├── core/

│ ├── trader.py # Main trade loop, symbol scanning, active trade logic

│ ├── strategy.py # Supertrend, EMA calculations and entry/exit conditions

│ ├── risk.py # Trade sizing, margin, and leverage calculations

│ └── logger.py # Trade history and audit logging

├── exchange/

│ ├── binance_api.py # ccxt Binance Futures integration

│ ├── orders.py # Market/limit order execution logic

│ └── balance.py # Balance checking and position management

├── config/
│ ├── settings.py # Load/save JSON config, update runtime parameters

│ └── symbols.py # Selected symbols and validation

├── utils/

│ ├── time.py # Time sync, UTC/IST conversion

│ └── errors.py # Error handling and retry mechanisms

6.6 Screenshots:

Figure 6.1:CMD logs


Figure 6.2:Telegram dashboard

Figure 6.3:Telegram take trade


Figure 6.4:Telegram trade close
Figure 6.5:Telegram Bot control Menu

Figure 6.6:Binance trading Dashboard


References

1. Nakamoto, S. (2008). Bitcoin: A Peer-to-Peer Electronic Cash System.


https://bitcoin.org/bitcoin.pdf

2. Wood, G. (2014). Ethereum: A Secure Decentralised Generalised Transaction Ledger.


Ethereum Yellow Paper

3. Buterin, V. (2017). Ethereum White Paper: A Next-Generation Smart Contract and


Decentralized Application Platform. https://ethereum.org/en/whitepaper/

4. Binance. (2023). Binance Futures API Documentation. https://binance-


docs.github.io/apidocs/futures/en/

5. CCXT. (2023). CCXT Crypto Trading Library Documentation. https://docs.ccxt.com/

6. Python Software Foundation. (2023). Asyncio — Asynchronous I/O.


https://docs.python.org/3/library/asyncio.html

7. Telegram. (2023). Telegram Bot API Documentation.


https://core.telegram.org/bots/api

8. Pandas Development Team. (2023). Pandas Documentation.


https://pandas.pydata.org/docs/

9. Numpy Developers. (2023). NumPy Reference Documentation.


https://numpy.org/doc/

10. Mozilla Developer Network. (2023). Web Crypto API Documentation.


https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API

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 ccxt.async_support as ccxt

from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup

import platform

import json

from datetime import datetime, timedelta, timezone

from telegram.ext import CallbackContext, Application, CommandHandler, CallbackQueryHandler,


MessageHandler, filters

from telegram.error import BadRequest, TimedOut

# Configure logging

logging.basicConfig(

format="%(asctime)s - %(levelname)s - %(message)s",

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)

binance_config = config.get('binance', {})

if not binance_config.get('api_key') or not binance_config.get('api_secret'):

raise ValueError("Missing api_key or api_secret in config.json")

return binance_config

except Exception as e:

logging.error(f"Error loading config: {e}")

return {'api_key': '', 'api_secret': ''}

binance_config = load_binance_config()

exchange = ccxt.binance({

'apiKey': binance_config['api_key'],

'secret': binance_config['api_secret'],

'enableRateLimit': True,

'options': {'defaultType': 'future'}

})

exchange.set_sandbox_mode(True)

application = Application.builder().token(TELEGRAM_TOKEN).build()

bot = application.bot

def load_config():

with open('config.json', 'r') as f:

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()

params = config.get("parameters", {})

atr_period = params.get("atr", 10)

multiplier = params.get("multiplier", 3)

ema_period1 = params.get("ema1", 21)

ema_period2 = params.get("ema2", 60)

ema_period3 = params.get("ema3", 365)

take_profit_pct = params.get("tp", 0.5)

stop_loss_pct = params.get("sl", 2)

exit_minutes = params.get("exitmin", 2)

use_exitmin = params.get("use_exitmin", True)

timeframe = params.get("timeframe", "1m")

margin_mode = "cross"

def init_from_config():

global atr_period, multiplier, ema_period1, ema_period2, ema_period3, take_profit_pct, stop_loss_pct,


exit_minutes, use_exitmin, timeframe

config = load_config()

params = config.get("parameters", {})

atr_period = params.get("atr", 10)

multiplier = params.get("multiplier", 3)

ema_period1 = params.get("ema1", 21)

ema_period2 = params.get("ema2", 60)

ema_period3 = params.get("ema3", 365)

take_profit_pct = params.get("tp", 0.5)

stop_loss_pct = params.get("sl", 2)

exit_minutes = params.get("exitmin", 2)

use_exitmin = params.get("use_exitmin", True)


timeframe = params.get("timeframe", "1m")

def get_selected_coins():

config = load_config()

return config.get("selected_coins", [])

def save_config(config):

with open('config.json', 'w') as f:

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()

params = config.get("parameters", {})

return InlineKeyboardMarkup([

[InlineKeyboardButton(f"EMA1: {params.get('ema1', 21)}", callback_data='set_ema1'),

InlineKeyboardButton(f"EMA2: {params.get('ema2', 60)}", callback_data='set_ema2')],

[InlineKeyboardButton(f"ATR: {params.get('atr', 10)}", callback_data='set_atr'),

InlineKeyboardButton(f"Multiplier: {params.get('multiplier', 3)}", callback_data='set_multiplier')],

[InlineKeyboardButton(f"Max Duration: {params.get('exitmin', 2)}m", callback_data='set_max_duration'),

InlineKeyboardButton(f"Leverage: {LEVERAGE}x", callback_data='set_leverage')],

[InlineKeyboardButton(" 🔄 Refresh", callback_data='config'),

InlineKeyboardButton(" ⬅️ Back", callback_data='menu')],


])

def get_settings_menu():

config = load_config()

params = config.get("parameters", {})

return InlineKeyboardMarkup([

[InlineKeyboardButton(f" ⏳
callback_data='set_use_exitmin')],
ExitMin: {'On' if params.get('use_exitmin', True) else 'Off'}",

[InlineKeyboardButton(f" ⏰ Timeframe: {params.get('timeframe', '1m')}", callback_data='set_timeframe')],

[InlineKeyboardButton(" ⬅️ Back to Config", callback_data='menu')],

])

def get_exitmin_menu():

return InlineKeyboardMarkup([

[InlineKeyboardButton("on", callback_data='set_exitmin_on'),

InlineKeyboardButton("off", callback_data='set_exitmin_off')],

[InlineKeyboardButton(" ⬅️ Back to Config", callback_data='menu')],

])

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')],

[InlineKeyboardButton(" ⬅️ Back to Settings", callback_data='settings')],

])

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')],

[InlineKeyboardButton(" ⬅️ Back to Config", callback_data='config')],

])

async def handle_message(update: Update, context: CallbackContext):

if update.message and update.message.chat and str(update.message.chat.id) == CHAT_ID:

if update.message.text == "/menu":

await update.message.reply_text("Main Menu:", reply_markup=get_main_menu())

elif update.message.text not in ["/start", "/stop", "/balance", "/status", "/showconfig", "/set", "/help"]:

await update.message.reply_text("Unknown command! Use the menu below:",


reply_markup=get_main_menu())

else:

logging.warning(f"Unauthorized access attempt from chat ID: {update.message.chat.id}")

async def handle_callback(update: Update, context: CallbackContext):

query = update.callback_query

await query.answer()

data = query.data

if data == 'start_bot':

await start_bot(update, context)

elif data == 'stop_bot':

await stop_bot(update, context)

elif data == 'balance':


await send_balance(update, context)

elif data == 'status':

await send_status(update, context)

elif data == 'config':

new_text = "Configuration Menu:"

new_markup = get_config_menu()

if query.message.text != new_text or str(query.message.reply_markup) != str(new_markup):

await query.edit_message_text(new_text, reply_markup=new_markup)

elif data == 'settings':

new_text = "Settings Menu:"

new_markup = get_settings_menu()

if query.message.text != new_text or str(query.message.reply_markup) != str(new_markup):

await query.edit_message_text(new_text, reply_markup=new_markup)

elif data == 'trades':

await send_trades(update, context)

elif data == 'help':

await send_help(update, context)

elif data.startswith('set_'):

param = data.replace('set_', '')

config = load_config()

params = config.get("parameters", {})

if param == 'use_exitmin':

await query.edit_message_text("Select ExitMin:", reply_markup=get_exitmin_menu())

elif param == 'exitmin_on':

params['use_exitmin'] = True

config['parameters'] = params

save_config(config)

global use_exitmin
use_exitmin = True

await query.edit_message_text("Exit Minutes condition enabled", reply_markup=get_main_menu())

elif param == 'exitmin_off':

params['use_exitmin'] = False

config['parameters'] = params

save_config(config)

use_exitmin = False

await query.edit_message_text("Exit Minutes condition disabled", reply_markup=get_main_menu())

elif param == 'timeframe':

await query.edit_message_text("Select Timeframe:", reply_markup=get_timeframe_menu())

amount = float(pos['contracts'])

logging.info(f"Closing short position for {active_trade}: {amount} contracts")

order = await place_market_buy_order(active_trade, amount)

if order and order['status'] == 'closed':

logging.info(f"Successfully closed short position for {active_trade}: {amount} contracts")

await send_signal(f" 🔔 Closed short position for {active_trade}: {amount} contracts on bot stop")

else:

logging.error(f"Failed to close short position for {active_trade}")

except Exception as e:

logging.error(f"Error closing position for {active_trade}: {e}")

active_trade = None

usdt_balance = await get_balance('USDT')

net_pl_usdt = usdt_balance - start_balance

net_pl_pct = (net_pl_usdt / start_balance) * 100 if start_balance > 0 else -100.00

stop_message = f"""

🚫 BOT DEACTIVATED 🚫
📊 Session Report:

├─ Start Balance: {start_balance:.2f} USDT


├─ End Balance: {usdt_balance:.2f} USDT

├─ Net P/L: {net_pl_pct:.2f}% ({net_pl_usdt:.2f} USDT)

└─ Trades: {len(trade_history)}

⚙️ Leverage: {LEVERAGE}x

📅 Date: {datetime.now().strftime("%Y-%m-%d")}

🕒 Time: {get_current_ist_time()} IST | {get_current_utc_time()} UTC

📋 Summary: Session ended

"""

await reset_global_states()

if update.callback_query:

query = update.callback_query

await query.edit_message_text(stop_message, reply_markup=get_main_menu())

else:

await update.message.reply_text(stop_message, reply_markup=get_main_menu())

await send_signal(stop_message)

logging.info("Bot stopped.")

else:

if update.callback_query:

await update.callback_query.edit_message_text("Bot is already stopped!", reply_markup=get_main_menu())

else:

await update.message.reply_text("Bot is already stopped!", reply_markup=get_main_menu())

async def send_balance(update: Update, context: CallbackContext):

try:

await sync_time()

balance = await exchange.fetch_balance()

usdt_balance = balance['total'].get('USDT', 0.0) if balance.get('total') else 0.0

margin_used = balance['used'].get('USDT', 0.0) if balance.get('used') else 0.0

equity = usdt_balance + margin_used if margin_used else usdt_balance


margin_pct = (margin_used / equity * 100) if equity > 0 else 0

message = f"""

💰 ACCOUNT STATUS 💰
📈 Current Balance:

├─ USDT: {usdt_balance:.2f}

├─ Margin Used: {margin_used:.2f} USDT ({margin_pct:.1f}%)

└─ Equity: {equity:.2f} USDT

⚙️ Settings:

├─ Timeframe: {timeframe}

├─ Margin Mode: cross

├─ Leverage: {LEVERAGE}x

├─ Take-Profit: {take_profit_pct}%

└─ Stop-Loss: {stop_loss_pct}%

📊 Open Positions:

└─ {active_trade if active_trade else 'None'}

📅 Date: {datetime.now().strftime("%Y-%m-%d")}

🕒 Time: {get_current_ist_time()} IST | {get_current_utc_time()} UTC

"""

if update.callback_query:

query = update.callback_query

back_markup = InlineKeyboardMarkup([[InlineKeyboardButton(" ⬅️ Menu", callback_data='menu')]])

if query.message.text != message or str(query.message.reply_markup) != str(back_markup):

await query.edit_message_text(message, reply_markup=back_markup)

else:

await update.message.reply_text(message, reply_markup=get_main_menu())

except ccxt.AuthenticationError as e:

logging.error(f"Authentication error fetching balance: {e}")


message = "Authentication error: Please check your API credentials in config.json"

if update.callback_query:

query = update.callback_query

back_markup = InlineKeyboardMarkup([[InlineKeyboardButton(" ⬅️ Menu", callback_data='menu')]])

if query.message.text != message or str(query.message.reply_markup) != str(back_markup):

await query.edit_message_text(message, reply_markup=back_markup)

else:

await update.message.reply_text(message, reply_markup=get_main_menu())

except Exception as e:

logging.error(f"Error fetching balance: {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

back_markup = InlineKeyboardMarkup([[InlineKeyboardButton(" ⬅️ Menu", callback_data='menu')]])

if query.message.text != message or str(query.message.reply_markup) != str(back_markup):

await query.edit_message_text(message, reply_markup=back_markup)

else:

await update.message.reply_text(message, reply_markup=get_main_menu())

async def send_status(update: Update, context: CallbackContext):

status_message = f"""

📡 BOT STATUS UPDATE 📡



{' Running' if is_running else ' ❌ Stopped'}

⏰ Timeframe: {timeframe}

⚖️ Margin Mode: cross

📊 Active Trade: {active_trade if active_trade else 'None'}

📅 Date: {datetime.now().strftime("%Y-%m-%d")}

🕒 Time: {get_current_ist_time()} IST | {get_current_utc_time()} UTC

"""
if update.callback_query:

query = update.callback_query

back_markup = InlineKeyboardMarkup([[InlineKeyboardButton(" ⬅️ Menu", callback_data='menu')]])

if query.message.text != status_message or str(query.message.reply_markup) != str(back_markup):

await query.edit_message_text(status_message, reply_markup=back_markup)

"""

back_markup = InlineKeyboardMarkup([[InlineKeyboardButton(" ⬅️ Back", callback_data='menu')]])

if update.callback_query:

query = update.callback_query

if query.message.text != help_message or str(query.message.reply_markup) != str(back_markup):

await query.edit_message_text(help_message, reply_markup=back_markup)

else:

await update.message.reply_text(help_message, reply_markup=back_markup)

async def reset_global_states():

global checked_symbols_state, is_running, active_trade

checked_symbols_state = {}

active_trade = None

is_running = False

logging.info("Global states have been reset.")

def has_active_trade():

global active_trade

return active_trade is not None

async def fetch_binance_data(symbol, timeframe, limit=500, max_retries=5, retry_delay=5):

for attempt in range(max_retries):

try:

await sync_time()

ohlcv = await exchange.fetch_ohlcv(symbol, timeframe, limit=limit)

if not ohlcv:
raise ValueError(f"No data returned for {symbol}")

df = pd.DataFrame(ohlcv, columns=["timestamp", "open", "high", "low", "close", "volume"])

df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")

return df

except Exception as e:

logging.error(f"Attempt {attempt + 1} failed for {symbol}: {str(e)}")

if attempt < max_retries - 1:

await asyncio.sleep(retry_delay)

else:

logging.error(f"All {max_retries} attempts failed for {symbol}. Skipping...")

return pd.DataFrame()

def calculate_sma(prices, period):

return prices.rolling(window=period, min_periods=1).mean()

def EMA(close, length, previous_ema):

alpha = 2 / (length + 1)

return (close * alpha) + (previous_ema * (1 - alpha))

def calculate_ema_with_sma_smoothing(prices, period, smoothing_period=9):

ema = prices.copy()

initial_sma = calculate_sma(prices, smoothing_period)

ema[:smoothing_period] = initial_sma[:smoothing_period]

for i in range(smoothing_period, len(prices)):

ema.iloc[i] = EMA(prices.iloc[i], period, ema.iloc[i - 1])

except Exception as e:

logging.error(f"Error clearing mismatched positions: {e}")

async def place_market_sell_order(symbol, amount):

try:

await sync_time()
await exchange.set_margin_mode('cross', symbol)

await exchange.set_leverage(LEVERAGE, symbol)

max_retries = 3

retry_delay = 1

for attempt in range(max_retries):

try:

adjusted_amount = round(amount, 3)

order = await exchange.create_market_sell_order(symbol, adjusted_amount)

logging.info(f"Market sell order placed: {order}")

return order

except ccxt.BaseError as e:

if 'Margin is insufficient' in str(e) or '-2019' in str(e):

logging.warning(f" ❗ Margin insufficient for {symbol} (attempt {attempt + 1})")

await send_signal(f" ❌ Margin insufficient for {symbol}, reducing position size and retrying...")

amount = amount * 0.5

await asyncio.sleep(retry_delay)

continue

elif str(e).find('-4131') != -1 and attempt < max_retries - 1:

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:

order_book = await exchange.fetch_order_book(symbol)

best_bid = order_book['bids'][0][0] if order_book['bids'] else None

if best_bid:
limit_price = best_bid * 0.999

adjusted_amount = round(amount, 3)

order = await exchange.create_limit_sell_order(symbol, adjusted_amount, limit_price)

logging.info(f"Limit sell order placed for {symbol} at {limit_price}: {order}")

return order

else:

logging.error(f"No bid price available for {symbol} to place limit order")

return None

except Exception as fallback_e:

logging.error(f"Fallback limit sell failed for {symbol}: {fallback_e}")

return None

except Exception as e:

logging.error(f"Final error placing market sell order for {symbol}: {e}")

return None

async def place_market_buy_order(symbol, amount):

try:

await sync_time()

order = await exchange.create_market_buy_order(symbol, amount)

logging.info(f"Market buy order placed: {order}")

return order

except Exception as e:

logging.error(f"Error placing market buy order for {symbol}: {e}")

return None

async def get_balance(symbol, retries=5, delay=5):

for attempt in range(retries):

try:

await sync_time()
balance = await exchange.fetch_balance()

return balance['total'].get(symbol, 0.0)

except ccxt.AuthenticationError as e:

logging.error(f"Authentication error fetching balance: {e}")

raise

except Exception as e:

logging.error(f"Error fetching balance for {symbol} (attempt {attempt + 1}/{retries}): {e}")

if attempt < retries - 1:

await asyncio.sleep(delay)

else:

return 0.0

async def process_trade(symbol, entry_price):

global active_trade, take_profit_pct, stop_loss_pct, exit_minutes, use_exitmin, trade_history

trade_start_time = datetime.now(timezone.utc)

while active_trade and active_trade == symbol:

try:

ticker = await exchange.fetch_ticker(symbol)

current_price = ticker['last']

positions = await exchange.fetch_positions([symbol])

open_position = None

normalized_symbol = symbol.replace('/', '')

for pos in positions:

pos_symbol_normalized = pos['symbol'].replace('/', '').replace(':USDT', '')

await asyncio.sleep(wait_time)

async def load_valid_symbols():

global valid_symbols

try:
await sync_time()

markets = await exchange.load_markets()

valid_symbols = set(markets.keys())

logging.info(f"Loaded {len(valid_symbols)} valid symbols from Binance")

selected_coins = [coin for coin in get_selected_coins() if coin in valid_symbols]

config = load_config()

config['selected_coins'] = selected_coins

save_config(config)

logging.info(f"Updated config with valid coins: {selected_coins}")

except Exception as e:

logging.error(f"Error loading valid symbols: {e}")

valid_symbols = set(get_selected_coins())

async def main_loop():

try:

await load_valid_symbols()

selected_coins = [coin for coin in get_selected_coins() if coin in valid_symbols]

logging.info(f"Processing symbols: {selected_coins}")

while True:

if is_running:

await wait_for_next_candle()

for symbol in selected_coins:

if has_active_trade():

logging.error(f"Unexpected error in bot loop: {e}")

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:

logging.error(f"Error starting main loop: {e}")

You might also like