Skip to content

Commit c2d9428

Browse files
alsk1992claude
andcommitted
Fix all TypeScript errors + add gateway server and realtime alerts
TypeScript fixes: - Fix 'this' references in extension factory functions (memory-lancedb, open-prose, copilot-proxy, google-auth, llm-task, lobster) - Add type annotations to feed methods (drift, betfair, smarkets) - Fix db.run() return type usage (logger, secrets, builder) - Fix tuple types in kalshi orderbook - Fix sharp module import types - Add type declarations for tmi.js and lancedb - Fix export conflicts in trading/index.ts New features: - Add gateway server with REST API and WebSocket support - Add realtime alerts system - Expand trading documentation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent e779dbf commit c2d9428

40 files changed

Lines changed: 2094 additions & 143 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ coverage/
3636
# Local config (user's personal settings)
3737
# Note: clodds.json is the main config, don't commit with secrets
3838
workspace/pm-indexer
39+
.vercel

docs/TRADING.md

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -389,17 +389,73 @@ const result = await measure(devtools, 'order_execution', async () => {
389389
Test strategies on historical data.
390390

391391
```typescript
392-
const engine = createBacktestEngine(db, {
392+
import { createBacktestEngine } from './trading';
393+
394+
const engine = createBacktestEngine(db);
395+
396+
const result = await engine.run(myStrategy, {
393397
startDate: new Date('2024-01-01'),
394398
endDate: new Date('2024-12-31'),
395399
initialCapital: 10000,
400+
commissionPct: 0.1,
401+
slippagePct: 0.05,
402+
riskFreeRate: 5,
396403
});
397404

398-
const result = await engine.run(myStrategy, historicalPrices);
399-
400405
console.log('Sharpe:', result.metrics.sharpeRatio);
406+
console.log('Sortino:', result.metrics.sortinoRatio);
407+
console.log('Calmar:', result.metrics.calmarRatio);
401408
console.log('Max DD:', result.metrics.maxDrawdownPct);
402409
console.log('Win Rate:', result.metrics.winRate);
410+
console.log('Profit Factor:', result.metrics.profitFactor);
411+
```
412+
413+
### Backtest Metrics
414+
415+
| Metric | Description |
416+
|--------|-------------|
417+
| totalReturnPct | Total return over period |
418+
| annualizedReturnPct | Annualized return |
419+
| sharpeRatio | Risk-adjusted return (vs risk-free rate) |
420+
| sortinoRatio | Downside risk-adjusted return |
421+
| calmarRatio | Return / max drawdown |
422+
| maxDrawdownPct | Maximum peak-to-trough decline |
423+
| profitFactor | Gross profit / gross loss |
424+
| winRate | Percentage of winning trades |
425+
426+
### Monte Carlo Simulation
427+
428+
```typescript
429+
const monte = engine.monteCarlo(result, 10000);
430+
431+
console.log('Prob of Profit:', monte.probabilityOfProfit);
432+
console.log('5th percentile:', monte.percentiles.p5);
433+
console.log('Expected value:', monte.expectedValue);
434+
```
435+
436+
### Compare Strategies
437+
438+
```typescript
439+
const comparison = await engine.compare(
440+
[strategy1, strategy2, strategy3],
441+
config
442+
);
443+
444+
console.log('Ranking:', comparison.ranking); // Best to worst by Sharpe
445+
```
446+
447+
### API Endpoint
448+
449+
```bash
450+
POST /api/backtest
451+
Content-Type: application/json
452+
453+
{
454+
"strategyId": "mean-reversion",
455+
"startDate": "2024-01-01",
456+
"endDate": "2024-12-31",
457+
"initialCapital": 10000
458+
}
403459
```
404460

405461
## Bot State Persistence
@@ -494,6 +550,28 @@ trading.stream.addChannel({
494550
"slippageBps": 50,
495551
"mevProtection": "basic",
496552
"maxPriceImpact": 3
553+
},
554+
"realtimeAlerts": {
555+
"enabled": false,
556+
"targets": [
557+
{ "platform": "telegram", "chatId": "123456789" }
558+
],
559+
"whaleTrades": { "enabled": true, "minSize": 50000, "cooldownMs": 300000 },
560+
"arbitrage": { "enabled": true, "minEdge": 2, "cooldownMs": 600000 },
561+
"priceMovement": { "enabled": true, "minChangePct": 5, "windowMs": 300000 },
562+
"copyTrading": { "enabled": true, "onCopied": true, "onFailed": true }
563+
},
564+
"arbitrageExecution": {
565+
"enabled": false,
566+
"dryRun": true,
567+
"minEdge": 1.0,
568+
"minLiquidity": 500,
569+
"maxPositionSize": 100,
570+
"maxDailyLoss": 500,
571+
"maxConcurrentPositions": 3,
572+
"platforms": ["polymarket", "kalshi"],
573+
"preferMakerOrders": true,
574+
"confirmationDelayMs": 0
497575
}
498576
}
499577
```

docs/USER_GUIDE.md

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,106 @@ Configure advanced trading features in `clodds.json`:
166166
| `copyTrading.sizingMode` | fixed/proportional/percentage | How to size copied trades |
167167
| `smartRouting.mode` | best_price/best_liquidity/lowest_fee/balanced | Routing strategy |
168168
| `evmDex.mevProtection` | none/basic/aggressive | MEV protection level |
169+
| `realtimeAlerts.enabled` | boolean | Enable push notifications (default: false) |
170+
| `realtimeAlerts.whaleTrades.minSize` | number | Min whale trade to alert (default: 50000) |
171+
| `realtimeAlerts.arbitrage.minEdge` | number | Min arb edge % to alert (default: 2) |
172+
| `arbitrageExecution.enabled` | boolean | Enable auto-execution (default: false) |
173+
| `arbitrageExecution.dryRun` | boolean | Simulate without executing (default: true) |
174+
| `arbitrageExecution.minEdge` | number | Min edge % to execute (default: 1.0) |
175+
176+
## Auto-Arbitrage Execution
177+
178+
Automatically execute detected arbitrage opportunities:
179+
180+
```json
181+
{
182+
"arbitrageExecution": {
183+
"enabled": true,
184+
"dryRun": true,
185+
"minEdge": 1.0,
186+
"minLiquidity": 500,
187+
"maxPositionSize": 100,
188+
"maxDailyLoss": 500,
189+
"maxConcurrentPositions": 3,
190+
"platforms": ["polymarket", "kalshi"],
191+
"preferMakerOrders": true,
192+
"confirmationDelayMs": 0
193+
}
194+
}
195+
```
196+
197+
| Setting | Description |
198+
|---------|-------------|
199+
| dryRun | Simulate trades without executing (recommended for testing) |
200+
| minEdge | Minimum edge % to trigger execution |
201+
| maxPositionSize | Max USD per trade |
202+
| maxDailyLoss | Stop executing if daily loss exceeds this |
203+
| maxConcurrentPositions | Maximum simultaneous positions |
204+
| confirmationDelayMs | Wait time before executing (allows price recheck) |
205+
206+
The executor listens for opportunities from the opportunity finder and automatically places orders when criteria are met. Always test with `dryRun: true` first.
207+
208+
## Real-time Alerts
209+
210+
Push notifications for trading events. Configure in `clodds.json`:
211+
212+
```json
213+
{
214+
"realtimeAlerts": {
215+
"enabled": true,
216+
"targets": [
217+
{ "platform": "telegram", "chatId": "123456789" }
218+
],
219+
"whaleTrades": {
220+
"enabled": true,
221+
"minSize": 50000,
222+
"cooldownMs": 300000
223+
},
224+
"arbitrage": {
225+
"enabled": true,
226+
"minEdge": 2,
227+
"cooldownMs": 600000
228+
},
229+
"priceMovement": {
230+
"enabled": true,
231+
"minChangePct": 5,
232+
"windowMs": 300000
233+
},
234+
"copyTrading": {
235+
"enabled": true,
236+
"onCopied": true,
237+
"onFailed": true
238+
}
239+
}
240+
}
241+
```
242+
243+
| Alert Type | Trigger |
244+
|------------|---------|
245+
| Whale Trade | Large trades above minSize threshold |
246+
| Arbitrage | Opportunities above minEdge % |
247+
| Price Movement | Price changes above minChangePct % |
248+
| Copy Trading | When trades are copied or fail |
249+
250+
## Performance Dashboard
251+
252+
Access the web-based performance dashboard at:
253+
254+
```
255+
http://127.0.0.1:18789/dashboard
256+
```
257+
258+
The dashboard shows:
259+
- Total trades and win rate
260+
- Cumulative P&L with interactive chart
261+
- Sharpe ratio and max drawdown
262+
- Strategy breakdown with P&L per strategy
263+
- Recent trades table with entry/exit prices
264+
265+
API endpoint for programmatic access:
266+
```
267+
GET /api/performance
268+
```
169269

170270
## Portfolio and P&L
171271

@@ -287,6 +387,83 @@ MEV protection is automatically enabled for swaps:
287387
- **Solana**: Jito bundles
288388
- **L2s**: Sequencer protection (built-in)
289389

390+
## Telegram Mini App
391+
392+
Access Clodds as a Telegram Mini App (Web App) for mobile-friendly portfolio and market access.
393+
394+
### Setup
395+
396+
1. Register your Mini App with BotFather:
397+
```
398+
/newapp
399+
```
400+
401+
2. Set the Web App URL to your gateway:
402+
```
403+
https://your-domain.com/miniapp
404+
```
405+
406+
3. Users can access via the menu button in your bot's chat.
407+
408+
### Features
409+
410+
- **Portfolio**: View total value, P&L, and recent positions
411+
- **Markets**: Search prediction markets across platforms
412+
- **Arbitrage**: Scan for opportunities with one tap
413+
414+
The Mini App uses Telegram's native theming and haptic feedback for a native experience.
415+
416+
### Direct Link
417+
418+
Share the Mini App directly:
419+
```
420+
https://t.me/YourBot/app
421+
```
422+
423+
## Data Sources
424+
425+
Clodds integrates multiple external data sources for edge detection and trading signals.
426+
427+
### News Feed
428+
429+
RSS feeds from political and financial news sources:
430+
- Reuters Politics
431+
- NPR Politics
432+
- Politico
433+
- FiveThirtyEight
434+
435+
Twitter/X integration (requires `X_BEARER_TOKEN` or `TWITTER_BEARER_TOKEN`):
436+
```json
437+
{
438+
"feeds": {
439+
"news": {
440+
"enabled": true,
441+
"twitter": {
442+
"accounts": ["nikiivan", "NateSilver538", "redistrict"]
443+
}
444+
}
445+
}
446+
}
447+
```
448+
449+
### External Probability Sources
450+
451+
Edge detection compares market prices to external data:
452+
453+
| Source | Env Var | Description |
454+
|--------|---------|-------------|
455+
| CME FedWatch | `CME_FEDWATCH_ACCESS_TOKEN` | Fed rate probabilities |
456+
| FiveThirtyEight | `FIVETHIRTYEIGHT_FORECAST_URL` | Election model |
457+
| Silver Bulletin | `SILVER_BULLETIN_FORECAST_URL` | Nate Silver's model |
458+
| Odds API | `ODDS_API_KEY` | Sports betting odds |
459+
460+
### Crypto Price Feed
461+
462+
Real-time prices via Binance WebSocket with Coinbase/CoinGecko fallback:
463+
- BTC, ETH, SOL, XRP, DOGE, ADA, AVAX, MATIC, DOT, LINK
464+
- 24h volume and price changes
465+
- OHLCV historical data
466+
290467
## Tips
291468

292469
- Keep the gateway on loopback unless you add auth and a reverse proxy.

src/@types/lancedb.d.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Type declarations for lancedb
3+
*/
4+
5+
declare module 'lancedb' {
6+
export interface LanceConnection {
7+
openTable(name: string): Promise<LanceTable>;
8+
createTable(name: string, data: unknown[]): Promise<LanceTable>;
9+
tableNames(): Promise<string[]>;
10+
dropTable(name: string): Promise<void>;
11+
}
12+
13+
export interface LanceTable {
14+
add(data: unknown[]): Promise<void>;
15+
search(query: number[]): LanceSearch;
16+
delete(filter: string): Promise<void>;
17+
countRows(): Promise<number>;
18+
update(filter: string, updates: Record<string, unknown>): Promise<void>;
19+
}
20+
21+
export interface LanceSearch {
22+
limit(n: number): LanceSearchResult;
23+
where?(filter: string): LanceSearch;
24+
select?(columns: string[]): LanceSearch;
25+
}
26+
27+
export interface LanceSearchResult {
28+
execute(): Promise<Array<Record<string, unknown>>>;
29+
}
30+
31+
export function connect(uri: string): Promise<LanceConnection>;
32+
}

0 commit comments

Comments
 (0)