📄
pasted-code-1791471544786.txt
txt
1066 lines
▶
You are a senior Python backend engineer, quantitative trading-system developer, Telegram Bot developer, AI integration engineer, and security-focused software architect.
Build a professional Telegram trading-signal bot called:
AUREX AI SIGNAL
The bot is designed for automated market monitoring and high-quality trading setup alerts.
IMPORTANT:
This is NOT a football bot, general chatbot, entertainment bot, or unrestricted AI assistant.
The bot’s scope must be STRICTLY limited to:
* Trading
* Technical analysis
* Market analysis
* Trading strategies
* Risk management
* AUREX AI features
* Signals generated by AUREX
* Questions about how AUREX works
If a user asks about football tips, football betting, movies, coding unrelated to AUREX, homework, politics, general trivia, or any unrelated topic, the bot MUST politely refuse.
Example:
“I’m AUREX AI Signal. I can only help with trading, market analysis, trading strategies, risk management, and AUREX features.”
==================================================
1. TECHNOLOGY STACK
==================================================
Use:
* Python 3.11+
* python-telegram-bot
* Twelve Data API for market data
* Gemini API for AI analysis
* SQLite for development, with architecture easy to migrate to PostgreSQL
* asyncio for background monitoring
* .env for secrets
* Logging system
* Modular architecture
Never hardcode API keys.
Environment variables:
TWELVE_DATA_API_KEY=
GEMINI_API_KEY=
TELEGRAM_BOT_TOKEN=
Optional:
ADMIN_TELEGRAM_ID=
DATABASE_URL=
TIMEZONE=Asia/Phnom_Penh
==================================================
2. TELEGRAM BOT IDENTITY
Bot name:
AUREX AI SIGNAL
Brand style:
Premium
Dark
Professional
Minimal
Financial-terminal inspired
Clean
No childish design
No excessive emojis
Main welcome message:
“Welcome to AUREX AI SIGNAL.
AI-powered market monitoring, technical analysis and trading setup detection.
AUREX continuously monitors supported markets and alerts you when a high-quality setup is detected.
Select an option below.”
==================================================
3. MAIN MENU
Create an inline-keyboard based menu.
Main menu:
[ Live Signals ]
[ Market Analysis ]
[ Watchlist ]
[ Strategies ]
[ Risk Management ]
[ Signal History ]
[ AUREX AI ]
[ Settings ]
Admin-only:
[ Admin Panel ]
==================================================
4. LIVE SIGNALS
When the user selects Live Signals, show:
AUREX LIVE SIGNALS
Status:
Market Scanner: ONLINE
AI Engine: ONLINE
Data Feed: ONLINE
Supported assets should initially include:
XAUUSD
BTCUSD
Design the architecture so additional symbols can easily be added later.
For each active signal show:
Asset
Direction
Entry
Stop Loss
TP1
TP2
TP3
Risk/Reward
Timeframe
Signal Score
Confidence
Setup Type
Status
Example:
AUREX SIGNAL
XAUUSD
BUY
Entry:
4107.67
SL:
4098.50
TP1:
4116.00
TP2:
4125.00
TP3:
4138.00
Risk/Reward:
1:3.3
Setup:
Bullish Breakout + Pullback
Score:
89/100
Status:
ACTIVE
==================================================
5. AUTOMATIC SIGNAL DETECTION
The bot must NOT wait for the user to type /signal.
Create a background market scanner.
The scanner continuously checks market data from Twelve Data.
Recommended scan intervals should be configurable.
Example:
SCAN_INTERVAL_SECONDS=60
The scanner should:
1. Fetch latest market data.
2. Validate the data.
3. Calculate technical indicators.
4. Detect potential setups.
5. Reject weak setups.
6. Send qualifying setups to Gemini.
7. Gemini analyzes and confirms/rejects the setup.
8. Apply final risk and quality filters.
9. Send Telegram alert only when the setup passes all filters.
IMPORTANT:
Do NOT spam signals.
Only send a signal when there is a meaningful setup.
Add duplicate-signal protection.
Do not send the same setup repeatedly.
==================================================
6. TECHNICAL ANALYSIS ENGINE
Create a deterministic technical-analysis layer BEFORE Gemini.
Use multiple factors.
Include:
* EMA 20
* EMA 50
* EMA 200
* RSI
* MACD
* ATR
* Volume when available
* Support
* Resistance
* Swing highs
* Swing lows
* Market structure
* Breakout detection
* Pullback detection
* Trend detection
* Momentum
* Volatility
Detect structures such as:
* Trend continuation
* Breakout
* Pullback
* Support bounce
* Resistance rejection
* Liquidity sweep
* Higher-high / higher-low
* Lower-high / lower-low
* Momentum expansion
* Consolidation breakout
Do NOT generate a signal simply because RSI is overbought/oversold.
Use confluence.
==================================================
7. MULTI-TIMEFRAME ANALYSIS
Use multiple timeframes.
Recommended:
Higher timeframe:
4H / 1H
Confirmation:
15M
Entry:
5M
The exact timeframes should be configurable.
Example:
HTF = 1H
CONFIRMATION_TF = 15M
ENTRY_TF = 5M
The system should determine:
Higher timeframe trend
Market structure
Momentum
Entry setup
Avoid trading against strong higher-timeframe structure unless the setup specifically supports a reversal.
==================================================
8. GEMINI AI ANALYSIS
Use Gemini API as the AI confirmation and explanation layer.
Do NOT let Gemini blindly invent prices.
Gemini must receive verified market data generated by the technical engine.
Send Gemini:
* Current price
* OHLC data
* Indicators
* Market structure
* Support/resistance
* ATR
* Trend
* Candidate entry
* Candidate SL
* Candidate TP
* Risk/reward
* Timeframe
* Recent price movement
Gemini must return STRICT JSON.
Example:
{
“decision”: “BUY”,
“confidence”: 89,
“score”: 89,
“setup_quality”: “HIGH”,
“entry”: 4107.67,
“stop_loss”: 4098.50,
“tp1”: 4116.00,
“tp2”: 4125.00,
“tp3”: 4138.00,
“risk_reward”: “1:3.3”,
“setup_type”: “Bullish Breakout + Pullback”,
“trend”: “BULLISH”,
“reasoning”: “…”,
“invalidated_if”: “…”,
“warnings”: []
}
If Gemini returns invalid JSON, safely handle the error.
Never crash the bot.
==================================================
9. SIGNAL QUALITY FILTER
Create a strict scoring system.
Example:
Trend alignment: 20
Market structure: 20
Momentum: 15
Entry quality: 15
Support/resistance: 10
Volume: 5
Risk/reward: 10
AI confirmation: 5
Total:
100 points
Only send an automatic signal when:
Score >= 85
Make the threshold configurable.
Example:
MIN_SIGNAL_SCORE=85
Do NOT claim that 85 means an 85% probability of winning.
“Score” and “confidence” are analytical metrics, NOT guaranteed win probability.
==================================================
10. RISK MANAGEMENT
Every signal must contain:
Entry
SL
TP1
TP2
TP3
Risk/reward
Invalidation condition
Reject setups with poor risk/reward.
Recommended minimum:
1:2
Configurable:
MIN_RISK_REWARD=2.0
Never promise guaranteed profits.
Add educational risk warning:
“Trading involves significant risk. AUREX signals are analytical information, not guaranteed financial advice.”
==================================================
11. SIGNAL STATUS TRACKING
Every signal must have a status:
WAITING
ACTIVE
TP1 HIT
TP2 HIT
TP3 HIT
SL HIT
INVALIDATED
EXPIRED
The bot should continuously monitor active signals.
When price reaches TP1:
“TP1 HIT”
When TP2:
“TP2 HIT”
When TP3:
“TP3 HIT”
When SL:
“SL HIT”
Update the database after every status change.
Prevent duplicate status notifications.
==================================================
12. SIGNAL EXPIRATION
Signals should not remain active forever.
Create configurable expiration.
Example:
SIGNAL_EXPIRATION_MINUTES=360
If a setup becomes invalid before entry:
INVALIDATED
If the market moves away without triggering entry:
EXPIRED
==================================================
13. NEWS FILTER
Design the architecture for an optional economic-news module.
If no news API is configured yet, do NOT fake news data.
Instead show:
“News filter unavailable — external economic calendar not configured.”
Create a placeholder interface so a news API can be added later.
The system should eventually be able to detect:
CPI
NFP
FOMC
Interest rate decisions
PPI
GDP
Unemployment
Major central-bank announcements
For XAUUSD, major USD news should be treated as high-impact events.
==================================================
14. MARKET ANALYSIS MENU
When user selects Market Analysis:
Show:
[ XAUUSD ]
[ BTCUSD ]
After selecting an asset:
AUREX MARKET ANALYSIS
Price:
…
Trend:
…
Market Structure:
…
Momentum:
…
RSI:
…
MACD:
…
ATR:
…
Support:
…
Resistance:
…
Bias:
BUY / SELL / NEUTRAL
Setup Quality:
…
Then provide:
[ Ask AUREX ]
[ Back ]
==================================================
15. ASK AUREX
Allow users to ask trading-related questions.
Examples:
“What is a liquidity sweep?”
“Explain risk/reward.”
“What does RSI mean?”
“Why is XAUUSD bullish?”
“Explain this setup.”
“What’s the difference between scalping and swing trading?”
Gemini should answer only trading-related questions.
STRICT TOPIC FILTER:
Allowed:
Trading
Forex
Crypto
Technical analysis
Trading psychology
Risk management
Market structure
Indicators
AUREX features
Not allowed:
Football
Football betting
Sports predictions
Movies
Homework
Politics
Programming unrelated to AUREX
General trivia
Illegal activities
Unrelated personal questions
For unrelated questions return:
“I’m AUREX AI Signal. I can only answer questions related to trading, markets, trading strategies, risk management, and AUREX.”
==================================================
16. STRATEGIES MENU
Create:
[ Trend Following ]
[ Breakout ]
[ Pullback ]
[ Support & Resistance ]
[ Market Structure ]
[ Scalping ]
[ Swing Trading ]
[ Risk Management ]
Each option should provide a concise educational explanation.
==================================================
17. WATCHLIST
Allow users to create a watchlist.
Example:
My Watchlist
XAUUSD
BTCUSD
Buttons:
[ Add Asset ]
[ Remove Asset ]
[ Analyze ]
[ Back ]
Architecture must support more symbols later.
==================================================
18. SIGNAL HISTORY
Show historical AUREX signals.
Example:
Signal #1024
XAUUSD BUY
TP1 HIT
TP2 HIT
TP3 HIT
Signal #1023
BTCUSD SELL
SL HIT
Provide:
Total signals
TP hits
SL hits
Win/loss statistics
Average R:R
IMPORTANT:
Do not manipulate statistics.
Calculate them directly from stored signal records.
==================================================
19. SETTINGS
Settings menu:
[ Notifications ]
[ Default Asset ]
[ Timeframe ]
[ Signal Score ]
[ Risk Preference ]
[ Timezone ]
Allow users to enable/disable automatic signal notifications.
==================================================
20. NOTIFICATION TYPES
Allow:
New Signal
TP1
TP2
TP3
SL
Invalidated
Expired
Users can enable/disable each notification type.
==================================================
21. TELEGRAM COMMANDS
Implement:
/start
/menu
/signals
/market
/watchlist
/strategies
/history
/settings
/about
/help
Admin:
/admin
==================================================
22. /ABOUT
Show:
AUREX AI SIGNAL
AI-powered market monitoring and technical analysis platform.
Powered by:
Twelve Data
Gemini AI
AUREX analyzes market conditions and identifies potential trading setups using technical analysis, market structure, risk management and AI-assisted confirmation.
No guaranteed profits.
==================================================
23. ADMIN PANEL
Only ADMIN_TELEGRAM_ID can access.
Admin features:
* Bot status
* API status
* Scanner status
* Number of users
* Active signals
* Signal history
* Broadcast message
* Enable/disable scanner
* Change minimum score
* Change scan interval
* Add/remove supported symbols
* Maintenance mode
* View error logs
Never expose API keys in Telegram.
==================================================
24. API FAILURE HANDLING
The bot must gracefully handle:
Twelve Data timeout
Twelve Data rate limit
Gemini timeout
Gemini rate limit
Invalid Gemini response
Telegram API error
Network error
Missing data
Insufficient candles
Never crash the entire application because one API request fails.
Use:
Retries
Exponential backoff
Timeouts
Logging
Graceful fallback
If data is unreliable:
DO NOT generate a signal.
Return:
“Market data unavailable. Signal generation paused.”
==================================================
25. DATA VALIDATION
Before generating a signal verify:
* Symbol is correct
* Timestamp is current
* Price is valid
* OHLC values are valid
* Enough candles exist
* No NaN values
* Indicators calculated successfully
* Entry is realistic
* SL is logically positioned
* TP levels are logically positioned
* Risk/reward is valid
Never invent missing data.
==================================================
26. SECURITY
Use .env.
Never print API keys.
Never expose:
TWELVE_DATA_API_KEY
GEMINI_API_KEY
TELEGRAM_BOT_TOKEN
Validate admin Telegram ID.
Rate-limit user commands.
Protect against prompt injection through user messages.
User input must NEVER override system trading rules.
==================================================
27. DATABASE
Create tables for:
users
watchlists
signals
signal_events
user_settings
bot_settings
Signal fields should include:
id
symbol
direction
entry
stop_loss
tp1
tp2
tp3
score
confidence
setup_type
timeframe
reasoning
status
created_at
updated_at
tp1_hit_at
tp2_hit_at
tp3_hit_at
sl_hit_at
expired_at
==================================================
28. LOGGING
Create structured logs.
Examples:
[INFO] Scanner started
[INFO] XAUUSD data received
[INFO] Potential setup detected
[INFO] Gemini analysis started
[INFO] Setup rejected: score 72
[INFO] Signal approved: XAUUSD BUY
[INFO] Telegram alert sent
[INFO] TP1 reached
[ERROR] Gemini API timeout
Do not log secrets.
==================================================
29. PERFORMANCE
Do not make unnecessary API requests.
Cache market data where appropriate.
Avoid sending duplicate Gemini requests for identical setups.
Respect Twelve Data API rate limits.
Use asynchronous requests where appropriate.
==================================================
30. BOT RESPONSE STYLE
Use concise professional language.
Do not overuse emojis.
Prefer:
AUREX SIGNAL
XAUUSD
BUY
instead of excessive decorative text.
Use clean Telegram formatting with Markdown/HTML where appropriate.
==================================================
31. IMPORTANT TRADING LOGIC
AUREX must NEVER:
* Guarantee profits
* Claim 100% accuracy
* Invent market prices
* Invent news
* Invent indicators
* Invent historical performance
* Generate signals when data is missing
* Generate signals just to satisfy the user
* Spam signals
* Treat AI confidence as guaranteed probability
If no high-quality setup exists:
“NO HIGH-QUALITY SETUP
AUREX is currently monitoring the market.
No trade is better than a low-quality trade.”
This behavior is extremely important.
==================================================
32. AUTOMATIC SIGNAL EXAMPLE
When a high-quality setup is detected, Telegram should receive:
AUREX AI SIGNAL
XAUUSD — BUY
Entry:
4107.67
Stop Loss:
4098.50
TP1:
4116.00
TP2:
4125.00
TP3:
4138.00
Risk/Reward:
1:3.3
Timeframe:
5M / 15M / 1H
Setup:
Bullish Breakout + Pullback
Signal Score:
89/100
AI Confidence:
HIGH
Analysis:
Higher-timeframe structure is bullish. Price broke resistance and is attempting a controlled pullback. Momentum remains supportive and the proposed stop is positioned beyond structural invalidation.
Invalidation:
A confirmed break below 4098.50 invalidates the setup.
Status:
ACTIVE
Risk Warning:
Trading involves significant risk. This signal is analytical information, not guaranteed financial advice.
==================================================
33. PROJECT STRUCTURE
Use a clean modular structure such as:
aurex_bot/
│
├── bot.py
├── config.py
├── database.py
├── requirements.txt
├── .env.example
│
├── handlers/
│ ├── start.py
│ ├── menu.py
│ ├── market.py
│ ├── signals.py
│ ├── strategies.py
│ ├── watchlist.py
│ ├── history.py
│ ├── settings.py
│ └── admin.py
│
├── services/
│ ├── twelve_data.py
│ ├── gemini.py
│ ├── scanner.py
│ ├── signal_engine.py
│ ├── risk_manager.py
│ ├── signal_tracker.py
│ └── news.py
│
├── analysis/
│ ├── indicators.py
│ ├── market_structure.py
│ ├── setup_detector.py
│ └── scoring.py
│
└── utils/
├── logger.py
├── validators.py
└── formatting.py
==================================================
34. INSTALLATION
Generate:
requirements.txt
.env.example
README.md
The README must explain:
1. How to create a Telegram bot using BotFather.
2. How to obtain Twelve Data API key.
3. How to obtain Gemini API key.
4. How to configure .env.
5. How to install dependencies.
6. How to start the bot.
7. How to run the scanner.
8. How to configure symbols.
9. How to configure signal threshold.
10. How to configure admin ID.
==================================================
35. FINAL REQUIREMENT
Do NOT create a fake/demo bot.
Build a functional implementation with real:
Twelve Data API
Gemini API
Telegram Bot API
Database
Automatic scanner
Signal engine
AI analysis
Signal tracking
Telegram notifications
If an API capability is unavailable, clearly isolate it behind a service interface instead of pretending it works.
Prioritize reliability and data validation over generating more signals.
The core philosophy of AUREX is:
“WAIT FOR THE SETUP. DON’T FORCE THE TRADE.”
Generate all necessary source files and provide exact setup instructions.
Set up the modular AUREX bot, configuration, SQLite storage, and installation docs.
Implement validated Twelve Data feeds, deterministic multi-timeframe analysis, Gemini confirmation, and signal tracking.
Add the Telegram menus, commands, user settings, admin controls, and background scanner.
Created the AUREX AI SIGNAL Telegram bot with a background scanner, Twelve Data market feeds, deterministic multi-timeframe analysis, Gemini setup confirmation, SQLite persistence, signal tracking, inline menus, user settings, and admin controls.
To run it: use Python 3.11+, copy .env.example to .env, add your Telegram, Twelve Data, and Gemini API keys, then run:
python -m pip install -r requirements.txt
python bot.py
The scanner starts with the bot and pauses signal generation if either market data or Gemini confirmation is unavailable. The optional news filter is explicitly marked as unconfigured rather than inventing news. Setup details and admin commands are in README.md.
If not done yet continue do
The project has no explicit TODOs or unimplemented stubs, but I don’t have the earlier task you want me to continue. It’s currently a Telegram market-analysis bot; the README notes that its news filter is intentionally unavailable. Tell me which feature or change you meant.
Continue
Plan:
Add optional Finnhub economic-calendar configuration and caching.
Block new setups near high-impact events; fail closed if configured calendar data is unavailable.
Update the market-status text and setup instructions.
Implemented the economic-calendar news filter with optional Finnhub support. When FINNHUB_API_KEY is set, high-impact events block new setups for 30 minutes before and after release; calendar failures fail closed. Without the key, the filter remains disabled.
Add FINNHUB_API_KEY=your_finnhub_key to .env to enable it.
Done?
Yes—the Finnhub economic-calendar filter is implemented. Add FINNHUB_API_KEY to .env to enable it; without the key, the filter stays disabled.
What that for
It’s a news filter for the trading bot. When enabled with a Finnhub API key, it checks for high-impact economic events and pauses new trade setups for 30 minutes before and after them, when markets can be unusually volatile. Without the key, it does nothing.
How to get telegram id?
To get your Telegram user ID, open Telegram and message @userinfobot. It will reply with your numeric ID.
If you need a group’s chat ID instead, add your bot to the group and send a message there; the ID will be available from the bot’s updates. Don’t share your bot token.
Did it auto alert if have best setup?
Yes. It automatically sends a Telegram alert when the scanner finds a new qualifying “HIGH” setup that meets the configured score threshold. You’ll receive it after you send the bot /start and have notifications enabled with /notifications on.
It won’t alert on every market scan, and duplicate setups are suppressed.
Why bot said this Market data unavailable. Signal generation paused. when analyzing market
That message means the bot couldn’t get valid candle data from Twelve Data, so it paused analysis rather than create a signal from incomplete data.
Common causes are a missing/invalid TWELVE_DATA_API_KEY in .env, Twelve Data rate limits, a provider/network error, or stale/insufficient data for the selected symbol or timeframe. Check the bot’s logs around the time it happened—the underlying error should say which one.
from __future__ import annotations
import asyncio
import logging
import aiohttp
from telegram.ext import Application
from aurex_bot.config import Config, load_config
from aurex_bot.database import Database
from aurex_bot.handlers import register_handlers
from aurex_bot.scanner import Scanner
from aurex_bot.services import AurexServices
def configure_logging() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logging.getLogger("httpx").setLevel(logging.WARNING)
async def post_init(application: Application) -> None:
config: Config = application.bot_data["config"]
database = Database(config.database_path)
await database.initialize()
session = aiohttp.ClientSession()
services = AurexServices(config, database, session)
scanner = Scanner(config, database, services, application.bot)
application.bot_data.update(database=database, session=session, services=services, scanner=scanner)
application.bot_data["scanner_task"] = application.create_task(scanner.run(), name="aurex-market-scanner")
logging.getLogger("aurex").info("AUREX services initialized")
async def post_shutdown(application: Application) -> None:
task = application.bot_data.get("scanner_task")
if task:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
session = application.bot_data.get("session")
if session and not session.closed:
await session.close()
def main() -> None:
configure_logging()
config = load_config()
application = (
Application.builder()
.token(config.telegram_token)
.post_init(post_init)
.post_shutdown(post_shutdown)
.build()
)
application.bot_data["config"] = config
register_handlers(application)
logging.getLogger("aurex").info("Starting AUREX AI SIGNAL")
application.run_polling(allowed_updates=["message", "callback_query"])
if __name__ == "__main__":
main()