The First AI Trading System with On-Chain Verification π
Combines real-time AI analysis with Flare Network blockchain verification to ensure every trading signal is cryptographically verified and tamper-proof.
Demo Video: https://www.loom.com/share/b8aaefd1e8654fb380e7e2461bbada2f
Deployed Link: https://veridict.netlify.app
Traditional AI trading tools have a trust problem: You can't verify if the price data and recommendations are authentic or have been tampered with.
VERIDICT solves this by integrating blockchain verification at every step:
β
FTSO Price Feeds - Decentralized oracle price data from Flare Network validators
β
Smart Contract Verification - Every trading signal is verified on-chain
β
Tamper Detection - Automatically detects and blocks manipulated data
β
Cryptographic Proofs - Each recommendation includes a verification hash
β
Component Health Monitoring - Real-time status of all verification systems
β
Rules Engine - Configurable verification rules to ensure signal quality
- π€ Gemini AI Sentiment Analysis - Advanced NLP-based market sentiment scoring
- π Real-time Market Data - Live price, volume, and market cap from CoinMarketCap
- βοΈ On-Chain Analysis - Flare blockchain activity and liquidity metrics
- π― Smart Recommendations - LONG, SHORT, or HOLD signals with confidence scores
- β‘ Leverage Suggestions - Risk-adjusted leverage recommendations (1x-20x)
- π° PnL Calculations - Projected profit/loss scenarios for perpetual trading
- π FTSO Price Feeds - Get verified prices from Flare's decentralized oracle
- π Smart Contract Verification - On-chain verification of every trading signal
- π‘οΈ FDC Integration - Flare Data Connector for cross-chain data attestation
- π Verification Hash - SHA-256 hash of every recommendation for audit trails
- β Price Matching - Ensures AI price matches blockchain-verified price (Β±1% tolerance)
Real-time health tracking of all verification components:
- FTSO Price Feed status
- CoinMarketCap API availability
- FDC endpoint health
- Smart contract connectivity
- Response time monitoring
- Automatic failure detection
Demonstrates the verification system's robustness:
- Price Manipulation - Simulates fake price data to test detection
- Sentiment Corruption - Tests resilience against manipulated sentiment
- Proof Invalidation - Verifies FDC attestation proof validation
- Real-time tamper detection and blocking
Configurable verification rules with a mini DSL:
- YAML-based rule configuration
- Dynamic rule evaluation
- Critical vs. warning severity levels
- Automatic signal blocking on rule failures
- 29+ built-in verification rules
- π Autonomous Agent Loop - Background analysis every second
- π‘ RESTful API - Poll for instant recommendations
- π WebSocket Support - Real-time streaming updates
- Live Price Tracking - Smooth price updates with adaptive variation
- π Price History - Last 100 data points with timestamps
- π Automated Position Tracking - Track LONG/SHORT positions
- π΅ Real-time PnL - Live profit/loss calculations
- π¦ Exit Signals - Automatic take-profit and stop-loss triggers
- βοΈ Risk-Based Sizing - Position sizing based on risk level (conservative/moderate/aggressive)
- π Multi-Session Support - Track multiple positions simultaneously
- π¦ Official Python SDK -
verdict-sdkfor easy integration - π Bring Your Own Key (BYOK) - Use your own API keys
- π No Backend Required - Works with any deployed VERDICT API
- π Comprehensive Docs - Examples, guides, and best practices
- π Async/Await Support - Built for modern Python applications
- π§ Environment Configuration -
.envfile management - π Comprehensive Logging - Detailed logs for debugging
- π§ͺ Test Suite - Unit tests and integration tests
- π API Documentation - Interactive Swagger/ReDoc docs
- π Deployment Guides - Render, Railway, AWS, DigitalOcean
- Quick Start
- Installation
- API Endpoints
- Flare Network Verification
- Advanced Features
- Python SDK Usage
- Project Structure
- How It Works
- Deployment
- Risk Disclaimer
git clone <repository-url>
cd VERIDICT
cd backend
pip install -r requirements.txtCreate a .env file in the backend/ directory:
# Required API Keys
CMC_API_KEY=your_coinmarketcap_api_key
GEMINI_API_KEY=your_gemini_api_key
# Flare Network Configuration
FLARE_RPC_URL=https://coston2-api.flare.network/ext/C/rpc
VERIFIER_CONTRACT_ADDRESS=your_deployed_contract_address
DEPLOYER_PRIVATE_KEY=your_wallet_private_keyGet API Keys:
- CoinMarketCap: https://coinmarketcap.com/api/ (Free: 333 calls/day)
- Gemini AI: https://aistudio.google.com/app/apikey (Free: 60 req/min)
cd backend
python app.pyThe API will be available at:
- API: http://localhost:8000
- Interactive Docs: http://localhost:8000/docs
- Alternative Docs: http://localhost:8000/redoc
curl -X POST "http://localhost:8000/api/analyze" \
-H "Content-Type: application/json" \
-d '{
"token": "BTC",
"stablecoin": "USDC",
"portfolio_amount": 1000.0,
"risk_level": "moderate"
}'cd backend
pip install -r requirements.txtcd backend
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txtPOST /api/analyzeRequest:
{
"token": "APT",
"stablecoin": "USDC",
"portfolio_amount": 100.0,
"risk_level": "moderate",
"cmc_api_key": "optional_user_key",
"gemini_api_key": "optional_user_key"
}Response:
{
"token": "APT",
"recommendation": "LONG",
"confidence": 78.5,
"signal_score": 35.67,
"market_data": {
"price": 8.52,
"percent_change_24h": 2.45,
"volume_24h": 45234567
},
"sentiment_data": {
"overall_sentiment": 45.23,
"risk_level": "Medium",
"key_factors": ["Strong volume", "Positive momentum"]
},
"leverage_suggestion": {
"suggested_leverage": 10,
"max_safe_leverage": 20
},
"perp_trade_details": {
"position_size_usd": 1000.0,
"if_price_moves_5pct_up": {
"pnl": 50.0,
"roi_pct": 50.0
}
},
"verified": true,
"ftso_price": 8.53,
"verification_hash": "a3f5e2..."
}| Endpoint | Method | Description |
|---|---|---|
/api/activate |
POST | Start autonomous agent loop (updates every 1s) |
/api/deactivate |
POST | Stop autonomous agent |
/api/status/{token}/{stablecoin}/{amount} |
GET | Check agent status |
/api/historical/{token}?days=7 |
GET | Historical OHLC data |
/api/component-status |
GET | Component health status |
/api/simulate-attack |
POST | Simulate data tampering |
/api/reset-simulation |
POST | Reset attack simulation |
/api/rules |
GET | View verification rules |
/api/health |
GET | API health check |
VERDICT uses a multi-layer verification approach:
graph LR
A[AI Analysis] --> B[Get CMC Price]
B --> C[Get FTSO Price]
C --> D{Price Match?}
D -->|Yes| E[FDC Attestation]
D -->|No| F[BLOCK Signal]
E --> G[Smart Contract Verify]
G --> H{Rules Engine}
H -->|Pass| I[β
Verified]
H -->|Fail| F
I --> J[Generate Hash]
-
FTSO Price Verification
- Gets decentralized oracle price from Flare validators
- Compares AI declared price vs. FTSO price
- Accepts Β±1% tolerance
- Blocks signals if mismatch detected
-
FDC Data Connector
- Provides cross-chain data attestation
- Validates external data sources
- Generates cryptographic proofs
-
Smart Contract Logging
- Stores every verified decision on-chain
- Immutable audit trail
- Query past decisions and statistics
-
Rules Engine Evaluation
- 29+ configurable verification rules
- Checks:
- Price deviation limits
- Confidence thresholds
- Leverage safety bounds
- Sentiment consistency
- Data freshness
- Automatically blocks signals that fail critical rules
Every recommendation includes a SHA-256 verification hash:
hash = SHA256(token + timestamp + ftso_price + ai_price + verified + recommendation)
This hash can be:
- Stored in your database
- Compared against on-chain records
- Used for audit trails
- Verified by third parties
Check the health of all verification systems:
curl http://localhost:8000/api/component-statusResponse:
{
"overall": "healthy",
"components": {
"ftso_feed": {
"status": "healthy",
"response_time_ms": 234,
"last_check": "2024-01-15T10:30:00"
},
"cmc_api": {
"status": "healthy",
"response_time_ms": 156
},
"fdc_endpoint": {
"status": "healthy"
},
"contract_verifier": {
"status": "healthy"
}
},
"summary": {
"healthy": 4,
"warning": 0,
"offline": 0,
"avg_response_time_ms": 195
}
}Test the verification system's resilience:
# Simulate price manipulation
curl -X POST "http://localhost:8000/api/simulate-attack" \
-H "Content-Type: application/json" \
-d '{"attack_type": "price_manipulation"}'
# Reset simulation
curl -X POST "http://localhost:8000/api/reset-simulation"Available Attack Types:
price_manipulation- Corrupt price datasentiment_corruption- Manipulate sentiment scoresproof_invalidation- Invalidate FDC proofs
The system will automatically detect and block tampered signals.
View and configure verification rules:
curl http://localhost:8000/api/rulesRules are defined in backend/verification_rules.yaml:
- name: "FTSO Price Deviation Check"
type: "verification"
severity: "critical"
condition: "ftso_price_diff_pct <= 2.0"
message: "FTSO price deviates too much from AI price"
- name: "Confidence Threshold"
type: "quality"
severity: "warning"
condition: "confidence >= 60.0"
message: "Confidence score too low"Rule Evaluation:
- Critical rules block signals if they fail
- Warning rules only log warnings
- Rules use Python-like expressions
- Full access to analysis context (market_data, sentiment, etc.)
pip install verdict-sdk
# or from source:
cd sdk-python && pip install -e .import asyncio
from verdict_sdk import VerdictClient
async def main():
client = VerdictClient(
api_url="http://localhost:8000",
cmc_api_key="YOUR_CMC_KEY",
gemini_api_key="YOUR_GEMINI_KEY"
)
# Single analysis
result = await client.analyze("BTC", portfolio_amount=1000)
print(f"{result.recommendation} - {result.confidence}% confident")
print(f"Verified: {'β
' if result.verified else 'β'}")
await client.close()
asyncio.run(main())async def monitor():
client = VerdictClient(...)
async for analysis in client.stream_agent("BTC", portfolio_amount=1000, interval=2.0):
print(f"[{analysis.timestamp}] ${analysis.market_data.price:,.2f} | {analysis.recommendation}")
asyncio.run(monitor())See SDK_USAGE_GUIDE.md for complete documentation.
VERDICT/
βββ backend/ # Backend API Server
β βββ app.py # Main FastAPI application
β βββ app_flare.py # Flare Network integration
β βββ market_data.py # CoinMarketCap API
β βββ sentiment_analyzer.py # Gemini AI sentiment analysis
β βββ decision_engine.py # Signal combination & recommendation
β βββ position_manager.py # Position tracking & management
β βββ flare_analyzer.py # On-chain data analysis
β βββ ftso_price_feed.py # FTSO price feed integration
β βββ flare_data_connector.py # FDC integration
β βββ flare_verifier.py # Smart contract verification
β βββ component_monitor.py # Component health monitoring
β βββ attack_simulator.py # Security testing & tamper detection
β βββ rules_engine.py # Verification rules engine
β βββ verification_rules.yaml # Rules configuration
β βββ websocket_client.py # WebSocket support
β βββ requirements.txt # Python dependencies
β
βββ frontend/ # Web Dashboard
β βββ dashboard.html # Main trading dashboard
β βββ verification.html # Flare verification UI
β βββ README.md
β
βββ contracts/ # Smart Contracts
β βββ VerifierContract.sol # Flare verifier contract
β βββ scripts/deploy.js # Deployment script
β
βββ sdk-python/ # Python SDK
β βββ verdict_sdk/ # SDK source code
β βββ examples/ # Usage examples
β βββ setup.py # Package configuration
β βββ README.md
β
βββ scripts/ # Utility scripts
βββ DEPLOYMENT_GUIDE.md # Deployment instructions
βββ SDK_USAGE_GUIDE.md # SDK documentation
βββ CURL_COMMANDS.md # API examples
βββ README.md # This file
- Fetches real-time price, volume, and market metrics from CoinMarketCap
- Tracks 1h, 24h, and 7d price changes
- Monitors market cap and trading volume
- Uses Google Gemini AI to analyze market conditions
- Generates sentiment scores (-100 to +100)
- Identifies key market factors
- Assesses risk levels (Low/Medium/High)
- Analyzes flare blockchain activity
- Tracks transaction volume and liquidity
- Generates on-chain trading signals
- FTSO: Gets decentralized oracle price from Flare validators
- Price Matching: Ensures AI price matches blockchain price (Β±1%)
- FDC: Validates data with cryptographic attestation
- Smart Contract: Logs verified decisions on-chain
- Rules Engine: Evaluates 29+ verification rules
Combines all signals with weighted scoring:
- Sentiment: 35%
- Market Momentum: 30%
- On-Chain Signals: 20%
- Risk Assessment: 15%
Generates final recommendation (LONG/SHORT/HOLD) with:
- Confidence score (0-100%)
- Suggested leverage (1x-20x based on confidence and risk)
- Potential PnL calculations
- Verification status and hash
- Tracks open positions (LONG/SHORT)
- Calculates real-time PnL based on current price
- Automatic exit signals:
- Take Profit: 15% gain
- Stop Loss: -10% loss
- Signal Reversal: Opposite recommendation with high confidence
- Push code to GitHub
- Go to https://render.com
- Create new Web Service from your repo
- Configure:
- Build:
pip install -r backend/requirements.txt - Start:
python backend/app.py - Environment Variables: Add your API keys
- Build:
docker build -t verdict-api .
docker run -p 8000:8000 --env-file backend/.env verdict-apiSee DEPLOYMENT_GUIDE.md for detailed instructions.
Deploy the VerifierContract to Flare Coston2 testnet:
cd contracts
npx hardhat run scripts/deploy.js --network coston2See DEPLOYMENT_GUIDE.md for complete setup.
This tool is for informational and research purposes only.
- β Not financial advice
- β No guarantees on accuracy or profitability
- β Cryptocurrency trading is highly risky
- β Leverage amplifies both gains and losses
Always:
- β Do your own research (DYOR)
- β Never invest more than you can afford to lose
- β Understand leverage and liquidation risks
- β Use stop-loss orders
- β Start with small positions
- β Test thoroughly before using real funds
Blockchain verification ensures data authenticity, NOT trading profitability.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
MIT License - see LICENSE
- Documentation: See README files in each directory
- API Examples: CURL_COMMANDS.md
- SDK Guide: SDK_USAGE_GUIDE.md
- Deployment: DEPLOYMENT_GUIDE.md
- Flare Network: https://flare.network
- Flare Docs: https://docs.flare.network
- FTSO: https://docs.flare.network/tech/ftso/
- FDC: https://docs.flare.network/tech/state-connector/
- Gemini AI: https://ai.google.dev/
Built with β€οΈ for transparent, verifiable AI trading
Combining the power of AI with the trust of blockchain verification