Practical examples for integrating with the Phi Protocol API
Base URL: https://api-live.phiprotocol.ai
Authentication: Add your API key in the header: X-API-Key: phi_live_your_key_here
⚡ Credit Usage:
Get real-time bridge quotes for cross-chain transfers.
const getBridgeQuote = async (amount, fromChain, toChain, token) => { const params = new URLSearchParams({ amount: amount, fromChain: fromChain, toChain: toChain, token: token }); const response = await fetch( `https://api-live.phiprotocol.ai/api/bridge/quote/wormhole?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const quote = await response.json(); console.log('Bridge Quote:', quote); return quote; }; // Usage getBridgeQuote('1000000000', 'solana', 'ethereum', 'USDC') .then(quote => { console.log('Amount Out:', quote.data.amountOut); console.log('Estimated Time:', quote.data.estimatedTime); console.log('Bridge Fee:', quote.data.fees.bridgeFee); });
Get real-time token prices and market data.
const getTokenPrices = async (tokens) => { const params = new URLSearchParams({ tokens: tokens.join(','), currency: 'USD' }); const response = await fetch( `https://api-live.phiprotocol.ai/api/market-data/prices?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getTokenPrices(['BTC', 'ETH', 'SOL']) .then(data => { Object.entries(data.data.prices).forEach(([token, info]) => { console.log(`${token}: $${info.price}`); console.log(`24h Change: ${info.priceChangePercent24h.toFixed(2)}%`); }); });
Get historical price data for charting.
const getChartData = async (symbol, interval = '1d', limit = 100) => { const params = new URLSearchParams({ symbol: symbol, interval: interval, limit: limit }); const response = await fetch( `https://api-live.phiprotocol.ai/api/market-data/chart?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage with Chart.js getChartData('BTC', '1d', 30) .then(data => { const chartData = { labels: data.data.timestamps, datasets: [{ label: 'BTC Price', data: data.data.prices, borderColor: 'rgb(75, 192, 192)', backgroundColor: 'rgba(75, 192, 192, 0.2)', tension: 0.1 }] }; // Use with Chart.js new Chart(ctx, { type: 'line', data: chartData, options: { responsive: true, plugins: { title: { display: true, text: 'Bitcoin Price Chart' } } } }); });
Get comprehensive AI-powered market analysis.
const getMarketAnalysis = async (tokens, analysisType = 'all') => { const response = await fetch( 'https://api-live.phiprotocol.ai/api/defi-intelligence/analysis', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': 'phi_live_1234567890abcdef' }, body: JSON.stringify({ tokens: tokens, analysisType: analysisType, timeframe: '7d' }) } ); const analysis = await response.json(); return analysis; }; // Usage getMarketAnalysis(['BTC', 'ETH', 'SOL']) .then(analysis => { console.log('Market Overview:', analysis.data.analysis.overview); console.log('Technical Analysis:', analysis.data.analysis.technicalAnalysis); console.log('Risk Assessment:', analysis.data.analysis.riskAssessment); });
A comprehensive class for building DeFi dashboards.
class DeFiDashboard { constructor(apiKey, baseUrl = 'https://api-live.phiprotocol.ai') { this.apiKey = apiKey; this.baseUrl = baseUrl; this.headers = { 'X-API-Key': apiKey, 'Content-Type': 'application/json' }; } async getBridgeQuote(amount, fromChain, toChain, token) { const params = new URLSearchParams({ amount, fromChain, toChain, token }); const response = await fetch( `${this.baseUrl}/bridge/wormhole-quote?${params}`, { headers: this.headers } ); return await response.json(); } async getTokenPrices(tokens) { const params = new URLSearchParams({ tokens: tokens.join(','), currency: 'USD' }); const response = await fetch( `${this.baseUrl}/market/prices?${params}`, { headers: this.headers } ); return await response.json(); } async getPortfolio(address) { const response = await fetch( `${this.baseUrl}/market/portfolio/${address}`, { headers: this.headers } ); return await response.json(); } async getMarketAnalysis(tokens) { const response = await fetch( `${this.baseUrl}/defi/analysis`, { method: 'POST', headers: this.headers, body: JSON.stringify({ tokens: tokens, analysisType: 'all', timeframe: '7d' }) } ); return await response.json(); } async getSupportedChains() { const response = await fetch( `${this.baseUrl}/bridge/supported-chains`, { headers: this.headers } ); return await response.json(); } } // Usage const dashboard = new DeFiDashboard('YOUR_API_KEY'); // Get comprehensive market data Promise.all([ dashboard.getTokenPrices(['BTC', 'ETH', 'SOL']), dashboard.getMarketAnalysis(['BTC', 'ETH', 'SOL']), dashboard.getSupportedChains() ]).then(([prices, analysis, chains]) => { console.log('Prices:', prices); console.log('Analysis:', analysis); console.log('Supported Chains:', chains); });
A complete Python client for the Phi Protocol API.
import requests import json from typing import List, Dict, Any class PhiDeFiClient: def __init__(self, api_key: str, base_url: str = "https://api-live.phiprotocol.ai"): self.api_key = api_key self.base_url = base_url self.headers = { 'X-API-Key': api_key, 'Content-Type': 'application/json' } def get_bridge_quote(self, amount: str, from_chain: str, to_chain: str, token: str) -> Dict[str, Any]: """Get bridge quote for cross-chain transfers""" params = { 'amount': amount, 'fromChain': from_chain, 'toChain': to_chain, 'token': token } response = requests.get( f"{self.base_url}/bridge/wormhole-quote", params=params, headers=self.headers ) return response.json() def get_token_prices(self, tokens: List[str], currency: str = "USD") -> Dict[str, Any]: """Get real-time token prices""" params = { 'tokens': ','.join(tokens), 'currency': currency } response = requests.get( f"{self.base_url}/market/prices", params=params, headers=self.headers ) return response.json() def get_chart_data(self, symbol: str, interval: str = "1d", limit: int = 100) -> Dict[str, Any]: """Get historical chart data""" params = { 'symbol': symbol, 'interval': interval, 'limit': limit } response = requests.get( f"{self.base_url}/market/chart", params=params, headers=self.headers ) return response.json() def get_market_analysis(self, tokens: List[str], analysis_type: str = "all", timeframe: str = "7d") -> Dict[str, Any]: """Get comprehensive market analysis""" payload = { 'tokens': tokens, 'analysisType': analysis_type, 'timeframe': timeframe } response = requests.post( f"{self.base_url}/defi/analysis", json=payload, headers=self.headers ) return response.json() def get_portfolio(self, address: str) -> Dict[str, Any]: """Get portfolio data for a wallet address""" response = requests.get( f"{self.base_url}/market/portfolio/{address}", headers=self.headers ) return response.json() # Usage Example if __name__ == "__main__": client = PhiDeFiClient("YOUR_API_KEY") # Get token prices prices = client.get_token_prices(['BTC', 'ETH', 'SOL']) print("Token Prices:", json.dumps(prices, indent=2)) # Get bridge quote quote = client.get_bridge_quote('1000000000', 'solana', 'ethereum', 'USDC') print("Bridge Quote:", json.dumps(quote, indent=2)) # Get market analysis analysis = client.get_market_analysis(['BTC', 'ETH']) print("Market Analysis:", analysis['data']['analysis']['overview'])
A simple trading bot that uses market analysis for decision making.
import time import logging from datetime import datetime class SimpleTradingBot: def __init__(self, api_key: str, tokens: List[str]): self.client = PhiDeFiClient(api_key) self.tokens = tokens self.logger = logging.getLogger(__name__) def analyze_market(self) -> Dict[str, Any]: """Get comprehensive market analysis""" analysis = self.client.get_market_analysis(self.tokens) return analysis['data']['analysis'] def get_current_prices(self) -> Dict[str, float]: """Get current token prices""" prices = self.client.get_token_prices(self.tokens) return { token: data['price'] for token, data in prices['data']['prices'].items() } def should_buy(self, token: str, analysis: Dict[str, Any]) -> bool: """Simple buy logic based on analysis""" technical = analysis.get('technicalAnalysis', {}) sentiment = analysis.get('sentimentAnalysis', {}) # Simple strategy: buy if trend is bullish and sentiment is positive return ( technical.get('trend') == 'bullish' and sentiment.get('overall') == 'positive' and technical.get('indicators', {}).get('rsi', 0) < 70 ) def should_sell(self, token: str, analysis: Dict[str, Any]) -> bool: """Simple sell logic based on analysis""" technical = analysis.get('technicalAnalysis', {}) risk = analysis.get('riskAssessment', {}) # Simple strategy: sell if risk is high or RSI is overbought return ( risk.get('riskLevel') == 'high' or technical.get('indicators', {}).get('rsi', 0) > 80 ) def run_analysis_cycle(self): """Run one analysis cycle""" try: print(f"[{datetime.now()}] Running market analysis...") # Get analysis and prices analysis = self.analyze_market() prices = self.get_current_prices() # Make decisions for each token for token in self.tokens: current_price = prices.get(token) if self.should_buy(token, analysis): print(f"🟢 BUY SIGNAL: {token} at ${current_price}") print(f" Trend: {analysis['technicalAnalysis']['trend']}") print(f" Sentiment: {analysis['sentimentAnalysis']['overall']}") elif self.should_sell(token, analysis): print(f"🔴 SELL SIGNAL: {token} at ${current_price}") print(f" Risk Level: {analysis['riskAssessment']['riskLevel']}") else: print(f"⚪ HOLD: {token} at ${current_price}") print("-" * 50) except Exception as e: self.logger.error(f"Analysis cycle failed: {e}") def start(self, interval: int = 300): # 5 minutes """Start the trading bot""" print(f"Starting trading bot for tokens: {', '.join(self.tokens)}") print(f"Analysis interval: {interval} seconds") while True: self.run_analysis_cycle() time.sleep(interval) # Usage if __name__ == "__main__": bot = SimpleTradingBot("YOUR_API_KEY", ['BTC', 'ETH', 'SOL']) bot.start(interval=300) # Run every 5 minutes
Handle API errors gracefully in production applications.
class ApiClient { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://api-live.phiprotocol.ai'; this.rateLimitDelay = 1000; // 1 second between requests this.lastRequestTime = 0; } async makeRequest(endpoint, options = {}) { // Rate limiting const now = Date.now(); const timeSinceLastRequest = now - this.lastRequestTime; if (timeSinceLastRequest < this.rateLimitDelay) { await new Promise(resolve => setTimeout(resolve, this.rateLimitDelay - timeSinceLastRequest) ); } try { const response = await fetch(`${this.baseUrl}${endpoint}`, { ...options, headers: { 'X-API-Key': this.apiKey, 'Content-Type': 'application/json', ...options.headers } }); this.lastRequestTime = Date.now(); if (!response.ok) { const errorData = await response.json().catch(() => ({})); switch (response.status) { case 401: throw new Error('Invalid API key. Please check your credentials.'); case 429: throw new Error('Rate limit exceeded. Please slow down requests.'); case 400: throw new Error(`Bad request: ${errorData.details || 'Invalid parameters'}`); case 500: throw new Error('Server error. Please try again later.'); default: throw new Error(`HTTP ${response.status}: ${errorData.error || 'Unknown error'}`); } } return await response.json(); } catch (error) { if (error.name === 'TypeError' && error.message.includes('fetch')) { throw new Error('Network error. Please check your connection.'); } throw error; } } async getTokenPricesWithRetry(tokens, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { const params = new URLSearchParams({ tokens: tokens.join(','), currency: 'USD' }); return await this.makeRequest(`/market/prices?${params}`); } catch (error) { console.warn(`Attempt ${i + 1} failed:`, error.message); if (i === maxRetries - 1) { throw error; } // Exponential backoff const delay = Math.pow(2, i) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); } } } } // Usage const client = new ApiClient('YOUR_API_KEY'); client.getTokenPricesWithRetry(['BTC', 'ETH', 'SOL']) .then(prices => console.log('Prices:', prices)) .catch(error => console.error('Failed to get prices:', error.message));
Access institutional-grade liquidity analysis, arbitrage opportunities, and advanced volatility metrics.
const getLiquidityAnalysis = async (token, chains = 'ethereum,bsc,polygon') => { const params = new URLSearchParams({ token: token, chains: chains, depth_levels: '1,5,10' }); const response = await fetch( `https://api-live.phiprotocol.ai/api/advanced-market-data/liquidity?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getLiquidityAnalysis('ethereum', 'ethereum,bsc') .then(data => { console.log('Total Liquidity:', data.data.liquidity_analysis.total_liquidity_usd); console.log('Price Impact Analysis:', data.data.liquidity_analysis.depth_analysis); });
const getArbitrageOpportunities = async (token, minProfit = 0.5) => { const params = new URLSearchParams({ token: token, min_profit: minProfit, exchanges: 'uniswap,pancakeswap,sushiswap' }); const response = await fetch( `https://api-live.phiprotocol.ai/api/advanced-market-data/arbitrage?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getArbitrageOpportunities('ethereum', 1.0) .then(data => { data.data.opportunities.forEach(opp => { console.log(`Profit: ${opp.profit_percentage}% between ${opp.buy_exchange} and ${opp.sell_exchange}`); }); });
const getVolatilityAnalysis = async (token, timeframe = '24h', type = 'realized') => { const params = new URLSearchParams({ token: token, timeframe: timeframe, type: type }); const response = await fetch( `https://api-live.phiprotocol.ai/api/advanced-market-data/volatility?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getVolatilityAnalysis('ethereum', '7d', 'realized') .then(data => { console.log('Current Volatility:', data.data.volatility.current); console.log('Historical Average:', data.data.volatility.average); console.log('Risk Level:', data.data.volatility.risk_level); });
const getYieldOpportunities = async (token = null, minApy = 5, riskLevel = 'medium') => { const params = new URLSearchParams({ min_apy: minApy, risk_level: riskLevel, chains: 'ethereum,bsc,polygon,avalanche,solana' }); if (token) { params.append('token', token); } const response = await fetch( `https://api-live.phiprotocol.ai/api/advanced-market-data/yield-opportunities?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getYieldOpportunities('ethereum', 8, 'medium') .then(data => { console.log(`Found ${data.data.total_opportunities} opportunities`); console.log(`Highest APY: ${data.data.highest_apy}`); data.data.opportunities.forEach(opp => { console.log(`${opp.protocol} on ${opp.chain}: ${opp.apy} APY (${opp.risk_level} risk)`); }); });
const getTokenCorrelations = async (baseToken, compareTokens = 'ethereum,solana,binancecoin', timeframe = '30d') => { const params = new URLSearchParams({ base_token: baseToken, compare_tokens: compareTokens, timeframe: timeframe }); const response = await fetch( `https://api-live.phiprotocol.ai/api/advanced-market-data/correlations?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getTokenCorrelations('ethereum', 'solana,binancecoin,hyperliquid', '30d') .then(data => { console.log(`Correlations for ${data.data.base_token}:`); Object.entries(data.data.correlations).forEach(([token, corr]) => { console.log(`${token}: ${corr.correlation} (${corr.strength} ${corr.direction})`); }); console.log(`Diversification Score: ${data.data.market_insights.diversification_score}/100`); console.log(`Portfolio Risk: ${data.data.market_insights.portfolio_risk}`); });
const getFearGreedIndex = async (timeframe = '7d', includeBreakdown = true) => { const params = new URLSearchParams({ timeframe: timeframe, include_breakdown: includeBreakdown }); const response = await fetch( `https://api-live.phiprotocol.ai/api/advanced-market-data/fear-greed?${params}`, { headers: { 'X-API-Key': 'phi_live_1234567890abcdef' } } ); const data = await response.json(); return data; }; // Usage getFearGreedIndex('7d', true) .then(data => { console.log(`Current Index: ${data.data.current_index}/100 (${data.data.sentiment})`); console.log(`Weekly Average: ${data.data.weekly_average}`); console.log(`Trend: ${data.data.market_analysis.trend}`); if (data.data.component_breakdown) { console.log('Component Breakdown:'); Object.entries(data.data.component_breakdown).forEach(([component, info]) => { console.log(` ${component}: ${info.value}/100 (${info.weight})`); }); } console.log(`Recommendation: ${data.data.market_analysis.recommendation}`); });
class AdvancedMarketAnalytics { constructor(apiKey, baseUrl = 'https://api-live.phiprotocol.ai') { this.apiKey = apiKey; this.baseUrl = baseUrl; this.headers = { 'X-API-Key': apiKey, 'Content-Type': 'application/json' }; } async getLiquidityAnalysis(token, chains = 'ethereum,bsc,polygon', depthLevels = '1,5,10') { const params = new URLSearchParams({ token, chains, depth_levels: depthLevels }); const response = await fetch( `${this.baseUrl}/api/advanced-market-data/liquidity?${params}`, { headers: this.headers } ); return await response.json(); } async getArbitrageOpportunities(token, minProfit = 0.5, exchanges = 'all') { const params = new URLSearchParams({ token, min_profit: minProfit, exchanges }); const response = await fetch( `${this.baseUrl}/api/advanced-market-data/arbitrage?${params}`, { headers: this.headers } ); return await response.json(); } async getVolatilityAnalysis(token, timeframe = '24h', type = 'realized') { const params = new URLSearchParams({ token, timeframe, type }); const response = await fetch( `${this.baseUrl}/api/advanced-market-data/volatility?${params}`, { headers: this.headers } ); return await response.json(); } async getYieldOpportunities(token = null, minApy = 1, riskLevel = 'all', chains = 'ethereum,bsc,polygon,avalanche,solana') { const params = new URLSearchParams({ min_apy: minApy, risk_level: riskLevel, chains }); if (token) params.append('token', token); const response = await fetch( `${this.baseUrl}/api/advanced-market-data/yield-opportunities?${params}`, { headers: this.headers } ); return await response.json(); } async getTokenCorrelations(baseToken, compareTokens = 'ethereum,solana,binancecoin', timeframe = '30d') { const params = new URLSearchParams({ base_token: baseToken, compare_tokens: compareTokens, timeframe }); const response = await fetch( `${this.baseUrl}/api/advanced-market-data/correlations?${params}`, { headers: this.headers } ); return await response.json(); } async getFearGreedIndex(timeframe = '1d', includeBreakdown = true) { const params = new URLSearchParams({ timeframe, include_breakdown: includeBreakdown }); const response = await fetch( `${this.baseUrl}/api/advanced-market-data/fear-greed?${params}`, { headers: this.headers } ); return await response.json(); } // Combined analysis method async getComprehensiveAnalysis(token) { const [liquidity, arbitrage, volatility, correlations, fearGreed] = await Promise.all([ this.getLiquidityAnalysis(token), this.getArbitrageOpportunities(token, 0.5), this.getVolatilityAnalysis(token, '7d'), this.getTokenCorrelations(token), this.getFearGreedIndex('7d') ]); return { token, liquidity: liquidity.data, arbitrage: arbitrage.data, volatility: volatility.data, correlations: correlations.data, market_sentiment: fearGreed.data, analysis_timestamp: new Date().toISOString() }; } } // Usage const analytics = new AdvancedMarketAnalytics('YOUR_API_KEY'); // Get comprehensive analysis for Ethereum analytics.getComprehensiveAnalysis('ethereum') .then(analysis => { console.log('Comprehensive Analysis:', analysis); // Extract key insights console.log('Key Insights:'); console.log(`- Total Liquidity: ${analysis.liquidity.total_liquidity}`); console.log(`- Arbitrage Opportunities: ${analysis.arbitrage.opportunities_found}`); console.log(`- Volatility Level: ${analysis.volatility.current_volatility}`); console.log(`- Market Sentiment: ${analysis.market_sentiment.sentiment}`); });
Build a comprehensive portfolio tracking application.
// Track portfolio performance
dashboard.getPortfolio(walletAddress)
// Get price alerts
dashboard.getTokenPrices(['BTC', 'ETH'])
// Analyze market trends
dashboard.getMarketAnalysis(['BTC', 'ETH'])
Create a bridge aggregator that finds the best routes.
// Compare bridge options
const wormholeQuote = await getBridgeQuote(...)
const debrIdgeQuote = await getDebrIdgeQuote(...)
// Find best route
const bestRoute = findOptimalRoute(quotes)
Build an AI-powered trading assistant.
// Get AI analysis
const analysis = await getMarketAnalysis(['BTC'])
// Risk assessment
const riskLevel = analysis.riskAssessment.riskLevel
// Trading recommendations
const recommendations = analysis.recommendations
Create a mobile app with real-time market data.
// React Native / Flutter
const prices = await fetchTokenPrices()
// Real-time updates
setInterval(updatePrices, 30000)
// Push notifications
sendPriceAlert(priceChange > 5)