
Taapi
- 127 installs
- 21 repo stars
- Updated August 3, 2026
- starchild-ai-agent/official-skills
Helps with ai & agent building tasks during AI-assisted development.
About
taapi is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- taapi
- AI & Agent Building
- AI-coding skill
Taapi by the numbers
- 127 all-time installs (skills.sh)
- +6 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #3,688 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/starchild-ai-agent/official-skills --skill taapiAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 127 |
|---|---|
| repo stars | ★ 21 |
| Last updated | August 3, 2026 |
| Repository | starchild-ai-agent/official-skills ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Script Usage
Script-mode skill — read this file, then invoke from a bash block:
python3 - <<'EOF'
import sys, json
sys.path.insert(0, "/data/workspace/skills/taapi")
from exports import indicator, support_resistance
# RSI on BTC/USDT 1h
rsi = indicator(name="rsi", symbol="BTC/USDT", interval="1h", exchange="binance")
print(json.dumps(rsi, indent=2))
# Support/resistance on BTC/USDT daily
sr = support_resistance(symbol="BTC/USDT", interval="1d", exchange="binance")
print(json.dumps(sr, indent=2))
EOFAvailable functions in exports.py: indicator, support_resistance. Read exports.py directly for exact signatures.
TaAPI
TaAPI provides technical analysis indicators including RSI, MACD, Bollinger Bands, support/resistance, and 200+ pre-calculated indicators. No local computation needed.
Function Reference (signatures)
All functions are in exports.py. exchange defaults to binance. symbol uses slash format like BTC/USDT. interval accepts 1m / 5m / 15m / 30m / 1h / 2h / 4h / 1d / 1w.
| Function | Description |
|---|---|
indicator(name, symbol, interval, exchange='binance', backtrack=0, backtracks=None) | Get a technical indicator. name = rsi / macd / bbands / ema / sma / adx / stoch / atr / vwap / etc (200+ supported). Returns dict like {value: 67.78} for single-output indicators or {macd, signal, histogram} for multi-output. |
support_resistance(symbol, interval, exchange='binance', indicator_type='pivots') | Compute support/resistance levels. indicator_type = pivots / fibonacciretracement / donchianchannels / etc. |
backtrack returns a single historical bar N candles back. backtracks (int) returns an array of the last N candles.
When to Use TaAPI
Use TaAPI for:
- Technical indicators - RSI, MACD, Bollinger Bands, ADX, Stochastic, etc.
- Support/Resistance - Key price levels
- Trend analysis - Moving averages, ADX, trend indicators
- Momentum - RSI, Stochastic, CCI
- Volatility - Bollinger Bands, ATR
Common Workflows
Get Indicator
indicator(exchange="binance", symbol="BTC/USDT", interval="1h", indicator="rsi")
indicator(exchange="binance", symbol="ETH/USDT", interval="4h", indicator="macd")
indicator(exchange="binance", symbol="SOL/USDT", interval="1d", indicator="bbands")Support/Resistance
support_resistance(exchange="binance", symbol="BTC/USDT", interval="1d")Available Indicators
Momentum Indicators
rsi- Relative Strength Indexstoch- Stochastic Oscillatorcci- Commodity Channel Indexwilliams- Williams %Rroc- Rate of Change
Trend Indicators
macd- Moving Average Convergence Divergenceadx- Average Directional Indexema- Exponential Moving Averagesma- Simple Moving Averagedema- Double Exponential Moving Average
Volatility Indicators
bbands- Bollinger Bandsatr- Average True Rangekeltner- Keltner Channels
Volume Indicators
obv- On Balance Volumevwap- Volume Weighted Average Price
See TaAPI documentation for the full list of 200+ indicators.
Intervals
1m,5m,15m,30m- Minutes1h,2h,4h,8h,12h- Hours1d,1w,1M- Days, Weeks, Months
Exchanges
Default exchange is Binance. Supports:
binancecoinbasekrakenbitfinex- And many more...
Symbol Format
Use exchange format: BTC/USDT, ETH/USDT, SOL/USDT
Interpretation Guides
Common Indicator Reads
| Indicator | Bullish | Bearish |
|---|---|---|
| RSI | < 30 (oversold) | > 70 (overbought) |
| MACD | Histogram crossing above zero | Histogram crossing below zero |
| Bollinger Bands | Price touching lower band | Price touching upper band |
| ADX | > 25 with +DI > -DI | > 25 with -DI > +DI |
| Stochastic | < 20 (oversold) | > 80 (overbought) |
RSI Levels
- > 70: Overbought (potential reversal down)
- 50-70: Bullish momentum
- 30-50: Bearish momentum
- < 30: Oversold (potential reversal up)
MACD Signals
- Histogram > 0: Bullish
- Histogram < 0: Bearish
- Histogram crossing zero: Trend change
- MACD line crossing signal line: Buy/sell signal
Bollinger Bands
- Price at upper band: Overbought
- Price at lower band: Oversold
- Bands widening: Increasing volatility
- Bands narrowing: Decreasing volatility (squeeze)
Analysis Patterns
Trend confirmation: Use ADX + EMA/SMA. ADX > 25 indicates strong trend. EMA crossing SMA confirms direction.
Overbought/Oversold: Use RSI + Stochastic together. Both confirming increases signal strength.
Divergence: Price making new highs/lows but indicator not confirming = potential reversal.
Important Notes
- API Key: Requires TAAPI_API_KEY environment variable
- Pre-calculated: All indicators are pre-calculated by TaAPI - no local computation needed
- Real-time: Data is near real-time from exchanges
- 200+ Indicators: TaAPI supports 200+ technical indicators
"""
TaAPI Extension - Technical Analysis Indicators
Provides technical analysis indicators including:
- RSI, MACD, Bollinger Bands
- Support/Resistance levels
- 200+ pre-calculated indicators
Environment Variables Required:
- TAAPI_API_KEY: TaAPI.io API key
Usage:
This extension is auto-loaded by the ExtensionLoader.
Tools are available to agents configured with these tools in agents.yaml.
"""
import os
import sys
import logging
from typing import List
try:
from core.tool import ToolRegistry
except Exception:
ToolRegistry = None # Standalone script usage
logger = logging.getLogger(__name__)
# Add local tools directory to path for imports
TOOLS_DIR = os.path.join(os.path.dirname(__file__), 'tools')
if TOOLS_DIR not in sys.path:
sys.path.insert(0, TOOLS_DIR)
def register(api) -> List[str]:
"""
Extension entry point - register all TaAPI tools.
Args:
api: ExtensionApi instance with registry and config
Returns:
List of registered tool names
"""
registered = []
try:
from .taapi import IndicatorTool, SupportResistanceTool
api.register_tool(IndicatorTool())
api.register_tool(SupportResistanceTool())
registered.extend(["indicator", "support_resistance"])
logger.info("Registered TaAPI tools (2 tools)")
except Exception as e:
logger.warning(f"Failed to load TaAPI tools: {e}")
return registered
# Extension metadata
EXTENSION_INFO = {
"name": "taapi",
"version": "1.0.0",
"description": "TaAPI technical analysis indicators",
"tools": [
"indicator",
"support_resistance",
],
"env_vars": [
"TAAPI_API_KEY",
],
}
"""
TaAPI skill exports — tool names match SKILL.md frontmatter.
Usage in task scripts:
from core.skill_tools import taapi
rsi = taapi.indicator(name="rsi", exchange="binance", symbol="BTC/USDT", interval="1h")
sr = taapi.support_resistance(exchange="binance", symbol="BTC/USDT", interval="1d")
"""
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "tools"))
from indicators import get_indicator
from support_resistance import get_support_resistance
def indicator(name, symbol, interval, exchange="binance", backtrack=0, backtracks=None):
"""Get technical analysis indicator (RSI, MACD, Bollinger Bands, etc.)."""
return get_indicator(
indicator=name,
exchange=exchange,
symbol=symbol,
interval=interval,
backtrack=backtrack,
backtracks=backtracks,
)
def support_resistance(symbol, interval, exchange="binance", indicator_type="pivots"):
"""Get support and resistance levels."""
return get_support_resistance(
exchange=exchange,
symbol=symbol,
interval=interval,
indicator=indicator_type,
)
"""
TaAPI Tool Wrappers
Wraps tools from /tools/taapi/ for use in Agent framework.
Provides pre-calculated technical analysis indicators.
"""
import asyncio
import logging
from core.tool import BaseTool, ToolContext, ToolResult
logger = logging.getLogger(__name__)
# Import original tools from local tools directory
try:
from .tools.indicators import get_indicator
from .tools.support_resistance import get_support_resistance
TAAPI_AVAILABLE = True
except ImportError as e:
logger.warning(f"TaAPI tools not available: {e}")
TAAPI_AVAILABLE = False
class IndicatorTool(BaseTool):
"""
Get technical analysis indicators (RSI, MACD, Bollinger Bands, etc.)
"""
@property
def name(self) -> str:
return "indicator"
@property
def description(self) -> str:
return """Get technical analysis indicators from TaAPI.
Supported indicators: rsi, macd, bbands, ema, sma, stoch, adx, cci, atr, obv, mfi
Supported intervals: 1m, 5m, 15m, 30m, 1h, 2h, 4h, 12h, 1d, 1w
Supported exchanges: binance, binancefutures, bybit, okex
Examples:
- Get BTC RSI: indicator(name="rsi", symbol="BTC/USDT", interval="1h")
- Get ETH MACD: indicator(name="macd", symbol="ETH/USDT", interval="4h")
- Get BTC Bollinger Bands: indicator(name="bbands", symbol="BTC/USDT", interval="1d")"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Indicator name: rsi, macd, bbands, ema, sma, stoch, adx, cci, atr, obv, mfi"
},
"symbol": {
"type": "string",
"description": "Trading pair in COIN/MARKET format (BTC/USDT, ETH/USDT)"
},
"interval": {
"type": "string",
"description": "Timeframe: 1m, 5m, 15m, 30m, 1h, 2h, 4h, 12h, 1d, 1w",
"default": "1h"
},
"exchange": {
"type": "string",
"description": "Exchange: binance, binancefutures, bybit, okex",
"default": "binance"
}
},
"required": ["name", "symbol"]
}
async def execute(
self,
ctx: ToolContext,
name: str,
symbol: str,
interval: str = "1h",
exchange: str = "binance"
) -> ToolResult:
if not TAAPI_AVAILABLE:
return ToolResult(
success=False,
output=None,
error="TaAPI tools not available. Check if /tools/taapi exists."
)
try:
result = await asyncio.to_thread(
get_indicator,
indicator=name,
exchange=exchange,
symbol=symbol,
interval=interval
)
if result is None:
return ToolResult(
success=False,
output=None,
error="Failed to fetch indicator. Check TAAPI_API_KEY."
)
return ToolResult(success=True, output=result)
except Exception as e:
return ToolResult(success=False, output=None, error=str(e))
class SupportResistanceTool(BaseTool):
"""
Get support and resistance levels for a trading pair.
"""
@property
def name(self) -> str:
return "support_resistance"
@property
def description(self) -> str:
return """Get support and resistance price levels.
Useful for identifying key price levels for entries, exits, and stop losses.
Examples:
- Get BTC S/R levels: support_resistance(symbol="BTC/USDT", interval="4h")
- Get ETH daily levels: support_resistance(symbol="ETH/USDT", interval="1d")"""
@property
def parameters(self) -> dict:
return {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "Trading pair (BTC/USDT, ETH/USDT)"
},
"interval": {
"type": "string",
"description": "Timeframe: 1h, 4h, 1d",
"default": "4h"
},
"exchange": {
"type": "string",
"default": "binance"
}
},
"required": ["symbol"]
}
async def execute(
self,
ctx: ToolContext,
symbol: str,
interval: str = "4h",
exchange: str = "binance"
) -> ToolResult:
if not TAAPI_AVAILABLE:
return ToolResult(
success=False,
output=None,
error="TaAPI tools not available."
)
try:
result = await asyncio.to_thread(
get_support_resistance,
exchange=exchange,
symbol=symbol,
interval=interval
)
if result is None:
return ToolResult(
success=False,
output=None,
error="Failed to fetch S/R levels. Check TAAPI_API_KEY."
)
return ToolResult(success=True, output=result)
except Exception as e:
return ToolResult(success=False, output=None, error=str(e))
"""
TaAPI.IO Integration Tools
Professional technical analysis indicators and support/resistance detection
using TaAPI.IO's 200+ indicator API.
"""
__version__ = "1.0.0"
#!/usr/bin/env python3
"""
TaAPI Indicators Module
Fetch pre-calculated technical analysis indicators from TaAPI.IO including
RSI, MACD, Bollinger Bands, Moving Averages, and 200+ other indicators.
Dependencies:
- requests: For HTTP API calls
- python-dotenv: For environment variable management
Environment Variables Required:
- TAAPI_API_KEY: Your TaAPI.IO API key (get free key at taapi.io)
Usage Example:
from tools.taapi.indicators import get_indicator
# Get RSI for Bitcoin
rsi = get_indicator("rsi", exchange="binance", symbol="BTC/USDT", interval="1h")
# Get MACD
macd = get_indicator("macd", exchange="binance", symbol="BTC/USDT", interval="4h")
CLI Usage:
python indicators.py --indicator rsi --exchange binance --symbol BTC/USDT --interval 1h
python indicators.py --indicator macd --exchange binance --symbol ETH/USDT --interval 4h
python indicators.py --indicator bbands --exchange binance --symbol BTC/USDT --interval 1d
"""
import os
import sys
import json
import argparse
from typing import Dict, Any, Optional, List
try:
from dotenv import load_dotenv
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../..'))
load_dotenv(os.path.join(project_root, '.env'))
except ImportError:
pass
from core.http_client import proxied_get, proxied_post
# TaAPI Configuration
BASE_URL = "https://api.taapi.io"
# Supported indicators
INDICATORS = [
"rsi", "macd", "bbands", "ema", "sma", "stoch", "adx", "cci", "roc",
"willr", "atr", "obv", "mfi", "ao", "kc", "dmi", "ichimoku", "psar"
]
# Supported exchanges
EXCHANGES = ["binance", "binancefutures", "bitstamp", "gateio", "bybit", "okex"]
# Supported intervals
INTERVALS = ["1m", "5m", "15m", "30m", "1h", "2h", "4h", "12h", "1d", "1w"]
def get_indicator(
indicator: str,
exchange: str,
symbol: str,
interval: str,
backtrack: int = 0,
backtracks: Optional[int] = None
) -> Optional[Dict[str, Any]]:
"""
Fetch pre-calculated indicator from TaAPI.
Args:
indicator: Indicator name (rsi, macd, bbands, etc.)
exchange: Exchange name (binance, binancefutures, etc.)
symbol: Trading pair in COIN/MARKET format (BTC/USDT)
interval: Timeframe (1m, 5m, 15m, 30m, 1h, 2h, 4h, 12h, 1d, 1w)
backtrack: Number of candles to backtrack (0 = latest)
backtracks: Number of historical values to return
Returns:
Dictionary with indicator values or None if request fails
"""
api_key = os.getenv('TAAPI_API_KEY') or os.getenv('TA_API_KEY')
if not api_key:
print("Error: TAAPI_API_KEY not found in environment variables", file=sys.stderr)
return None
# Validate inputs
if indicator.lower() not in INDICATORS:
print(f"Warning: {indicator} not in common indicators list", file=sys.stderr)
# Build request URL
url = f"{BASE_URL}/{indicator.lower()}"
params = {
'secret': api_key,
'exchange': exchange.lower(),
'symbol': symbol,
'interval': interval
}
if backtrack > 0:
params['backtrack'] = backtrack
if backtracks is not None and backtracks > 0:
params['backtracks'] = backtracks
try:
response = proxied_get(url, params=params, timeout=30)
response.raise_for_status()
data = response.json()
# Add metadata
result = {
'indicator': indicator,
'exchange': exchange,
'symbol': symbol,
'interval': interval,
'values': data
}
return result
except Exception as e:
# Handle HTTP errors
if hasattr(e, 'response') and e.response is not None:
status = e.response.status_code
if status == 401:
print("Error: Invalid API key", file=sys.stderr)
elif status == 429:
print("Error: Rate limit exceeded", file=sys.stderr)
else:
print(f"HTTP Error: {status} - {e.response.text}", file=sys.stderr)
else:
print(f"Request Error: {str(e)}", file=sys.stderr)
return None
def get_multiple_indicators(
indicators: List[str],
exchange: str,
symbol: str,
interval: str
) -> Dict[str, Any]:
"""
Fetch multiple indicators at once (sequential - use bulk_indicators for faster).
Args:
indicators: List of indicator names
exchange: Exchange name
symbol: Trading pair
interval: Timeframe
Returns:
Dictionary with all indicator values
"""
results = {}
for indicator in indicators:
data = get_indicator(indicator, exchange, symbol, interval)
if data:
results[indicator] = data['values']
return results
def bulk_indicators(
indicators: List[Dict[str, Any]],
exchange: str,
symbol: str,
interval: str
) -> Dict[str, Any]:
"""
Fetch up to 20 indicators in ONE API request using TaAPI bulk endpoint.
This is MUCH faster than individual calls - 1 request instead of N requests.
Args:
indicators: List of indicator configs, each can have:
- {"indicator": "rsi"}
- {"indicator": "macd"}
- {"indicator": "ema", "period": 50}
- {"id": "custom_id", "indicator": "rsi", "backtrack": 1}
exchange: Exchange name (binance, binancefutures, etc.)
symbol: Trading pair (BTC/USDT)
interval: Timeframe (1h, 4h, 1d, etc.)
Returns:
Dictionary with all indicator results keyed by indicator name or custom id
Example:
result = bulk_indicators(
[{"indicator": "rsi"}, {"indicator": "macd"}, {"indicator": "bbands"}],
"binance", "BTC/USDT", "4h"
)
"""
api_key = os.getenv('TAAPI_API_KEY') or os.getenv('TA_API_KEY')
if not api_key:
print("Error: TAAPI_API_KEY not found in environment variables", file=sys.stderr)
return {}
if len(indicators) > 20:
print("Warning: Maximum 20 indicators per bulk request. Truncating.", file=sys.stderr)
indicators = indicators[:20]
# Build bulk request payload
payload = {
"secret": api_key,
"construct": {
"exchange": exchange.lower(),
"symbol": symbol,
"interval": interval,
"indicators": indicators
}
}
try:
response = proxied_post(
f"{BASE_URL}/bulk",
json=payload,
timeout=30
)
response.raise_for_status()
data = response.json()
# Parse response - TaAPI returns {"data": [...]}
results = {}
if "data" in data:
for item in data["data"]:
# Get indicator name from the response
indicator_name = item.get("indicator", "unknown")
# Check for errors
if item.get("errors") and len(item["errors"]) > 0:
results[indicator_name] = {"error": item["errors"]}
else:
# Store the result values directly
results[indicator_name] = item.get("result", {})
return {
"exchange": exchange,
"symbol": symbol,
"interval": interval,
"indicators": results
}
except Exception as e:
if hasattr(e, 'response') and e.response is not None:
print(f"HTTP Error: {e.response.status_code} - {e.response.text}", file=sys.stderr)
else:
print(f"Error: {str(e)}", file=sys.stderr)
return {}
def format_output(data: Dict[str, Any], output_format: str = "json") -> str:
"""Format output for display.
Formats:
json: Full JSON with metadata (default)
concise: Minimal key=value pairs, optimized for agent consumption
text: Human-readable formatted text
"""
if output_format == "json":
return json.dumps(data, indent=2)
elif output_format == "concise":
# Token-efficient format for agents (per Anthropic best practices)
parts = []
if 'indicators' in data:
# Bulk mode response
for ind_name, ind_data in data['indicators'].items():
if isinstance(ind_data, dict):
vals = [f"{k}={v:.2f}" if isinstance(v, float) else f"{k}={v}"
for k, v in ind_data.items() if not k.startswith('error')]
parts.append(f"{ind_name}:{','.join(vals)}")
return f"{data.get('symbol','?')}@{data.get('interval','?')}|" + "|".join(parts)
elif 'values' in data:
# Single indicator response
values = data['values']
if isinstance(values, dict):
vals = [f"{k}={v:.2f}" if isinstance(v, float) else f"{k}={v}"
for k, v in values.items()]
return f"{data.get('indicator','?')}@{data.get('symbol','?')}@{data.get('interval','?')}:{','.join(vals)}"
else:
return f"{data.get('indicator','?')}={values}"
return str(data)
elif output_format == "text":
lines = []
lines.append("=" * 60)
lines.append(f"INDICATOR: {data['indicator'].upper()}")
lines.append(f"Symbol: {data['symbol']} | Exchange: {data['exchange']}")
lines.append(f"Interval: {data['interval']}")
lines.append("=" * 60)
lines.append("")
values = data['values']
if isinstance(values, dict):
for key, value in values.items():
if isinstance(value, float):
lines.append(f"{key}: {value:.4f}")
else:
lines.append(f"{key}: {value}")
elif isinstance(values, list):
for i, val in enumerate(values):
lines.append(f"[{i}]: {val}")
else:
lines.append(f"Value: {values}")
lines.append("")
lines.append("=" * 60)
return "\n".join(lines)
return json.dumps(data, indent=2)
def main():
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
description="TaAPI Indicators - Pre-calculated technical indicators",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=f"""
Examples:
# Get RSI for Bitcoin
python indicators.py --indicator rsi --exchange binance --symbol BTC/USDT --interval 1h
# Get MACD for Ethereum
python indicators.py --indicator macd --exchange binance --symbol ETH/USDT --interval 4h
# BULK MODE - Get multiple indicators in ONE request (FAST!)
python indicators.py --bulk --indicators rsi,macd,bbands --exchange binance --symbol BTC/USDT --interval 4h
# Bulk with pivots
python indicators.py --bulk --indicators rsi,macd,bbands,ema,sma --exchange binance --symbol BTC/USDT --interval 1d
# Get Bollinger Bands with text output
python indicators.py --indicator bbands --exchange binance --symbol BTC/USDT --interval 1d --output_format text
# Get historical values (last 10 candles)
python indicators.py --indicator rsi --exchange binance --symbol BTC/USDT --interval 1h --backtracks 10
Supported Indicators:
{', '.join(INDICATORS[:10])}
... and 200+ more at taapi.io/indicators/
Supported Exchanges:
{', '.join(EXCHANGES)}
Supported Intervals:
{', '.join(INTERVALS)}
"""
)
parser.add_argument('--indicator', type=str,
help='Single indicator name (rsi, macd, bbands, etc.)')
parser.add_argument('--bulk', action='store_true',
help='Use bulk mode to fetch multiple indicators in ONE request')
parser.add_argument('--indicators', type=str,
help='Comma-separated indicators for bulk mode (e.g., rsi,macd,bbands)')
parser.add_argument('--exchange', type=str, required=True,
help='Exchange name (binance, binancefutures, etc.)')
parser.add_argument('--symbol', type=str, required=True,
help='Trading pair (BTC/USDT, ETH/USDT, etc.)')
parser.add_argument('--interval', type=str, required=True,
help='Timeframe (1m, 5m, 15m, 30m, 1h, 2h, 4h, 12h, 1d, 1w)')
parser.add_argument('--backtrack', type=int, default=0,
help='Candles to backtrack (0 = latest)')
parser.add_argument('--backtracks', type=int,
help='Number of historical values to return')
parser.add_argument('--output_format', type=str, default='json',
choices=['json', 'concise', 'text'],
help='Output format (concise=token-efficient for agents)')
parser.add_argument('--output-example', action='store_true',
help='Show example output')
args = parser.parse_args()
if args.output_example:
example = {
'indicator': 'rsi',
'exchange': 'binance',
'symbol': 'BTC/USDT',
'interval': '1h',
'values': {'value': 65.3421}
}
print(format_output(example, args.output_format))
return 0
# BULK MODE - fetch multiple indicators in ONE request
if args.bulk:
if not args.indicators:
print("Error: --indicators required for bulk mode (e.g., --indicators rsi,macd,bbands)", file=sys.stderr)
return 1
indicator_list = [{"indicator": ind.strip()} for ind in args.indicators.split(",")]
result = bulk_indicators(indicator_list, args.exchange, args.symbol, args.interval)
if result:
print(format_output(result, args.output_format))
return 0
else:
return 1
# SINGLE INDICATOR MODE
if not args.indicator:
print("Error: --indicator required (or use --bulk with --indicators)", file=sys.stderr)
return 1
result = get_indicator(
args.indicator,
args.exchange,
args.symbol,
args.interval,
args.backtrack,
args.backtracks
)
if result:
print(format_output(result, args.output_format))
return 0
else:
return 1
if __name__ == "__main__":
sys.exit(main())
#!/usr/bin/env python3
"""
TaAPI Support & Resistance Module
Fetch professional support/resistance levels including pivot points,
Fibonacci levels, and pattern-based key levels from TaAPI.IO.
Dependencies:
- requests: For HTTP API calls
- python-dotenv: For environment variable management
Environment Variables Required:
- TAAPI_API_KEY: Your TaAPI.IO API key
Usage Example:
from tools.taapi.support_resistance import get_pivot_points
# Get pivot points for Bitcoin
pivots = get_pivot_points("binance", "BTC/USDT", "1d")
CLI Usage:
python support_resistance.py --type pivots --exchange binance --symbol BTC/USDT --interval 1d
python support_resistance.py --type fibonacci --exchange binance --symbol ETH/USDT --interval 4h
"""
import os
import sys
import json
import argparse
from typing import Dict, Any, Optional
try:
from dotenv import load_dotenv
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../..'))
load_dotenv(os.path.join(project_root, '.env'))
except ImportError:
pass
from core.http_client import proxied_get
BASE_URL = "https://api.taapi.io"
def get_pivot_points(
exchange: str,
symbol: str,
interval: str = "1d",
pivot_type: str = "standard"
) -> Optional[Dict[str, Any]]:
"""
Get pivot points (support/resistance levels).
Args:
exchange: Exchange name (binance, binancefutures, etc.)
symbol: Trading pair (BTC/USDT)
interval: Timeframe (1d or 1w recommended for pivots)
pivot_type: Type of pivots (standard, fibonacci, camarilla)
Returns:
Dictionary with pivot point levels
"""
api_key = os.getenv('TAAPI_API_KEY') or os.getenv('TA_API_KEY')
if not api_key:
print("Error: TAAPI_API_KEY not found", file=sys.stderr)
return None
url = f"{BASE_URL}/pivotpoints"
params = {
'secret': api_key,
'exchange': exchange.lower(),
'symbol': symbol,
'interval': interval,
'type': pivot_type
}
try:
response = proxied_get(url, params=params, timeout=30)
response.raise_for_status()
data = response.json()
result = {
'type': 'pivot_points',
'pivot_type': pivot_type,
'exchange': exchange,
'symbol': symbol,
'interval': interval,
'levels': data
}
return result
except Exception as e:
if hasattr(e, 'response') and e.response is not None:
print(f"HTTP Error: {e.response.status_code}", file=sys.stderr)
else:
print(f"Error: {str(e)}", file=sys.stderr)
return None
def get_support_resistance(
exchange: str,
symbol: str,
interval: str,
indicator: str = "pivots"
) -> Optional[Dict[str, Any]]:
"""
Get support and resistance levels using various methods.
Args:
exchange: Exchange name
symbol: Trading pair
interval: Timeframe
indicator: Method (pivots, ichimoku, etc.)
Returns:
Dictionary with support/resistance levels
"""
if indicator == "pivots":
return get_pivot_points(exchange, symbol, interval)
# For other S/R indicators, use generic approach
api_key = os.getenv('TAAPI_API_KEY') or os.getenv('TA_API_KEY')
if not api_key:
print("Error: TAAPI_API_KEY not found", file=sys.stderr)
return None
url = f"{BASE_URL}/{indicator}"
params = {
'secret': api_key,
'exchange': exchange.lower(),
'symbol': symbol,
'interval': interval
}
try:
response = proxied_get(url, params=params, timeout=30)
response.raise_for_status()
data = response.json()
return {
'type': indicator,
'exchange': exchange,
'symbol': symbol,
'interval': interval,
'levels': data
}
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
return None
def format_output(data: Dict[str, Any], output_format: str = "json") -> str:
"""Format output for display."""
if output_format == "json":
return json.dumps(data, indent=2)
elif output_format == "text":
lines = []
lines.append("=" * 60)
lines.append("SUPPORT & RESISTANCE LEVELS")
lines.append(f"Type: {data.get('type', 'Unknown').upper()}")
lines.append(f"Symbol: {data['symbol']} | Exchange: {data['exchange']}")
lines.append(f"Interval: {data['interval']}")
lines.append("=" * 60)
lines.append("")
levels = data.get('levels', {})
# Handle pivot points format
if 'pp' in levels or 'pivot' in levels:
pivot = levels.get('pp', levels.get('pivot', 0))
lines.append(f"PIVOT POINT: {pivot:.2f}")
lines.append("")
lines.append("RESISTANCE LEVELS:")
for i in range(1, 4):
r_key = f'r{i}'
if r_key in levels:
lines.append(f" R{i}: {levels[r_key]:.2f}")
lines.append("")
lines.append("SUPPORT LEVELS:")
for i in range(1, 4):
s_key = f's{i}'
if s_key in levels:
lines.append(f" S{i}: {levels[s_key]:.2f}")
else:
# Generic format
for key, value in levels.items():
if isinstance(value, float):
lines.append(f"{key}: {value:.4f}")
else:
lines.append(f"{key}: {value}")
lines.append("")
lines.append("=" * 60)
return "\n".join(lines)
return json.dumps(data, indent=2)
def main():
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
description="TaAPI Support & Resistance - Professional S/R levels",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Get pivot points for Bitcoin (daily)
python support_resistance.py --type pivots --exchange binance --symbol BTC/USDT --interval 1d
# Get Fibonacci pivots
python support_resistance.py --type pivots --exchange binance --symbol ETH/USDT --interval 1d --pivot_type fibonacci
# Get weekly pivots with text output
python support_resistance.py --type pivots --exchange binance --symbol BTC/USDT --interval 1w --output_format text
Pivot Types:
- standard: Traditional pivot points
- fibonacci: Fibonacci-based pivots
- camarilla: Camarilla pivot points
"""
)
parser.add_argument('--type', type=str, default='pivots',
help='S/R type (pivots, ichimoku, etc.)')
parser.add_argument('--exchange', type=str, required=True,
help='Exchange name')
parser.add_argument('--symbol', type=str, required=True,
help='Trading pair (BTC/USDT)')
parser.add_argument('--interval', type=str, default='1d',
help='Timeframe (1d or 1w recommended)')
parser.add_argument('--pivot_type', type=str, default='standard',
choices=['standard', 'fibonacci', 'camarilla'],
help='Pivot calculation method')
parser.add_argument('--output_format', type=str, default='json',
choices=['json', 'text'],
help='Output format')
parser.add_argument('--output-example', action='store_true',
help='Show example output')
args = parser.parse_args()
if args.output_example:
example = {
'type': 'pivot_points',
'pivot_type': 'standard',
'exchange': 'binance',
'symbol': 'BTC/USDT',
'interval': '1d',
'levels': {
'pp': 43250.50,
'r1': 44100.25,
'r2': 45200.75,
'r3': 46050.50,
's1': 42150.25,
's2': 41050.75,
's3': 40200.50
}
}
print(format_output(example, args.output_format))
return 0
# Fetch S/R levels
if args.type == 'pivots':
result = get_pivot_points(
args.exchange,
args.symbol,
args.interval,
args.pivot_type
)
else:
result = get_support_resistance(
args.exchange,
args.symbol,
args.interval,
args.type
)
if result:
print(format_output(result, args.output_format))
return 0
else:
return 1
if __name__ == "__main__":
sys.exit(main())