Skip to main content

Overview

This page provides practical examples of how to use the Maikers SDK for various use cases. Each example includes complete, runnable code that you can adapt for your own projects.

Trading Automation

Build automated trading strategies with AI agents

Content Creation

Automate content generation and publishing workflows

Market Research

Create intelligent market analysis and research pipelines

DeFi Automation

Automate DeFi strategies and yield optimization

Trading Automation Example

Automated Trading Bot

This example creates a trading bot that monitors market conditions and executes trades based on AI analysis:
import { MaikersSDK } from "@maikers/mainframe-sdk";

class TradingBot {
  private sdk: MaikersSDK;
  private agentId: string;

  constructor(apiKey: string) {
    this.sdk = new MaikersSDK({ apiKey });
    this.agentId = "trading-bot-" + Date.now();
  }

  async initialize() {
    // Create a trading agent with Sniper and Analyst skills
    const agent = await this.sdk.agent.create({
      id: this.agentId,
      name: "Automated Trading Bot",
      description: "AI agent for automated cryptocurrency trading",
      riskLevel: "medium",
      jobTypes: ["trading", "analysis"],
      skills: ["sniper", "analyst", "strategist"],
      personaId: "professional-trader",
    });

    console.log("✅ Trading bot initialized:", agent.name);
    return agent;
  }

  async analyzeMarket(symbol: string) {
    const response = await this.sdk.agent.query(this.agentId, {
      message: `Analyze the current market conditions for ${symbol}. 
                Provide trading signals and risk assessment.`,
    });

    return response.data;
  }

  async executeTrade(action: "buy" | "sell", symbol: string, amount: number) {
    const response = await this.sdk.agent.query(this.agentId, {
      message: `Execute ${action} order for ${amount} ${symbol}. 
                Confirm optimal timing and execution strategy.`,
    });

    return response.data;
  }

  async runTradingLoop() {
    const symbols = ["BTC", "ETH", "SOL"];

    for (const symbol of symbols) {
      try {
        console.log(`🔍 Analyzing ${symbol}...`);
        const analysis = await this.analyzeMarket(symbol);

        console.log(`📊 Analysis for ${symbol}:`, analysis);

        // Example: Execute trade based on analysis
        if (analysis.includes("bullish") || analysis.includes("buy")) {
          console.log(`📈 Executing buy order for ${symbol}`);
          const tradeResult = await this.executeTrade("buy", symbol, 0.1);
          console.log("Trade result:", tradeResult);
        }

        // Wait between analyses
        await new Promise((resolve) => setTimeout(resolve, 5000));
      } catch (error) {
        console.error(`❌ Error analyzing ${symbol}:`, error.message);
      }
    }
  }
}

// Usage
async function main() {
  const bot = new TradingBot(process.env.MAIKERS_API_KEY!);

  await bot.initialize();
  await bot.runTradingLoop();
}

main().catch(console.error);

Content Creation Pipeline

Automated Content Generator

This example creates a content pipeline that generates, reviews, and publishes content:
import { MaikersSDK } from "@maikers/mainframe-sdk";

class ContentPipeline {
  private sdk: MaikersSDK;
  private writerAgentId: string;
  private entertainerAgentId: string;

  constructor(apiKey: string) {
    this.sdk = new MaikersSDK({ apiKey });
    this.writerAgentId = "writer-" + Date.now();
    this.entertainerAgentId = "entertainer-" + Date.now();
  }

  async initialize() {
    // Create writer agent
    const writer = await this.sdk.agent.create({
      id: this.writerAgentId,
      name: "Content Writer",
      description: "AI agent specialized in creating engaging content",
      riskLevel: "low",
      jobTypes: ["content-creation", "writing"],
      skills: ["writer"],
      personaId: "creative-writer",
    });

    // Create entertainer agent for promotion
    const entertainer = await this.sdk.agent.create({
      id: this.entertainerAgentId,
      name: "Content Promoter",
      description: "AI agent for content promotion and marketing",
      riskLevel: "low",
      jobTypes: ["marketing", "promotion"],
      skills: ["entertainer"],
      personaId: "marketing-expert",
    });

    console.log("✅ Content pipeline initialized");
    return { writer, entertainer };
  }

  async generateArticle(topic: string, wordCount: number = 800) {
    const response = await this.sdk.agent.query(this.writerAgentId, {
      message: `Write a comprehensive ${wordCount}-word article about "${topic}". 
                Include engaging headlines, clear structure, and actionable insights.
                Target audience: crypto enthusiasts and investors.`,
    });

    return response.data;
  }

  async createSocialMediaContent(article: string) {
    const response = await this.sdk.agent.query(this.entertainerAgentId, {
      message: `Based on this article, create social media content:
                1. Twitter thread (5-7 tweets)
                2. LinkedIn post
                3. Instagram caption with hashtags
                
                Article: ${article.substring(0, 1000)}...`,
    });

    return response.data;
  }

  async generateContentSeries(topics: string[]) {
    const contentSeries = [];

    for (const topic of topics) {
      try {
        console.log(`📝 Generating content for: ${topic}`);

        // Generate main article
        const article = await this.generateArticle(topic);

        // Create promotional content
        const socialContent = await this.createSocialMediaContent(article);

        contentSeries.push({
          topic,
          article,
          socialContent,
          createdAt: new Date().toISOString(),
        });

        console.log(`✅ Content created for: ${topic}`);

        // Rate limiting
        await new Promise((resolve) => setTimeout(resolve, 2000));
      } catch (error) {
        console.error(`❌ Error creating content for ${topic}:`, error.message);
      }
    }

    return contentSeries;
  }
}

// Usage
async function main() {
  const pipeline = new ContentPipeline(process.env.MAIKERS_API_KEY!);

  await pipeline.initialize();

  const topics = [
    "DeFi Yield Farming Strategies",
    "NFT Market Trends 2024",
    "AI in Cryptocurrency Trading",
  ];

  const contentSeries = await pipeline.generateContentSeries(topics);

  console.log("📚 Content series generated:", contentSeries.length, "articles");
}

main().catch(console.error);

Market Research Automation

Alpha Hunter & Analyst Combo

This example combines Hunter and Analyst skills for comprehensive market research:
import { MaikersSDK } from "@maikers/mainframe-sdk";

class MarketResearcher {
  private sdk: MaikersSDK;
  private hunterAgentId: string;
  private analystAgentId: string;

  constructor(apiKey: string) {
    this.sdk = new MaikersSDK({ apiKey });
    this.hunterAgentId = "hunter-" + Date.now();
    this.analystAgentId = "analyst-" + Date.now();
  }

  async initialize() {
    // Create hunter agent for alpha discovery
    const hunter = await this.sdk.agent.create({
      id: this.hunterAgentId,
      name: "Alpha Hunter",
      description: "AI agent for discovering market opportunities",
      riskLevel: "medium",
      jobTypes: ["research", "discovery"],
      skills: ["hunter"],
      personaId: "research-specialist",
    });

    // Create analyst agent for data analysis
    const analyst = await this.sdk.agent.create({
      id: this.analystAgentId,
      name: "Market Analyst",
      description: "AI agent for market data analysis",
      riskLevel: "low",
      jobTypes: ["analysis", "research"],
      skills: ["analyst"],
      personaId: "data-analyst",
    });

    console.log("✅ Research team initialized");
    return { hunter, analyst };
  }

  async huntForAlpha(sector: string) {
    const response = await this.sdk.agent.query(this.hunterAgentId, {
      message: `Hunt for alpha opportunities in the ${sector} sector. 
                Look for:
                - Emerging projects with strong fundamentals
                - Undervalued tokens with growth potential
                - Market inefficiencies and arbitrage opportunities
                - Upcoming events that could impact prices`,
    });

    return response.data;
  }

  async analyzeFindings(alphaData: string) {
    const response = await this.sdk.agent.query(this.analystAgentId, {
      message: `Analyze these alpha findings and provide:
                1. Risk assessment for each opportunity
                2. Potential ROI estimates
                3. Timeline for potential gains
                4. Entry and exit strategies
                
                Alpha Data: ${alphaData}`,
    });

    return response.data;
  }

  async generateResearchReport(sector: string) {
    try {
      console.log(`🔍 Hunting for alpha in ${sector}...`);
      const alphaFindings = await this.huntForAlpha(sector);

      console.log(`📊 Analyzing findings...`);
      const analysis = await this.analyzeFindings(alphaFindings);

      const report = {
        sector,
        timestamp: new Date().toISOString(),
        alphaFindings,
        analysis,
        summary: `Research report for ${sector} sector completed`,
      };

      console.log(`✅ Research report generated for ${sector}`);
      return report;
    } catch (error) {
      console.error(`❌ Error generating report for ${sector}:`, error.message);
      throw error;
    }
  }

  async runDailyResearch() {
    const sectors = ["DeFi", "Gaming", "NFTs", "Layer 1", "AI"];
    const reports = [];

    for (const sector of sectors) {
      try {
        const report = await this.generateResearchReport(sector);
        reports.push(report);

        // Rate limiting between sectors
        await new Promise((resolve) => setTimeout(resolve, 3000));
      } catch (error) {
        console.error(`Failed to research ${sector}:`, error.message);
      }
    }

    return reports;
  }
}

// Usage
async function main() {
  const researcher = new MarketResearcher(process.env.MAIKERS_API_KEY!);

  await researcher.initialize();

  // Generate daily research reports
  const dailyReports = await researcher.runDailyResearch();

  console.log("📈 Daily research completed:", dailyReports.length, "reports");

  // Save reports (example)
  dailyReports.forEach((report, index) => {
    console.log(`\n--- Report ${index + 1}: ${report.sector} ---`);
    console.log(
      "Alpha Findings:",
      report.alphaFindings.substring(0, 200) + "...",
    );
    console.log("Analysis:", report.analysis.substring(0, 200) + "...");
  });
}

main().catch(console.error);

DeFi Automation

Yield Farming Optimizer

This example automates DeFi yield farming strategies:
import { MaikersSDK } from "@maikers/mainframe-sdk";

class DeFiAutomator {
  private sdk: MaikersSDK;
  private automatonAgentId: string;
  private strategistAgentId: string;

  constructor(apiKey: string) {
    this.sdk = new MaikersSDK({ apiKey });
    this.automatonAgentId = "automaton-" + Date.now();
    this.strategistAgentId = "strategist-" + Date.now();
  }

  async initialize() {
    // Create automaton for routine tasks
    const automaton = await this.sdk.agent.create({
      id: this.automatonAgentId,
      name: "DeFi Automaton",
      description: "AI agent for DeFi automation tasks",
      riskLevel: "medium",
      jobTypes: ["automation", "defi"],
      skills: ["automaton"],
      personaId: "defi-specialist",
    });

    // Create strategist for planning
    const strategist = await this.sdk.agent.create({
      id: this.strategistAgentId,
      name: "DeFi Strategist",
      description: "AI agent for DeFi strategy planning",
      riskLevel: "medium",
      jobTypes: ["strategy", "planning"],
      skills: ["strategist"],
      personaId: "strategy-expert",
    });

    console.log("✅ DeFi automation team initialized");
    return { automaton, strategist };
  }

  async planYieldStrategy(portfolio: any) {
    const response = await this.sdk.agent.query(this.strategistAgentId, {
      message: `Plan an optimal yield farming strategy for this portfolio:
                ${JSON.stringify(portfolio)}
                
                Consider:
                - Risk tolerance: Medium
                - Time horizon: 3-6 months
                - Gas costs optimization
                - Impermanent loss mitigation
                - Diversification across protocols`,
    });

    return response.data;
  }

  async executeYieldFarming(strategy: string) {
    const response = await this.sdk.agent.query(this.automatonAgentId, {
      message: `Execute this yield farming strategy:
                ${strategy}
                
                Tasks:
                1. Monitor current APY rates
                2. Identify optimal entry points
                3. Execute position entries
                4. Set up automated compounding
                5. Monitor for exit signals`,
    });

    return response.data;
  }

  async monitorPositions() {
    const response = await this.sdk.agent.query(this.automatonAgentId, {
      message: `Monitor all active DeFi positions and report:
                1. Current yields and performance
                2. Any risks or warnings
                3. Rebalancing opportunities
                4. Harvest/compound recommendations
                5. Exit signals if any`,
    });

    return response.data;
  }

  async runDeFiAutomation() {
    try {
      // Example portfolio
      const portfolio = {
        tokens: ["USDC", "ETH", "MATIC"],
        amounts: [10000, 5, 1000],
        riskTolerance: "medium",
      };

      console.log("📋 Planning yield strategy...");
      const strategy = await this.planYieldStrategy(portfolio);

      console.log("🚀 Executing yield farming...");
      const execution = await this.executeYieldFarming(strategy);

      console.log("👀 Monitoring positions...");
      const monitoring = await this.monitorPositions();

      return {
        strategy,
        execution,
        monitoring,
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      console.error("❌ DeFi automation error:", error.message);
      throw error;
    }
  }
}

// Usage
async function main() {
  const defiBot = new DeFiAutomator(process.env.MAIKERS_API_KEY!);

  await defiBot.initialize();

  // Run automation cycle
  const result = await defiBot.runDeFiAutomation();

  console.log("🎯 DeFi automation completed");
  console.log("Strategy:", result.strategy.substring(0, 200) + "...");
  console.log("Execution:", result.execution.substring(0, 200) + "...");
  console.log("Monitoring:", result.monitoring.substring(0, 200) + "...");
}

main().catch(console.error);

Multi-Agent Collaboration

Coordinated Agent Workflow

This example shows how multiple agents can work together:
import { MaikersSDK } from "@maikers/mainframe-sdk";

class AgentOrchestrator {
  private sdk: MaikersSDK;
  private agents: Map<string, string> = new Map();

  constructor(apiKey: string) {
    this.sdk = new MaikersSDK({ apiKey });
  }

  async createAgentTeam() {
    const agentConfigs = [
      {
        role: "hunter",
        config: {
          id: "hunter-" + Date.now(),
          name: "Market Hunter",
          skills: ["hunter"],
          jobTypes: ["research", "discovery"],
        },
      },
      {
        role: "analyst",
        config: {
          id: "analyst-" + Date.now(),
          name: "Data Analyst",
          skills: ["analyst"],
          jobTypes: ["analysis", "research"],
        },
      },
      {
        role: "strategist",
        config: {
          id: "strategist-" + Date.now(),
          name: "Strategy Planner",
          skills: ["strategist"],
          jobTypes: ["strategy", "planning"],
        },
      },
      {
        role: "sniper",
        config: {
          id: "sniper-" + Date.now(),
          name: "Trade Executor",
          skills: ["sniper"],
          jobTypes: ["trading", "execution"],
        },
      },
    ];

    for (const { role, config } of agentConfigs) {
      const agent = await this.sdk.agent.create({
        ...config,
        description: `Specialized ${role} agent`,
        riskLevel: "medium",
      });

      this.agents.set(role, config.id);
      console.log(`✅ Created ${role} agent: ${agent.name}`);
    }

    return this.agents;
  }

  async executeWorkflow(target: string) {
    const workflow = [];

    try {
      // Step 1: Hunter finds opportunities
      console.log("🔍 Step 1: Hunting for opportunities...");
      const hunterResponse = await this.sdk.agent.query(
        this.agents.get("hunter")!,
        { message: `Find trading opportunities related to ${target}` },
      );
      workflow.push({ step: "hunt", data: hunterResponse.data });

      // Step 2: Analyst evaluates findings
      console.log("📊 Step 2: Analyzing findings...");
      const analystResponse = await this.sdk.agent.query(
        this.agents.get("analyst")!,
        {
          message: `Analyze these opportunities: ${hunterResponse.data.substring(0, 500)}`,
        },
      );
      workflow.push({ step: "analyze", data: analystResponse.data });

      // Step 3: Strategist plans approach
      console.log("🎯 Step 3: Planning strategy...");
      const strategistResponse = await this.sdk.agent.query(
        this.agents.get("strategist")!,
        {
          message: `Create trading strategy based on: ${analystResponse.data.substring(0, 500)}`,
        },
      );
      workflow.push({ step: "strategize", data: strategistResponse.data });

      // Step 4: Sniper executes trades
      console.log("⚡ Step 4: Executing trades...");
      const sniperResponse = await this.sdk.agent.query(
        this.agents.get("sniper")!,
        {
          message: `Execute this strategy: ${strategistResponse.data.substring(0, 500)}`,
        },
      );
      workflow.push({ step: "execute", data: sniperResponse.data });

      console.log("✅ Workflow completed successfully");
      return workflow;
    } catch (error) {
      console.error("❌ Workflow error:", error.message);
      throw error;
    }
  }
}

// Usage
async function main() {
  const orchestrator = new AgentOrchestrator(process.env.MAIKERS_API_KEY!);

  console.log("🚀 Creating agent team...");
  await orchestrator.createAgentTeam();

  console.log("🔄 Executing coordinated workflow...");
  const workflow = await orchestrator.executeWorkflow(
    "Solana ecosystem tokens",
  );

  console.log("\n📋 Workflow Summary:");
  workflow.forEach((step, index) => {
    console.log(`${index + 1}. ${step.step.toUpperCase()}:`);
    console.log(`   ${step.data.substring(0, 150)}...\n`);
  });
}

main().catch(console.error);

Best Practices

Always implement proper error handling:
try {
  const response = await sdk.agent.query(agentId, { message });
  return response.data;
} catch (error) {
  console.error('Agent query failed:', error.message);
  // Implement retry logic or fallback
}
Respect API rate limits:
// Add delays between requests
await new Promise(resolve => setTimeout(resolve, 1000));

// Implement exponential backoff for retries
const delay = Math.pow(2, retryCount) * 1000;
Use descriptive agent IDs and clean up unused agents: typescript // Use meaningful IDs const agentId = `trading-bot-${strategy}-${Date.now()}`; // Clean up when done await sdk.agent.delete(agentId);
Use environment variables for configuration:
const config = {
  apiKey: process.env.MAIKERS_API_KEY,
  baseUrl: process.env.MAIKERS_BASE_URL,
  timeout: parseInt(process.env.REQUEST_TIMEOUT || '30000')
};

Next Steps