A professional-grade algorithmic trading system built in R with advanced technical analysis, risk management, and paper trading capabilities.
An end-to-end algorithmic trading system designed for cryptocurrency markets. Features real-time data acquisition, technical analysis, multiple trading strategies, comprehensive backtesting, risk management, and paper trading simulationโall built from scratch in R.
- ๐ Real-time & Historical Data - CryptoCompare API integration
- ๐ฌ Technical Analysis - 10+ indicators (RSI, MACD, MA, Bollinger Bands)
- ๐ฏ Multiple Strategies - MA Crossover, RSI Mean Reversion, customizable templates
- ๐งช Professional Backtesting - Transaction costs, performance metrics, equity curves
- ๐ก๏ธ Risk Management - Position sizing (Fixed, Kelly Criterion, ATR), stop-loss/take-profit
- ๐ฐ Paper Trading - Test strategies with simulated capital
- ๐ Visualization - Publication-quality charts (equity curves, drawdowns, indicators)
Strategy: RSI Mean Reversion
Period: 90 days (Oct 2025 - Jan 2026)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Initial Capital: $10,000
Final Value: $10,432
Total Return: +4.32%
Win Rate: 25%
Sharpe Ratio: -1.67
Max Drawdown: -0.14%
crypto-trading-bot/
โโโ config/ # Configuration files
โโโ data/ # Data storage
โ โโโ raw/ # Raw market data
โ โโโ processed/ # Processed data with indicators
โโโ src/
โ โโโ data_acquisition/ # API integration & data fetching
โ โโโ indicators/ # Technical indicators
โ โโโ strategies/ # Trading strategies
โ โโโ backtesting/ # Backtesting engine
โ โโโ risk_management/ # Position sizing & risk tools
โ โโโ trading/ # Paper trading simulator
โ โโโ visualization/ # Chart generation
โโโ results/
โ โโโ backtest_results/ # Backtest outputs
โ โโโ plots/ # Generated charts
โโโ logs/ # Application logs
โโโ tests/ # Unit tests
Total Lines of Code: ~4,200
Total Files: 18
Development Time: 5 weeks
- R (version 4.5+)
- RStudio (recommended)
- Clone the repository
git clone https://github.com/SNMiguel/R-Cryptocurrency-Trading-Bot.git
cd R-Cryptocurrency-Trading-Bot- Install dependencies
source("setup.R")- Configure settings
# Edit config/config.R to customize:
# - Cryptocurrencies to track
# - Risk parameters
# - Initial capital
# - Trading mode (PAPER/LIVE)# Load the system
source("demo_priority2.R")
# This will:
# 1. Download 90 days of BTC data
# 2. Calculate technical indicators
# 3. Run MA Crossover strategy
# 4. Run RSI Mean Reversion strategy
# 5. Compare results
# 6. Save backtest reportssource("demo_priority3.R")
# This will:
# 1. Set up paper trading portfolio
# 2. Run strategies with stop-loss/take-profit
# 3. Generate risk reports
# 4. Create professional charts| Indicator | Description | Parameters |
|---|---|---|
| SMA/EMA | Moving Averages | Periods: 10, 20, 50, 200 |
| RSI | Relative Strength Index | Period: 14, Oversold: 30, Overbought: 70 |
| MACD | Moving Average Convergence Divergence | Fast: 12, Slow: 26, Signal: 9 |
| Bollinger Bands | Volatility bands | Period: 20, Std Dev: 2 |
| Volume | Volume analysis | MA Period: 20 |
strategy <- create_ma_crossover_strategy(
fast_period = 10,
slow_period = 20,
ma_type = "SMA"
)Logic: Buy when fast MA crosses above slow MA, sell when it crosses below.
strategy <- create_rsi_strategy(
rsi_period = 14,
oversold = 30,
overbought = 70
)Logic: Buy when RSI < 30 (oversold), sell when RSI > 70 (overbought).
# Create your own strategy using the base template
my_strategy <- create_base_strategy(
name = "My Strategy",
parameters = list(...)
)
# Define signal generation
generate_signals.MyStrategy <- function(strategy, data) {
# Your logic here
return(data)
}# Position sizing
position <- calculate_position_size_fixed(capital = 10000, risk_pct = 0.02)
position <- calculate_position_size_kelly(capital, win_rate, avg_win, avg_loss)
# Stop-loss & Take-profit
stop_loss <- calculate_stop_loss(entry_price = 90000, stop_pct = 0.02)
take_profit <- calculate_take_profit(entry_price = 90000, profit_pct = 0.05)
# Risk-reward ratio
rr_ratio <- calculate_risk_reward_ratio(entry_price, stop_loss, take_profit)# Get historical data
btc_data <- get_historical_days("BTC", limit = 90)
# Add indicators
btc_data <- add_all_indicators(btc_data)
# Create strategy
strategy <- create_ma_crossover_strategy(10, 20)
# Run backtest with transaction costs
results <- run_backtest(
strategy = strategy,
data = btc_data,
initial_capital = 10000,
commission = 0.001, # 0.1%
slippage = 0.0005 # 0.05%
)
# View results
print_backtest_results(results)The backtesting engine calculates:
- Returns: Total return, return percentage
- Risk Metrics: Sharpe ratio, maximum drawdown, volatility
- Trade Stats: Win rate, profit factor, avg win/loss
- Execution Costs: Commission, slippage
-
Fixed Percentage
- Risk fixed % of capital per trade
- Simple and conservative
-
Kelly Criterion
- Optimal bet sizing based on edge
- Maximizes long-term growth
-
ATR-Based
- Volatility-adjusted position sizing
- Adapts to market conditions
- Automatic stop-loss calculation
- Trailing stop support
- Risk-reward ratio validation
- Portfolio risk monitoring
Generate professional charts:
# Equity curve
plot <- plot_equity_curve(results$equity_curve)
save_plot(plot, "my_equity_curve")
# Price with indicators
plot <- plot_price_with_indicators(data, show_ma = TRUE, show_bb = TRUE)
save_plot(plot, "price_chart")
# RSI indicator
plot <- plot_rsi(data, oversold = 30, overbought = 70)
save_plot(plot, "rsi")
# Trades on chart
plot <- plot_trades(data, trade_history)
save_plot(plot, "trades")All charts saved as high-resolution PNG files (300 DPI).
# config/config.R
API_BASE_URL <- "https://min-api.cryptocompare.com"
CRYPTOCURRENCIES <- c("BTC", "ETH", "BNB", "SOL", "ADA")
BASE_CURRENCY <- "USD"RISK_MANAGEMENT <- list(
stop_loss_pct = 0.02, # 2% stop-loss
take_profit_pct = 0.05, # 5% take-profit
max_daily_loss_pct = 0.05, # 5% max daily loss
max_open_positions = 3
)POSITION_SIZING <- list(
initial_capital = 10000,
max_position_size = 0.10, # 10% per trade
min_position_size = 100
)- Start with
demo_priority2.R- Learn backtesting basics - Experiment with indicator parameters
- Try different cryptocurrencies
- Compare strategy performance
- Create custom strategies using
base_strategy.R - Optimize parameters with grid search
- Implement multi-indicator strategies
- Add your own risk management rules
=== BACKTEST RESULTS ===
Strategy: Moving Average Crossover
--- PERFORMANCE METRICS ---
Initial Capital: $10,000.00
Final Value: $9,338.02
Total Return: -$661.98 (-6.62%)
--- TRADING ACTIVITY ---
Total Trades: 3
Completed Trades: 1
Win Rate: 0.00%
--- RISK METRICS ---
Sharpe Ratio: -1.71
Max Drawdown: -6.00%
Profit Factor: 0.00
--- TRANSACTION COSTS ---
Total Commission: $27.36
Total Slippage: $13.68
Total Costs: $41.03
- Real-time & historical data acquisition
- Technical indicators (10+ indicators)
- Multiple trading strategies
- Professional backtesting engine
- Risk management system
- Paper trading simulator
- Visualization tools
- Live trading integration
- Advanced order types (limit, stop)
- Multi-asset portfolio management
- Machine learning strategies
- Real-time alerts & notifications
- Web interface (React + FastAPI)
- Mobile app
- Social trading features
- Strategy marketplace
- API for external integrations
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
This software is for educational purposes only.
- Cryptocurrency trading carries significant risk
- Past performance does not guarantee future results
- Always do your own research (DYOR)
- Never invest more than you can afford to lose
- The authors are not responsible for any financial losses
- CryptoCompare API - Real-time cryptocurrency data
- R Community - Excellent packages (tidyverse, TTR, ggplot2)
- Quantitative Finance - Algorithmic trading research
Chawana Smith
- GitHub: @SNMiguel
- LinkedIn: MigzTech LinkedIn
- Email: shemamiguel2023@gmail.com
If you find this project helpful, please consider:
- โญ Starring the repository
- ๐ Reporting bugs
- ๐ก Suggesting new features
- ๐ข Sharing with others
Built with โค๏ธ using R
โญ Star this repo if you found it useful! โญ
Last Updated: January 2026 Version: 0.1.0 (Data Acquisition Phase)


