| Title: | Execution and Simulation Engine for Trading Strategies |
| Version: | 0.18.7 |
| Description: | An R-native trading simulation package with a C++ execution core that turns strategy intentions and explicit orders into simulated trades, positions, cash, profit and loss, risk, and performance outputs under configurable execution, margin, funding, and cost assumptions. The package provides historical replay, incremental exchange stepping, durable event tables, append-only agent command logs, registered assets, per-agent shared-cash cross-margin live accounts, AI agent competitors, scheduled live-feed stepping, strategy-backed AI agents with diagnostics, calibrated and coordinated multi-asset market simulation with static covariance, AR-GARCH, factor, and regime models, durable per-feed simulation state, profile-aware heterogeneous inventory and margin execution with atomic mixed-profile order groups, optional portfolio-margin enforcement through a multi-asset C++ step kernel, local live-service APIs, import/export helpers, separate replay, live-state, and agent dashboard exports, and installed local orchestration scripts. It is designed to consume signals, order intents, or target exposure decisions from compatible strategy packages and market data from compatible adapters. |
| Depends: | R (≥ 4.2.0) |
| Imports: | data.table, Rcpp, R6 |
| LinkingTo: | Rcpp |
| Suggests: | testthat, fst, ggplot2, jsonlite, lubridate, plumber, strategyr, zoo |
| URL: | https://github.com/OliverLDS/tradesimr |
| BugReports: | https://github.com/OliverLDS/tradesimr/issues |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| Config/roxygen2/version: | 7.2.3 |
| RoxygenNote: | 7.2.3 |
| NeedsCompilation: | yes |
| Packaged: | 2026-09-28 11:49:14 UTC; oliver |
| Author: | Oliver Zhou [aut, cre] |
| Maintainer: | Oliver Zhou <oliver.yxzhou@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-10-08 10:40:02 UTC |
tradesimr
Description
Execution and simulation engine for trading strategies, with durable event exports, append-only agent commands, registered assets, multi-asset order routing, per-agent shared-cash cross-margin live accounts, AI agent competitors, strategy-backed agent diagnostics, scheduled live-feed stepping, calibrated multi-asset market simulation, durable per-feed simulation state, profile-aware heterogeneous inventory and margin execution with atomic mixed-profile order groups, optional portfolio-margin enforcement through a multi-asset C++ step kernel, local live-service APIs, separate replay, live-state, and agent dashboards, and local orchestration entrypoints.
Author(s)
Maintainer: Oliver Zhou oliver.yxzhou@gmail.com
See Also
Useful links:
Calculate Unrealized PnL
Description
Internal function to update unrealized PnL
Usage
.calculate_unrealized_pnl(
price,
long_avg_entry_price,
short_avg_entry_price,
long_notional,
short_notional,
fee_rate
)
Paper trader demo client
Description
Legacy R6 demonstration client for PaperTradingPlatform. The production
simulation path is sim_backtest() and the C++ execution engine.
Public fields
user_idUser identifier registered on the demo platform.
platformReference to a
PaperTradingPlatforminstance.
Methods
Public methods
PaperTrader$new()
Create a paper trader demo client.
Usage
PaperTrader$new(user_id, platform)
Arguments
user_idUser identifier.
platformA
PaperTradingPlatforminstance.
PaperTrader$place_order()
Place a demo order through the platform.
Usage
PaperTrader$place_order(inst_id, type, pos, size, price, pricing_method, tag)
Arguments
inst_idInstrument identifier.
typeOrder type label.
posPosition side label.
sizeOrder size.
priceOrder price.
pricing_methodPricing method label.
tagOptional order tag.
Returns
Order id.
PaperTrader$cancel_order()
Cancel a demo order.
Usage
PaperTrader$cancel_order(order_id)
Arguments
order_idOrder id.
Returns
Platform cancel result.
PaperTrader$get_all_orders()
Get all orders for this trader.
Usage
PaperTrader$get_all_orders()
Returns
A data.table of orders.
PaperTrader$get_order()
Get one order for this trader.
Usage
PaperTrader$get_order(order_id)
Arguments
order_idOrder id.
Returns
A data.table with matching order rows.
PaperTrader$get_wallet()
Get this trader's wallet balance.
Usage
PaperTrader$get_wallet()
Returns
Wallet balance or account cash.
PaperTrader$get_position()
Get this trader's position.
Usage
PaperTrader$get_position()
Returns
A data.table of positions.
PaperTrader$clone()
The objects of this class are cloneable with this method.
Usage
PaperTrader$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Paper trading platform demo
Description
Legacy R6 demonstration of a paper trading platform. The production
simulation path is sim_backtest() and the C++ execution engine.
Public fields
inst_infoInstrument metadata used by the demo platform.
bar_infoLatest market bar data by instrument.
user_dataDemo user wallet and position state.
exchangeBacking
tradesimr_exchangeobject.order_poolDemo order table.
order_id_counterNext demo order id counter.
Methods
Public methods
PaperTradingPlatform$new()
Create a paper trading platform demo.
Usage
PaperTradingPlatform$new(config = list())
Arguments
configSimulation config passed to
sim_exchange_new().
PaperTradingPlatform$register_user()
Register a demo user and return a trader client.
Usage
PaperTradingPlatform$register_user(user_id, initial_balance = 10000)
Arguments
user_idUser identifier.
initial_balanceInitial wallet balance.
Returns
A PaperTrader instance.
PaperTradingPlatform$place_user_order()
Place a demo user order.
Usage
PaperTradingPlatform$place_user_order( user_id, inst_id, type, pos, size, price, pricing_method, tag )
Arguments
user_idUser identifier.
inst_idInstrument identifier.
typeOrder type label.
posPosition side label.
sizeOrder size.
priceOrder price.
pricing_methodPricing method label.
tagOptional order tag.
Returns
Order id.
PaperTradingPlatform$cancel_user_order()
Cancel a demo user order.
Usage
PaperTradingPlatform$cancel_user_order(user_id, order_id)
Arguments
user_idUser identifier.
order_idOrder id.
PaperTradingPlatform$get_user_orders()
Get all orders for a user.
Usage
PaperTradingPlatform$get_user_orders(user_id)
Arguments
user_idUser identifier.
Returns
A data.table of orders.
PaperTradingPlatform$get_user_order()
Get a user order.
Usage
PaperTradingPlatform$get_user_order(user_id, order_id)
Arguments
user_idUser identifier.
order_idOrder id.
Returns
A data.table with matching order rows.
PaperTradingPlatform$get_live_orders()
Get live demo orders.
Usage
PaperTradingPlatform$get_live_orders()
Returns
A data.table of live orders.
PaperTradingPlatform$get_order()
Get an order by id.
Usage
PaperTradingPlatform$get_order(order_id)
Arguments
order_idOrder id.
Returns
A data.table with matching order rows.
PaperTradingPlatform$update_bar()
Update the latest market bar and append it to the exchange.
Usage
PaperTradingPlatform$update_bar(inst_id, timestamp, open, high, low, close)
Arguments
inst_idInstrument identifier.
timestampBar timestamp.
open, high, low, closeOHLC prices.
PaperTradingPlatform$process_order()
Process one demo order against the latest bar.
Usage
PaperTradingPlatform$process_order(order)
Arguments
orderOrder row.
PaperTradingPlatform$fill_order()
Fill a demo order and pass target exposure to the exchange.
Usage
PaperTradingPlatform$fill_order(order_id, fill_price)
Arguments
order_idOrder id.
fill_priceFill price.
PaperTradingPlatform$get_user_wallet()
Get a user's wallet balance.
Usage
PaperTradingPlatform$get_user_wallet(user_id)
Arguments
user_idUser identifier.
Returns
Wallet balance or account cash.
PaperTradingPlatform$get_user_position()
Get a user's position.
Usage
PaperTradingPlatform$get_user_position(user_id)
Arguments
user_idUser identifier.
Returns
A data.table of positions.
PaperTradingPlatform$update_user_wallet()
Update a user's demo wallet balance.
Usage
PaperTradingPlatform$update_user_wallet(user_id, delta_wallet_balance)
Arguments
user_idUser identifier.
delta_wallet_balanceWallet balance delta.
PaperTradingPlatform$update_user_position()
Update a user's demo position after a fill.
Usage
PaperTradingPlatform$update_user_position(order)
Arguments
orderFilled order row.
Returns
Wallet balance delta.
PaperTradingPlatform$clone()
The objects of this class are cloneable with this method.
Usage
PaperTradingPlatform$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Heterogeneous account schema version
Description
Heterogeneous account schema version
Usage
TRADESIMR_ACCOUNT_SCHEMA_VERSION
Format
An object of class character of length 1.
tradesimr durable schema version
Description
tradesimr durable schema version
Usage
TRADESIMR_SCHEMA_VERSION
Format
An object of class character of length 1.
Normalize market bars for tradesimr
Description
Normalize market bars for tradesimr
Usage
as_market_bars(
data,
timestamp_col = "timestamp",
symbol_col = NULL,
asset_id_col = NULL,
symbol = NULL,
asset_id = NULL,
open_col = "open",
high_col = "high",
low_col = "low",
close_col = "close",
observation_timestamp_col = NULL,
bar_start_col = NULL,
bar_end_col = NULL,
market_timezone = "UTC"
)
Arguments
data |
A table-like object. |
timestamp_col, open_col, high_col, low_col, close_col |
Column names. |
symbol_col |
Optional input symbol column name. |
asset_id_col |
Optional input asset identifier column name. |
symbol |
Optional scalar symbol when the input has no symbol column. |
asset_id |
Optional scalar asset identifier when the input has no asset identifier column. |
observation_timestamp_col, bar_start_col, bar_end_col |
Optional source
columns for explicit market-time metadata. |
market_timezone |
Time zone label when the input has no timezone column. |
Value
A data.table with canonical timestamp, open, high, low,
close columns.
Normalize target-position intents for tradesimr
Description
Normalize target-position intents for tradesimr
Usage
as_target_positions(
data,
timestamp_col = NULL,
tgt_pos_col = "tgt_pos",
pos_strat_col = NULL,
tol_pos_col = NULL,
strat = 0L,
tol_pos = 0
)
Arguments
data |
A table-like object. |
timestamp_col |
Optional timestamp column name. |
tgt_pos_col |
Target-position column name. |
pos_strat_col |
Optional strategy-id column name. |
tol_pos_col |
Optional tolerance column name. |
strat |
Default strategy id. |
tol_pos |
Default target-position tolerance. |
Value
A data.table with canonical intent columns.
Extract account snapshots from a simulation
Description
Extract account snapshots from a simulation
Usage
sim_account(sim)
Arguments
sim |
A simulation result returned by |
Value
A data.table of bar-level account snapshots.
Add an AI or human agent to a live exchange
Description
AI agents generate ordinary order requests; they do not bypass the exchange command/execution path.
Usage
sim_agent_add(
exchange,
agent_id = NULL,
agent_type = c("chaos", "momentum", "contrarian", "mean_reversion", "strategy",
"human"),
config = list(),
status = c("active", "paused")
)
Arguments
exchange |
A |
agent_id |
Agent identifier. If omitted, one is generated. |
agent_type |
Agent type: |
config |
Named list of agent settings. Supported values include |
status |
Initial status: |
Value
The agent id.
Get live-agent command schemas
Description
Get live-agent command schemas
Usage
sim_agent_command_schema()
Value
A named list of empty data.tables for append-only agent commands, order requests, and order cancellations.
Export an agent-facing live dashboard
Description
Export an agent-facing live dashboard
Usage
sim_agent_dashboard_export(exchange, path)
Arguments
exchange |
A |
path |
Output directory. |
Value
Invisibly returns a named character vector of written files.
Open an agent-facing live dashboard
Description
Open an agent-facing live dashboard
Usage
sim_agent_dashboard_open(
exchange = sim_exchange_new(),
path = tempfile("tradesimr-live-agent-")
)
Arguments
exchange |
A |
path |
Output directory. |
Value
Invisibly returns the dashboard index path.
Compute current agent rankings
Description
Rankings combine current per-agent account equity with order activity.
Usage
sim_agent_rankings(exchange)
Arguments
exchange |
A |
Value
A data.table of agent rankings.
Remove an agent from a live exchange
Description
Removed agents stay in the durable registry with status removed.
Usage
sim_agent_remove(exchange, agent_id)
Arguments
exchange |
A |
agent_id |
Agent identifier. |
Value
Invisibly returns TRUE when an agent was updated.
Set an agent status
Description
Set an agent status
Usage
sim_agent_set_status(
exchange,
agent_id,
status = c("active", "paused", "removed")
)
Arguments
exchange |
A |
agent_id |
Agent identifier. |
status |
New status: |
Value
Invisibly returns TRUE when an agent was updated.
Step active AI agents and append their order commands
Description
Step active AI agents and append their order commands
Usage
sim_agents_step(exchange, bar = NULL)
Arguments
exchange |
A |
bar |
Optional current bar used for decision timestamps and prices. |
Value
A data.table of generated decisions.
Register a tradable asset on an exchange
Description
Register a tradable asset on an exchange
Usage
sim_asset_add(
exchange,
symbol,
asset_id = NULL,
status = c("active", "paused", "delisted", "expired", "removed"),
asset_class = "other",
instrument_profile = NULL,
contract_size = 1,
tick_size = NA_real_,
qty_step = 1,
base_ccy = NA_character_,
quote_ccy = NA_character_,
calendar_id = NULL,
timezone = NULL,
settlement_lag_days = NULL,
margin_model = NULL,
bar_cadence_seconds = NA_real_,
metadata = list()
)
Arguments
exchange |
A |
symbol |
Asset symbol, for example |
asset_id |
Optional integer asset id. Defaults to a stable id derived
from |
status |
Asset status: |
asset_class |
Asset class label, such as |
instrument_profile |
Canonical accounting/calendar profile. Defaults to
the profile implied by |
contract_size |
Contract multiplier used by execution/accounting. |
tick_size |
Minimum price increment. |
qty_step |
Minimum order quantity increment. |
base_ccy, quote_ccy |
Optional currency labels. |
calendar_id, timezone |
Optional market-calendar metadata. Defaults are supplied by the selected instrument profile. |
settlement_lag_days |
Optional settlement lag override. |
margin_model |
Optional margin-model override. |
bar_cadence_seconds |
Optional expected completed-bar cadence in seconds. |
metadata |
Optional named list of durable profile metadata. |
Value
Invisibly returns the registered asset row.
Remove an asset from an exchange registry
Description
Removed assets remain in the durable registry with status removed.
Usage
sim_asset_remove(exchange, symbol = NULL, asset_id = NULL)
Arguments
exchange |
A |
symbol |
Optional symbol. |
asset_id |
Optional integer asset id. |
Value
Invisibly returns TRUE when an asset was updated.
List registered exchange assets
Description
List registered exchange assets
Usage
sim_assets(exchange)
Arguments
exchange |
A |
Value
A data.table of assets.
Run a stateful trading simulation backtest
Description
sim_backtest() executes target-position intentions through the package's
C++ exchange/accounting engine. Orders are planned at bar close and market
orders are filled on the next bar open. Target-derived opening and increase
orders are fee-aware: they are clipped at the executable price to the
largest step-rounded quantity satisfying equity - fee >= initial_margin.
Thus a tgt_pos of 1 at lev = 1 produces the largest near-100%-notional
position that reserves its transaction fee rather than a failed order.
Usage
sim_backtest(
data,
timestamp_col = "timestamp",
open_col = "open",
high_col = "high",
low_col = "low",
close_col = "close",
tgt_pos_col = "tgt_pos",
pos_strat_col = NULL,
tol_pos_col = NULL,
order_type_col = NULL,
limit_price_col = NULL,
strat = 0L,
asset = 0L,
init_cash = 10000,
ctr_size = 1,
ctr_step = 1,
lev = 10,
fee_rt = 0,
maker_fee_rt = NA_real_,
taker_fee_rt = NA_real_,
fund_rt = 0,
funding_interval_hours = 8,
mmr = 0.02,
fill_model = c("next_open", "same_close"),
slippage = 0,
spread = 0,
tol_pos = 0,
record = TRUE
)
Arguments
data |
A data frame/data.table with timestamp, open, high, low, close, and target-position columns. |
timestamp_col, open_col, high_col, low_col, close_col, tgt_pos_col |
Column
names in |
pos_strat_col |
Optional strategy-id column. If absent, |
tol_pos_col |
Optional target-position tolerance column. If absent,
|
order_type_col |
Optional order type column using |
limit_price_col |
Optional limit price column. |
strat, asset |
Integer identifiers for the simulation and asset. |
init_cash |
Initial account cash. |
ctr_size |
Contract size. |
ctr_step |
Minimum contract increment. |
lev |
Leverage used for initial margin. |
fee_rt |
Trading fee rate on notional. Fees are reserved by target-derived opening/increase actions at their fill boundary; explicit contract orders continue to fail if their requested quantity is infeasible. |
maker_fee_rt, taker_fee_rt |
Optional maker/taker fee rates. Missing
values fall back to |
fund_rt |
Funding rate per 8 hours on notional. |
funding_interval_hours |
Funding interval in hours. |
mmr |
Maintenance margin rate. |
fill_model |
Fill timing model: |
slippage |
Absolute slippage added against trade direction. |
spread |
Absolute bid/ask spread; half spread is added against trade direction. |
tol_pos |
Scalar default target-position tolerance used when
|
record |
Whether to attach the execution recorder. |
Value
A data.table with timestamp and equity. If record = TRUE, an
execution recorder is attached as attribute orders.
Register a calendar-driven bond schedule
Description
The schedule uses a fixed ACT/day-count convention and equal coupon periods. At each eligible heterogeneous account boundary, C++ emits non-cash accrual events, books due coupons into settled cash, and redeems remaining inventory at maturity. A sparse replay boundary crossing multiple coupon dates is processed coupon-by-coupon before any remaining partial-period accrual. The cursor fields are durable exchange state, so resumed replay continues from the same coupon boundary.
Usage
sim_bond_schedule_add(
exchange,
symbol,
coupon_rate,
coupon_frequency = 2L,
issue_timestamp,
maturity_timestamp,
face_value = 100,
accrual_day_count = 365,
currency = NULL
)
Arguments
exchange |
A |
symbol |
Registered bond symbol. |
coupon_rate |
Annual decimal coupon rate. |
coupon_frequency |
Number of equal coupon payments per 365-day year. |
issue_timestamp |
Schedule start timestamp. |
maturity_timestamp |
Maturity/redemption timestamp after |
face_value |
Redemption value per inventory unit. |
accrual_day_count |
Positive ACT denominator used for accrual events. |
currency |
Coupon and redemption currency. Defaults to the asset quote currency. |
Value
Invisibly returns the registered schedule row.
List durable bond schedules
Description
List durable bond schedules
Usage
sim_bond_schedules(exchange)
Arguments
exchange |
A |
Value
A data.table of bond schedule state.
Generate expected completed bar timestamps from a calendar
Description
Generate expected completed bar timestamps from a calendar
Usage
sim_calendar_expected_bars(
calendar_id,
start,
end,
cadence_seconds,
exceptions = NULL
)
Arguments
calendar_id |
Built-in calendar identifier. |
start, end |
Timestamp bounds. |
cadence_seconds |
Positive bar cadence in seconds. |
exceptions |
Optional exception table with |
Value
A data.table of expected completed-bar timestamps.
List deterministic built-in calendar holidays
Description
List deterministic built-in calendar holidays
Usage
sim_calendar_holidays(calendar_id, start, end)
Arguments
calendar_id |
Built-in calendar identifier. |
start, end |
Date/POSIXct bounds. |
Value
A data.table of session dates, labels, and optional early close time.
Test whether timestamps fall in a built-in tradable session
Description
This deliberately provides deterministic session rules, not a vendor
holiday database. XNYS includes fixed-date observed holidays; callers may
mark exceptional closures with is_tradable = FALSE in market bars.
Usage
sim_calendar_is_open(timestamp, calendar_id = "ALWAYS_OPEN", exceptions = NULL)
Arguments
timestamp |
POSIXct timestamps. |
calendar_id |
Built-in calendar identifier. |
exceptions |
Optional calendar-exception rows from
|
Value
A logical vector.
Calculate a calendar-aware settlement timestamp
Description
Settlement lags count tradable calendar dates, not raw 24-hour periods. This gives FX spot its conventional weekday progression while preserving same-day settlement for 24/7 instruments. Exchange-specific closed-date exceptions are respected.
Usage
sim_calendar_settlement_timestamp(
calendar_id,
timestamp,
settlement_lag_days = 0L,
exceptions = NULL
)
Arguments
calendar_id |
Built-in settlement calendar identifier. |
timestamp |
Trade timestamp. |
settlement_lag_days |
Non-negative whole settlement days. |
exceptions |
Optional calendar-exception rows. |
Value
A UTC POSIXct settlement timestamp.
Get a trading-calendar specification
Description
Get a trading-calendar specification
Usage
sim_calendar_spec(calendar_id)
Arguments
calendar_id |
Built-in calendar identifier. |
Value
A one-row data.table with timezone, session rule, and holiday policy.
Submit an agent order cancellation command
Description
Submit an agent order cancellation command
Usage
sim_cancel_order(
exchange,
agent_id,
order_id,
client_order_id = NA_character_,
timestamp = Sys.time(),
process = TRUE
)
Arguments
exchange |
A |
agent_id |
Agent identifier. |
order_id |
Order id to cancel. |
client_order_id |
Optional client order id for audit purposes. |
timestamp |
Command timestamp. |
process |
Whether to process pending commands immediately. |
Value
The generated command id.
Extract cash ledger entries from a simulation
Description
Extract cash ledger entries from a simulation
Usage
sim_cash_ledger(sim)
Arguments
sim |
A simulation result returned by |
Value
A data.table of event-level cash changes.
Compute cross-asset risk for live exchange agents
Description
Compute cross-asset risk for live exchange agents
Usage
sim_cross_asset_risk(exchange, stress_sigma = 2)
Arguments
exchange |
A |
stress_sigma |
Multiplier applied to portfolio return volatility for the stress-loss estimate. |
Value
A data.table with one row per agent and exposed asset.
Export a static simulation dashboard
Description
Compatibility alias for sim_replay_dashboard_export().
Usage
sim_dashboard_export(sim, path)
Arguments
sim |
A simulation result returned by |
path |
Output directory. |
Value
Invisibly returns a named character vector of written files.
Open an exported static dashboard
Description
Open an exported static dashboard
Usage
sim_dashboard_open(path)
Arguments
path |
Directory created by a dashboard export helper. |
Value
Invisibly returns the dashboard index path.
Convert a simulation recorder into an event table
Description
Convert a simulation recorder into an event table
Usage
sim_events(x)
Arguments
x |
A simulation result returned by |
Value
A data.table of recorded simulation events.
Get simulated exchange account state
Description
Get simulated exchange account state
Usage
sim_exchange_account(exchange)
Arguments
exchange |
A |
Value
A one-row data.table with the latest account snapshot.
Get the durable heterogeneous account state
Description
Returns the typed, profile-aware account projection used by the
heterogeneous execution engine. Cash is valued in the exchange base
currency; fully paid inventory contributes marked market value, while
margin positions contribute marked unrealized P&L and maintenance margin.
sim_exchange_account() remains the compatibility account snapshot API.
Usage
sim_exchange_account_state(exchange, agent_id = NULL)
Arguments
exchange |
A |
agent_id |
Optional account identifier. |
Value
A named list containing account, cash_balances,
inventory_positions, margin_positions, and events data.tables.
Accrue profile-aware borrow and cash interest
Description
The function is idempotent at a timestamp and is called automatically before every executable exchange boundary. Call it explicitly to establish an initial accrual cursor or to accrue a durable account without new bars.
Usage
sim_exchange_accrue_carry(exchange, timestamp)
Arguments
exchange |
A |
timestamp |
Accrual boundary. |
Value
A data.table of booked carry events.
Append market bars to a simulated exchange
Description
Append market bars to a simulated exchange
Usage
sim_exchange_add_bars(exchange, bars)
Arguments
exchange |
A |
bars |
Market bars coercible by |
Value
The exchange, invisibly.
Add an exchange-specific calendar exception
Description
Add an exchange-specific calendar exception
Usage
sim_exchange_calendar_exception(
exchange,
session_date,
action = c("closed", "early_close"),
calendar_id = NULL,
symbol = NULL,
asset_id = NULL,
close_time = NULL,
message = ""
)
Arguments
exchange |
A |
session_date |
Local session date. |
action |
|
calendar_id |
Optional calendar identifier. |
symbol, asset_id |
Optional registered-asset scope. |
close_time |
Required |
message |
Public-safe description. |
Value
Invisibly returns the durable exception row.
Calendarize registered-asset market bars
Description
Calendarize registered-asset market bars
Usage
sim_exchange_calendarize_bars(exchange, bars, strict = FALSE)
Arguments
exchange |
A |
bars |
Market bars. |
strict |
Whether a supplied tradable bar outside its registered session should error rather than be converted to valuation-only. |
Value
Canonical market bars with calendar-derived is_tradable values.
Cancel an intent-level order in a simulated exchange
Description
Cancel an intent-level order in a simulated exchange
Usage
sim_exchange_cancel_order(exchange, order_id)
Arguments
exchange |
A |
order_id |
Order id returned by |
Value
Invisibly returns TRUE if an order was cancelled.
Deposit or withdraw a profile-aware currency balance
Description
Deposit or withdraw a profile-aware currency balance
Usage
sim_exchange_cash_adjust(
exchange,
agent_id,
amount,
currency = NULL,
timestamp = Sys.time(),
message = "Manual cash adjustment"
)
Arguments
exchange |
A |
agent_id |
Account identifier. |
amount |
Signed amount. |
currency |
Currency code. Defaults to the exchange base currency. |
timestamp |
Ledger timestamp. |
message |
Public-safe ledger description. |
Value
Invisibly returns the resulting currency balance.
Get profile-aware cash balances
Description
Get profile-aware cash balances
Usage
sim_exchange_cash_balances(exchange, agent_id = NULL)
Arguments
exchange |
A |
agent_id |
Optional account identifier. |
Value
A data.table where amount is settled cash (kept for compatibility),
unsettled is pending settlement cash, and the base-value columns report
settled-only and total cash valuation respectively.
Convert cash between currencies at an authoritative exchange FX mark
Description
Convert cash between currencies at an authoritative exchange FX mark
Usage
sim_exchange_convert_cash(
exchange,
agent_id,
amount,
from_ccy,
to_ccy,
timestamp = Sys.time()
)
Arguments
exchange |
A |
agent_id |
Account identifier. |
amount |
Source-currency amount to convert. |
from_ccy, to_ccy |
Currency codes. |
timestamp |
Ledger timestamp. |
Value
Invisibly returns the destination amount.
Register a durable inventory corporate action
Description
Actions are applied at the first exchange step at or after their effective timestamp and retained in a durable audit table.
Usage
sim_exchange_corporate_action(
exchange,
symbol,
action_type = c("dividend", "split", "coupon", "bond_accrual", "redemption",
"delisting", "future_expiry", "future_roll"),
amount,
effective_timestamp,
currency = NULL
)
Arguments
exchange |
A |
symbol |
Registered symbol. |
action_type |
One of |
amount |
Cash per inventory unit for dividend/coupon/accrual/redemption,
split ratio for |
effective_timestamp |
Action timestamp. |
currency |
Action currency. Defaults to the asset quote currency. |
Value
Invisibly returns the action id.
Export and open a simulated exchange dashboard
Description
Export and open a simulated exchange dashboard
Usage
sim_exchange_dashboard(exchange, path)
Arguments
exchange |
A |
path |
Output directory. |
Value
Invisibly returns written dashboard files.
Export exchange simulation events
Description
Export exchange simulation events
Usage
sim_exchange_export_events(exchange, path, format = c("csv", "fst"))
Arguments
exchange |
A |
path |
Output directory. |
format |
File format, either |
Value
Invisibly returns written file paths.
Register a futures expiry or contract roll
Description
Expiry settles the old contract's marked P&L into settled quote-currency
cash and terminates its open margin position. A roll additionally opens the
same signed quantity in a registered successor contract at roll_price.
The successor must not already have an open margin position for an affected
account; callers should make any independent successor adjustment first.
Usage
sim_exchange_future_roll(
exchange,
symbol,
effective_timestamp,
settlement_price,
successor_symbol = NULL,
roll_price = NULL
)
Arguments
exchange |
A |
symbol |
Expiring registered futures symbol. |
effective_timestamp |
Lifecycle boundary. |
settlement_price |
Cash-settlement price for the expiring contract. |
successor_symbol |
Optional registered successor futures symbol. |
roll_price |
Required successor reference price when rolling. |
Value
Invisibly returns the corporate action id.
Set a foreign-exchange conversion rate
Description
Rates express units of to_ccy per one unit of from_ccy. They are used
only for account valuation and explicit currency conversion; they never
alter an execution price.
Usage
sim_exchange_fx_rate(
exchange,
from_ccy,
to_ccy,
rate,
timestamp = Sys.time(),
source = "manual"
)
Arguments
exchange |
A |
from_ccy |
Source currency. |
to_ccy |
Destination currency. |
rate |
Positive conversion rate. |
timestamp |
Valuation timestamp. |
source |
Public-safe source label. |
Value
Invisibly returns the added rate row.
Load exchange state from disk
Description
Load exchange state from disk
Usage
sim_exchange_load(path)
Arguments
path |
Directory produced by |
Value
A tradesimr_exchange.
Create an in-memory simulated exchange state
Description
Create an in-memory simulated exchange state
Usage
sim_exchange_new(config = list())
Arguments
config |
Named simulation parameters. Set |
Value
A mutable environment containing market, intent, order, and result tables.
Get new events since the previous exchange run
Description
Get new events since the previous exchange run
Usage
sim_exchange_new_events(exchange)
Arguments
exchange |
A |
Value
A data.table of newly observed simulation events.
Get simulated exchange orders
Description
Get simulated exchange orders
Usage
sim_exchange_orders(exchange)
Arguments
exchange |
A |
Value
A data.table of accepted/cancelled intent-level orders.
Place an order into a simulated exchange
Description
Explicit orders use qty_type = "contracts" by default for buy/sell/flat
orders. Use qty_type = "target_pos" or side = "target" for exposure
targets consumed by replay-style backtests.
Usage
sim_exchange_place_order(
exchange,
agent_id,
timestamp,
symbol = NULL,
asset_id = NULL,
tgt_pos = NULL,
tol_pos = 0,
order_type = c("market", "limit"),
side = c("target", "buy", "sell", "flat"),
qty_type = NULL,
qty = NULL,
limit_price = NA_real_,
time_in_force = "gtc",
atomic_group_id = NULL,
client_order_id = NA_character_
)
Arguments
exchange |
A |
agent_id |
Agent identifier. |
timestamp |
Order timestamp. |
symbol |
Registered asset symbol. |
asset_id |
Registered asset identifier. Provide |
tgt_pos |
Target exposure. Kept for compatibility with earlier intent-level calls. |
tol_pos |
Target-position tolerance. |
order_type |
Order type: |
side |
Order side: |
qty_type |
Quantity semantics: |
qty |
Order quantity. Meaning is controlled by |
limit_price |
Optional limit price for limit orders. |
time_in_force |
Time-in-force label. |
atomic_group_id |
Optional atomic execution group. Explicit orders in the same group either commit together or are rejected together. |
client_order_id |
Optional client order id. |
Value
The generated order id.
Get simulated exchange positions
Description
Get simulated exchange positions
Usage
sim_exchange_positions(exchange)
Arguments
exchange |
A |
Value
A one-row data.table with the latest position snapshot.
Process pending agent commands
Description
Converts pending append-only order request and cancellation commands into exchange orders and cancellation attempts.
Usage
sim_exchange_process_commands(exchange)
Arguments
exchange |
A |
Value
A data.table of processed command rows.
Run or refresh a simulated exchange replay
Description
Run or refresh a simulated exchange replay
Usage
sim_exchange_run(exchange)
Arguments
exchange |
A |
Value
A simulation result returned by sim_backtest().
Export exchange events and state
Description
Export exchange events and state
Usage
sim_exchange_save(exchange, path, format = c("csv", "fst"))
Arguments
exchange |
A |
path |
Output directory. |
format |
File format, either |
Value
Invisibly returns written file paths.
Configure borrow and cash interest rates
Description
Rates are annualized simple rates keyed by registered symbol for borrow and by currency for settled-cash interest. Positive cash earns the configured rate; negative cash is charged it. Short inventory is charged its symbol's borrow rate from the inventory quote-currency balance.
Usage
sim_exchange_set_carry_rates(
exchange,
borrow_rates = numeric(),
cash_interest_rates = numeric()
)
Arguments
exchange |
A |
borrow_rates |
Named numeric annualized rates keyed by symbol. |
cash_interest_rates |
Named numeric annualized rates keyed by currency. |
Value
Invisibly returns the configured rates.
Settle due profile-aware cash movements
Description
Settle due profile-aware cash movements
Usage
sim_exchange_settle(exchange, timestamp = Sys.time())
Arguments
exchange |
A |
timestamp |
Settlement cutoff. |
Value
A data.table of settled ledger rows.
Step a simulated exchange with one or more bars
Description
Step a simulated exchange with one or more bars
Usage
sim_exchange_step(exchange, bars)
Arguments
exchange |
A |
bars |
Market bars coercible by |
Value
The incremental simulation snapshots.
Validate registered-asset bar cadence
Description
Validate registered-asset bar cadence
Usage
sim_exchange_validate_cadence(exchange, bars, strict = FALSE)
Arguments
exchange |
A |
bars |
Market bars. |
strict |
Whether cadence violations should error. |
Value
A data.table with calendar_open and cadence_ok columns.
Export simulation tables to durable files
Description
Export simulation tables to durable files
Usage
sim_export(
sim,
path,
format = c("csv", "fst"),
tables = c("simulation", "market_events", "events", "orders", "fills", "positions",
"cash_ledger", "account", "risk")
)
Arguments
sim |
A simulation result returned by |
path |
Output directory. |
format |
File format, either |
tables |
Names of tables to export. |
Value
Invisibly returns a named character vector of written file paths.
Default live feed configuration
Description
Default live feed configuration
Usage
sim_feed_config(
symbol = "BTC-USDT-SWAP",
asset_id = NULL,
timeframe = "4h",
tz = "UTC",
feed_mode = c("simulation", "external"),
feed_adapter = NULL,
start_time = NULL,
simulation_model = c("random_walk", "ar", "garch11", "ar_garch", "regime"),
random_walk = list(start_price = 100, drift = 0, vol = 0.02, seed = 1L),
simulation = list()
)
Arguments
symbol |
Instrument symbol. |
asset_id |
Optional integer asset id. |
timeframe |
Bar interval, such as |
tz |
Time zone used to align completed bar boundaries. |
feed_mode |
Feed mode: |
feed_adapter |
Optional external adapter function with signature
|
start_time |
Optional first completed boundary to process. |
simulation_model |
Simulation model: |
random_walk |
List of random-walk simulation settings: |
simulation |
Advanced simulation settings. Supported nested lists are
|
Value
A list suitable for sim_feed_configure().
Configure a live exchange feed
Description
Configure a live exchange feed
Usage
sim_feed_configure(exchange, config = sim_feed_config())
Arguments
exchange |
A |
config |
Feed configuration list. A list with |
Value
The feed configuration, invisibly.
Start a configured live feed
Description
Start a configured live feed
Usage
sim_feed_start(exchange, now = Sys.time(), symbol = NULL, asset_id = NULL)
Arguments
exchange |
A |
now |
Current time used to initialize the schedule. |
symbol, asset_id |
Optional feed asset selector. If omitted, all configured active asset feeds are started. |
Value
Feed status.
Get live feed status
Description
Get live feed status
Usage
sim_feed_status(exchange)
Arguments
exchange |
A |
Value
A list describing feed state.
Step a live feed through completed bars
Description
Generates or fetches all completed bars after the last processed feed
boundary and appends them through sim_exchange_step().
Usage
sim_feed_step(
exchange,
now = Sys.time(),
max_bars = Inf,
symbol = NULL,
asset_id = NULL
)
Arguments
exchange |
A |
now |
Current time. |
max_bars |
Maximum bars to append in one call. |
symbol, asset_id |
Optional feed asset selector. If omitted, all configured active asset feeds are stepped. |
Value
A data.table of bars appended by this call.
Stop a configured live feed
Description
Stop a configured live feed
Usage
sim_feed_stop(exchange, symbol = NULL, asset_id = NULL)
Arguments
exchange |
A |
symbol, asset_id |
Optional feed asset selector. If omitted, all configured active asset feeds are stopped. |
Value
Feed status.
Generate historical simulation bars before starting a live feed
Description
Appends n_bars simulated OHLC bars ending at the latest completed boundary.
This is a market-history warmup: it does not step AI agents or process
pending orders.
Usage
sim_feed_warmup(
exchange,
n_bars = 100L,
now = Sys.time(),
symbol = NULL,
asset_id = NULL
)
Arguments
exchange |
A |
n_bars |
Number of historical bars to append. |
now |
Current time used to align the latest completed boundary. |
symbol, asset_id |
Optional feed asset selector. If omitted, all configured active asset feeds are warmed up. |
Value
A data.table of appended market bars.
Extract fill events from a simulation
Description
Extract fill events from a simulation
Usage
sim_fills(sim)
Arguments
sim |
A simulation result returned by |
Value
A data.table of filled trade events.
Step a heterogeneous profile-aware account kernel
Description
Marks inventory, settles futures/perpetual variation margin, and evaluates a normalized order batch without mutating the supplied R input tables.
Usage
sim_heterogeneous_account_step(
base_currency,
cash_balances,
inventory_positions = data.frame(),
margin_positions,
bars,
fx_rates,
settlements = data.frame(),
corporate_actions = data.frame(),
orders = data.frame(),
timestamp = Sys.time()
)
Arguments
base_currency |
Account reporting currency. |
cash_balances |
Data frame with |
inventory_positions |
Data frame with inventory units and valuation. |
margin_positions |
Data frame with margin positions and settlement prices. |
bars |
Profile-tagged market bars. |
fx_rates |
Data frame with |
settlements |
Durable engine settings and settlement inputs. |
corporate_actions |
A durable input table. Rows with |
orders |
A normalized heterogeneous order batch. |
timestamp |
Market-boundary timestamp. |
Value
Updated account state, typed events, fills, and group outcomes.
Empty normalized heterogeneous order-batch schema
Description
The schema carries generic order identity and eligibility fields plus derivative compatibility fields: action/direction codes, strategy/action identifiers, target-derived admission flag, per-asset quantity step, and funding settings. Inventory adapters may leave the compatibility fields at their typed defaults.
Usage
sim_heterogeneous_order_batch_schema()
Value
A typed empty data.table accepted by
sim_heterogeneous_account_step().
Import exported simulation tables
Description
Import exported simulation tables
Usage
sim_import(path)
Arguments
path |
Export directory created by |
Value
A named list containing manifest, simulation, and available
durable tables.
Resolve an instrument profile
Description
Resolve an instrument profile
Usage
sim_instrument_profile(instrument_profile)
Arguments
instrument_profile |
Supported profile name. |
Value
A one-row data.table of profile defaults.
List supported instrument profiles
Description
Instrument profiles define accounting and calendar defaults. They are
intentionally declarative: the current C++ execution kernel still uses the
registered contract multiplier and quantity step as its numeric inputs.
The synthetic_price_return profile models signed marked price exposure
only. It makes no custody, borrow availability or cost, dividend, funding,
carry, settlement, or corporate-action claims, and is therefore suitable
for stated price-return simulations rather than brokerage execution.
Target-derived fee scaling preserves target ratios subject to contract-step
rounding and records fee_scaled fills as durable partial
execution-quality outcomes. Explicit contract orders remain all-or-nothing.
Usage
sim_instrument_profiles()
Value
A data.table of supported profiles and their defaults.
Create a local live exchange service
Description
Builds an optional plumber app exposing local HTTP endpoints for agent
commands. The service is a thin API over append-only command logs and the
existing exchange APIs.
Usage
sim_live_service(exchange = sim_exchange_new())
Arguments
exchange |
A |
Value
A plumber router.
Run a local live exchange service
Description
Run a local live exchange service
Usage
sim_live_service_run(
exchange = sim_exchange_new(),
host = "127.0.0.1",
port = 8080
)
Arguments
exchange |
A |
host |
Host interface. |
port |
Port. |
Value
The result of plumber's run() method.
Open a live-state dashboard
Description
Open a live-state dashboard
Usage
sim_live_state_dashboard_open(
exchange = sim_exchange_new(),
path = tempfile("tradesimr-live-state-")
)
Arguments
exchange |
A |
path |
Output directory. |
Value
Invisibly returns the dashboard index path.
Build an export manifest
Description
Build an export manifest
Usage
sim_manifest(paths, tables, format, config = list())
Arguments
paths |
Named character vector of exported files. |
tables |
Named list of exported tables. |
format |
Export file format. |
config |
Optional simulation configuration. |
Value
A data.table manifest.
Extract market bars from a simulation
Description
Extract market bars from a simulation
Usage
sim_market_events(sim)
Arguments
sim |
A simulation result returned by |
Value
A data.table with timestamp, open, high, low, and close.
Calibrate a market model from historical OHLC bars
Description
Estimates per-asset drift, volatility, AR coefficients, GARCH-like variance persistence, covariance/correlation, one-factor loadings, and simple low/high-volatility regime covariance from historical closes.
Usage
sim_market_model_calibrate(
bars,
model = c("multi_asset_random_walk", "multi_asset_ar_garch", "factor_random_walk",
"regime_random_walk"),
ar_order = 1L,
seed = 1L,
timeframe = NULL,
tz = "UTC"
)
Arguments
bars |
Market bars coercible by |
model |
Market model to configure from the calibration. |
ar_order |
Number of autoregressive lags to estimate per asset. |
seed |
Simulation seed recorded in the returned config. |
timeframe, tz |
Optional scheduling metadata for the returned config. |
Value
A sim_market_model_config() list with calibration metadata.
Configure an exchange market model from historical bars
Description
Configure an exchange market model from historical bars
Usage
sim_market_model_calibrate_exchange(
exchange,
bars,
model = c("multi_asset_random_walk", "multi_asset_ar_garch", "factor_random_walk",
"regime_random_walk"),
ar_order = 1L,
seed = 1L,
timeframe = NULL,
tz = "UTC"
)
Arguments
exchange |
A |
bars |
Market bars coercible by |
model |
Market model to configure from the calibration. |
ar_order |
Number of autoregressive lags to estimate per asset. |
seed |
Simulation seed recorded in the returned config. |
timeframe, tz |
Optional scheduling metadata for the returned config. |
Value
The calibrated market model config, invisibly.
Configure market-level multi-asset simulation
Description
Configure market-level multi-asset simulation
Usage
sim_market_model_config(
model = c("independent", "multi_asset_random_walk", "multi_asset_ar_garch",
"factor_random_walk", "regime_random_walk"),
corr = NULL,
cov = NULL,
factors = NULL,
regimes = NULL,
calibration = NULL,
seed = 1L,
timeframe = NULL,
tz = NULL,
start_time = NULL
)
Arguments
model |
Market model. |
corr |
Optional static correlation matrix. |
cov |
Optional static covariance matrix. If supplied, it takes
precedence over |
factors |
Optional factor model settings for |
regimes |
Optional regime settings for |
calibration |
Optional calibration object from
|
seed |
Base random seed for synchronized draws. |
timeframe |
Optional common timeframe. If omitted, all selected feeds must share the same timeframe. |
tz |
Optional common time zone. If omitted, all selected feeds must share the same time zone. |
start_time |
Optional first completed boundary to process. |
Value
A market model configuration list.
Configure a market-level simulation model
Description
Configure a market-level simulation model
Usage
sim_market_model_configure(exchange, config = sim_market_model_config())
Arguments
exchange |
A |
config |
A list from |
Value
The market model configuration, invisibly.
Get market-level simulation model status
Description
Get market-level simulation model status
Usage
sim_market_model_status(exchange)
Arguments
exchange |
A |
Value
A list describing the market-level simulation model.
Calculate core performance metrics from a simulation result
Description
Calculate core performance metrics from a simulation result
Usage
sim_metrics(sim)
Arguments
sim |
A simulation result from |
Value
A one-row data.table with return, drawdown, and event counts.
Convert a simulation recorder into an order/event table
Description
Convert a simulation recorder into an order/event table
Usage
sim_orders(x)
Arguments
x |
A simulation result returned by |
Value
A data.table of recorded execution events.
Define a portfolio decision policy
Description
A policy controls which completed market observations may create a target-weight decision. It never changes execution eligibility: every order still fills only on a strictly later, tradable bar for its own asset.
Usage
sim_portfolio_decision_policy(
mode = c("complete_universe", "as_of_valuation", "per_asset_decision"),
max_staleness = Inf
)
Arguments
mode |
Decision policy. |
max_staleness |
Maximum age in seconds of a carried valuation for
|
Value
A validated decision-policy list.
Build execution assumptions for a target-weight portfolio replay
Description
Build execution assumptions for a target-weight portfolio replay
Usage
sim_portfolio_execution(
timing = "next_eligible_open",
fee_rt = 0,
maker_fee_rt = NA_real_,
slippage = 0,
spread = 0,
lev = 1,
mmr = 0.02,
max_gross_weight = 1
)
Arguments
timing |
Execution timing. Phase 1 supports only
|
fee_rt |
Taker fee rate applied to filled notional. |
maker_fee_rt |
Optional maker fee rate for future limit-order support. |
slippage |
Absolute adverse price adjustment per unit. |
spread |
Absolute bid/ask spread; half is applied adversely on fills. |
lev |
Leverage used for initial-margin checks. |
mmr |
Maintenance-margin rate. |
max_gross_weight |
Maximum sum of absolute target weights. |
Value
A named execution configuration list.
Project execution quality for durable portfolio target rebalances
Description
The projection evaluates each target using its decision-time target record, canonical order lifecycle, durable fills, and the position/account snapshot at the relevant settlement boundary. It never uses a later current mark to classify an earlier rebalance. Filled fee-aware target orders are assessed against their exact C++-recorded executable quantity.
Usage
sim_portfolio_execution_quality(exchange, agent_id = NULL, summary = FALSE)
Arguments
exchange |
A |
agent_id |
Optional account identifier used to filter the projection. |
summary |
If |
Value
A public-safe data.table. Symbol rows contain rebalance_id,
agent_id, symbol, asset_id, decision_timestamp, eligible_after,
settlement_timestamp, target_weight, decision_equity,
decision_price, qty_step, contract_size,
current_signed_quantity, expected_signed_quantity,
expected_notional, realized_signed_quantity, realized_notional,
quantity_deviation, notional_deviation, weight_deviation,
execution_quality, and message.
Export a safe portfolio replay snapshot for an external consumer
Description
Export a safe portfolio replay snapshot for an external consumer
Usage
sim_portfolio_export(exchange, agent_id, path, format = "json")
Arguments
exchange |
A |
agent_id |
Agent identifier. |
path |
Output directory. |
format |
Export format. Phase 1 supports JSON. |
Value
A named vector of written paths. fills.json is sourced from the
durable portfolio fill ledger and links every filled portfolio order to
its order_id and rebalance_id; rebalances.json contains the linked
accepted/rejected rebalance records.
Advance an Arena exchange at one completed market boundary
Description
This API advances a timestamped batch of completed bars exactly once. It executes only orders submitted at earlier boundaries; it never creates a target decision or rebalance. Each supplied asset bar must be genuinely new, so duplicate and stale batches fail rather than being silently reprocessed.
Usage
sim_portfolio_market_step(
exchange,
bars,
execution = sim_portfolio_execution()
)
Arguments
exchange |
A |
bars |
One timestamped batch of registered, completed OHLC bars. |
execution |
Execution assumptions from |
Value
A public-safe list with bars, fills, events, positions,
account, and outcomes.
Step the C++ portfolio-margin kernel once
Description
Processes one timestamp batch of bars and explicit orders for one agent under
one shared cash balance. This is the multi-asset primitive used by live
exchanges when portfolio_margin = TRUE.
Usage
sim_portfolio_step(
states,
bars,
orders = data.frame(),
cov = diag(nrow(as_market_bars(bars))),
shared_cash = 10000,
ctr_size = 1,
ctr_step = 1,
lev = 10,
fee_rt = 0,
maker_fee_rt = NA_real_,
taker_fee_rt = NA_real_,
fund_rt = 0,
funding_interval_hours = 8,
mmr = 0.02,
portfolio_margin_sigma = 3,
portfolio_margin_floor = mmr,
slippage = 0,
spread = 0,
record = TRUE
)
Arguments
states |
Named list of prior |
bars |
One timestamp batch of market bars. |
orders |
Order data frame with |
cov |
Return covariance matrix aligned to |
shared_cash |
Shared account cash before this step. |
ctr_size, ctr_step |
Contract size and quantity step. Supply one value
for all assets or one value per row of |
lev |
Leverage used for initial margin. |
fee_rt |
Trading fee rate on notional. Fees are reserved by target-derived opening/increase actions at their fill boundary; explicit contract orders continue to fail if their requested quantity is infeasible. |
maker_fee_rt, taker_fee_rt |
Optional maker/taker fee rates. Missing
values fall back to |
fund_rt |
Funding rate per 8 hours on notional. |
funding_interval_hours |
Funding interval in hours. |
mmr |
Maintenance margin rate. |
portfolio_margin_sigma |
Sigma multiplier for covariance margin. |
portfolio_margin_floor |
Floor margin rate applied to gross exposure. |
slippage |
Absolute slippage added against trade direction. |
spread |
Absolute bid/ask spread; half spread is added against trade direction. |
record |
Whether to attach the execution recorder. |
Value
A list with states, cash, equity, maintenance_margin,
liquidated, and events. The state-list input is a compatibility
projection; exchange and replay callers should use the typed
heterogeneous account route.
Replay a historical multi-asset target-weight panel
Description
This bulk API is intended for historical reconstruction. It preserves the
public market-boundary and target-submission semantics while accumulating
durable snapshots and events in batches rather than repeatedly growing their
history tables. Live callers should continue to use
sim_portfolio_market_step() and sim_portfolio_target_submit_batch().
Usage
sim_portfolio_target_replay(
exchange,
bars,
target_weights,
allowed_symbols = NULL,
execution = sim_portfolio_execution(),
decision_policy = sim_portfolio_decision_policy(),
rebalance_policy = NULL,
export_path = NULL,
profile = FALSE,
production_calendar = FALSE
)
Arguments
exchange |
A |
bars |
Completed OHLC bars with |
target_weights |
A data frame with |
allowed_symbols |
Optional named list of allowed-symbol vectors by agent. When omitted, each agent's universe is inferred from all symbols in its panel rows. Multi-asset target groups are submitted only at boundaries containing one completed bar for every allowed symbol; incomplete groups are treated as absent decisions. |
execution |
Execution assumptions from |
decision_policy |
Market-observation policy from
|
rebalance_policy |
Optional policy for sparse deterministic target
panels. |
export_path |
Optional directory for public-safe per-agent exports. |
profile |
Whether to return wall-time categories. |
production_calendar |
When |
Value
A list with the exchange, durable orders/fills/positions/accounts, targets/rebalances, execution quality, optional export paths, and timings.
Step one agent portfolio from target weights
Description
This is the stable Vox Arena integration point. It accepts a batch of
genuinely new completed OHLC bars and, optionally, an explicit target-weight
decision. Existing eligible orders are stepped first. A new target decision
is then translated atomically into contract orders using current account
equity and the decision-bar close (or the latest carried valuation for an
asset absent from the batch). New orders are eligible only on a strictly
later bar for their own asset. At that later fill boundary, target-derived
opening/increase orders are capped to the largest step-rounded quantity whose
fee and initial margin fit the account. Consequently a target weight of 1
at lev = 1 is near 100% notional after reserving the fee, rather than a
failed all-cash order. Explicit contract orders retain reject-on-insufficient
margin semantics.
Usage
sim_portfolio_target_step(
exchange,
agent_id,
bars,
target_weights = NULL,
execution = sim_portfolio_execution(),
decision_label = "target_weight",
allowed_symbols = NULL,
allowed_asset_ids = NULL,
decision_policy = sim_portfolio_decision_policy()
)
Arguments
exchange |
A |
agent_id |
Account identifier. Each agent has an isolated account. |
bars |
One timestamped batch of registered, completed OHLC bars. |
target_weights |
Optional named numeric target weights keyed by registered symbols. |
execution |
Execution assumptions from |
decision_label |
Optional durable label for the decision source. |
allowed_symbols |
Optional registered symbols this agent may target, hold, or trade. |
allowed_asset_ids |
Optional registered asset ids this agent may target, hold, or trade. |
decision_policy |
Market-observation policy from
|
Details
A named target vector updates only its named symbols; supply an explicit
zero target weight to flatten an asset. A NULL target is a no-decision:
positions are retained and no new orders are submitted. Repeated/stale bars
are ignored, so closed markets can retain their last valuation without
creating strategy reactions or fills.
Value
A list containing orders, fills, positions, account,
targets, realized_weights, and outcomes.
Submit one Arena target-weight decision after a market boundary
Description
The supplied decision bars must already have been accepted by
sim_portfolio_market_step(). Targets are converted atomically using the
completed-bar close and the post-step account state. Submitted orders are
eligible only on a strictly later bar of the same asset. NULL records a
durable no-decision outcome and preserves current positions.
Target-derived opening and increasing orders are clipped down to the largest
executable contract-step quantity when fees or shared portfolio margin make
the exact target infeasible. Explicit contract orders remain all-or-nothing.
For inventory-profile target groups, fee-aware scaling is applied once to
the atomic group, preserving target ratios subject to contract-step
rounding. Such fills retain the durable fee_scaled reason code and are
reported as partial execution-quality outcomes when the requested target is
not fully reached.
A later accepted target decision supersedes still-unfilled target-derived
orders for the same agent and overlapping allowed assets; explicit contract
orders are never superseded.
For a multi-asset allowed universe, a non-NULL target decision is accepted
only when the same market boundary contains exactly one completed bar for
every allowed asset. This prevents target allocation from being planned from
a partial cross-asset information set. Single-asset submissions are
unaffected.
Usage
sim_portfolio_target_submit(
exchange,
agent_id,
bars,
target_weights = NULL,
execution = sim_portfolio_execution(),
decision_label = "target_weight",
allowed_symbols = NULL,
allowed_asset_ids = NULL,
decision_policy = sim_portfolio_decision_policy()
)
Arguments
exchange |
A |
agent_id |
Account identifier. Each agent has an isolated account. |
bars |
The already accepted timestamped completed-bar batch. |
target_weights |
Optional named numeric target weights keyed by registered symbols. |
execution |
Execution assumptions from |
decision_label |
Optional durable label for the decision source. |
allowed_symbols |
Optional registered symbols this agent may target, hold, or trade. Persisted on the agent after a successful submission. |
allowed_asset_ids |
Optional registered asset ids this agent may target,
hold, or trade. When supplied with |
decision_policy |
Market-observation policy from
|
Value
A list containing orders, fills, positions, account,
targets, realized_weights, and outcomes.
Submit multiple Arena target-weight decisions after one market boundary
Description
This is the efficient replay interface for a common completed market
boundary. It does not step market data. Instead, it validates the accepted
boundary once and snapshots account, position, and carried-price state once
before translating each agent's decision atomically. Each decisions
element is a named list containing target_weights (or NULL for a
no-decision), and optionally decision_label, allowed_symbols, and
allowed_asset_ids. A multi-asset decision requires exactly one completed
bar for every allowed asset at the common decision boundary.
Usage
sim_portfolio_target_submit_batch(
exchange,
bars,
decisions,
execution = sim_portfolio_execution(),
decision_policy = sim_portfolio_decision_policy()
)
Arguments
exchange |
A |
bars |
The already accepted timestamped completed-bar batch. |
decisions |
A named list keyed by |
execution |
Execution assumptions from |
decision_policy |
Market-observation policy applied to every decision. |
Value
A list with the common boundary timestamp, public account and
position snapshots, and a named submissions list containing the same
result contract as sim_portfolio_target_submit() for each agent.
Extract position snapshots from a simulation
Description
Extract position snapshots from a simulation
Usage
sim_positions(sim)
Arguments
sim |
A simulation result returned by |
Value
A data.table of bar-level position snapshots.
Read exported account snapshots
Description
Read exported account snapshots
Usage
sim_read_account(path)
Arguments
path |
Export directory created by |
Value
A data.table of account snapshots.
Read exported simulation events
Description
Read exported simulation events
Usage
sim_read_events(path)
Arguments
path |
Export directory created by |
Value
A data.table of events.
Read an export manifest
Description
Read an export manifest
Usage
sim_read_manifest(path)
Arguments
path |
Export directory or manifest file path. |
Value
A data.table manifest.
Read an exported simulation table
Description
Read an exported simulation table
Usage
sim_read_table(path, table, format = NULL)
Arguments
path |
Export directory or table file path. |
table |
Table name when |
format |
Optional format. Inferred from manifest or file extension when absent. |
Value
A data.table.
Replay historical bars through the simulation engine
Description
Alias for sim_backtest() reserved for replay-oriented workflows.
Usage
sim_replay(data, ...)
Arguments
data |
A data frame/data.table with timestamp, open, high, low, close, and target-position columns. |
... |
Additional arguments passed to |
Export a static replay dashboard
Description
Writes dashboard-ready CSV tables, a manifest, and static HTML/CSS/JS assets. The dashboard is a read-only consumer of durable market, strategy, event, account, risk, order, and fill tables; it does not call C++, R6, or live exchange internals.
Usage
sim_replay_dashboard_export(sim, path)
Arguments
sim |
A simulation result returned by |
path |
Output directory. |
Value
Invisibly returns a named character vector of written files.
Extract risk snapshots from a simulation
Description
Extract risk snapshots from a simulation
Usage
sim_risk(sim)
Arguments
sim |
A simulation result returned by |
Value
A data.table of bar-level risk snapshots.
Reconstruct simulation views from exported events
Description
Reconstruct simulation views from exported events
Usage
sim_run_from_events(path)
Arguments
path |
Export directory created by |
Value
A data.table simulation result when a simulation table exists,
otherwise event-level account state reconstructed from events.
Migrate durable tables to the current schema
Description
Missing columns are added with typed NA values and existing columns are
retained unchanged. This makes older CSV/fst exports readable without
silently discarding consumer-defined extension columns.
Usage
sim_schema_migrate(tables, from_version = NULL)
Arguments
tables |
A named list of durable data tables. |
from_version |
Optional source schema version retained in the returned metadata for audit. Missing fields are migrated deterministically. |
Value
A named list upgraded to sim_schema_version().
Get the tradesimr schema version
Description
Get the tradesimr schema version
Usage
sim_schema_version()
Value
A scalar character schema version.
Simulation table schemas
Description
Simulation table schemas
Usage
sim_schemas()
Value
A named list of empty data.tables representing durable simulation table schemas.
Step a fully paid spot-inventory state
Description
This Rcpp-backed state machine is separate from the derivatives margin kernel. It models long-only inventory, quote-currency cash, fees, marked inventory value, dividends, and stock splits.
Usage
sim_spot_step(
state = NULL,
close,
signed_qty = 0,
execution_price = NA_real_,
contract_size = 1,
fee_rt = 0,
dividend_per_unit = 0,
split_ratio = 1
)
Arguments
state |
A prior spot state, or |
close |
Current mark price. |
signed_qty |
Positive to buy units and negative to sell units. |
execution_price |
Optional execution price; defaults to |
contract_size |
Units represented by one inventory unit. |
fee_rt |
Fee rate applied to execution notional. |
dividend_per_unit |
Cash dividend per unit. |
split_ratio |
Inventory split ratio. |
Value
A list containing cash, units, average cost, market value, equity, P&L, fees, corporate-action cash, and execution status.
Submit spot target weights for next-bar execution
Description
This is the inventory-accounting counterpart to the derivatives portfolio target API. It plans all supplied spot legs from one completed boundary and emits only next-eligible explicit inventory orders.
Usage
sim_spot_target_submit(exchange, agent_id, bars, target_weights, fee_rt = 0)
Arguments
exchange |
A |
agent_id |
Account identifier. |
bars |
Completed registered spot bars at one timestamp. |
target_weights |
Named target weights keyed by symbols. |
fee_rt |
Non-negative execution fee rate. |
Value
A list of accepted orders and planned target quantities.
Create a simulation state object
Description
Create a simulation state object
Usage
sim_state(
cash = 10000,
pos_dir = 0L,
ctr_unit = 0,
avg_price = NA_real_,
last_px = 0,
strat = 0L,
asset = 0L,
action_id_now = 1L,
old_timestamp = NA_real_,
liquidated = FALSE
)
Arguments
cash |
Account cash. |
pos_dir |
Position direction: |
ctr_unit |
Contract units held. |
avg_price |
Average entry price. |
last_px |
Last mark price. |
strat, asset |
Integer identifiers. |
action_id_now |
Next action id. |
old_timestamp |
Previous bar timestamp, used for funding accrual. |
liquidated |
Whether the account is liquidated. |
Value
A list suitable for sim_step().
Export a live-state dashboard
Description
Writes the current exchange state using the god-facing live-state dashboard shell. This dashboard can configure and step the feed but cannot place orders.
Usage
sim_state_dashboard_export(exchange, path)
Arguments
exchange |
A |
path |
Output directory. |
Value
Invisibly returns a named character vector of written files.
Step the C++ exchange kernel once
Description
Processes one bar and a batch of explicit order actions against prior account state. This is the incremental primitive underneath future live exchange workflows; it does not replay earlier bars.
Usage
sim_step(
state,
bar,
orders = data.frame(),
asset = state$asset %||% 0L,
ctr_size = 1,
ctr_step = 1,
lev = 10,
fee_rt = 0,
maker_fee_rt = NA_real_,
taker_fee_rt = NA_real_,
fund_rt = 0,
funding_interval_hours = 8,
mmr = 0.02,
slippage = 0,
spread = 0,
record = TRUE
)
Arguments
state |
Prior state created by |
bar |
One-row market bar coercible by |
orders |
Data frame with order columns: |
asset |
Integer asset identifier. |
ctr_size |
Contract size. |
ctr_step |
Minimum contract increment. |
lev |
Leverage used for initial margin. |
fee_rt |
Trading fee rate on notional. Fees are reserved by target-derived opening/increase actions at their fill boundary; explicit contract orders continue to fail if their requested quantity is infeasible. |
maker_fee_rt, taker_fee_rt |
Optional maker/taker fee rates. Missing
values fall back to |
fund_rt |
Funding rate per 8 hours on notional. |
funding_interval_hours |
Funding interval in hours. |
mmr |
Maintenance margin rate. |
slippage |
Absolute slippage added against trade direction. |
spread |
Absolute bid/ask spread; half spread is added against trade direction. |
record |
Whether to attach the execution recorder. |
Value
A list with state and events.
List registered strategy ids
Description
List registered strategy ids
Usage
sim_strategy_list(exchange)
Arguments
exchange |
A |
Value
Character vector of registered strategy ids.
Register a strategy function for strategy-backed AI agents
Description
Registered functions are runtime-only and are not serialized into exported
CSV files. Store the durable strategy name in the agent config via
strategy_id; register the function again after loading a saved exchange.
Usage
sim_strategy_register(exchange, strategy_id, strategy_fn)
Arguments
exchange |
A |
strategy_id |
Strategy identifier used by agent config. |
strategy_fn |
Function returning target positions, strategyr action plans, or order-intent rows. |
Value
The strategy id, invisibly.
Unregister a strategy function
Description
Unregister a strategy function
Usage
sim_strategy_unregister(exchange, strategy_id)
Arguments
exchange |
A |
strategy_id |
Strategy identifier used by agent config. |
Value
Invisibly returns TRUE when a strategy was removed.
Validate strategy-backed agent config
Description
Checks that a strategy agent config points to a registered function or a
resolvable function name, and that supplied param_ keys are compatible with
the strategy function signature when the function does not accept ....
Usage
sim_strategy_validate_config(exchange, config)
Arguments
exchange |
A |
config |
Agent config list. |
Value
A list with valid, message, strategy_id, strategy_fun, and
params.
Submit an agent order command
Description
Appends an order request to the exchange command log. By default the command
is processed immediately into the same exchange order model used by
sim_exchange_step().
Usage
sim_submit_order(
exchange,
agent_id,
timestamp = Sys.time(),
symbol = NULL,
asset_id = NULL,
tgt_pos = NULL,
tol_pos = 0,
order_type = c("market", "limit"),
side = c("target", "buy", "sell", "flat"),
qty_type = NULL,
qty = NULL,
limit_price = NA_real_,
time_in_force = "gtc",
client_order_id = NA_character_,
process = TRUE
)
Arguments
exchange |
A |
agent_id |
Agent identifier. |
timestamp |
Order timestamp. |
symbol |
Registered asset symbol. |
asset_id |
Registered asset identifier. Provide |
tgt_pos |
Target exposure. Kept for compatibility with earlier intent-level calls. |
tol_pos |
Target-position tolerance. |
order_type |
Order type: |
side |
Order side: |
qty_type |
Quantity semantics: |
qty |
Order quantity. Meaning is controlled by |
limit_price |
Optional limit price for limit orders. |
time_in_force |
Time-in-force label. |
client_order_id |
Optional client order id. |
process |
Whether to process pending commands immediately. |
Value
The generated command id.
List built-in trading calendars
Description
List built-in trading calendars
Usage
sim_trading_calendars()
Value
A data.table describing the deterministic built-in session rules.
Validate target-position intent columns
Description
Validate target-position intent columns
Usage
validate_intents(data, tgt_pos_col = "tgt_pos", tol_pos_col = NULL)
Arguments
data |
A table-like object. |
tgt_pos_col |
Target-position column name. |
tol_pos_col |
Optional tolerance column name. |
Value
Invisibly returns TRUE on success.
Validate core market-bar columns
Description
Validate core market-bar columns
Usage
validate_market_data(
data,
timestamp_col = "timestamp",
open_col = "open",
high_col = "high",
low_col = "low",
close_col = "close"
)
Arguments
data |
A table-like object. |
timestamp_col, open_col, high_col, low_col, close_col |
Column names. |
Value
Invisibly returns TRUE on success.
Generate vectorized simulation inputs for multiple instruments
Description
Legacy helper that loads candle data through strategyr and applies signal strategies before forming long, short, and both-side position series.
Usage
vec_batch_run_simulations(
inst_ids,
bar,
signal_strategies,
root_path = Sys.getenv("OKX_Candle_Data_Path"),
bg_time = NULL,
ed_time = NULL
)
Arguments
inst_ids |
Instrument identifiers. |
bar |
Bar size passed to strategyr loaders. |
signal_strategies |
Named list of functions that add a |
root_path |
Candle data root path. |
bg_time |
Optional begin time. |
ed_time |
Optional end time. |
Value
A named list of data.tables.
Plot vectorized simulation results
Description
Plot vectorized simulation results
Usage
vec_sim_gen_plot(vec_sim_res, report_mode = c("simple", "full"))
Arguments
vec_sim_res |
Result from |
report_mode |
Plot report mode. |
Summarize vectorized simulation results
Description
Summarize vectorized simulation results
Usage
vec_sim_gen_summary(
vec_sim_res,
report_mode = c("short_txt", "long_txt", "dt")
)
Arguments
vec_sim_res |
Result from |
report_mode |
Summary mode. |
Value
Text or a one-row data.table depending on report_mode.
Summarize a batch of vectorized simulations
Description
Summarize a batch of vectorized simulations
Usage
vec_sim_gen_summary_table(DTs)
Arguments
DTs |
List of vectorized simulation data.tables. |
Value
A data.table of summaries.
Run a vectorized approximate backtest
Description
Lightweight legacy helper that converts a precomputed position column into
log returns and an equity curve. It does not model the stateful exchange,
order, margin, funding, or liquidation mechanics used by sim_backtest().
Usage
vec_sim_run_backtest(DT)
Arguments
DT |
A data.table containing at least |
Value
A list containing equity series and summary statistics.