A Java Spring Boot trading bot that integrates with Binance's WebSocket API for real-time market data streaming and automated trading operations.
- Prerequisites
- Configuration
- Architecture Overview
- BinanceConfig Integration
- WebSocket Components
- WebsocketTradeService Integration
- Data Flow
- Getting Started
- Java 21 or higher
- Maven 3.6+
- Binance API credentials (API Key and Secret Key)
Before running the application, you must set the following environment variables with your Binance API credentials:
# Windows (PowerShell)
$env:BINANCE_KEY="your_binance_api_key_here"
$env:BINANCE_SECRET="your_binance_secret_key_here"
# Linux/Mac
export BINANCE_KEY="your_binance_api_key_here"
export BINANCE_SECRET="your_binance_secret_key_here"The application also supports configuration through application.yaml:
binance:
key: ${BINANCE_KEY}
secret: ${BINANCE_SECRET}
trading:
symbol: BTCUSDT # Default trading symbolThe application follows a layered architecture with clear separation of concerns:
BinanceConfig → BinanceWebsocketComponent → WebSocket Streams → WebsocketTradeService
The BinanceConfig class serves as the central configuration hub for all Binance API interactions. It creates and configures the necessary beans for both REST API and WebSocket connections.
@Bean
public SpotClient binanceSpotClient() {
return new SpotClientImpl(key, secret);
}- Creates the main Binance Spot trading client
- Used for placing orders and REST API operations
- Automatically configured with API credentials from environment variables
@Bean
public SpotRestApi binanceSpotRestClient() {
return new SpotRestApi(getConfig());
}- Provides REST API functionality
- Used for market data queries and account information
@Bean
public ExchangeInfoResponse tradingSymbol() {
// Fetches exchange information for the configured trading symbol
}- Retrieves exchange information for the trading symbol
- Contains symbol filters, lot sizes, and trading rules
- Used for order validation and quantity calculations
@Bean
public SignatureConfiguration signatureConfiguration() {
SignatureConfiguration signatureConfiguration = new SignatureConfiguration();
signatureConfiguration.setApiKey(key);
signatureConfiguration.setSecretKey(secret);
return signatureConfiguration;
}- Critical Component: This bean is the bridge between
BinanceConfigand WebSocket components - Encapsulates API credentials in a secure configuration object
- Injected into
BinanceWebsocketComponentfor WebSocket authentication
This component acts as the WebSocket factory, creating authenticated WebSocket connections:
@Component
@RequiredArgsConstructor
public class BinanceWebsocketComponent {
private final SignatureConfiguration signatureConfig; // ← Injected from BinanceConfig
@Bean
public SpotWebSocketStreams initSpotStream() {
// Creates public WebSocket streams (market data)
}
@Bean
public WebSocketApiClientImpl initAccountWebsocketStream() {
// Creates private WebSocket streams (account data)
}
}Integration Point: The SignatureConfiguration from BinanceConfig is injected here, enabling secure WebSocket connections.
- Purpose: Streams real-time trade executions for the configured symbol
- Data: Individual trade events (price, quantity, timestamp)
- Integration:
private final SpotWebSocketStreams spotWebSocketStreams; // ← From BinanceWebsocketComponent private final WebsocketTradeService websocketTradeService; // ← Target service
- Purpose: Streams real-time best bid/offer (book ticker) data
- Data: Current bid price, ask price, and quantities
- Integration:
private final SpotWebSocketStreams spotWebSocketStreams; // ← From BinanceWebsocketComponent private final WebsocketTradeService websocketTradeService; // ← Target service
- Purpose: Monitors account status and balance changes
- Data: Account permissions, balances, and trading status
- Integration: Uses
WebSocketApiClientImplfor authenticated streams
WebsocketTradeService is the core trading engine that processes incoming WebSocket data and makes trading decisions.
public void updateTrade(TradeResponse trade) {
// Called by TradeWebsocketStream
// Processes individual trade executions
// Updates market momentum analysis
// Triggers scalping opportunity analysis
}public void updateTicker(BookTickerResponse ticker) {
// Called by TickerWebsocketStream
// Updates current bid/ask spreads
// Triggers trading analysis when conditions are met
}private BigDecimal getAssetBalance(String asset) {
var acc = AccountListenerWebsocketStream.accountStatus.getResult();
// Accesses current account balances
// Used for position sizing and risk management
}- Data Ingestion: WebSocket streams feed real-time data
- Analysis: Market momentum and scalping opportunities are analyzed
- Decision Making: Trading signals are generated based on:
- Spread analysis
- Momentum indicators
- Account balance checks
- Risk management rules
- Order Execution: Buy/sell orders are placed through the
OrderService
graph TD;
A[Environment Variables] --> B[BinanceConfig];
B --> C[SignatureConfiguration];
C --> D[BinanceWebsocketComponent];
D --> E[SpotWebSocketStreams];
D --> F[WebSocketApiClientImpl];
E --> G[TradeWebsocketStream];
E --> H[TickerWebsocketStream];
F --> I[AccountListenerWebsocketStream];
G --> J[WebsocketTradeService.updateTrade];
H --> J2[WebsocketTradeService.updateTicker];
I --> K[AccountStatusResponse];
J --> L[Trading Analysis];
J2 --> L;
K --> L;
L --> M[Order Execution];
- Startup: Application loads environment variables (
BINANCE_KEY,BINANCE_SECRET) - Configuration:
BinanceConfigcreatesSignatureConfigurationwith credentials - WebSocket Setup:
BinanceWebsocketComponentuses the signature config to create authenticated connections - Stream Initialization: Individual stream classes (
TradeWebsocketStream,TickerWebsocketStream) start listening - Data Processing: Incoming WebSocket messages are routed to
WebsocketTradeService - Trading Decisions: Service analyzes market data and executes trading strategies
- Order Management: Orders are placed through the configured Binance client
-
Set Environment Variables:
$env:BINANCE_KEY="your_api_key" $env:BINANCE_SECRET="your_secret_key"
-
Configure Trading Symbol (optional):
binance: trading: symbol: BTCUSDT # Change to your preferred trading pair
-
Run the Application:
mvn spring-boot:run
-
Monitor Logs:
- WebSocket connection status
- Real-time market data ingestion
- Trading decisions and order executions
- Account balance updates
The application will automatically start all WebSocket streams and begin processing market data for automated trading operations.
Note: This is a high-frequency trading application. Ensure you understand the risks involved and test thoroughly in a sandbox environment before using with real funds.