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
src/server/db/.
Repository Structure
The codebase has three main repositories:tradingRepository.ts: Models, invocations, tool calls, portfolio snapshotsordersRepository.server.ts: Orders (positions and trades) - SSOT for tradingpositionsRepository.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:ToolCallType.CREATE_POSITION: Opened new positionToolCallType.CLOSE_POSITION: Closed existing positionToolCallType.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: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
- Create order → status =
OPEN(active position) - 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: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):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):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: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
| Feature | Positions Repo | Orders Repo |
|---|---|---|
| Table | Orders | Orders |
| Status tracking | Deletes on close | Sets status = CLOSED |
| History | No trade history | Full trade history |
| Realized P&L | Not stored | Stored in DB |
| Exit details | Not tracked | exitPrice, closeTrigger |
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:- 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
Testing Repositories
Use test database for unit tests:Next Steps
- Database Schema - Review table structure
- Migrations - Learn how to modify schema
- oRPC Procedures - Call repositories from API endpoints

