Binance Telegram Bot is an automated trading bot that integrates Binance's trading capabilities with signals received from Telegram channels. It executes trades on Binance based on signals from Telegram, ensuring automated and timely responses to market changes.
- Signal Processing
- Trade Execution
- Configurable Settings
- Detailed Logging and Monitoring
- Robust Error Handling
- Java 21
- Maven
- Binance account
- Telegram account
- Clone the repo:
git clone https://github.com/ozgen/binance-telegram-bot.git
- Navigate to the directory:
cd binance-telegram-bot
- Build with Maven:
mvn clean install
Configure the application using environment variables or a .env
file. Here are the key variables you need to set:
spring.datasource.url
: URL to the Azure databasespring.datasource.username
: Azure database usernamespring.datasource.password
: Azure database password
azure.keyvault.uri
: Azure keyvault URIazure.keyvault.client-id
: Azure keyvault client IDazure.keyvault.client-key
: Azure keyvault client keyazure.keyvault.tenant-id
: Azure keyvault tenant ID
bot.telegram.token
: Telegram bot tokenbot.telegram.enabled
: Enable Telegram bot (true
orfalse
)
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation
: Hibernate setting for LOB creationspring.jpa.hibernate.ddl-auto
: Hibernate DDL auto strategy (create
,create-drop
,validate
,update
)
app.bot.investment.currency
: Investment currency (e.g.,BTC
)app.bot.investment.amount
: Total investment amountapp.bot.investment.perAmount
: Amount per tradeapp.bot.investment.currencyRate
: Currency rate for conversion (e.g.,BTCUSD
)app.bot.investment.percentageInc
: Percentage increase for buyingapp.bot.investment.profitPercentage
: Profit percentage target
app.bot.schedule.buyError
: Schedule interval for buy error in msapp.bot.schedule.sellError
: Schedule interval for sell error in msapp.bot.schedule.insufficient
: Schedule interval for insufficient balance in msapp.bot.schedule.notInRange
: Schedule interval for not in range status in msapp.bot.schedule.tradingSignal
: Schedule interval for trading signals in msapp.bot.schedule.openSellOrder
: Schedule interval for open sell orders in msapp.bot.schedule.openBuyOrder
: Schedule interval for open buy orders in msapp.bot.schedule.sellLater
: Schedule interval for sell later orders in msapp.bot.schedule.monthBefore
: Number of months before for date calculations
bot.telegram.error.enabled
: Set totrue
to enable error reporting on Telegram.
Start the bot with:
java -jar target/binance-telegram-bot-0.0.1-SNAPSHOT.jar
To ensure the system functions correctly, follow these setup requirements:
- Create a Telegram Bot: Follow the instructions on Telegram's official documentation to create a new bot.
- Generate a Bot Token: Use this guide to generate a token for your Telegram bot.
- Create a new bot for error reporting following the steps above.
- Create a troubleshooting channel on Telegram and add the error bot as an admin.
- Start the system, then send a message to the troubleshooting channel to initialize the error bot correctly.
- Make sure the bot is an admin of the Telegram channel you want to monitor.
- This setup uses Azure Key Vault and Azure SQL Database. For local or alternative databases, update the
application.properties
file accordingly.
- Create an Azure Key Vault: Follow the steps outlined here.
- Connect to Azure Key Vault: Use the instructions provided here to connect.
- Create an Azure SQL Database: Detailed instructions can be found here. Opting for a serverless configuration is cost-effective.
- Connect to Azure SQL Database: Follow these steps to connect.
Set up the following environment variables for your application:
AZURE_DB_PASSWORD=<db-password>
AZURE_DB_URL=<azure-db-url>
AZURE_DB_USERNAME=<db-user-name>
AZURE_KEYVAULT_CLIENT_ID=<azure-keyvault-client-id>
AZURE_KEYVAULT_CLIENT_KEY=<azure-keyvault-client-key>
AZURE_KEYVAULT_TENANT_ID=<azure-keyvault-tenant-id>
AZURE_KEYVAULT_URL=<keyvault-url>
TELEGRAM_ERROR_TOKEN=<telegram-error-token>
TELEGRAM_TOKEN=<telegram-channel-token>
TELEGRAM_USERNAME=<telegram-bot-username>
TELEGRAM_ERROR_USERNAME=<telegram-error-bot-username>
Replace the placeholder values with your actual configuration details.
Ensure all prerequisites are met for the system to run smoothly.
For local development, you can run the PostgreSQL database via Docker and run the Spring Boot application locally with the local
profile.
From the project root, run:
docker-compose -f docker/docker-compose.yml up -d
Make sure your docker-compose.yml
exposes the correct PostgreSQL port (5432
) and includes environment variables like:
environment:
POSTGRES_DB: binancebot
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypass
Export these variables in your terminal session (or place them in a .env
file if your tooling supports it):
# Database
SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/binancebot
SPRING_DATASOURCE_USERNAME=myuser
SPRING_DATASOURCE_PASSWORD=mypass
# Telegram Bot
BOT_TELEGRAM_TOKEN=<your-telegram-token>
BOT_TELEGRAM_ENABLED=true
# Binance API
BINANCE_API_KEY=<your-binance-api-key>
BINANCE_API_SECRET=<your-binance-api-secret>
Example env file can be found in here
Build and run the app:
mvn clean install
java -Dspring.profiles.active=local -jar target/binance-telegram-bot-0.0.1-SNAPSHOT.jar
This setup:
- Connects to the PostgreSQL instance running in Docker
- Loads credentials from local environment variables
- Avoids any cloud integrations not enabled in the
local
profile
The bot monitors specified Telegram channels for trading signals and executes corresponding trades on Binance. Here's an example of a trading signal the bot can process:
Trading Signal Example:
NKNBTC
ENTRY: 0.00000260 - 0.00000290
TP1: 0.00000315
TP2: 0.00000360
TP3: 0.00000432
TP4: 0.00000486
TP5: 0.00000550
TP6: 0.00000666
TP7: 0.00000741
STOP: Close weekly below 0.00000240
The bot allows two optional parameters in trading signals:
- INVEST → Specifies how much to invest in the trade.
- STRATEGY: SELL_LATER → Delays selling until a future condition is met.
Parameter | Description |
---|---|
INVEST |
Defines the amount allocated for the trade (e.g., "0.0001 BTC" ). If omitted, the bot will use the default investment settings. |
STRATEGY |
If set to SELL_LATER , the bot will not immediately create sell order. Instead, It creates sell order when profit targets (TPs) are reached. |
Trading Signal Example:
NKNBTC
ENTRY: 0.00000260 - 0.00000290
TP1: 0.00000315
TP2: 0.00000360
TP3: 0.00000432
TP4: 0.00000486
TP5: 0.00000550
TP6: 0.00000666
TP7: 0.00000741
STOP: Close weekly below 0.00000240
# Optional Parameters
INVEST: 0.001
STRATEGY: SELL_LATER
- Normally, the bot automatically sells when a TP level is reached.
- If
SELL_LATER
is set:- The bot holds the asset instead of selling at TP levels.
- The sell order will be triggered later based on other conditions (e.g., price spikes, custom alerts).
Scenario | Expected Bot Behavior |
---|---|
No INVEST value |
Uses the default investment configuration. |
INVEST set | Overrides the default investment amount. |
No SELL_LATER |
The bot sells at the defined profit percentage. |
SELL_LATER enabled |
The bot holds the asset and delays selling. |
- INVEST → Gives you flexibility to change investment size per trade.
- SELL_LATER → Useful for longer-term holds instead of auto-selling.
The bot now supports placing buy and sell orders in smaller parts (called "chunks"). This helps avoid problems like sudden price changes when trading large amounts.
To turn on chunked order execution, add the following to your application.properties
or environment variables:
# app execution strategy: CHUNKED or DEFAULT
app.bot.execution.strategy=CHUNKED
When you use the CHUNKED
setting:
- The bot checks the average trading volume for the coin.
- Based on the volume, it decides how many small orders (chunks) to place.
- Your total investment is divided across these small buy orders.
- Each buy order is tracked separately.
- When the price target is reached, the bot creates separate sell orders for each chunk.
- Helps avoid moving the market price by placing smaller orders.
- Adapts to how actively a coin is being traded.
- Makes it easier to manage and track each trade.
This advanced execution strategy builds upon CHUNKED
by reacting dynamically to real-time market conditions. It also supports multiple entries, margin-split investments, calculated leverage, and multiple take-profit levels.
To enable:
app.bot.execution.strategy=CHUNKED_PROGRESSIVE
-
The bot calculates average quote volume using recent 5-minute candlesticks.
-
Based on this liquidity, it dynamically sets the number of chunks:
- Higher liquidity → more chunks.
- Lower liquidity → fewer chunks.
-
Before placing each chunk, the bot ensures:
- The price is within the signal's entry range.
- The market shows a short-term bullish trend (based on recent price movements).
-
For each chunk:
-
It uses a fixed portion of the total margin (e.g., 5% of portfolio split evenly).
-
It calculates leverage using the formula:
leverage = entryPrice / (entryPrice - stopLoss)
-
It assigns a specific take-profit level based on chunk index.
-
-
Each chunk is sold independently once its target profit price is reached.
NKNBTC
ENTRY: 0.00000260 - 0.00000290
TP1: 0.00000315
TP2: 0.00000360
TP3: 0.00000432
TP4: 0.00000486
TP5: 0.00000550
TP6: 0.00000666
TP7: 0.00000741
STOP: Close weekly below 0.00000240
In this case:
- The bot averages the entry range (e.g., midpoint of 0.00000260 and 0.00000290).
- Calculates leverage using that midpoint and the stop price (e.g., 0.00000275 / (0.00000275 - 0.00000240)).
- Distributes investment and assigns a corresponding take-profit (TP1–TP7) per chunk.
- Reacts to live market signals for smarter trade timing.
- Dynamically adjusts chunking based on market liquidity.
- Calculates leverage based on real risk (entry vs. stop).
- Supports multiple TP levels for staggered profit-taking.
If you want the bot to place just one buy and one sell order per signal, change the setting back to:
app.bot.execution.strategy=DEFAULT
Execute the test suite using Maven:
mvn test
After running the tests, generate a coverage report using JaCoCo (Java Code Coverage Library):
mvn jacoco:report
The coverage report can be found in target/site/jacoco/index.html
. Open it in a web browser to view detailed coverage statistics.
This project is licensed under the MIT License - see LICENSE.md for details.
- Binance API
- Telegram API