API Documentation

Technical reference for integrating with CycleTrader

Introduction

The CycleTrader API allows developers to integrate our advanced cycle analysis capabilities into their own applications. This RESTful API provides programmatic access to all features available in the web interface, including data processing, cycle detection, recommendation generation, and visualization creation.

API Status

The CycleTrader API is currently in beta. While we strive for stability, endpoints and response formats may change. Please check this documentation regularly for updates.

Use Cases

Automated Trading Systems

Integrate cycle analysis into algorithmic trading strategies, using our API to generate signals for your trading bots.

Custom Dashboards

Build personalized trading dashboards that incorporate cycle analysis alongside other technical indicators.

Portfolio Analysis

Analyze multiple securities programmatically and aggregate results for portfolio-level insights.

Research Applications

Incorporate cycle analysis into financial research projects, backtesting frameworks, or educational tools.

Authentication

All API requests require authentication using an API key. To obtain an API key, please contact our support team.

API Key Authentication

Include your API key in the request header:

X-API-Key: your_api_key_here
Security Notice

Your API key grants access to perform actions on your behalf. Keep it secure and never share it publicly. If you believe your API key has been compromised, contact us immediately for a replacement.

Rate Limits

To ensure service quality for all users, the API enforces rate limits. Current limits are as follows:

Plan Rate Limit Period
Basic 100 requests Per day
Professional 1,000 requests Per day
Enterprise 5,000 requests Per day

Rate Limit Headers

The API includes rate limit information in the response headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Exceeding the rate limit will result in a 429 (Too Many Requests) response. We recommend implementing proper retry logic with exponential backoff in your application.

Error Handling

The API uses standard HTTP status codes to indicate success or failure:

Status Code Description
200 - OK Request succeeded
400 - Bad Request Invalid request parameters
401 - Unauthorized Authentication failed
403 - Forbidden You don't have permission to access this resource
404 - Not Found The requested resource could not be found
429 - Too Many Requests Rate limit exceeded
500 - Internal Server Error Server error occurred

Error Response Format

Error responses include a JSON body with detailed information:

{
  "error": {
    "code": "invalid_parameters",
    "message": "The ticker symbol provided is not valid",
    "details": {
      "parameter": "ticker",
      "value": "INVALIDTICKER",
      "reason": "Not found in our database"
    }
  }
}

API Endpoints

Analysis Endpoints

POST /api/v1/analyze/ticker
Analyze Stock by Ticker Symbol

Perform cycle analysis on a stock based on its ticker symbol.

Request Parameters:
Parameter Type Required Description
ticker string Yes Valid stock ticker symbol (e.g., AAPL)
period string No Time period for analysis (1y, 2y, 5y, 10y, max). Default: 2y
Example Request:
curl -X POST https://api.cycletrader.com/api/v1/analyze/ticker \
  -H "X-API-Key: your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"ticker": "AAPL", "period": "2y"}'
Example Response:
{
  "analysis_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "ticker": "AAPL",
  "created_at": "2023-10-15T14:30:45Z",
  "recommendation": {
    "action": "buy",
    "confidence": 75,
    "reasoning": "Multiple cycles approaching bottom phase"
  },
  "dominant_cycles": [
    {
      "period": 21.5,
      "strength": 0.78,
      "phase": 0.25,
      "description": "21-day cycle in rising phase"
    },
    ...
  ],
  "links": {
    "time_series_plot": "/api/v1/plots/a1b2c3d4-e5f6-7890-abcd-ef1234567890/time_series",
    "frequency_plot": "/api/v1/plots/a1b2c3d4-e5f6-7890-abcd-ef1234567890/frequency",
    "forecast_plot": "/api/v1/plots/a1b2c3d4-e5f6-7890-abcd-ef1234567890/forecast"
  }
}
POST /api/v1/analyze/csv
Analyze Custom CSV Data

Perform cycle analysis on custom price data provided in CSV format.

Request Parameters:

Content-Type: multipart/form-data

Parameter Type Required Description
file file Yes CSV file with date and price columns
Example Request:
curl -X POST https://api.cycletrader.com/api/v1/analyze/csv \
  -H "X-API-Key: your_api_key_here" \
  -F "file=@/path/to/your/data.csv"
Example Response:

Same format as the ticker analysis endpoint.

Results Endpoints

GET /api/v1/analysis/{analysis_id}
Get Analysis Results

Retrieve the results of a previously performed analysis.

Path Parameters:
Parameter Type Description
analysis_id string Unique identifier for the analysis
Example Request:
curl -X GET https://api.cycletrader.com/api/v1/analysis/a1b2c3d4-e5f6-7890-abcd-ef1234567890 \
  -H "X-API-Key: your_api_key_here"
GET /api/v1/plots/{analysis_id}/{plot_type}
Get Plot Data

Retrieve the data for a specific plot type from an analysis.

Path Parameters:
Parameter Type Description
analysis_id string Unique identifier for the analysis
plot_type string Type of plot (time_series, frequency, forecast)
Example Request:
curl -X GET https://api.cycletrader.com/api/v1/plots/a1b2c3d4-e5f6-7890-abcd-ef1234567890/time_series \
  -H "X-API-Key: your_api_key_here"
Response Format:

Returns a JSON object with Plotly.js figure data that can be directly rendered in a web application.

Data Models

Analysis Object

Field Type Description
analysis_id string Unique identifier for the analysis (UUID format)
ticker string Stock ticker symbol (null if analysis was performed on CSV data)
created_at string Timestamp of analysis creation (ISO 8601 format)
source_type string Data source type ("api" or "file")
recommendation object Trading recommendation object
dominant_cycles array Array of cycle objects
links object Links to related resources

Recommendation Object

Field Type Description
action string Recommended action ("buy", "hold", or "sell")
confidence number Confidence level as a percentage (0-100)
reasoning string Explanation of the recommendation

Cycle Object

Field Type Description
period number Length of the cycle in trading days
strength number Relative strength of the cycle (0-1)
phase number Current phase position (0-1, where 0 is the cycle bottom)
description string Human-readable description of the cycle

Code Examples

import requests
import json

API_KEY = "your_api_key_here"
BASE_URL = "https://api.cycletrader.com/api/v1"

# Set up headers
headers = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

# Analyze a stock by ticker
def analyze_ticker(ticker, period="2y"):
    url = f"{BASE_URL}/analyze/ticker"
    payload = {
        "ticker": ticker,
        "period": period
    }
    
    response = requests.post(url, headers=headers, json=payload)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        print(response.text)
        return None

# Get analysis results
def get_analysis(analysis_id):
    url = f"{BASE_URL}/analysis/{analysis_id}"
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        print(response.text)
        return None

# Example usage
if __name__ == "__main__":
    # Analyze Apple stock
    analysis = analyze_ticker("AAPL")
    
    if analysis:
        analysis_id = analysis["analysis_id"]
        print(f"Analysis ID: {analysis_id}")
        print(f"Recommendation: {analysis['recommendation']['action']} (Confidence: {analysis['recommendation']['confidence']}%)")
        print(f"Reasoning: {analysis['recommendation']['reasoning']}")
        
        # Print dominant cycles
        print("\nDominant Cycles:")
        for cycle in analysis["dominant_cycles"]:
            print(f"- {cycle['period']:.1f} days (Strength: {cycle['strength']:.2f})")
const API_KEY = 'your_api_key_here';
const BASE_URL = 'https://api.cycletrader.com/api/v1';

// Analyze a stock by ticker
async function analyzeTicker(ticker, period = '2y') {
  try {
    const response = await fetch(`${BASE_URL}/analyze/ticker`, {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ticker,
        period
      })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Error analyzing ticker:', error);
    return null;
  }
}

// Get analysis results
async function getAnalysis(analysisId) {
  try {
    const response = await fetch(`${BASE_URL}/analysis/${analysisId}`, {
      method: 'GET',
      headers: {
        'X-API-Key': API_KEY
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Error getting analysis:', error);
    return null;
  }
}

// Example usage
async function runExample() {
  // Analyze Apple stock
  const analysis = await analyzeTicker('AAPL');
  
  if (analysis) {
    const analysisId = analysis.analysis_id;
    console.log(`Analysis ID: ${analysisId}`);
    console.log(`Recommendation: ${analysis.recommendation.action} (Confidence: ${analysis.recommendation.confidence}%)`);
    console.log(`Reasoning: ${analysis.recommendation.reasoning}`);
    
    // Print dominant cycles
    console.log('\nDominant Cycles:');
    analysis.dominant_cycles.forEach(cycle => {
      console.log(`- ${cycle.period.toFixed(1)} days (Strength: ${cycle.strength.toFixed(2)})`);
    });
  }
}

runExample();
library(httr)
library(jsonlite)

API_KEY <- "your_api_key_here"
BASE_URL <- "https://api.cycletrader.com/api/v1"

# Set up headers
headers <- c(
  `X-API-Key` = API_KEY,
  `Content-Type` = "application/json"
)

# Analyze a stock by ticker
analyze_ticker <- function(ticker, period = "2y") {
  url <- paste0(BASE_URL, "/analyze/ticker")
  payload <- list(
    ticker = ticker,
    period = period
  )
  
  response <- POST(
    url = url,
    add_headers(.headers = headers),
    body = toJSON(payload, auto_unbox = TRUE),
    encode = "json"
  )
  
  if (status_code(response) == 200) {
    return(fromJSON(content(response, "text", encoding = "UTF-8")))
  } else {
    cat("Error:", status_code(response), "\n")
    cat(content(response, "text", encoding = "UTF-8"), "\n")
    return(NULL)
  }
}

# Get analysis results
get_analysis <- function(analysis_id) {
  url <- paste0(BASE_URL, "/analysis/", analysis_id)
  
  response <- GET(
    url = url,
    add_headers(.headers = headers)
  )
  
  if (status_code(response) == 200) {
    return(fromJSON(content(response, "text", encoding = "UTF-8")))
  } else {
    cat("Error:", status_code(response), "\n")
    cat(content(response, "text", encoding = "UTF-8"), "\n")
    return(NULL)
  }
}

# Example usage
# Analyze Apple stock
analysis <- analyze_ticker("AAPL")

if (!is.null(analysis)) {
  analysis_id <- analysis$analysis_id
  cat("Analysis ID:", analysis_id, "\n")
  cat("Recommendation:", analysis$recommendation$action, 
      "(Confidence:", analysis$recommendation$confidence, "%)\n")
  cat("Reasoning:", analysis$recommendation$reasoning, "\n\n")
  
  # Print dominant cycles
  cat("Dominant Cycles:\n")
  for (cycle in analysis$dominant_cycles) {
    cat("- ", sprintf("%.1f", cycle$period), " days (Strength: ", 
        sprintf("%.2f", cycle$strength), ")\n", sep = "")
  }
}

Best Practices

Implement Proper Error Handling

Always check for and handle error responses. Implement retry logic with exponential backoff for rate limit errors (429).

Cache Results When Possible

Analysis results are stored for 30 days. Cache results locally when appropriate to minimize API calls.

Use Polling for Long Operations

For large datasets, analysis may take time. Use status endpoints to poll for completion rather than blocking.

Optimize Batch Processing

When analyzing multiple securities, process them in batches and respect rate limits.

Need More Help?

For additional assistance with API integration, please contact our developer support team at api-support@cycletrader.com.