Skip to contents

Extract fill events from a backtest

Usage

ledgr_run_fills(bt)

Arguments

bt

A ledgr_backtest object.

Value

A tibble of fill rows. ts_utc is the economic execution time. recording_pulse_ts_utc is the close of the uniquely associated execution session and is NA when that association is unavailable or ambiguous.

Details

Fill rows describe execution events and may include both opening and closing actions. Closed trades are exposed by ledgr_results(bt, what = "trades"). To align fills with close-stamped equity, first aggregate fills by recording_pulse_ts_utc, then match or join that one-row-per-pulse table to equity ts_utc. A raw equality join on fill ts_utc is not session alignment, and joining unaggregated fills can duplicate equity rows.

Examples

bars <- data.frame(
  ts_utc = as.POSIXct("2020-01-01", tz = "UTC") + 86400 * 0:3,
  instrument_id = "AAA",
  open = c(100, 101, 102, 103),
  high = c(101, 102, 103, 104),
  low = c(99, 100, 101, 102),
  close = c(100, 101, 102, 103),
  volume = 1000
)
strategy <- function(ctx, params) {
  targets <- ctx$flat()
  targets["AAA"] <- 1
  targets
}
bt <- ledgr_backtest(data = bars, strategy = strategy, initial_cash = 1000, cost_model = ledgr_cost_zero())
fills <- ledgr_run_fills(bt)
equity <- ledgr_results(bt, "equity")
fills_by_pulse <- stats::aggregate(
  qty ~ recording_pulse_ts_utc,
  data = as.data.frame(fills),
  FUN = sum
)
equity$fill_qty <- fills_by_pulse$qty[match(
  equity$ts_utc,
  fills_by_pulse$recording_pulse_ts_utc
)]
nrow(equity)
#> [1] 4
close(bt)