Skip to main content

Overview

Autonome uses the Repository Pattern to abstract database operations. Repositories provide:
  • Type-safe queries with Drizzle ORM
  • Consistent error handling
  • Reusable business logic
  • Testable data access layer
All repositories are located in src/server/db/.

Repository Structure

The codebase has three main repositories:
  1. tradingRepository.ts: Models, invocations, tool calls, portfolio snapshots
  2. ordersRepository.server.ts: Orders (positions and trades) - SSOT for trading
  3. positionsRepository.ts: Legacy position helpers (being deprecated in favor of orders)

Trading Repository

Location: src/server/db/tradingRepository.ts

Model Operations

listModels()

Get all AI models:

listModelsOrderedAsc()

Get models ordered by name:

searchModels()

Search models by name or OpenRouter model name:

Invocation Operations

createInvocationRecord()

Create a new AI invocation record:

updateInvocationRecord()

Update invocation with AI response:

Tool Call Operations

createToolCallRecord()

Record an AI tool invocation:
Tool Call Types:
  • ToolCallType.CREATE_POSITION: Opened new position
  • ToolCallType.CLOSE_POSITION: Closed existing position
  • ToolCallType.HOLDING: No action taken

getRecentToolCallsForModel()

Get recent tool calls for a specific model:

getRecentToolCallsWithModel()

Get recent tool calls across all models with model info:

Portfolio Operations

createPortfolioSnapshot()

Record portfolio NAV at a point in time:

getPortfolioHistory()

Get portfolio history for a model:

fetchPortfolioSnapshots()

Get recent snapshots with model info:

Model Usage Tracking

incrementModelUsage()

Update model usage statistics:
Use case: Called after each AI invocation to track metrics.

Orders Repository

Location: src/server/db/ordersRepository.server.ts The Orders repository is the single source of truth for all trading positions and completed trades.

Order Lifecycle

  1. Create order → status = OPEN (active position)
  2. Close order → status = CLOSED (completed trade)

Creating Orders

createOrder()

Open a new position:

Querying Orders

getOpenOrdersByModel()

Get all active positions for a model:

getAllOpenOrders()

Get all active positions across all models:

getOpenOrderBySymbol()

Get specific open position:
Note: A model can only have one open position per symbol.

getClosedOrdersByModel()

Get completed trades for a model:

getAllClosedOrders()

Get completed trades across all models:

getOrderById()

Get order by ID:

Closing Orders

closeOrder()

Close a position (mark as completed trade):
Close Triggers:
  • null: Manual close by user
  • "STOP": Auto-closed by stop-loss
  • "TARGET": Auto-closed by take-profit

closeOrdersByIds()

Bulk close multiple orders:

Updating Orders

updateOrderExitPlan()

Update exit plan for an open position:

scaleIntoOrder()

Scale into existing position (add to position):
Weighted average formula:

SL/TP Order Management

For live trading mode, track real stop-loss/take-profit orders placed on exchange:

updateSlTpOrders()

Store exchange order indices:

getSlTpOrders()

Retrieve SL/TP order indices:

clearSlTpOrders()

Clear SL/TP indices after canceling on exchange:

getOrdersWithExchangeSlTp()

Get orders with active SL/TP on exchange:

Analytics Helpers

getTotalRealizedPnl()

Calculate total realized P&L for a model:

getOrdersWithExitPlans()

Get orders that need auto-close monitoring:
Use case: Auto-close scheduler checks these orders against current prices.

Positions Repository (Legacy)

Location: src/server/db/positionsRepository.ts ⚠️ Deprecation Notice: This repository is being phased out in favor of ordersRepository.server.ts. Use Orders repository for new code.

Key Differences

Migration path: Use Orders repository for all new features. Positions repository remains for backward compatibility.

Best Practices

1. Use TypeScript Types

Always import and use generated types:

2. Store Money as TEXT

Always use strings for monetary values:

3. Handle NULL Values

Many fields are nullable - always check:

4. Use Repository Functions

Don’t write raw queries - use repository functions:
Why? Repository functions handle:
  • Type casting (TEXT → number)
  • NULL handling
  • Consistent error messages
  • Business logic validation

5. Validate Exit Plans

Exit plan structure is strictly typed:

6. Wrap in Transactions

For multi-step operations, use transactions:

Error Handling

Repositories throw errors for:
  • Missing records
  • Constraint violations
  • Database connection issues
Always wrap in try/catch:

Testing Repositories

Use test database for unit tests:

Next Steps