Principle:51bitquant Ai hedge fund crypto Simulated Trade Execution
| Knowledge Sources | |
|---|---|
| Domains | Trade_Execution, Backtesting |
| Last Updated | 2026-10-28 14:00 GMT |
Overview
A backtesting execution pattern that simulates buy, sell, short, and cover orders against an in-memory portfolio with weighted-average cost-basis accounting and margin tracking.
Description
Simulated trade execution models the effect of an order on a virtual portfolio without touching a real exchange. It supports long (`buy`/`sell`) and short (`short`/`cover`) actions. For buys, the cost is debited from cash and the long cost basis is the quantity-weighted average. For sells, gain is realized against the average cost. For shorts, margin equal to `proceeds × margin_requirement` is posted (cash increases by proceeds, decreases by margin), and the short cost basis is tracked. For covers, proportional margin is released and short PnL is realized. Each action caps the quantity to what the portfolio can afford (cash for buys, held shares for sells, margin capacity for shorts, held short for covers).
This addresses the need to evaluate a strategy's historical performance with realistic long/short mechanics, margin, and cost-basis accounting.
Usage
Use this pattern inside a bar-by-bar backtest loop. Pass the decision's action and quantity plus the bar's close price. Mutate the portfolio in place so subsequent bars see the updated cash, positions, and margin.
Theoretical Basis
For a buy of quantity at price :
Failed to parse (syntax error): {\displaystyle \text{cash} \mathrel{-}= q \cdot p,\quad \text{basis}_{\text{long}} = \frac{\text{old\_basis} \cdot \text{old\_shares} + q \cdot p}{\text{old\_shares} + q} }
For a short:
For a cover, realized gain:
and margin released proportionally.
Pseudo-code:
# Abstract pattern
if action == "buy":
q = min(q, cash / price); cash -= q * price; update_long_basis(q, price)
elif action == "sell":
q = min(q, long_shares); realized += (price - long_basis) * q; cash += q * price
elif action == "short":
margin = q * price * margin_req; q = cap_to_margin(q); cash += q*price - margin
elif action == "cover":
q = min(q, short_shares); realized += (short_basis - price) * q; release_margin(q)
Practical Guide
- Round quantities to a fixed precision (`QUANTITY_DECIMALS = 3`) to mimic exchange lot sizing.
- Cap orders to affordable quantities and return the executed (possibly reduced) quantity, not the requested one.
- Track `margin_used` globally so the portfolio knows total margin exposure.
- Reset cost basis to 0 when a position fully closes to avoid stale references.