@backtest-kit/ollama 0.2.0 → 1.0.1
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.
- package/README.md +263 -113
- package/build/index.cjs +500 -755
- package/build/index.mjs +492 -748
- package/package.json +1 -1
- package/types.d.ts +278 -396
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 🤖 @backtest-kit/ollama
|
|
2
2
|
|
|
3
|
-
> Multi-provider LLM
|
|
3
|
+
> Multi-provider LLM context wrapper for trading strategies. Supports 10+ providers with unified HOF API.
|
|
4
4
|
|
|
5
5
|

|
|
6
6
|
|
|
@@ -14,160 +14,309 @@ Transform technical analysis into trading decisions with multi-provider LLM supp
|
|
|
14
14
|
|
|
15
15
|
## ✨ Features
|
|
16
16
|
|
|
17
|
-
- 🔌
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
-
|
|
23
|
-
- 🛡️ **Type Safe**: Full TypeScript support with exported types
|
|
17
|
+
- 🔌 10+ LLM Providers: OpenAI, Claude, DeepSeek, Grok, Mistral, Perplexity, Cohere, Alibaba, Hugging Face, Ollama, GLM-4
|
|
18
|
+
- ⚡ Higher-Order Functions: Wrap async functions with inference context via `di-scoped`
|
|
19
|
+
- 📝 Userspace Prompts: Load prompts from `.cjs` modules in `config/prompt/`
|
|
20
|
+
- 🎯 Userspace Schema: Define your own Zod or JSON schema with `addOutline`
|
|
21
|
+
- 🔄 Token Rotation: Pass array of API keys for automatic rotation
|
|
22
|
+
- 🗄️ Memoized Cache: Prompt modules cached with `memoize` from `functools-kit`
|
|
24
23
|
|
|
25
|
-
##
|
|
24
|
+
## 📦 Installation
|
|
26
25
|
|
|
27
|
-
|
|
26
|
+
```bash
|
|
27
|
+
npm install @backtest-kit/ollama backtest-kit agent-swarm-kit
|
|
28
|
+
```
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
|----------|----------|----------|
|
|
31
|
-
| **OpenAI** | `gpt5()` | `https://api.openai.com/v1/` |
|
|
32
|
-
| **Claude** | `claude()` | `https://api.anthropic.com/v1/` |
|
|
33
|
-
| **DeepSeek** | `deepseek()` | `https://api.deepseek.com/` |
|
|
34
|
-
| **Grok** | `grok()` | `https://api.x.ai/v1/` |
|
|
35
|
-
| **Mistral** | `mistral()` | `https://api.mistral.ai/v1/` |
|
|
36
|
-
| **Perplexity** | `perplexity()` | `https://api.perplexity.ai/` |
|
|
37
|
-
| **Cohere** | `cohere()` | `https://api.cohere.ai/compatibility/v1/` |
|
|
38
|
-
| **Alibaba** | `alibaba()` | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1/` |
|
|
39
|
-
| **Hugging Face** | `hf()` | `https://router.huggingface.co/v1/` |
|
|
40
|
-
| **Ollama** | `ollama()` | `https://ollama.com/` |
|
|
41
|
-
| **Zhipu AI** | `glm4()` | `https://api.z.ai/api/paas/v4/` |
|
|
42
|
-
|
|
43
|
-
**Output Schema:**
|
|
30
|
+
## 🚀 Usage
|
|
44
31
|
|
|
45
|
-
|
|
46
|
-
{
|
|
47
|
-
id: string; // Unique signal ID
|
|
48
|
-
position: "long" | "short"; // Trading direction
|
|
49
|
-
minuteEstimatedTime: number; // Hold duration estimate
|
|
50
|
-
priceStopLoss: number; // Stop loss price
|
|
51
|
-
priceTakeProfit: number; // Take profit price
|
|
52
|
-
note: string; // Risk assessment note
|
|
53
|
-
priceOpen: number; // Entry price
|
|
54
|
-
}
|
|
55
|
-
```
|
|
32
|
+
### Signal Schema (userspace)
|
|
56
33
|
|
|
57
|
-
|
|
34
|
+
```typescript
|
|
35
|
+
// schema/Signal.schema.ts
|
|
36
|
+
import { z } from 'zod';
|
|
37
|
+
import { str } from 'functools-kit';
|
|
38
|
+
|
|
39
|
+
export const SignalSchema = z.object({
|
|
40
|
+
position: z.enum(['long', 'short', 'wait']).describe(
|
|
41
|
+
str.newline(
|
|
42
|
+
'Position direction:',
|
|
43
|
+
'long: bullish signals, uptrend potential',
|
|
44
|
+
'short: bearish signals, downtrend potential',
|
|
45
|
+
'wait: conflicting signals or unfavorable conditions',
|
|
46
|
+
)
|
|
47
|
+
),
|
|
48
|
+
price_open: z.number().describe(
|
|
49
|
+
str.newline(
|
|
50
|
+
'Entry price in USD',
|
|
51
|
+
'Current market price or limit order price',
|
|
52
|
+
)
|
|
53
|
+
),
|
|
54
|
+
price_stop_loss: z.number().describe(
|
|
55
|
+
str.newline(
|
|
56
|
+
'Stop-loss price in USD',
|
|
57
|
+
'LONG: below price_open',
|
|
58
|
+
'SHORT: above price_open',
|
|
59
|
+
)
|
|
60
|
+
),
|
|
61
|
+
price_take_profit: z.number().describe(
|
|
62
|
+
str.newline(
|
|
63
|
+
'Take-profit price in USD',
|
|
64
|
+
'LONG: above price_open',
|
|
65
|
+
'SHORT: below price_open',
|
|
66
|
+
)
|
|
67
|
+
),
|
|
68
|
+
minute_estimated_time: z.number().describe(
|
|
69
|
+
'Estimated time to reach TP in minutes'
|
|
70
|
+
),
|
|
71
|
+
risk_note: z.string().describe(
|
|
72
|
+
str.newline(
|
|
73
|
+
'Risk assessment:',
|
|
74
|
+
'- Whale manipulations',
|
|
75
|
+
'- Order book imbalance',
|
|
76
|
+
'- Technical divergences',
|
|
77
|
+
'Provide specific numbers and percentages',
|
|
78
|
+
)
|
|
79
|
+
),
|
|
80
|
+
});
|
|
58
81
|
|
|
59
|
-
|
|
60
|
-
npm install @backtest-kit/ollama agent-swarm-kit backtest-kit
|
|
82
|
+
export type TSignalSchema = z.infer<typeof SignalSchema>;
|
|
61
83
|
```
|
|
62
84
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
### Quick Start - OpenAI
|
|
85
|
+
### Signal Outline with Zod (userspace)
|
|
66
86
|
|
|
67
87
|
```typescript
|
|
68
|
-
|
|
69
|
-
import {
|
|
88
|
+
// outline/signal.outline.ts
|
|
89
|
+
import { addOutline } from 'agent-swarm-kit';
|
|
90
|
+
import { zodResponseFormat } from 'openai/helpers/zod';
|
|
91
|
+
import { SignalSchema, TSignalSchema } from '../schema/Signal.schema';
|
|
92
|
+
import { CompletionName } from '@backtest-kit/ollama';
|
|
93
|
+
|
|
94
|
+
addOutline<TSignalSchema>({
|
|
95
|
+
outlineName: 'SignalOutline',
|
|
96
|
+
completion: CompletionName.RunnerOutlineCompletion,
|
|
97
|
+
format: zodResponseFormat(SignalSchema, 'position_decision'),
|
|
98
|
+
getOutlineHistory: async ({ history, param: messages = [] }) => {
|
|
99
|
+
await history.push(messages);
|
|
100
|
+
},
|
|
101
|
+
validations: [
|
|
102
|
+
{
|
|
103
|
+
validate: ({ data }) => {
|
|
104
|
+
if (data.position === 'long' && data.price_stop_loss >= data.price_open) {
|
|
105
|
+
throw new Error('For LONG, stop_loss must be below price_open');
|
|
106
|
+
}
|
|
107
|
+
if (data.position === 'short' && data.price_stop_loss <= data.price_open) {
|
|
108
|
+
throw new Error('For SHORT, stop_loss must be above price_open');
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
],
|
|
113
|
+
});
|
|
114
|
+
```
|
|
70
115
|
|
|
71
|
-
|
|
72
|
-
const messages = [
|
|
73
|
-
{
|
|
74
|
-
role: 'system',
|
|
75
|
-
content: 'You are a trading bot. Analyze indicators and return JSON: { position: "long"|"short", priceStopLoss, priceTakeProfit, minuteEstimatedTime, priceOpen, note }'
|
|
76
|
-
}
|
|
77
|
-
];
|
|
116
|
+
### Signal Outline without Zod (userspace)
|
|
78
117
|
|
|
79
|
-
|
|
118
|
+
```typescript
|
|
119
|
+
// outline/signal.outline.ts
|
|
120
|
+
import { addOutline, IOutlineFormat } from 'agent-swarm-kit';
|
|
121
|
+
import { CompletionName } from '@backtest-kit/ollama';
|
|
122
|
+
|
|
123
|
+
const format: IOutlineFormat = {
|
|
124
|
+
type: 'object',
|
|
125
|
+
properties: {
|
|
126
|
+
take_profit_price: { type: 'number', description: 'Take profit price in USD' },
|
|
127
|
+
stop_loss_price: { type: 'number', description: 'Stop-loss price in USD' },
|
|
128
|
+
description: { type: 'string', description: 'User-friendly explanation of risks, min 10 sentences' },
|
|
129
|
+
reasoning: { type: 'string', description: 'Technical analysis, min 15 sentences' },
|
|
130
|
+
},
|
|
131
|
+
required: ['take_profit_price', 'stop_loss_price', 'description', 'reasoning'],
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
addOutline({
|
|
135
|
+
outlineName: 'SignalOutline',
|
|
136
|
+
format,
|
|
137
|
+
prompt: 'Generate crypto trading signals based on price and volume indicators in JSON format.',
|
|
138
|
+
completion: CompletionName.RunnerOutlineCompletion,
|
|
139
|
+
getOutlineHistory: async ({ history, param }) => {
|
|
140
|
+
const signalReport = await ioc.signalReportService.getSignalReport(param);
|
|
141
|
+
await commitReports(history, signalReport);
|
|
142
|
+
await history.push({ role: 'user', content: 'Generate JSON based on reports.' });
|
|
143
|
+
},
|
|
144
|
+
validations: [
|
|
145
|
+
{
|
|
146
|
+
validate: ({ data }) => {
|
|
147
|
+
if (data.action !== 'buy') return;
|
|
148
|
+
const stopLossChange = percentDiff(data.current_price, data.stop_loss_price);
|
|
149
|
+
if (stopLossChange > CC_LADDER_STOP_LOSS) {
|
|
150
|
+
throw new Error(`Stop loss must not exceed -${CC_LADDER_STOP_LOSS}%`);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
docDescription: 'Checks stop-loss price against max loss percentage.',
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
validate: ({ data }) => {
|
|
157
|
+
if (data.action !== 'buy') return;
|
|
158
|
+
const sellChange = percentDiff(data.current_price, data.take_profit_price);
|
|
159
|
+
if (sellChange > CC_LADDER_TAKE_PROFIT) {
|
|
160
|
+
throw new Error(`Take profit must not exceed +${CC_LADDER_TAKE_PROFIT}%`);
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
docDescription: 'Checks take-profit price against max profit percentage.',
|
|
164
|
+
},
|
|
165
|
+
],
|
|
166
|
+
});
|
|
167
|
+
```
|
|
80
168
|
|
|
81
|
-
|
|
82
|
-
const signal = await gpt5(messages, 'gpt-4o', process.env.CC_OPENAI_API_KEY);
|
|
169
|
+
### Prompt Module (userspace)
|
|
83
170
|
|
|
84
|
-
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
171
|
+
```typescript
|
|
172
|
+
// config/prompt/signal.prompt.cjs
|
|
173
|
+
module.exports = {
|
|
174
|
+
system: (symbol, strategyName, exchangeName, frameName, backtest) => [
|
|
175
|
+
`You are analyzing ${symbol} on ${exchangeName}`,
|
|
176
|
+
`Strategy: ${strategyName}, Timeframe: ${frameName}`,
|
|
177
|
+
backtest ? 'Backtest mode' : 'Live mode',
|
|
178
|
+
],
|
|
179
|
+
user: (symbol) => `Analyze ${symbol} and return trading decision`,
|
|
180
|
+
};
|
|
94
181
|
```
|
|
95
182
|
|
|
96
|
-
###
|
|
183
|
+
### Strategy
|
|
97
184
|
|
|
98
185
|
```typescript
|
|
99
|
-
|
|
186
|
+
// strategy.ts
|
|
187
|
+
import './outline/signal.outline'; // register outline
|
|
188
|
+
|
|
189
|
+
import { deepseek, Module, commitPrompt, MessageModel } from '@backtest-kit/ollama';
|
|
100
190
|
import { addStrategy } from 'backtest-kit';
|
|
101
|
-
import {
|
|
191
|
+
import { json } from 'agent-swarm-kit';
|
|
192
|
+
|
|
193
|
+
const signalModule = Module.fromPath('./signal.prompt.cjs');
|
|
194
|
+
|
|
195
|
+
const getSignal = async () => {
|
|
196
|
+
const messages: MessageModel[] = [];
|
|
197
|
+
await commitPrompt(signalModule, messages);
|
|
198
|
+
|
|
199
|
+
const { data } = await json('SignalOutline', messages);
|
|
200
|
+
return data;
|
|
201
|
+
};
|
|
102
202
|
|
|
103
203
|
addStrategy({
|
|
104
|
-
strategyName: '
|
|
204
|
+
strategyName: 'llm-signal',
|
|
105
205
|
interval: '5m',
|
|
106
|
-
|
|
107
|
-
getSignal: async (symbol) => {
|
|
108
|
-
const messages = [
|
|
109
|
-
{
|
|
110
|
-
role: 'system',
|
|
111
|
-
content: 'Analyze technical data and return trading signal as JSON'
|
|
112
|
-
}
|
|
113
|
-
];
|
|
114
|
-
|
|
115
|
-
await commitHistorySetup(symbol, messages);
|
|
116
|
-
|
|
117
|
-
// Try multiple providers with fallback
|
|
118
|
-
try {
|
|
119
|
-
return await deepseek(messages, 'deepseek-chat');
|
|
120
|
-
} catch (err) {
|
|
121
|
-
console.warn('DeepSeek failed, trying Claude:', err);
|
|
122
|
-
try {
|
|
123
|
-
return await claude(messages, 'claude-3-5-sonnet-20241022');
|
|
124
|
-
} catch (err2) {
|
|
125
|
-
console.warn('Claude failed, using GPT-5:', err2);
|
|
126
|
-
return await gpt5(messages, 'gpt-4o');
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
206
|
+
getSignal: deepseek(getSignal, 'deepseek-chat', process.env.DEEPSEEK_API_KEY),
|
|
130
207
|
});
|
|
131
208
|
```
|
|
132
209
|
|
|
133
|
-
###
|
|
210
|
+
### Dynamic Prompt
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
// config/prompt/risk.prompt.cjs
|
|
214
|
+
module.exports = {
|
|
215
|
+
system: ['You are a risk analyst', 'Be conservative'],
|
|
216
|
+
user: (symbol, strategyName, exchangeName, frameName, backtest) =>
|
|
217
|
+
`Evaluate risk for ${symbol} position on ${frameName} timeframe`,
|
|
218
|
+
};
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Inline Prompt
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
import { Prompt, commitPrompt, MessageModel } from '@backtest-kit/ollama';
|
|
225
|
+
|
|
226
|
+
const prompt = Prompt.fromPrompt({
|
|
227
|
+
system: ['You are a trading bot'],
|
|
228
|
+
user: (symbol) => `What is the trend for ${symbol}?`,
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
const messages: MessageModel[] = [];
|
|
232
|
+
await commitPrompt(prompt, messages);
|
|
233
|
+
```
|
|
134
234
|
|
|
135
|
-
|
|
235
|
+
### Token Rotation
|
|
136
236
|
|
|
137
237
|
```typescript
|
|
138
238
|
import { ollama } from '@backtest-kit/ollama';
|
|
139
239
|
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
);
|
|
240
|
+
const wrappedFn = ollama(myFn, 'llama3.3:70b', ['key1', 'key2', 'key3']);
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
## 🔌 Providers
|
|
145
244
|
|
|
146
|
-
|
|
147
|
-
|
|
245
|
+
| Provider | Function | Base URL |
|
|
246
|
+
|----------|----------|----------|
|
|
247
|
+
| OpenAI | `gpt5()` | `https://api.openai.com/v1/` |
|
|
248
|
+
| Claude | `claude()` | `https://api.anthropic.com/v1/` |
|
|
249
|
+
| DeepSeek | `deepseek()` | `https://api.deepseek.com/` |
|
|
250
|
+
| Grok | `grok()` | `https://api.x.ai/v1/` |
|
|
251
|
+
| Mistral | `mistral()` | `https://api.mistral.ai/v1/` |
|
|
252
|
+
| Perplexity | `perplexity()` | `https://api.perplexity.ai/` |
|
|
253
|
+
| Cohere | `cohere()` | `https://api.cohere.ai/compatibility/v1/` |
|
|
254
|
+
| Alibaba | `alibaba()` | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1/` |
|
|
255
|
+
| Hugging Face | `hf()` | `https://router.huggingface.co/v1/` |
|
|
256
|
+
| Ollama | `ollama()` | `http://localhost:11434/` |
|
|
257
|
+
| Zhipu AI | `glm4()` | `https://open.bigmodel.cn/api/paas/v4/` |
|
|
258
|
+
|
|
259
|
+
## 📖 API
|
|
260
|
+
|
|
261
|
+
### Provider HOF
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
ollama | gpt5 | claude | deepseek | grok | mistral | perplexity | cohere | alibaba | hf | glm4
|
|
265
|
+
(fn, model, apiKey?) => fn
|
|
148
266
|
```
|
|
149
267
|
|
|
150
|
-
###
|
|
268
|
+
### Module
|
|
269
|
+
|
|
270
|
+
```typescript
|
|
271
|
+
Module.fromPath(path: string, baseDir?: string): Module
|
|
272
|
+
```
|
|
151
273
|
|
|
152
|
-
|
|
274
|
+
Default baseDir: `{cwd}/config/prompt/`
|
|
275
|
+
|
|
276
|
+
### Prompt
|
|
153
277
|
|
|
154
278
|
```typescript
|
|
155
|
-
|
|
279
|
+
Prompt.fromPrompt(source: PromptModel): Prompt
|
|
280
|
+
```
|
|
156
281
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
282
|
+
### commitPrompt
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
async function commitPrompt(source: Module | Prompt, history: MessageModel[]): Promise<void>
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### PromptModel
|
|
289
|
+
|
|
290
|
+
```typescript
|
|
291
|
+
interface PromptModel {
|
|
292
|
+
system?: string[] | SystemPromptFn;
|
|
293
|
+
user: string | UserPromptFn;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
type SystemPromptFn = (
|
|
297
|
+
symbol: string,
|
|
298
|
+
strategyName: string,
|
|
299
|
+
exchangeName: string,
|
|
300
|
+
frameName: string,
|
|
301
|
+
backtest: boolean
|
|
302
|
+
) => Promise<string[]> | string[];
|
|
303
|
+
|
|
304
|
+
type UserPromptFn = (
|
|
305
|
+
symbol: string,
|
|
306
|
+
strategyName: string,
|
|
307
|
+
exchangeName: string,
|
|
308
|
+
frameName: string,
|
|
309
|
+
backtest: boolean
|
|
310
|
+
) => Promise<string> | string;
|
|
163
311
|
```
|
|
164
312
|
|
|
165
313
|
## 💡 Why Use @backtest-kit/ollama?
|
|
166
314
|
|
|
167
315
|
Instead of manually integrating LLM SDKs:
|
|
168
316
|
|
|
317
|
+
**❌ Without ollama (manual work)**
|
|
318
|
+
|
|
169
319
|
```typescript
|
|
170
|
-
// ❌ Without ollama (manual work)
|
|
171
320
|
import OpenAI from 'openai';
|
|
172
321
|
import Anthropic from '@anthropic-ai/sdk';
|
|
173
322
|
|
|
@@ -183,12 +332,13 @@ const signal = JSON.parse(response.choices[0].message.content);
|
|
|
183
332
|
// ... no fallback
|
|
184
333
|
```
|
|
185
334
|
|
|
335
|
+
**✅ With ollama (one line)**
|
|
336
|
+
|
|
186
337
|
```typescript
|
|
187
|
-
// ✅ With ollama (one line)
|
|
188
338
|
const signal = await gpt5(messages, 'gpt-4o');
|
|
189
339
|
```
|
|
190
340
|
|
|
191
|
-
|
|
341
|
+
**🔥 Benefits:**
|
|
192
342
|
|
|
193
343
|
- ⚡ Unified API across 10+ providers
|
|
194
344
|
- 🎯 Enforced JSON schema (no parsing errors)
|