Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/theonetrade/backtest-kit/llms.txt

Use this file to discover all available pages before exploring further.

The @backtest-kit/ollama package provides unified LLM inference across more than 10 providers — OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, and local Ollama — through a single API designed from the ground up for trading strategy use cases. It returns structured trading signals with validated TP/SL levels, supports automatic token rotation for Ollama, and works identically in both backtest and live trading modes. The goal is to make it straightforward to build multi-provider fallback chains and ensemble prediction pipelines without managing multiple SDK clients.

Supported Providers

OpenAI

GPT-4o, GPT-4.1, GPT-5

Claude

claude-3-5-sonnet, claude-opus-4

DeepSeek

deepseek-chat, deepseek-reasoner

Grok

grok-3, grok-3-mini

Mistral

mistral-large, codestral

Perplexity

sonar, sonar-pro

Cohere

command-r-plus

Alibaba

qwen-plus, qwen-turbo

Hugging Face

Any hosted model

Ollama

Any local model

Key Features

Token Rotation

Automatic API key rotation for Ollama — cycle through multiple local instances to distribute inference load. Other providers throw clear errors on key exhaustion instead of silently failing.

Structured Output

Enforced JSON schema for trading signals. Every response is validated to contain a position direction, entry price, TP/SL levels, and risk notes before being returned.

Flexible Auth

Pass API keys directly in the call context or use environment variables — whichever fits your project structure. Both modes are supported across all providers.

Unified API

One function signature works across all providers. Switching from DeepSeek to Claude to Ollama requires changing only the provider name — no SDK swaps.

Trading-First Design

Built for getSignal functions in backtest-kit. The output shape matches addStrategySchema directly — no post-processing of LLM responses required.

Getting Started

1

Install the package and its peers

npm install @backtest-kit/ollama agent-swarm-kit backtest-kit
2

Configure your provider credentials

# .env — add keys for the providers you want to use
DEEPSEEK_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-proj-...
OLLAMA_HOST=http://localhost:11434
3

Call the inference function in getSignal

import { complete } from '@backtest-kit/ollama';
import { addStrategySchema, getCandles } from 'backtest-kit';
import { v4 as uuid } from 'uuid';

addStrategySchema({
  strategyName: 'llm-strategy',
  interval: '5m',
  riskName: 'demo',
  getSignal: async (symbol) => {
    const candles1h  = await getCandles(symbol, '1h', 24);
    const candles15m = await getCandles(symbol, '15m', 48);
    const candles5m  = await getCandles(symbol, '5m', 60);

    const messages = [
      {
        role: 'system',
        content: 'You are a crypto trading assistant. Analyze the provided market data and return a structured trading signal.',
      },
      {
        role: 'user',
        content: `Symbol: ${symbol}\n1h candles: ${JSON.stringify(candles1h.slice(-10))}\n15m candles: ${JSON.stringify(candles15m.slice(-20))}\n5m candles: ${JSON.stringify(candles5m.slice(-30))}`,
      },
    ];

    // complete() returns a validated structured trading signal
    const signal = await complete({
      provider: 'deepseek',
      messages,
    });

    return { ...signal, id: uuid() };
  },
});

Structured Output Schema

Every complete() call enforces a JSON schema on the LLM response. The returned object is validated before being passed back to your strategy:
interface TradingSignal {
  position: 'long' | 'short' | 'wait';
  priceOpen?: number;          // Entry price (null for market entry)
  priceTakeProfit: number;     // Take-profit level
  priceStopLoss: number;       // Stop-loss level
  reasoning?: string;          // LLM explanation of the signal
  riskNotes?: string;          // Additional risk considerations
}
The TP/SL levels are validated against the current price direction before being returned. A long signal with priceTakeProfit < priceOpen is rejected and triggers a retry — the LLM is asked to correct the output rather than returning an invalid signal to your strategy.

Multi-Provider Fallback Chains

The unified API makes it straightforward to build fallback chains where a faster or cheaper primary model handles most calls and a more capable model takes over on failure:
import { complete } from '@backtest-kit/ollama';

async function getSignalWithFallback(messages: Message[]) {
  // Try DeepSeek first — fast and cost-effective
  try {
    return await complete({ provider: 'deepseek', messages });
  } catch (primaryError) {
    console.warn('DeepSeek failed, trying Claude:', primaryError.message);
  }

  // Fall back to Claude on DeepSeek failure
  try {
    return await complete({ provider: 'claude', messages });
  } catch (secondaryError) {
    console.warn('Claude failed, falling back to GPT:', secondaryError.message);
  }

  // Final fallback to OpenAI
  return await complete({ provider: 'openai', messages });
}
The @backtest-kit/sidekick scaffold pre-configures this exact three-provider fallback chain (DeepSeek → Claude → GPT) out of the box. If you use Sidekick to initialize your project, the fallback chain is ready to run without any additional configuration.

Ollama Token Rotation

For local Ollama deployments running multiple model instances, @backtest-kit/ollama supports automatic token rotation to distribute inference requests:
import { complete } from '@backtest-kit/ollama';

// Provide multiple Ollama hosts — requests rotate across them automatically
const signal = await complete({
  provider: 'ollama',
  model: 'llama3.2',
  tokens: [
    'http://localhost:11434',
    'http://localhost:11435',
    'http://localhost:11436',
  ],
  messages,
});
Each call in a sequence is routed to the next host in the list. This spreads load across GPUs without requiring a separate load-balancer process.
Pair @backtest-kit/ollama with @backtest-kit/signals for the most effective LLM strategies. Use signals() to build a comprehensive Markdown market report, then pass it to complete() — the model receives full multi-timeframe indicator context without you writing any indicator logic.

Build docs developers (and LLMs) love