@backtest-kit/ollama 8.3.0 → 8.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +360 -360
  2. package/package.json +112 -112
package/README.md CHANGED
@@ -1,360 +1,360 @@
1
- <img src="https://github.com/tripolskypetr/backtest-kit/raw/refs/heads/master/assets/monade.svg" height="45px" align="right">
2
-
3
- # 🤖 @backtest-kit/ollama
4
-
5
- > Multi-provider LLM context wrapper for trading strategies. Supports 10+ providers with unified HOF API.
6
-
7
- ![screenshot](https://raw.githubusercontent.com/tripolskypetr/backtest-kit/HEAD/assets/screenshots/screenshot16.png)
8
-
9
- [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tripolskypetr/backtest-kit)
10
- [![npm](https://img.shields.io/npm/v/@backtest-kit/ollama.svg?style=flat-square)](https://npmjs.org/package/@backtest-kit/ollama)
11
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)]()
12
-
13
- Transform technical analysis into trading decisions with multi-provider LLM support, structured output, and built-in risk management.
14
-
15
- 📚 **[Backtest Kit Docs](https://backtest-kit.github.io/documents/article_07_ai_news_trading_signals.html)** | 🌟 **[GitHub](https://github.com/tripolskypetr/backtest-kit)**
16
-
17
- > **New to backtest-kit?** The fastest way to get a real, production-ready setup is to clone the [reference implementation](https://github.com/tripolskypetr/backtest-kit/tree/master/example) — a fully working news-sentiment AI trading system with LLM forecasting, multi-timeframe data, and a documented February 2026 backtest. Start there instead of from scratch.
18
-
19
- ## ✨ Features
20
-
21
- - 🔌 10+ LLM Providers: OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, Ollama, GLM-4
22
- - ⚡ Higher-Order Functions: Wrap async functions with inference context via `di-scoped`
23
- - 📝 Userspace Prompts: Load prompts from `.cjs` modules in `config/prompt/`
24
- - 🎯 Userspace Schema: Define your own Zod or JSON schema with `addOutline`
25
- - 🔄 Token Rotation: Pass array of API keys for automatic rotation
26
- - 🗄️ Memoized Cache: Prompt modules cached with `memoize` from `functools-kit`
27
-
28
- ## 📦 Installation
29
-
30
- ```bash
31
- npm install @backtest-kit/ollama backtest-kit agent-swarm-kit
32
- ```
33
-
34
- ## 🚀 Usage
35
-
36
- ### Signal Schema (userspace)
37
-
38
- ```typescript
39
- // schema/Signal.schema.ts
40
- import { z } from 'zod';
41
- import { str } from 'functools-kit';
42
-
43
- export const SignalSchema = z.object({
44
- position: z.enum(['long', 'short', 'wait']).describe(
45
- str.newline(
46
- 'Position direction:',
47
- 'long: bullish signals, uptrend potential',
48
- 'short: bearish signals, downtrend potential',
49
- 'wait: conflicting signals or unfavorable conditions',
50
- )
51
- ),
52
- price_open: z.number().describe(
53
- str.newline(
54
- 'Entry price in USD',
55
- 'Current market price or limit order price',
56
- )
57
- ),
58
- price_stop_loss: z.number().describe(
59
- str.newline(
60
- 'Stop-loss price in USD',
61
- 'LONG: below price_open',
62
- 'SHORT: above price_open',
63
- )
64
- ),
65
- price_take_profit: z.number().describe(
66
- str.newline(
67
- 'Take-profit price in USD',
68
- 'LONG: above price_open',
69
- 'SHORT: below price_open',
70
- )
71
- ),
72
- minute_estimated_time: z.number().describe(
73
- 'Estimated time to reach TP in minutes'
74
- ),
75
- risk_note: z.string().describe(
76
- str.newline(
77
- 'Risk assessment:',
78
- '- Whale manipulations',
79
- '- Order book imbalance',
80
- '- Technical divergences',
81
- 'Provide specific numbers and percentages',
82
- )
83
- ),
84
- });
85
-
86
- export type TSignalSchema = z.infer<typeof SignalSchema>;
87
- ```
88
-
89
- ### Signal Outline with Zod (userspace)
90
-
91
- ```typescript
92
- // outline/signal.outline.ts
93
- import { addOutline } from 'agent-swarm-kit';
94
- import { zodResponseFormat } from 'openai/helpers/zod';
95
- import { SignalSchema, TSignalSchema } from '../schema/Signal.schema';
96
- import { CompletionName } from '@backtest-kit/ollama';
97
-
98
- addOutline<TSignalSchema>({
99
- outlineName: 'SignalOutline',
100
- completion: CompletionName.RunnerOutlineCompletion,
101
- format: zodResponseFormat(SignalSchema, 'position_decision'),
102
- getOutlineHistory: async ({ history, param: messages = [] }) => {
103
- await history.push(messages);
104
- },
105
- validations: [
106
- {
107
- validate: ({ data }) => {
108
- if (data.position === 'long' && data.price_stop_loss >= data.price_open) {
109
- throw new Error('For LONG, stop_loss must be below price_open');
110
- }
111
- if (data.position === 'short' && data.price_stop_loss <= data.price_open) {
112
- throw new Error('For SHORT, stop_loss must be above price_open');
113
- }
114
- },
115
- },
116
- ],
117
- });
118
- ```
119
-
120
- ### Signal Outline without Zod (userspace)
121
-
122
- ```typescript
123
- // outline/signal.outline.ts
124
- import { addOutline, IOutlineFormat } from 'agent-swarm-kit';
125
- import { CompletionName } from '@backtest-kit/ollama';
126
-
127
- const format: IOutlineFormat = {
128
- type: 'object',
129
- properties: {
130
- take_profit_price: { type: 'number', description: 'Take profit price in USD' },
131
- stop_loss_price: { type: 'number', description: 'Stop-loss price in USD' },
132
- description: { type: 'string', description: 'User-friendly explanation of risks, min 10 sentences' },
133
- reasoning: { type: 'string', description: 'Technical analysis, min 15 sentences' },
134
- },
135
- required: ['take_profit_price', 'stop_loss_price', 'description', 'reasoning'],
136
- };
137
-
138
- addOutline({
139
- outlineName: 'SignalOutline',
140
- format,
141
- prompt: 'Generate crypto trading signals based on price and volume indicators in JSON format.',
142
- completion: CompletionName.RunnerOutlineCompletion,
143
- getOutlineHistory: async ({ history, param }) => {
144
- const signalReport = await ioc.signalReportService.getSignalReport(param);
145
- await commitReports(history, signalReport);
146
- await history.push({ role: 'user', content: 'Generate JSON based on reports.' });
147
- },
148
- validations: [
149
- {
150
- validate: ({ data }) => {
151
- if (data.action !== 'buy') return;
152
- const stopLossChange = percentDiff(data.current_price, data.stop_loss_price);
153
- if (stopLossChange > CC_LADDER_STOP_LOSS) {
154
- throw new Error(`Stop loss must not exceed -${CC_LADDER_STOP_LOSS}%`);
155
- }
156
- },
157
- docDescription: 'Checks stop-loss price against max loss percentage.',
158
- },
159
- {
160
- validate: ({ data }) => {
161
- if (data.action !== 'buy') return;
162
- const sellChange = percentDiff(data.current_price, data.take_profit_price);
163
- if (sellChange > CC_LADDER_TAKE_PROFIT) {
164
- throw new Error(`Take profit must not exceed +${CC_LADDER_TAKE_PROFIT}%`);
165
- }
166
- },
167
- docDescription: 'Checks take-profit price against max profit percentage.',
168
- },
169
- ],
170
- });
171
- ```
172
-
173
- ### Prompt Module (userspace)
174
-
175
- ```typescript
176
- // config/prompt/signal.prompt.cjs
177
- module.exports = {
178
- system: (symbol, strategyName, exchangeName, frameName, backtest) => [
179
- `You are analyzing ${symbol} on ${exchangeName}`,
180
- `Strategy: ${strategyName}, Timeframe: ${frameName}`,
181
- backtest ? 'Backtest mode' : 'Live mode',
182
- ],
183
- user: (symbol) => `Analyze ${symbol} and return trading decision`,
184
- };
185
- ```
186
-
187
- ### Strategy
188
-
189
- ```typescript
190
- // strategy.ts
191
- import './outline/signal.outline'; // register outline
192
-
193
- import { deepseek, Module, commitPrompt, MessageModel } from '@backtest-kit/ollama';
194
- import { addStrategy } from 'backtest-kit';
195
- import { json } from 'agent-swarm-kit';
196
-
197
- const signalModule = Module.fromPath('./signal.prompt.cjs');
198
-
199
- const getSignal = async () => {
200
- const messages: MessageModel[] = [];
201
- await commitPrompt(signalModule, messages);
202
-
203
- const { data } = await json('SignalOutline', messages);
204
- return data;
205
- };
206
-
207
- addStrategy({
208
- strategyName: 'llm-signal',
209
- interval: '5m',
210
- getSignal: deepseek(getSignal, 'deepseek-chat', process.env.DEEPSEEK_API_KEY),
211
- });
212
- ```
213
-
214
- ### Dynamic Prompt
215
-
216
- ```typescript
217
- // config/prompt/risk.prompt.cjs
218
- module.exports = {
219
- system: ['You are a risk analyst', 'Be conservative'],
220
- user: (symbol, strategyName, exchangeName, frameName, backtest) =>
221
- `Evaluate risk for ${symbol} position on ${frameName} timeframe`,
222
- };
223
- ```
224
-
225
- ### Inline Prompt
226
-
227
- ```typescript
228
- import { Prompt, commitPrompt, MessageModel } from '@backtest-kit/ollama';
229
-
230
- const prompt = Prompt.fromPrompt({
231
- system: ['You are a trading bot'],
232
- user: (symbol) => `What is the trend for ${symbol}?`,
233
- });
234
-
235
- const messages: MessageModel[] = [];
236
- await commitPrompt(prompt, messages);
237
- ```
238
-
239
- ### Token Rotation
240
-
241
- ```typescript
242
- import { ollama } from '@backtest-kit/ollama';
243
-
244
- const wrappedFn = ollama(myFn, 'llama3.3:70b', ['key1', 'key2', 'key3']);
245
- ```
246
-
247
- ## 🔌 Providers
248
-
249
- | Provider | Function | Base URL |
250
- |----------|----------|----------|
251
- | OpenAI | `gpt5()` | `https://api.openai.com/v1/` |
252
- | Claude | `claude()` | `https://api.anthropic.com/v1/` |
253
- | DeepSeek | `deepseek()` | `https://api.deepseek.com/` |
254
- | Grok | `grok()` | `https://api.x.ai/v1/` |
255
- | Mistral | `mistral()` | `https://api.mistral.ai/v1/` |
256
- | Perplexity | `perplexity()` | `https://api.perplexity.ai/` |
257
- | Cohere | `cohere()` | `https://api.cohere.ai/compatibility/v1/` |
258
- | Alibaba | `alibaba()` | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1/` |
259
- | Hugging Face | `hf()` | `https://router.huggingface.co/v1/` |
260
- | Ollama | `ollama()` | `http://localhost:11434/` |
261
- | Zhipu AI | `glm4()` | `https://open.bigmodel.cn/api/paas/v4/` |
262
-
263
- ## 📖 API
264
-
265
- ### Provider HOF
266
-
267
- ```typescript
268
- ollama | gpt5 | claude | deepseek | grok | mistral | perplexity | cohere | alibaba | hf | glm4
269
- (fn, model, apiKey?) => fn
270
- ```
271
-
272
- ### Module
273
-
274
- ```typescript
275
- Module.fromPath(path: string, baseDir?: string): Module
276
- ```
277
-
278
- Default baseDir: `{cwd}/config/prompt/`
279
-
280
- ### Prompt
281
-
282
- ```typescript
283
- Prompt.fromPrompt(source: PromptModel): Prompt
284
- ```
285
-
286
- ### commitPrompt
287
-
288
- ```typescript
289
- async function commitPrompt(source: Module | Prompt, history: MessageModel[]): Promise<void>
290
- ```
291
-
292
- ### PromptModel
293
-
294
- ```typescript
295
- interface PromptModel {
296
- system?: string[] | SystemPromptFn;
297
- user: string | UserPromptFn;
298
- }
299
-
300
- type SystemPromptFn = (
301
- symbol: string,
302
- strategyName: string,
303
- exchangeName: string,
304
- frameName: string,
305
- backtest: boolean
306
- ) => Promise<string[]> | string[];
307
-
308
- type UserPromptFn = (
309
- symbol: string,
310
- strategyName: string,
311
- exchangeName: string,
312
- frameName: string,
313
- backtest: boolean
314
- ) => Promise<string> | string;
315
- ```
316
-
317
- ## 💡 Why Use @backtest-kit/ollama?
318
-
319
- Instead of manually integrating LLM SDKs:
320
-
321
- **❌ Without ollama (manual work)**
322
-
323
- ```typescript
324
- import OpenAI from 'openai';
325
- import Anthropic from '@anthropic-ai/sdk';
326
-
327
- const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY });
328
- const response = await openai.chat.completions.create({
329
- model: 'gpt-4o',
330
- messages,
331
- response_format: { type: 'json_object' }
332
- });
333
- const signal = JSON.parse(response.choices[0].message.content);
334
- // ... manual schema validation
335
- // ... manual error handling
336
- // ... no fallback
337
- ```
338
-
339
- **✅ With ollama (one line)**
340
-
341
- ```typescript
342
- const signal = await gpt5(messages, 'gpt-4o');
343
- ```
344
-
345
- **🔥 Benefits:**
346
-
347
- - ⚡ Unified API across 10+ providers
348
- - 🎯 Enforced JSON schema (no parsing errors)
349
- - 🔄 Built-in token rotation (Ollama)
350
- - 🔑 Context-based API keys
351
- - 🛡️ Type-safe TypeScript interfaces
352
- - 📊 Trading-specific output format
353
-
354
- ## 🤝 Contribute
355
-
356
- Fork/PR on [GitHub](https://github.com/tripolskypetr/backtest-kit).
357
-
358
- ## 📜 License
359
-
360
- MIT © [tripolskypetr](https://github.com/tripolskypetr)
1
+ <img src="https://github.com/tripolskypetr/backtest-kit/raw/refs/heads/master/assets/monade.svg" height="45px" align="right">
2
+
3
+ # 🤖 @backtest-kit/ollama
4
+
5
+ > Multi-provider LLM context wrapper for trading strategies. Supports 10+ providers with unified HOF API.
6
+
7
+ ![screenshot](https://raw.githubusercontent.com/tripolskypetr/backtest-kit/HEAD/assets/screenshots/screenshot16.png)
8
+
9
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/tripolskypetr/backtest-kit)
10
+ [![npm](https://img.shields.io/npm/v/@backtest-kit/ollama.svg?style=flat-square)](https://npmjs.org/package/@backtest-kit/ollama)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)]()
12
+
13
+ Transform technical analysis into trading decisions with multi-provider LLM support, structured output, and built-in risk management.
14
+
15
+ 📚 **[Backtest Kit Docs](https://backtest-kit.github.io/documents/article_07_ai_news_trading_signals.html)** | 🌟 **[GitHub](https://github.com/tripolskypetr/backtest-kit)**
16
+
17
+ > **New to backtest-kit?** The fastest way to get a real, production-ready setup is to clone the [reference implementation](https://github.com/tripolskypetr/backtest-kit/tree/master/example) — a fully working news-sentiment AI trading system with LLM forecasting, multi-timeframe data, and a documented February 2026 backtest. Start there instead of from scratch.
18
+
19
+ ## ✨ Features
20
+
21
+ - 🔌 10+ LLM Providers: OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, Ollama, GLM-4
22
+ - ⚡ Higher-Order Functions: Wrap async functions with inference context via `di-scoped`
23
+ - 📝 Userspace Prompts: Load prompts from `.cjs` modules in `config/prompt/`
24
+ - 🎯 Userspace Schema: Define your own Zod or JSON schema with `addOutline`
25
+ - 🔄 Token Rotation: Pass array of API keys for automatic rotation
26
+ - 🗄️ Memoized Cache: Prompt modules cached with `memoize` from `functools-kit`
27
+
28
+ ## 📦 Installation
29
+
30
+ ```bash
31
+ npm install @backtest-kit/ollama backtest-kit agent-swarm-kit
32
+ ```
33
+
34
+ ## 🚀 Usage
35
+
36
+ ### Signal Schema (userspace)
37
+
38
+ ```typescript
39
+ // schema/Signal.schema.ts
40
+ import { z } from 'zod';
41
+ import { str } from 'functools-kit';
42
+
43
+ export const SignalSchema = z.object({
44
+ position: z.enum(['long', 'short', 'wait']).describe(
45
+ str.newline(
46
+ 'Position direction:',
47
+ 'long: bullish signals, uptrend potential',
48
+ 'short: bearish signals, downtrend potential',
49
+ 'wait: conflicting signals or unfavorable conditions',
50
+ )
51
+ ),
52
+ price_open: z.number().describe(
53
+ str.newline(
54
+ 'Entry price in USD',
55
+ 'Current market price or limit order price',
56
+ )
57
+ ),
58
+ price_stop_loss: z.number().describe(
59
+ str.newline(
60
+ 'Stop-loss price in USD',
61
+ 'LONG: below price_open',
62
+ 'SHORT: above price_open',
63
+ )
64
+ ),
65
+ price_take_profit: z.number().describe(
66
+ str.newline(
67
+ 'Take-profit price in USD',
68
+ 'LONG: above price_open',
69
+ 'SHORT: below price_open',
70
+ )
71
+ ),
72
+ minute_estimated_time: z.number().describe(
73
+ 'Estimated time to reach TP in minutes'
74
+ ),
75
+ risk_note: z.string().describe(
76
+ str.newline(
77
+ 'Risk assessment:',
78
+ '- Whale manipulations',
79
+ '- Order book imbalance',
80
+ '- Technical divergences',
81
+ 'Provide specific numbers and percentages',
82
+ )
83
+ ),
84
+ });
85
+
86
+ export type TSignalSchema = z.infer<typeof SignalSchema>;
87
+ ```
88
+
89
+ ### Signal Outline with Zod (userspace)
90
+
91
+ ```typescript
92
+ // outline/signal.outline.ts
93
+ import { addOutline } from 'agent-swarm-kit';
94
+ import { zodResponseFormat } from 'openai/helpers/zod';
95
+ import { SignalSchema, TSignalSchema } from '../schema/Signal.schema';
96
+ import { CompletionName } from '@backtest-kit/ollama';
97
+
98
+ addOutline<TSignalSchema>({
99
+ outlineName: 'SignalOutline',
100
+ completion: CompletionName.RunnerOutlineCompletion,
101
+ format: zodResponseFormat(SignalSchema, 'position_decision'),
102
+ getOutlineHistory: async ({ history, param: messages = [] }) => {
103
+ await history.push(messages);
104
+ },
105
+ validations: [
106
+ {
107
+ validate: ({ data }) => {
108
+ if (data.position === 'long' && data.price_stop_loss >= data.price_open) {
109
+ throw new Error('For LONG, stop_loss must be below price_open');
110
+ }
111
+ if (data.position === 'short' && data.price_stop_loss <= data.price_open) {
112
+ throw new Error('For SHORT, stop_loss must be above price_open');
113
+ }
114
+ },
115
+ },
116
+ ],
117
+ });
118
+ ```
119
+
120
+ ### Signal Outline without Zod (userspace)
121
+
122
+ ```typescript
123
+ // outline/signal.outline.ts
124
+ import { addOutline, IOutlineFormat } from 'agent-swarm-kit';
125
+ import { CompletionName } from '@backtest-kit/ollama';
126
+
127
+ const format: IOutlineFormat = {
128
+ type: 'object',
129
+ properties: {
130
+ take_profit_price: { type: 'number', description: 'Take profit price in USD' },
131
+ stop_loss_price: { type: 'number', description: 'Stop-loss price in USD' },
132
+ description: { type: 'string', description: 'User-friendly explanation of risks, min 10 sentences' },
133
+ reasoning: { type: 'string', description: 'Technical analysis, min 15 sentences' },
134
+ },
135
+ required: ['take_profit_price', 'stop_loss_price', 'description', 'reasoning'],
136
+ };
137
+
138
+ addOutline({
139
+ outlineName: 'SignalOutline',
140
+ format,
141
+ prompt: 'Generate crypto trading signals based on price and volume indicators in JSON format.',
142
+ completion: CompletionName.RunnerOutlineCompletion,
143
+ getOutlineHistory: async ({ history, param }) => {
144
+ const signalReport = await ioc.signalReportService.getSignalReport(param);
145
+ await commitReports(history, signalReport);
146
+ await history.push({ role: 'user', content: 'Generate JSON based on reports.' });
147
+ },
148
+ validations: [
149
+ {
150
+ validate: ({ data }) => {
151
+ if (data.action !== 'buy') return;
152
+ const stopLossChange = percentDiff(data.current_price, data.stop_loss_price);
153
+ if (stopLossChange > CC_LADDER_STOP_LOSS) {
154
+ throw new Error(`Stop loss must not exceed -${CC_LADDER_STOP_LOSS}%`);
155
+ }
156
+ },
157
+ docDescription: 'Checks stop-loss price against max loss percentage.',
158
+ },
159
+ {
160
+ validate: ({ data }) => {
161
+ if (data.action !== 'buy') return;
162
+ const sellChange = percentDiff(data.current_price, data.take_profit_price);
163
+ if (sellChange > CC_LADDER_TAKE_PROFIT) {
164
+ throw new Error(`Take profit must not exceed +${CC_LADDER_TAKE_PROFIT}%`);
165
+ }
166
+ },
167
+ docDescription: 'Checks take-profit price against max profit percentage.',
168
+ },
169
+ ],
170
+ });
171
+ ```
172
+
173
+ ### Prompt Module (userspace)
174
+
175
+ ```typescript
176
+ // config/prompt/signal.prompt.cjs
177
+ module.exports = {
178
+ system: (symbol, strategyName, exchangeName, frameName, backtest) => [
179
+ `You are analyzing ${symbol} on ${exchangeName}`,
180
+ `Strategy: ${strategyName}, Timeframe: ${frameName}`,
181
+ backtest ? 'Backtest mode' : 'Live mode',
182
+ ],
183
+ user: (symbol) => `Analyze ${symbol} and return trading decision`,
184
+ };
185
+ ```
186
+
187
+ ### Strategy
188
+
189
+ ```typescript
190
+ // strategy.ts
191
+ import './outline/signal.outline'; // register outline
192
+
193
+ import { deepseek, Module, commitPrompt, MessageModel } from '@backtest-kit/ollama';
194
+ import { addStrategy } from 'backtest-kit';
195
+ import { json } from 'agent-swarm-kit';
196
+
197
+ const signalModule = Module.fromPath('./signal.prompt.cjs');
198
+
199
+ const getSignal = async () => {
200
+ const messages: MessageModel[] = [];
201
+ await commitPrompt(signalModule, messages);
202
+
203
+ const { data } = await json('SignalOutline', messages);
204
+ return data;
205
+ };
206
+
207
+ addStrategy({
208
+ strategyName: 'llm-signal',
209
+ interval: '5m',
210
+ getSignal: deepseek(getSignal, 'deepseek-chat', process.env.DEEPSEEK_API_KEY),
211
+ });
212
+ ```
213
+
214
+ ### Dynamic Prompt
215
+
216
+ ```typescript
217
+ // config/prompt/risk.prompt.cjs
218
+ module.exports = {
219
+ system: ['You are a risk analyst', 'Be conservative'],
220
+ user: (symbol, strategyName, exchangeName, frameName, backtest) =>
221
+ `Evaluate risk for ${symbol} position on ${frameName} timeframe`,
222
+ };
223
+ ```
224
+
225
+ ### Inline Prompt
226
+
227
+ ```typescript
228
+ import { Prompt, commitPrompt, MessageModel } from '@backtest-kit/ollama';
229
+
230
+ const prompt = Prompt.fromPrompt({
231
+ system: ['You are a trading bot'],
232
+ user: (symbol) => `What is the trend for ${symbol}?`,
233
+ });
234
+
235
+ const messages: MessageModel[] = [];
236
+ await commitPrompt(prompt, messages);
237
+ ```
238
+
239
+ ### Token Rotation
240
+
241
+ ```typescript
242
+ import { ollama } from '@backtest-kit/ollama';
243
+
244
+ const wrappedFn = ollama(myFn, 'llama3.3:70b', ['key1', 'key2', 'key3']);
245
+ ```
246
+
247
+ ## 🔌 Providers
248
+
249
+ | Provider | Function | Base URL |
250
+ |----------|----------|----------|
251
+ | OpenAI | `gpt5()` | `https://api.openai.com/v1/` |
252
+ | Claude | `claude()` | `https://api.anthropic.com/v1/` |
253
+ | DeepSeek | `deepseek()` | `https://api.deepseek.com/` |
254
+ | Grok | `grok()` | `https://api.x.ai/v1/` |
255
+ | Mistral | `mistral()` | `https://api.mistral.ai/v1/` |
256
+ | Perplexity | `perplexity()` | `https://api.perplexity.ai/` |
257
+ | Cohere | `cohere()` | `https://api.cohere.ai/compatibility/v1/` |
258
+ | Alibaba | `alibaba()` | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1/` |
259
+ | Hugging Face | `hf()` | `https://router.huggingface.co/v1/` |
260
+ | Ollama | `ollama()` | `http://localhost:11434/` |
261
+ | Zhipu AI | `glm4()` | `https://open.bigmodel.cn/api/paas/v4/` |
262
+
263
+ ## 📖 API
264
+
265
+ ### Provider HOF
266
+
267
+ ```typescript
268
+ ollama | gpt5 | claude | deepseek | grok | mistral | perplexity | cohere | alibaba | hf | glm4
269
+ (fn, model, apiKey?) => fn
270
+ ```
271
+
272
+ ### Module
273
+
274
+ ```typescript
275
+ Module.fromPath(path: string, baseDir?: string): Module
276
+ ```
277
+
278
+ Default baseDir: `{cwd}/config/prompt/`
279
+
280
+ ### Prompt
281
+
282
+ ```typescript
283
+ Prompt.fromPrompt(source: PromptModel): Prompt
284
+ ```
285
+
286
+ ### commitPrompt
287
+
288
+ ```typescript
289
+ async function commitPrompt(source: Module | Prompt, history: MessageModel[]): Promise<void>
290
+ ```
291
+
292
+ ### PromptModel
293
+
294
+ ```typescript
295
+ interface PromptModel {
296
+ system?: string[] | SystemPromptFn;
297
+ user: string | UserPromptFn;
298
+ }
299
+
300
+ type SystemPromptFn = (
301
+ symbol: string,
302
+ strategyName: string,
303
+ exchangeName: string,
304
+ frameName: string,
305
+ backtest: boolean
306
+ ) => Promise<string[]> | string[];
307
+
308
+ type UserPromptFn = (
309
+ symbol: string,
310
+ strategyName: string,
311
+ exchangeName: string,
312
+ frameName: string,
313
+ backtest: boolean
314
+ ) => Promise<string> | string;
315
+ ```
316
+
317
+ ## 💡 Why Use @backtest-kit/ollama?
318
+
319
+ Instead of manually integrating LLM SDKs:
320
+
321
+ **❌ Without ollama (manual work)**
322
+
323
+ ```typescript
324
+ import OpenAI from 'openai';
325
+ import Anthropic from '@anthropic-ai/sdk';
326
+
327
+ const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY });
328
+ const response = await openai.chat.completions.create({
329
+ model: 'gpt-4o',
330
+ messages,
331
+ response_format: { type: 'json_object' }
332
+ });
333
+ const signal = JSON.parse(response.choices[0].message.content);
334
+ // ... manual schema validation
335
+ // ... manual error handling
336
+ // ... no fallback
337
+ ```
338
+
339
+ **✅ With ollama (one line)**
340
+
341
+ ```typescript
342
+ const signal = await gpt5(messages, 'gpt-4o');
343
+ ```
344
+
345
+ **🔥 Benefits:**
346
+
347
+ - ⚡ Unified API across 10+ providers
348
+ - 🎯 Enforced JSON schema (no parsing errors)
349
+ - 🔄 Built-in token rotation (Ollama)
350
+ - 🔑 Context-based API keys
351
+ - 🛡️ Type-safe TypeScript interfaces
352
+ - 📊 Trading-specific output format
353
+
354
+ ## 🤝 Contribute
355
+
356
+ Fork/PR on [GitHub](https://github.com/tripolskypetr/backtest-kit).
357
+
358
+ ## 📜 License
359
+
360
+ MIT © [tripolskypetr](https://github.com/tripolskypetr)
package/package.json CHANGED
@@ -1,112 +1,112 @@
1
- {
2
- "name": "@backtest-kit/ollama",
3
- "version": "8.3.0",
4
- "description": "Multi-provider LLM inference library for AI-powered trading strategies. Supports 10+ providers including OpenAI, Claude, DeepSeek, Grok, Mistral with unified API and automatic token rotation.",
5
- "author": {
6
- "name": "Petr Tripolsky",
7
- "email": "tripolskypetr@gmail.com",
8
- "url": "https://github.com/tripolskypetr"
9
- },
10
- "funding": {
11
- "type": "individual",
12
- "url": "http://paypal.me/tripolskypetr"
13
- },
14
- "license": "MIT",
15
- "homepage": "https://backtest-kit.github.io/documents/article_07_ai_news_trading_signals.html",
16
- "keywords": [
17
- "llm",
18
- "openai",
19
- "claude",
20
- "deepseek",
21
- "grok",
22
- "mistral",
23
- "perplexity",
24
- "cohere",
25
- "ollama",
26
- "huggingface",
27
- "ai",
28
- "machine-learning",
29
- "trading-bot",
30
- "algorithmic-trading",
31
- "quantitative-trading",
32
- "cryptocurrency",
33
- "trading-signals",
34
- "multi-provider",
35
- "inference",
36
- "structured-output",
37
- "token-rotation",
38
- "backtest",
39
- "risk-management"
40
- ],
41
- "files": [
42
- "build",
43
- "types.d.ts",
44
- "README.md"
45
- ],
46
- "repository": {
47
- "type": "git",
48
- "url": "https://github.com/tripolskypetr/backtest-kit",
49
- "documentation": "https://github.com/tripolskypetr/backtest-kit/tree/master/docs"
50
- },
51
- "bugs": {
52
- "url": "https://github.com/tripolskypetr/backtest-kit/issues"
53
- },
54
- "scripts": {
55
- "build": "rollup -c"
56
- },
57
- "main": "build/index.cjs",
58
- "module": "build/index.mjs",
59
- "source": "src/index.ts",
60
- "types": "./types.d.ts",
61
- "exports": {
62
- "require": "./build/index.cjs",
63
- "types": "./types.d.ts",
64
- "import": "./build/index.mjs",
65
- "default": "./build/index.cjs"
66
- },
67
- "devDependencies": {
68
- "@huggingface/inference": "4.7.1",
69
- "@langchain/core": "0.3.57",
70
- "@langchain/xai": "0.0.2",
71
- "@rollup/plugin-typescript": "11.1.6",
72
- "@types/node": "22.9.0",
73
- "glob": "11.0.1",
74
- "ollama": "0.6.0",
75
- "openai": "4.97.0",
76
- "groq-sdk": "0.37.0",
77
- "rimraf": "6.0.1",
78
- "rollup": "3.29.5",
79
- "rollup-plugin-dts": "6.1.1",
80
- "rollup-plugin-peer-deps-external": "2.2.4",
81
- "ts-morph": "27.0.2",
82
- "tslib": "2.7.0",
83
- "typedoc": "0.27.9",
84
- "backtest-kit": "8.3.0",
85
- "worker-testbed": "2.0.0"
86
- },
87
- "peerDependencies": {
88
- "@huggingface/inference": "^4.7.1",
89
- "@langchain/core": "^0.3.57",
90
- "@langchain/xai": "^0.0.2",
91
- "backtest-kit": "^8.3.0",
92
- "groq-sdk": "^0.37.0",
93
- "ollama": "^0.6.0",
94
- "openai": "^4.97.0",
95
- "typescript": "^5.0.0"
96
- },
97
- "dependencies": {
98
- "agent-swarm-kit": "^2.6.0",
99
- "di-kit": "^1.1.1",
100
- "di-scoped": "^1.0.21",
101
- "functools-kit": "^2.3.0",
102
- "get-moment-stamp": "^1.1.2",
103
- "jsonrepair": "^3.12.0",
104
- "markdown-it": "^14.1.0",
105
- "markdownlint": "^0.38.0",
106
- "sanitize-html": "^2.17.0",
107
- "zod": "^3.25.76"
108
- },
109
- "publishConfig": {
110
- "access": "public"
111
- }
112
- }
1
+ {
2
+ "name": "@backtest-kit/ollama",
3
+ "version": "8.5.0",
4
+ "description": "Multi-provider LLM inference library for AI-powered trading strategies. Supports 10+ providers including OpenAI, Claude, DeepSeek, Grok, Mistral with unified API and automatic token rotation.",
5
+ "author": {
6
+ "name": "Petr Tripolsky",
7
+ "email": "tripolskypetr@gmail.com",
8
+ "url": "https://github.com/tripolskypetr"
9
+ },
10
+ "funding": {
11
+ "type": "individual",
12
+ "url": "http://paypal.me/tripolskypetr"
13
+ },
14
+ "license": "MIT",
15
+ "homepage": "https://backtest-kit.github.io/documents/article_07_ai_news_trading_signals.html",
16
+ "keywords": [
17
+ "llm",
18
+ "openai",
19
+ "claude",
20
+ "deepseek",
21
+ "grok",
22
+ "mistral",
23
+ "perplexity",
24
+ "cohere",
25
+ "ollama",
26
+ "huggingface",
27
+ "ai",
28
+ "machine-learning",
29
+ "trading-bot",
30
+ "algorithmic-trading",
31
+ "quantitative-trading",
32
+ "cryptocurrency",
33
+ "trading-signals",
34
+ "multi-provider",
35
+ "inference",
36
+ "structured-output",
37
+ "token-rotation",
38
+ "backtest",
39
+ "risk-management"
40
+ ],
41
+ "files": [
42
+ "build",
43
+ "types.d.ts",
44
+ "README.md"
45
+ ],
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/tripolskypetr/backtest-kit",
49
+ "documentation": "https://github.com/tripolskypetr/backtest-kit/tree/master/docs"
50
+ },
51
+ "bugs": {
52
+ "url": "https://github.com/tripolskypetr/backtest-kit/issues"
53
+ },
54
+ "scripts": {
55
+ "build": "rollup -c"
56
+ },
57
+ "main": "build/index.cjs",
58
+ "module": "build/index.mjs",
59
+ "source": "src/index.ts",
60
+ "types": "./types.d.ts",
61
+ "exports": {
62
+ "require": "./build/index.cjs",
63
+ "types": "./types.d.ts",
64
+ "import": "./build/index.mjs",
65
+ "default": "./build/index.cjs"
66
+ },
67
+ "devDependencies": {
68
+ "@huggingface/inference": "4.7.1",
69
+ "@langchain/core": "0.3.57",
70
+ "@langchain/xai": "0.0.2",
71
+ "@rollup/plugin-typescript": "11.1.6",
72
+ "@types/node": "22.9.0",
73
+ "glob": "11.0.1",
74
+ "ollama": "0.6.0",
75
+ "openai": "4.97.0",
76
+ "groq-sdk": "0.37.0",
77
+ "rimraf": "6.0.1",
78
+ "rollup": "3.29.5",
79
+ "rollup-plugin-dts": "6.1.1",
80
+ "rollup-plugin-peer-deps-external": "2.2.4",
81
+ "ts-morph": "27.0.2",
82
+ "tslib": "2.7.0",
83
+ "typedoc": "0.27.9",
84
+ "backtest-kit": "8.5.0",
85
+ "worker-testbed": "2.0.0"
86
+ },
87
+ "peerDependencies": {
88
+ "@huggingface/inference": "^4.7.1",
89
+ "@langchain/core": "^0.3.57",
90
+ "@langchain/xai": "^0.0.2",
91
+ "backtest-kit": "^8.5.0",
92
+ "groq-sdk": "^0.37.0",
93
+ "ollama": "^0.6.0",
94
+ "openai": "^4.97.0",
95
+ "typescript": "^5.0.0"
96
+ },
97
+ "dependencies": {
98
+ "agent-swarm-kit": "^2.6.0",
99
+ "di-kit": "^1.1.1",
100
+ "di-scoped": "^1.0.21",
101
+ "functools-kit": "^2.3.0",
102
+ "get-moment-stamp": "^1.1.2",
103
+ "jsonrepair": "^3.12.0",
104
+ "markdown-it": "^14.1.0",
105
+ "markdownlint": "^0.38.0",
106
+ "sanitize-html": "^2.17.0",
107
+ "zod": "^3.25.76"
108
+ },
109
+ "publishConfig": {
110
+ "access": "public"
111
+ }
112
+ }