1. System Architecture
The Trading Bot is not just a script, but a complex ecosystem that joins technical analysis, artificial intelligence, and real-time execution. It was designed to operate 24/7 without human intervention, utilizing an "Integrity Shield" to avoid operations during data failure moments.
2. The Python Engine (Backend)
The heart of the project is in backend/services/bybit_service.py. It manages all communication with the exchange. Below is the real integration class code, with protected credentials.
import os
from pybit.unified_trading import HTTP
class BybitEngine:
def __init__(self):
# Credentials loaded from environment variables for security
self.api_key = os.getenv("BYBIT_API_KEY") # SUBST_YOUR_KEY
self.api_secret = os.getenv("BYBIT_API_SECRET") # SUBST_YOUR_SECRET
# Unified Trading Account (UTA) Session Initialization
self.session = HTTP(
testnet=False,
api_key=self.api_key,
api_secret=self.api_secret,
)
def get_candles(self, symbol="BTCUSDT", interval="1h", limit=100):
"""Fetches historical candles for technical analysis"""
res = self.session.get_kline(
category="spot",
symbol=symbol,
interval="60", # 1 hour
limit=limit
)
return res['result']['list'] # Returns OHLCV candle list
For Beginners:
The code above creates a "phone line" to talk to the Bybit exchange. The get_candles method asks the exchange for the price history (candles). Without this history, the bot wouldn't know if the price went up or down.
3. Indicator Intelligence
In indicators.py, we transform raw prices into logical decisions. The bot uses the EMA200 (Exponential Moving Average of 200 periods) to know if the long-term trend is bullish or bearish.
def calculate_all(candles_1h):
df = pd.DataFrame(candles_1h)
# 200-period average: The water divider
df['ema200'] = df['close'].ewm(span=200, adjust=False).mean()
# RSI: Indicates if the market is "expensive" or "cheap"
# RSI > 70 (Overbought) | RSI < 30 (Oversold)
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
df['rsi'] = 100 - (100 / (1 + (gain / loss)))
# Market Regime:
last = df.iloc[-1]
if last['close'] > last['ema200']:
regime = "UPTREND"
else:
regime = "DOWNTREND"
4. The AI Tribunal (Gemini 1.5)
The main differentiator of this project is using Artificial Intelligence to filter false signals. The bot sends all technical data to Gemini and asks: "Is it worth entering?".
class GeminiAnalyst:
def analyze_trend(self, indicators):
prompt = f"""
You are the SUPREME JUDGE of the Nômade Tribunal.
Analyze the data and reply if we should BUY or WAIT.
DATA: {indicators}
Reply in JSON: {{"signal": "BUY", "score": 85, "reasoning": "..."}}
"""
response = self.model.generate_content(prompt)
return response.text
5. Front-end Dashboard
Bot control is done via a high-tech web interface using trading.html and market.html. It connects to Firebase to show real-time data without needing to refresh the page.
<!-- Real-time monitoring logic example -->
<script type="module">
import { db } from './firebase-config.js';
import { ref, onValue } from "https://www.gstatic.com/firebasejs/10.12.0/firebase-database.js";
// Listens to the current Bitcoin price in the database
onValue(ref(db, 'market/BTCUSDT/current'), (snapshot) => {
const data = snapshot.val();
document.getElementById('btc-price').innerText = `$ ${data.price}`;
});
</script>