Implementation:51bitquant Ai hedge fund crypto Backtester execute trade
| Knowledge Sources | |
|---|---|
| Domains | Trade_Execution, Backtesting |
| Last Updated | 2026-10-28 14:00 GMT |
Overview
Concrete tool for executing simulated long and short trades against an in-memory portfolio with weighted-average cost-basis accounting provided by the `Backtester` class.
Description
Backtester.execute_trade supports four actions — `buy`, `sell`, `short`, `cover` — plus the implicit `hold` (returns 0.0). Quantity is rounded to `QUANTITY_DECIMALS` (3 decimal places). The `buy` branch caps quantity to available cash and updates weighted-average `long_cost_basis`. The `sell` branch caps to held long shares and realizes gain using average cost. The `short` branch posts `margin_required = proceeds × margin_requirement`, caps to margin capacity, and updates `short_cost_basis` and `margin_used`. The `cover` branch releases proportional margin and realizes short PnL. The method mutates `self.portfolio` in place and returns the executed quantity (0.0 if the trade cannot be filled).
Usage
Called per-ticker inside `Backtester.run_backtest` after `Agent.run` returns decisions. Pass the decision's `action` and `quantity` along with the bar's close price.
Code Reference
Source Location
- Repository: ai-hedge-fund-crypto
- File: src/backtest/backtester.py
Signature
class Backtester:
def execute_trade(self, ticker: str, action: str, quantity: float, current_price: float) -> float:
Import
from src.backtest.backtester import Backtester
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| ticker | str | Yes | Asset symbol |
| action | str | Yes | One of `"buy"`, `"sell"`, `"short"`, `"cover"` |
| quantity | float | Yes | Desired share count (rounded to 3 decimals) |
| current_price | float | Yes | Bar close price |
Outputs
| Name | Type | Description |
|---|---|---|
| return | float | Executed quantity; 0.0 if trade cannot be filled |
| side effect | self.portfolio | Mutates `cash`, `positions[ticker]` (long/short shares, cost bases, margin), `realized_gains[ticker]` |
Usage Examples
Per-Bar Execution
# Inside Backtester.run_backtest loop
for ticker in self.tickers:
decision = decisions.get(ticker, {"action": "hold", "quantity": 0.0})
action = decision.get("action", "hold")
quantity = decision.get("quantity", 0.0)
executed = self.execute_trade(ticker, action, quantity, current_prices[ticker])
executed_trades[ticker] = executed
Short and Cover
# Open a short position
executed = bt.execute_trade("BTCUSDT", "short", 0.5, 60000.0)
# Margin posted = 0.5 * 60000 * margin_requirement
# Later, cover the short
executed = bt.execute_trade("BTCUSDT", "cover", 0.5, 55000.0)
# Realized gain = (short_cost_basis - current_price) * quantity