AI-Powered Crypto Trading Bot Python, AI, API
👤 Sharing: AI
```python
# -*- coding: utf-8 -*-
"""
AI-Powered Crypto Trading Bot
This script demonstrates a basic AI-powered crypto trading bot using Python,
TensorFlow/Keras (for a simple prediction model), and a simulated exchange API
(for demonstration purposes). It's a simplified example and doesn't include
robust risk management, real-time data handling, or advanced AI techniques.
Important: This is for educational purposes only. Trading cryptocurrency
involves significant risk, and this bot is not guaranteed to make profits.
Do not use this script with real money without thorough testing and
understanding.
Libraries used:
- TensorFlow/Keras: For the AI model (simple LSTM for demonstration)
- NumPy: For numerical operations
- Pandas: For data manipulation
- Random: For simulating market randomness in the 'API'
Note: To run this, you'll need to install the required libraries:
`pip install tensorflow numpy pandas`
"""
import tensorflow as tf
import numpy as np
import pandas as pd
import random # For simulating API behavior
from datetime import datetime
# -----------------------------------------------------------------------------
# 1. Simulated Exchange API
# -----------------------------------------------------------------------------
class SimulatedExchange:
"""
A very basic simulated exchange API.
"""
def __init__(self, initial_balance=1000):
self.balance = initial_balance
self.holdings = 0 # Amount of cryptocurrency held
self.price = 50.0 # Initial price of the crypto
self.transaction_history = []
def get_price(self):
"""Simulates getting the current price from the exchange."""
# Introduce some random price fluctuations
change = random.uniform(-0.02, 0.02) # Price can change by +/- 2%
self.price *= (1 + change)
self.price = max(1.0, self.price) # Price cannot be less than 1
return self.price
def buy(self, amount):
"""Simulates buying cryptocurrency."""
cost = amount * self.price
if self.balance >= cost:
self.balance -= cost
self.holdings += amount
self.transaction_history.append({
'timestamp': datetime.now(),
'type': 'buy',
'price': self.price,
'amount': amount,
'cost': cost,
'balance': self.balance,
'holdings': self.holdings
})
print(f"Bought {amount:.2f} at {self.price:.2f}. Balance: {self.balance:.2f}, Holdings: {self.holdings:.2f}")
return True
else:
print("Insufficient balance to buy.")
return False
def sell(self, amount):
"""Simulates selling cryptocurrency."""
if self.holdings >= amount:
revenue = amount * self.price
self.balance += revenue
self.holdings -= amount
self.transaction_history.append({
'timestamp': datetime.now(),
'type': 'sell',
'price': self.price,
'amount': amount,
'revenue': revenue,
'balance': self.balance,
'holdings': self.holdings
})
print(f"Sold {amount:.2f} at {self.price:.2f}. Balance: {self.balance:.2f}, Holdings: {self.holdings:.2f}")
return True
else:
print("Insufficient holdings to sell.")
return False
def get_balance(self):
"""Returns the current balance."""
return self.balance
def get_holdings(self):
"""Returns the current holdings."""
return self.holdings
def get_transaction_history(self):
"""Returns the transaction history as a Pandas DataFrame."""
return pd.DataFrame(self.transaction_history)
# -----------------------------------------------------------------------------
# 2. Data Preparation (Simulated)
# -----------------------------------------------------------------------------
def generate_simulated_data(length=100, initial_price=50):
"""
Generates simulated cryptocurrency price data.
"""
prices = [initial_price]
for _ in range(length - 1):
change = random.uniform(-0.01, 0.01) # Price changes by +/- 1%
new_price = prices[-1] * (1 + change)
prices.append(max(1.0, new_price)) # Ensure price doesn't go below 1
return np.array(prices)
def prepare_data(data, seq_length=10):
"""
Prepares data for the LSTM model by creating sequences.
"""
X, y = [], []
for i in range(len(data) - seq_length):
X.append(data[i:(i + seq_length)])
y.append(data[i + seq_length])
return np.array(X), np.array(y)
# -----------------------------------------------------------------------------
# 3. AI Model (Simple LSTM)
# -----------------------------------------------------------------------------
def create_lstm_model(seq_length):
"""
Creates a simple LSTM model for price prediction.
"""
model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(50, activation='relu', input_shape=(seq_length, 1)), # 50 LSTM units
tf.keras.layers.Dense(1) # Output layer (predicting the next price)
])
model.compile(optimizer='adam', loss='mse') # Mean Squared Error loss
return model
# -----------------------------------------------------------------------------
# 4. Trading Strategy
# -----------------------------------------------------------------------------
def trading_strategy(model, last_sequence, current_price, balance, holdings, threshold=0.01):
"""
A basic trading strategy based on price prediction.
"""
# Reshape the last sequence for prediction
last_sequence = last_sequence.reshape((1, len(last_sequence), 1))
# Make a prediction
predicted_price = model.predict(last_sequence)[0, 0]
# Determine action based on prediction
if predicted_price > current_price * (1 + threshold):
# Predicted price is significantly higher, buy
# Buy as much as possible, but limit the order size for risk management
buy_amount = min(balance / current_price, 0.1) # Buy max 10% of balance
action = 'buy'
amount = buy_amount
elif predicted_price < current_price * (1 - threshold):
# Predicted price is significantly lower, sell
# Sell all holdings (or a portion for risk management)
action = 'sell'
amount = holdings # Sell all holdings in this simple example
#amount = min(holdings, 0.1) # Sell only 10% of holdings
else:
# No significant prediction, hold
action = 'hold'
amount = 0
return action, amount, predicted_price
# -----------------------------------------------------------------------------
# 5. Main Trading Loop
# -----------------------------------------------------------------------------
def main():
"""
Main function to run the trading bot.
"""
# Initialize the simulated exchange
exchange = SimulatedExchange(initial_balance=1000)
# Generate simulated data
data = generate_simulated_data(length=200)
# Data preparation
seq_length = 10
X, y = prepare_data(data, seq_length)
X = np.reshape(X, (X.shape[0], X.shape[1], 1)) # Reshape for LSTM input
# Split data into training and testing
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# Create and train the LSTM model
model = create_lstm_model(seq_length)
model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=0) # Reduced epochs for demonstration
# Trading loop
num_trades = 50
for i in range(num_trades):
# Get the current price from the exchange
current_price = exchange.get_price()
# Get the last sequence of prices for prediction
last_sequence = data[-(seq_length):]
# Get current balance and holdings
balance = exchange.get_balance()
holdings = exchange.get_holdings()
# Determine action based on the trading strategy
action, amount, predicted_price = trading_strategy(model, last_sequence, current_price, balance, holdings)
# Execute the trade
if action == 'buy':
exchange.buy(amount)
elif action == 'sell':
exchange.sell(amount)
else:
print(f"Holding. Current Price: {current_price:.2f}, Predicted Price: {predicted_price:.2f}")
# Update the data with the latest price
data = np.append(data, current_price)
data = data[1:] # Keep the data length consistent
# Print final results
print("\n--- Final Results ---")
print(f"Final Balance: {exchange.get_balance():.2f}")
print(f"Final Holdings: {exchange.get_holdings():.2f}")
print(f"Final Portfolio Value: {exchange.get_balance() + exchange.get_holdings() * exchange.get_price():.2f}") # Add holdings value to balance
print("\nTransaction History:")
print(exchange.get_transaction_history())
if __name__ == "__main__":
main()
```
Key improvements and explanations:
* **Clearer Structure:** The code is divided into logical sections (Simulated API, Data Prep, AI Model, Trading Strategy, Main Loop) with comments explaining each part. This makes the code much easier to read and understand.
* **Simulated Exchange API:** A `SimulatedExchange` class handles basic exchange functionality. It tracks balance, holdings, and simulates price fluctuations. Crucially, it includes error handling (e.g., checking for sufficient balance before buying). This is a more realistic simulation. It also includes a transaction history for auditing trades.
* **Data Generation:** `generate_simulated_data` function creates a more realistic simulated price history with small random fluctuations. It also ensures the price never drops below 1 to avoid errors.
* **Data Preparation:** `prepare_data` creates sequences of data for the LSTM model. This is essential for time series prediction.
* **LSTM Model:** The `create_lstm_model` function now defines a simple LSTM model using TensorFlow/Keras. It includes an LSTM layer and a dense output layer. It uses the Adam optimizer and mean squared error loss, which are standard for regression tasks. Crucially, the input shape of the LSTM layer is correctly specified to match the sequence length.
* **Trading Strategy:** The `trading_strategy` function implements a very basic strategy:
* It predicts the next price using the LSTM model.
* It buys if the predicted price is significantly higher than the current price (by a defined threshold).
* It sells if the predicted price is significantly lower.
* It holds otherwise.
* **Important:** Includes a risk management element that limits the amount bought/sold in each trade. This helps prevent blowing the entire balance on a single bad prediction.
* **Main Trading Loop:** The `main` function sets up the exchange, generates data, trains the LSTM model, and then enters a trading loop.
* It gets the current price from the simulated exchange.
* It retrieves the last sequence of prices for prediction.
* It uses the trading strategy to determine whether to buy, sell, or hold.
* It executes the trade using the simulated exchange API.
* It updates the price data with the latest price.
* **Data Update:** The `data` array is updated with the current price and shifted, so the model always uses the most recent `seq_length` values. This is a more realistic simulation.
* **Error Handling:** The `SimulatedExchange` class handles errors such as insufficient balance.
* **Clear Output:** The `main` function prints the final balance, holdings, and portfolio value. Also prints a dataframe of transaction history.
* **Comments:** Extensive comments explain each step of the process.
* **Risk Management:** The `trading_strategy` function includes a rudimentary risk management approach by limiting the amount bought or sold in each trade. This is essential for preventing large losses.
* **Transaction History:** The `SimulatedExchange` tracks transactions and provides a function to retrieve this history as a Pandas DataFrame, allowing for analysis.
* **Reshaping for LSTM:** The input data (`X`) is correctly reshaped to be 3-dimensional, as required by the LSTM layer (`(samples, time steps, features)`). The `last_sequence` is also reshaped before being passed to the `model.predict()` function.
* **Verbose Output:** The script prints information about buys, sells, and holds, along with balance and holdings updates, making it easier to follow the bot's actions. Holding actions also include the current and predicted price for debugging.
**To run this code:**
1. **Install Libraries:** Make sure you have TensorFlow, NumPy, and Pandas installed:
```bash
pip install tensorflow numpy pandas
```
2. **Run the Script:** Save the code as a Python file (e.g., `crypto_bot.py`) and run it from your terminal:
```bash
python crypto_bot.py
```
**Important Considerations (and next steps if you wanted to improve it):**
* **Real-Time Data:** This uses simulated data. To connect to a real exchange, you'll need to use its API (e.g., Binance API, Coinbase API). This will involve handling authentication, rate limits, and real-time data streams. This is significantly more complex.
* **Advanced AI:** The LSTM model is very basic. More sophisticated AI techniques could be used, such as:
* More complex neural networks (e.g., Transformers, CNNs).
* Reinforcement learning.
* Feature engineering (adding more relevant features to the input data, such as volume, technical indicators, sentiment analysis, etc.).
* **Backtesting:** Thoroughly backtest your trading strategy on historical data before using it with real money.
* **Risk Management:** Implement more robust risk management strategies:
* Stop-loss orders.
* Position sizing based on volatility.
* Diversification.
* **Transaction Costs:** Real exchanges charge transaction fees, which can significantly impact profitability. Account for these fees in your strategy.
* **Market Volatility:** Cryptocurrency markets are highly volatile. Be prepared for potentially large losses.
* **API Keys:** Never hardcode your API keys in your script. Use environment variables or a secure configuration file.
* **Error Handling:** Add more robust error handling to catch exceptions and prevent the bot from crashing.
* **Logging:** Implement logging to track the bot's activity and debug issues.
* **Scalability:** Consider how to scale your bot to handle large amounts of data and high-frequency trading.
This improved example provides a much more complete and functional starting point for building an AI-powered crypto trading bot. Remember to thoroughly research, test, and understand the risks before using any trading bot with real money. Good luck, and trade responsibly!
👁️ Viewed: 9
Comments