AI-Powered Crypto Trading Bot for Mobile Applications
Trading bot—not just if/else script on RSI. System with risk management, reliable exchange connection, secure key storage, and edge case protection: API rate limits, temporary exchange unavailability, sharp price moves. Mobile adds complexity: background mode, network interruptions, limited CPU.
Architecture: Server + Mobile Client
On-device trading logic—bad idea. Phone goes background, iOS suspends process, order not placed. Right architecture:
- Trading server (Python/Node.js)—strategy execution, WebSocket to exchange, orders
- Mobile client—bot management, position monitoring, strategy settings, alerts
Mobile app manages bot via REST API server, real-time data via WebSocket.
Exchange Integration: WebSocket and REST
Binance, Bybit, OKX—all provide analogous API structure. Trading operations—REST, market data and account updates—WebSocket.
// iOS: Binance User Data Stream subscription
class BinanceOrderStream: NSObject, URLSessionWebSocketDelegate {
private var webSocketTask: URLSessionWebSocketTask?
// Get listenKey via REST, then open WebSocket
func startStream(listenKey: String) {
let url = URL(string: "wss://stream.binance.com:9443/ws/\(listenKey)")!
let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
webSocketTask = session.webSocketTask(with: url)
webSocketTask?.resume()
receiveMessage()
}
private func receiveMessage() {
webSocketTask?.receive { [weak self] result in
switch result {
case .success(.string(let text)):
self?.processEvent(text)
self?.receiveMessage() // keep listening
case .failure:
self?.scheduleReconnect()
default: break
}
}
}
private func scheduleReconnect() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.startStream(listenKey: self.currentListenKey)
}
}
}
Reconnect on break—mandatory. Binance breaks WebSocket every 24 hours (listenKey expires). Must renew via PUT /api/v3/userDataStream every 30 minutes.
AI Strategies: What Actually Works in Production
"AI bot" often hides ordinary technical analysis. Real ML approaches:
Price Direction Prediction (Classification)
LSTM / Transformer on OHLCV data + technical indicators (RSI, MACD, Bollinger Bands). Predicts: up / down / sideways on next N candles.
Honest truth: accuracy > 55% on out-of-sample data—already good. Markets—adaptive systems, models degrade. Periodic retraining mandatory.
Reinforcement Learning (RL)
PPO / SAC agent learns trading in simulator on historical data. Reward: PnL with commissions. Penalties for drawdown.
RL works on backtest but suffers from overfitting to historical data. Need out-of-sample validation and paper trading before real money.
Ensemble: ML + Rules
Combine ML signal with rule-based filters: if ML says "buy" but RSI > 75 (overbought) and volume low—skip signal. Hybrid reduces false signals.
Risk Management — More Important Than Strategy
class RiskManager:
def __init__(self, max_position_pct=0.1, max_daily_loss_pct=0.05):
self.max_position_pct = max_position_pct # 10% balance per position
self.max_daily_loss_pct = max_daily_loss_pct # 5% daily stop
def can_open_position(self, signal, balance, daily_pnl):
if daily_pnl / balance < -self.max_daily_loss_pct:
return False, "Daily loss limit reached"
position_size = balance * self.max_position_pct * signal.confidence
return True, position_size
def calculate_stop_loss(self, entry_price, direction, atr):
# ATR-based stop: 1.5 × ATR from entry
multiplier = 1.5
if direction == "long":
return entry_price - atr * multiplier
return entry_price + atr * multiplier
ATR (Average True Range)—dynamic stop loss adapting to volatility. Fixed % stop (always -2%) works worse: calm market—too close, volatile—too far.
Key Security
API key with trading rights—critical data. iOS—only Keychain with kSecAttrAccessibleWhenUnlockedThisDeviceOnly. Android—EncryptedSharedPreferences or Android Keystore.
Never send keys to server unencrypted. Right flow: user enters key in app → encrypted → sent to server via HTTPS → stored encrypted in Vault (HashiCorp) or AWS Secrets Manager.
Separate keys per strategy with limited rights: only READ + SPOT_TRADING without WITHDRAWAL. Key compromise won't allow fund withdrawal.
Mobile UI: What Trader Needs
- Current open positions with real-time PnL
- Balance chart with history
- Strategy management: enable/disable, risk parameters
- Trade log with entry reason (which signal triggered)
- Alerts: stop triggered, position closed, unusual activity
Real-time WebSocket for position updates mandatory. Polling every 10 seconds gives lag on fast market.
Backtesting and Paper Trading
Before real money—minimum 6 months backtesting + 1 month paper trading (simulated trades on real market data without execution). Backtesting via Binance Historical Data (daily OHLCV snapshots), ccxt library for unified exchange API.
Development Process
Design server/client architecture. Integrate exchange API (REST + WebSocket). Develop trading strategy with ML component. Risk management and position sizing. Secure key storage. Backtesting and optimization. Mobile dashboard UI. Monitoring and alerting.
Timeframe Estimates
Bot with simple strategy (MA crossover / RSI) and mobile dashboard—3–5 weeks. Full ML strategy with RL, risk management, backtesting—2–3 months+.







