Welcome to the SOL/USDC Live Trading Bot project! This bot is designed to automate trading of the SOL/USDC pair (or any pair) using a sophisticated Fibonacci-based strategy. It includes robust features such as live charting with real-time Weighted Moving Average (WMA) Fibonacci levels, dynamic trade management, and comprehensive performance statistics reported in USDC.
This guide provides the essential steps to get your price tracker and trading bot running.
- Your
sol_usd_tracker.pyscript. - Your
main.pyscript (with thestartcommand). - All required Python packages installed in your virtual environment.
- (You can do a
pip install -r requirements.txtonce you activate the venv) - Your virtual environment activated.
Open your terminal, navigate to your project directory, activate your virtual environment, and run the price tracker in the background. This populates sol_usdc_price_history_jupiter.csv:
# Optional: Clean old price data for a fresh start
rm sol_usdc_price_history_jupiter.csv
# Start the price tracker in the background
python3 sol_usd_tracker.py &- Wait ~15-20 minutes to allow the tracker to generate enough initial 5-minute candle data (at least 65 candles are needed for full WMA Fibonacci calculations).
Open a new terminal tab (or window), navigate to your project directory, activate your virtual environment, and run the bot. This will launch the trading logic and the web-based live chart:
# Make sure you are in a NEW terminal tab/window
python3 main.py start- Your live chart will open in your web browser, typically at
http://localhost:8051.
- Stop the Trading Bot: Go to the terminal tab running
main.py startand pressCtrl + C. The bot will attempt a graceful shutdown and save trade history. - Stop the Price Tracker:
- Find its process ID:
ps aux | grep "sol_usd_tracker.py" - Terminate it:
kill <PID>(replace<PID>with the ID you found). - Alternatively (if all else fails): Close your WSL terminal or run
wsl --shutdownfrom Windows PowerShell/CMD to stop all WSL processes.
- Find its process ID:
- Features
- Getting Started
- Configuration
- Usage
- Modules Overview
- Trading Strategy
- FAQ
- Contributing
- License
- Acknowledgments
- Contact
This bot is designed to maximize capital (USDC) by strategically accumulating more Solana (SOL) during market dips, while managing risk.
- Automated Trading Strategy: Implements a refined Fibonacci-based strategy tailored for SOL/USDC trading.
- Live Charting (Web UI):
- Real-time candlestick chart.
- Dynamic Weighted Moving Average (WMA) Fibonacci levels plotted with customizable colors and dash styles.
- Real-time price line, open position lines (with live profit/loss percentages), and closed trade markers (entry, exit, profit/loss path).
- Displays real-time trade statistics and bot status (e.g., "Entry Switch Armed").
- Intelligent Trade Management:
- USDC-centric Trading: Manages capital and calculates profits primarily in USDC.
- Position Sizing: Configurable trade size (in USDC) and maximum number of concurrent open positions.
- Dip Accumulation: Implements a position spacing feature, requiring new concurrent trades to be a configurable percentage below the lowest existing entry, facilitating dollar-cost averaging on dips.
- Automated Entry: Based on price dipping below a Fibonacci threshold and then re-crossing the WMA Fib 0 level (buy signal).
- Automated Exit:
- Tiered Profit Targets: Uses
profit_target_1(higher, short-term) andprofit_target_2(lower, time-based fallback). - Fib 50 Holding Logic: Can hold trades that meet
profit_target_1if the price remains above WMA Fib 50, only closing when it drops back below, to maximize gains. - Cumulative Profit Target: Closes all positions if an overall portfolio profit target (in percentage of initial capital) is reached.
- Tiered Profit Targets: Uses
- Configurable: All key trading parameters, chart styles (colors, dash types, widths), and paths are easily adjustable via
config/config.yaml. - Robust Logging: Provides detailed console logs for tracking bot actions, calculations, and debugging.
- Historical Data Processing: Initializes with existing market data from CSV for faster startup and indicator calculation.
- Graceful Shutdown: Handles
Ctrl+Cfor clean exits and trade history saving.
- Python 3.7 or higher
- Pipenv or
pipfor managing Python packages - Git (optional, for cloning the repository)
-
Clone the Repository:
git clone [https://github.com/yourusername/wif-sol-trading-bot.git](https://github.com/yourusername/wif-sol-trading-bot.git) cd wif-sol-trading-bot -
Set Up a Virtual Environment:
Using Pipenv:
pipenv install pipenv shell
Or using
pipandvenv:python3 -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate`
-
Install Dependencies:
The required packages are listed in
requirements.txt. Install them with:pip install -r requirements.txt
-
Data Files:
- Ensure your
sol_usd_tracker.pyis correctly generatingsol_usdc_price_history_jupiter.csvwith real-time (or simulated) 1-minute price data inprice_data/(or your configured path). The bot reads this file.
- Ensure your
The bot is configured using the config/config.yaml file. This file contains critical settings for:
- Trading Parameters:
initial_balance: Your starting capital, implicitly in USDC.trade_size: The amount of USDC to spend per individual trade.max_positions: Maximum number of open SOL positions concurrently.fib_entry_threshold: How far below WMA Fib 0 the price must dip to arm.fib_reset_threshold: How far above WMA Fib 0 the price must go to disarm.profit_target_1: Higher profit percentage for initial exit attempts (e.g.,0.01for 1%).profit_target_2: Lower profit percentage ifcountdown_periodsare exceeded.cumulative_profit_target: Overall portfolio profit percentage target to close all trades.countdown_periods: Number of 5-minute candles before switching fromprofit_target_1toprofit_target_2.require_fib50_cross: Boolean to enable/disable specific Fib 50 conditions for exits.position_spacing_pct: Minimum percentage below the lowest open position required for a new entry (e.g.,-0.03for 3% dip).
- Chart Styles: Customizable
color,dashtype ("solid","dot","dash", etc.), andwidthfor all plotted lines (Fibonacci levels, current price, open positions, trade paths). - Paths: Location of live data CSV, and where to save trade history.
- Logging: Logging levels and file output.
Example config.yaml (Excerpts):
trading:
initial_balance: 1000.0 # Starting capital in USDC
trade_size: 100.0 # Amount of USDC to spend per trade
max_positions: 4
profit_target_1: 0.01 # 1% profit target
profit_target_2: 0.007 # 0.7% fallback profit target
cumulative_profit_target: 0.035 # 3.5% overall portfolio profit target
fib_entry_threshold: -0.003
fib_reset_threshold: 0.035
max_candle_range: 0.016
countdown_periods: 10 # Max 10 5-min candles to hit profit_target_1
require_fib50_cross: true
position_spacing_pct: -0.03 # Require 3% dip for new concurrent entry
paths:
live_data: sol_usdc_price_history_jupiter.csv
trade_history: trade_history.csv
chart_styles:
fib_0_line:
color: "#FFFFFF" # Solid White
dash: "solid"
width: 1
fib_50_line:
color: "#FFFF00" # Dotted Yellow
dash: "dot"
width: 1
entry_threshold_line:
color: "#FF0000" # Solid Red
dash: "solid"
width: 1
# ... other line stylesTo start the trading bot, follow the Quick Start Guide.
Optional Arguments for python3 main.py start:
-
--configor-c: Specify a custom configuration file.python3 main.py start --config config/my_custom_config.yaml
-
--intervalor-i: Set the check interval (in seconds) for new live data in the CSV.python3 main.py start --interval 5 # Check CSV file for updates every 5 seconds
If you want to simulate live data (e.g., for testing without a live price tracker), you can use a pre-populated CSV file and introduce delays in main.py's process_new_data loop. This allows you to observe the bot's behavior and live charts in a controlled manner.
Example: (Modify main.py accordingly for testing purposes only)
# In main.py, inside async def process_new_data(self, csv_path):
# ... existing code ...
for idx, row in new_data_df.iterrows():
# ... process data point ...
await asyncio.sleep(1) # Pause for 1 second between processing 1-minute price pointsmain.py: The bot's core entry point. Manages initialization of all components, orchestrates the market monitoring loop, and handles graceful shutdown.data_handler.py: Processes raw 1-minute price data from the CSV, aggregates it into 5-minute candlestick data, and maintains the historical data for indicators.indicators.py: Contains theFibonacciCalculatorclass, responsible for calculating raw Fibonacci levels and their Weighted Moving Averages (WMAs).trade_manager.py: Houses theTradeManagerclass, which evaluates the sophisticated entry and exit conditions based on market data and indicators. It decides when to execute a trade.position_manager.py: Manages all open positions, maintains the trade history, calculates individual and overall portfolio profits (in USDC), and tracks the bot's USDC balance and SOL holdings.live_chart.py: A Dash application that provides a real-time, interactive web interface for visualizing market data, Fibonacci levels, trade actions, and performance statistics.logger.py: Provides structured console logging for bot events, status updates, and debugging information.backtest_manager.py: (Currently commented out) Manages the backtesting process on historical data.
The live chart is a Dash application that displays:
- Candlestick Chart: Real-time price movements with completed and current forming candles.
- WMA Fibonacci Levels: Plots the
WMA Fib 0,WMA Fib 50, andEntry Thresholdlines dynamically, with customizable appearance. - Trade Markers: Visual indicators for trade entries, exits, and their profit/loss paths.
- Trade Statistics: Displays comprehensive metrics such as Total Trades, Win Rate, Average Profit per Trade, Best/Worst Trade, Total USDC Profit, and Overall Capital Gain Percentage.
- Bot Status: Shows whether the "Entry Switch" is armed.
Accessing the Live Chart:
By default, the live chart runs on http://localhost:8051. Open this URL in your web browser to view the chart and statistics.
The bot employs a dynamic Fibonacci-based strategy with precise entry, exit, and risk management rules:
-
Entry Conditions:
- The bot's "Entry Switch" is armed when the current candle's
lowprice touches or drops below a configurablefib_entry_thresholdrelative to theWMA Fib 0level. This identifies significant pullbacks. - An actual entry occurs (i.e., a buy order is placed) only if the switch is armed AND the current candle's close price re-crosses above the
WMA Fib 0level. - Crucially, the previous candle must have closed below the
WMA Fib 0level to confirm a true "re-cross from below" reversal. - The current candle's range must be within
max_candle_rangeto avoid volatile entries. - Position Spacing: If other positions are open, the new entry must be at least
position_spacing_pct(e.g., 3%) lower than the lowest existing entry price, promoting dollar-cost averaging. - The bot must have sufficient USDC balance and not exceed
max_positions.
- The bot's "Entry Switch" is armed when the current candle's
-
Exit Conditions:
- Profit Target 1: If the trade hits a specified
profit_target_1(e.g., 1%) withincountdown_periods(e.g., 10 5-min candles):- If
require_fib50_crossistrueAND the current price is above theWMA Fib 50level, the bot holds the trade, aiming for further gains. - If the price is not above
WMA Fib 50(i.e., at or below), the trade is closed forprofit_target_1.
- If
- Profit Target 2: If
countdown_periodsexpire andprofit_target_1hasn't been met (or wasn't closed due to Fib 50 hold), the bot attempts to close the trade at a lowerprofit_target_2(e.g., 0.7%). - Cumulative Profit Target: If the overall portfolio's cumulative profit (realized + unrealized) as a percentage of initial capital (
cumulative_profit_target) is reached, all open positions are closed, provided the_check_fib50_condition(previous candle closed below WMA Fib 50) is met. This ensures a strategic full portfolio exit. - (Self-correction): The "Entry Switch" will automatically disarm if the price moves too far above
WMA Fib 0after being armed, preventing stale signals.
- Profit Target 1: If the trade hits a specified
-
Risk Management:
- Strict limits on
max_positionscontrol total exposure. - Trade sizes are fixed in USDC, ensuring predictable capital deployment.
- Balance tracking prevents overspending.
- The position spacing strategy inherently reduces risk by averaging down.
- Strict limits on
Q: Can I use this bot for other trading pairs?
A: Yes, but you'll need to adjust the sol_usd_tracker.py script, config.yaml paths, and verify the strategy parameters are suitable for the new pair's volatility.
Q: Is this bot ready for live trading with real money?
A: This bot is provided for educational and simulated trading purposes. While robust features are implemented, real-money trading involves significant risk. Thorough testing (backtesting, paper trading), professional financial advice, and understanding of exchange APIs/fees are essential before deploying with real funds.
Q: How do I add more indicators or modify the strategy?
A: You can extend the indicators.py and trade_manager.py modules to incorporate additional indicators and adjust the trading logic. The config.yaml provides a centralized place for parameter tuning.
Q: The live chart doesn't display correctly. What should I do?
A: Ensure all dependencies are installed, the python3 sol_usd_tracker.py is running in a separate terminal and generating data, and main.py start is running. Check both terminals for any error messages. Verify the chart port (http://localhost:8051) is accessible.
Contributions are welcome! If you'd like to improve the bot, add new features, or fix bugs, please follow these steps:
-
Fork the Repository: Click the "Fork" button at the top right of this page to create a copy of the repository on your account.
-
Clone Your Fork:
git clone [https://github.com/yourusername/wif-sol-trading-bot.git](https://github.com/yourusername/wif-sol-trading-bot.git)
-
Create a New Branch:
git checkout -b my-feature
-
Make Your Changes: Add new features or fix issues as needed.
-
Commit Your Changes:
git commit -am 'Add new feature' -
Push to Your Fork:
git push origin my-feature
-
Submit a Pull Request: Go back to the original repository and open a pull request with a description of your changes.
This project is licensed under the MIT License - see the LICENSE file for details.
- Libraries Used:
- Pandas: Data manipulation and analysis.
- NumPy: Numerical computing.
- Plotly Dash: Interactive web applications and live charting.
- Rich: For beautiful console logging.
- PyYAML: YAML parsing and configuration handling.
- Asyncio: Asynchronous I/O.
- Typer: Building the command-line interface.
- pytz: Timezone handling.
For any questions or support, please open an issue on the repository or contact the maintainer.
Happy Trading! 🚀
