| Title: | Execution and Simulation Engine for Trading Strategies |
|---|---|
| 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. |
| Authors: | Oliver Zhou [aut, cre] |
| Maintainer: | Oliver Zhou <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.18.7 |
| Built: | 2026-10-09 17:00:18 UTC |
| Source: | https://github.com/oliverlds/tradesimr |
Normalize market bars for tradesimr
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" )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" )
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. |
A data.table with canonical timestamp, open, high, low,
close columns.
Normalize target-position intents for tradesimr
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 )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 )
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. |
A data.table with canonical intent columns.
Legacy R6 demonstration client for PaperTradingPlatform. The production
simulation path is sim_backtest() and the C++ execution engine.
user_idUser identifier registered on the demo platform.
platformReference to a PaperTradingPlatform instance.
PaperTrader$new()Create a paper trader demo client.
PaperTrader$new(user_id, platform)
user_idUser identifier.
platformA PaperTradingPlatform instance.
PaperTrader$place_order()Place a demo order through the platform.
PaperTrader$place_order(inst_id, type, pos, size, price, pricing_method, tag)
inst_idInstrument identifier.
typeOrder type label.
posPosition side label.
sizeOrder size.
priceOrder price.
pricing_methodPricing method label.
tagOptional order tag.
Order id.
PaperTrader$cancel_order()Cancel a demo order.
PaperTrader$cancel_order(order_id)
order_idOrder id.
Platform cancel result.
PaperTrader$get_all_orders()Get all orders for this trader.
PaperTrader$get_all_orders()
A data.table of orders.
PaperTrader$get_order()Get one order for this trader.
PaperTrader$get_order(order_id)
order_idOrder id.
A data.table with matching order rows.
PaperTrader$get_wallet()Get this trader's wallet balance.
PaperTrader$get_wallet()
Wallet balance or account cash.
PaperTrader$get_position()Get this trader's position.
PaperTrader$get_position()
A data.table of positions.
PaperTrader$clone()The objects of this class are cloneable with this method.
PaperTrader$clone(deep = FALSE)
deepWhether to make a deep clone.
Legacy R6 demonstration of a paper trading platform. The production
simulation path is sim_backtest() and the C++ execution engine.
inst_infoInstrument metadata used by the demo platform.
bar_infoLatest market bar data by instrument.
user_dataDemo user wallet and position state.
exchangeBacking tradesimr_exchange object.
order_poolDemo order table.
order_id_counterNext demo order id counter.
PaperTradingPlatform$new()Create a paper trading platform demo.
PaperTradingPlatform$new(config = list())
configSimulation config passed to sim_exchange_new().
PaperTradingPlatform$register_user()Register a demo user and return a trader client.
PaperTradingPlatform$register_user(user_id, initial_balance = 10000)
user_idUser identifier.
initial_balanceInitial wallet balance.
A PaperTrader instance.
PaperTradingPlatform$place_user_order()Place a demo user order.
PaperTradingPlatform$place_user_order( user_id, inst_id, type, pos, size, price, pricing_method, tag )
user_idUser identifier.
inst_idInstrument identifier.
typeOrder type label.
posPosition side label.
sizeOrder size.
priceOrder price.
pricing_methodPricing method label.
tagOptional order tag.
Order id.
PaperTradingPlatform$cancel_user_order()Cancel a demo user order.
PaperTradingPlatform$cancel_user_order(user_id, order_id)
user_idUser identifier.
order_idOrder id.
PaperTradingPlatform$get_user_orders()Get all orders for a user.
PaperTradingPlatform$get_user_orders(user_id)
user_idUser identifier.
A data.table of orders.
PaperTradingPlatform$get_user_order()Get a user order.
PaperTradingPlatform$get_user_order(user_id, order_id)
user_idUser identifier.
order_idOrder id.
A data.table with matching order rows.
PaperTradingPlatform$get_live_orders()Get live demo orders.
PaperTradingPlatform$get_live_orders()
A data.table of live orders.
PaperTradingPlatform$get_order()Get an order by id.
PaperTradingPlatform$get_order(order_id)
order_idOrder id.
A data.table with matching order rows.
PaperTradingPlatform$update_bar()Update the latest market bar and append it to the exchange.
PaperTradingPlatform$update_bar(inst_id, timestamp, open, high, low, close)
inst_idInstrument identifier.
timestampBar timestamp.
open, high, low, closeOHLC prices.
PaperTradingPlatform$process_order()Process one demo order against the latest bar.
PaperTradingPlatform$process_order(order)
orderOrder row.
PaperTradingPlatform$fill_order()Fill a demo order and pass target exposure to the exchange.
PaperTradingPlatform$fill_order(order_id, fill_price)
order_idOrder id.
fill_priceFill price.
PaperTradingPlatform$get_user_wallet()Get a user's wallet balance.
PaperTradingPlatform$get_user_wallet(user_id)
user_idUser identifier.
Wallet balance or account cash.
PaperTradingPlatform$get_user_position()Get a user's position.
PaperTradingPlatform$get_user_position(user_id)
user_idUser identifier.
A data.table of positions.
PaperTradingPlatform$update_user_wallet()Update a user's demo wallet balance.
PaperTradingPlatform$update_user_wallet(user_id, delta_wallet_balance)
user_idUser identifier.
delta_wallet_balanceWallet balance delta.
PaperTradingPlatform$update_user_position()Update a user's demo position after a fill.
PaperTradingPlatform$update_user_position(order)
orderFilled order row.
Wallet balance delta.
PaperTradingPlatform$clone()The objects of this class are cloneable with this method.
PaperTradingPlatform$clone(deep = FALSE)
deepWhether to make a deep clone.
Extract account snapshots from a simulation
sim_account(sim)sim_account(sim)
sim |
A simulation result returned by |
A data.table of bar-level account snapshots.
AI agents generate ordinary order requests; they do not bypass the exchange command/execution path.
sim_agent_add( exchange, agent_id = NULL, agent_type = c("chaos", "momentum", "contrarian", "mean_reversion", "strategy", "human"), config = list(), status = c("active", "paused") )sim_agent_add( exchange, agent_id = NULL, agent_type = c("chaos", "momentum", "contrarian", "mean_reversion", "strategy", "human"), config = list(), status = c("active", "paused") )
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: |
The agent id.
Get live-agent command schemas
sim_agent_command_schema()sim_agent_command_schema()
A named list of empty data.tables for append-only agent commands, order requests, and order cancellations.
Export an agent-facing live dashboard
sim_agent_dashboard_export(exchange, path)sim_agent_dashboard_export(exchange, path)
exchange |
A |
path |
Output directory. |
Invisibly returns a named character vector of written files.
Open an agent-facing live dashboard
sim_agent_dashboard_open( exchange = sim_exchange_new(), path = tempfile("tradesimr-live-agent-") )sim_agent_dashboard_open( exchange = sim_exchange_new(), path = tempfile("tradesimr-live-agent-") )
exchange |
A |
path |
Output directory. |
Invisibly returns the dashboard index path.
Rankings combine current per-agent account equity with order activity.
sim_agent_rankings(exchange)sim_agent_rankings(exchange)
exchange |
A |
A data.table of agent rankings.
Removed agents stay in the durable registry with status removed.
sim_agent_remove(exchange, agent_id)sim_agent_remove(exchange, agent_id)
exchange |
A |
agent_id |
Agent identifier. |
Invisibly returns TRUE when an agent was updated.
Set an agent status
sim_agent_set_status( exchange, agent_id, status = c("active", "paused", "removed") )sim_agent_set_status( exchange, agent_id, status = c("active", "paused", "removed") )
exchange |
A |
agent_id |
Agent identifier. |
status |
New status: |
Invisibly returns TRUE when an agent was updated.
Step active AI agents and append their order commands
sim_agents_step(exchange, bar = NULL)sim_agents_step(exchange, bar = NULL)
exchange |
A |
bar |
Optional current bar used for decision timestamps and prices. |
A data.table of generated decisions.
Register a tradable asset on an exchange
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() )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() )
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. |
Invisibly returns the registered asset row.
Removed assets remain in the durable registry with status removed.
sim_asset_remove(exchange, symbol = NULL, asset_id = NULL)sim_asset_remove(exchange, symbol = NULL, asset_id = NULL)
exchange |
A |
symbol |
Optional symbol. |
asset_id |
Optional integer asset id. |
Invisibly returns TRUE when an asset was updated.
List registered exchange assets
sim_assets(exchange)sim_assets(exchange)
exchange |
A |
A data.table of assets.
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.
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 )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 )
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. |
A data.table with timestamp and equity. If record = TRUE, an
execution recorder is attached as attribute orders.
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.
sim_bond_schedule_add( exchange, symbol, coupon_rate, coupon_frequency = 2L, issue_timestamp, maturity_timestamp, face_value = 100, accrual_day_count = 365, currency = NULL )sim_bond_schedule_add( exchange, symbol, coupon_rate, coupon_frequency = 2L, issue_timestamp, maturity_timestamp, face_value = 100, accrual_day_count = 365, currency = NULL )
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. |
Invisibly returns the registered schedule row.
List durable bond schedules
sim_bond_schedules(exchange)sim_bond_schedules(exchange)
exchange |
A |
A data.table of bond schedule state.
Generate expected completed bar timestamps from a calendar
sim_calendar_expected_bars( calendar_id, start, end, cadence_seconds, exceptions = NULL )sim_calendar_expected_bars( calendar_id, start, end, cadence_seconds, exceptions = NULL )
calendar_id |
Built-in calendar identifier. |
start, end
|
Timestamp bounds. |
cadence_seconds |
Positive bar cadence in seconds. |
exceptions |
Optional exception table with |
A data.table of expected completed-bar timestamps.
List deterministic built-in calendar holidays
sim_calendar_holidays(calendar_id, start, end)sim_calendar_holidays(calendar_id, start, end)
calendar_id |
Built-in calendar identifier. |
start, end
|
Date/POSIXct bounds. |
A data.table of session dates, labels, and optional early close time.
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.
sim_calendar_is_open(timestamp, calendar_id = "ALWAYS_OPEN", exceptions = NULL)sim_calendar_is_open(timestamp, calendar_id = "ALWAYS_OPEN", exceptions = NULL)
timestamp |
POSIXct timestamps. |
calendar_id |
Built-in calendar identifier. |
exceptions |
Optional calendar-exception rows from
|
A logical vector.
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.
sim_calendar_settlement_timestamp( calendar_id, timestamp, settlement_lag_days = 0L, exceptions = NULL )sim_calendar_settlement_timestamp( calendar_id, timestamp, settlement_lag_days = 0L, exceptions = NULL )
calendar_id |
Built-in settlement calendar identifier. |
timestamp |
Trade timestamp. |
settlement_lag_days |
Non-negative whole settlement days. |
exceptions |
Optional calendar-exception rows. |
A UTC POSIXct settlement timestamp.
Get a trading-calendar specification
sim_calendar_spec(calendar_id)sim_calendar_spec(calendar_id)
calendar_id |
Built-in calendar identifier. |
A one-row data.table with timezone, session rule, and holiday policy.
Submit an agent order cancellation command
sim_cancel_order( exchange, agent_id, order_id, client_order_id = NA_character_, timestamp = Sys.time(), process = TRUE )sim_cancel_order( exchange, agent_id, order_id, client_order_id = NA_character_, timestamp = Sys.time(), process = TRUE )
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. |
The generated command id.
Extract cash ledger entries from a simulation
sim_cash_ledger(sim)sim_cash_ledger(sim)
sim |
A simulation result returned by |
A data.table of event-level cash changes.
Compute cross-asset risk for live exchange agents
sim_cross_asset_risk(exchange, stress_sigma = 2)sim_cross_asset_risk(exchange, stress_sigma = 2)
exchange |
A |
stress_sigma |
Multiplier applied to portfolio return volatility for the stress-loss estimate. |
A data.table with one row per agent and exposed asset.
Compatibility alias for sim_replay_dashboard_export().
sim_dashboard_export(sim, path)sim_dashboard_export(sim, path)
sim |
A simulation result returned by |
path |
Output directory. |
Invisibly returns a named character vector of written files.
Open an exported static dashboard
sim_dashboard_open(path)sim_dashboard_open(path)
path |
Directory created by a dashboard export helper. |
Invisibly returns the dashboard index path.
Convert a simulation recorder into an event table
sim_events(x)sim_events(x)
x |
A simulation result returned by |
A data.table of recorded simulation events.
Get simulated exchange account state
sim_exchange_account(exchange)sim_exchange_account(exchange)
exchange |
A |
A one-row data.table with the latest account snapshot.
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.
sim_exchange_account_state(exchange, agent_id = NULL)sim_exchange_account_state(exchange, agent_id = NULL)
exchange |
A |
agent_id |
Optional account identifier. |
A named list containing account, cash_balances,
inventory_positions, margin_positions, and events data.tables.
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.
sim_exchange_accrue_carry(exchange, timestamp)sim_exchange_accrue_carry(exchange, timestamp)
exchange |
A |
timestamp |
Accrual boundary. |
A data.table of booked carry events.
Append market bars to a simulated exchange
sim_exchange_add_bars(exchange, bars)sim_exchange_add_bars(exchange, bars)
exchange |
A |
bars |
Market bars coercible by |
The exchange, invisibly.
Add an exchange-specific calendar exception
sim_exchange_calendar_exception( exchange, session_date, action = c("closed", "early_close"), calendar_id = NULL, symbol = NULL, asset_id = NULL, close_time = NULL, message = "" )sim_exchange_calendar_exception( exchange, session_date, action = c("closed", "early_close"), calendar_id = NULL, symbol = NULL, asset_id = NULL, close_time = NULL, message = "" )
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. |
Invisibly returns the durable exception row.
Calendarize registered-asset market bars
sim_exchange_calendarize_bars(exchange, bars, strict = FALSE)sim_exchange_calendarize_bars(exchange, bars, strict = FALSE)
exchange |
A |
bars |
Market bars. |
strict |
Whether a supplied tradable bar outside its registered session should error rather than be converted to valuation-only. |
Canonical market bars with calendar-derived is_tradable values.
Cancel an intent-level order in a simulated exchange
sim_exchange_cancel_order(exchange, order_id)sim_exchange_cancel_order(exchange, order_id)
exchange |
A |
order_id |
Order id returned by |
Invisibly returns TRUE if an order was cancelled.
Deposit or withdraw a profile-aware currency balance
sim_exchange_cash_adjust( exchange, agent_id, amount, currency = NULL, timestamp = Sys.time(), message = "Manual cash adjustment" )sim_exchange_cash_adjust( exchange, agent_id, amount, currency = NULL, timestamp = Sys.time(), message = "Manual cash adjustment" )
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. |
Invisibly returns the resulting currency balance.
Get profile-aware cash balances
sim_exchange_cash_balances(exchange, agent_id = NULL)sim_exchange_cash_balances(exchange, agent_id = NULL)
exchange |
A |
agent_id |
Optional account identifier. |
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
sim_exchange_convert_cash( exchange, agent_id, amount, from_ccy, to_ccy, timestamp = Sys.time() )sim_exchange_convert_cash( exchange, agent_id, amount, from_ccy, to_ccy, timestamp = Sys.time() )
exchange |
A |
agent_id |
Account identifier. |
amount |
Source-currency amount to convert. |
from_ccy, to_ccy
|
Currency codes. |
timestamp |
Ledger timestamp. |
Invisibly returns the destination amount.
Actions are applied at the first exchange step at or after their effective timestamp and retained in a durable audit table.
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 )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 )
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. |
Invisibly returns the action id.
Export and open a simulated exchange dashboard
sim_exchange_dashboard(exchange, path)sim_exchange_dashboard(exchange, path)
exchange |
A |
path |
Output directory. |
Invisibly returns written dashboard files.
Export exchange simulation events
sim_exchange_export_events(exchange, path, format = c("csv", "fst"))sim_exchange_export_events(exchange, path, format = c("csv", "fst"))
exchange |
A |
path |
Output directory. |
format |
File format, either |
Invisibly returns written file paths.
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.
sim_exchange_future_roll( exchange, symbol, effective_timestamp, settlement_price, successor_symbol = NULL, roll_price = NULL )sim_exchange_future_roll( exchange, symbol, effective_timestamp, settlement_price, successor_symbol = NULL, roll_price = NULL )
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. |
Invisibly returns the corporate action id.
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.
sim_exchange_fx_rate( exchange, from_ccy, to_ccy, rate, timestamp = Sys.time(), source = "manual" )sim_exchange_fx_rate( exchange, from_ccy, to_ccy, rate, timestamp = Sys.time(), source = "manual" )
exchange |
A |
from_ccy |
Source currency. |
to_ccy |
Destination currency. |
rate |
Positive conversion rate. |
timestamp |
Valuation timestamp. |
source |
Public-safe source label. |
Invisibly returns the added rate row.
Load exchange state from disk
sim_exchange_load(path)sim_exchange_load(path)
path |
Directory produced by |
A tradesimr_exchange.
Create an in-memory simulated exchange state
sim_exchange_new(config = list())sim_exchange_new(config = list())
config |
Named simulation parameters. Set |
A mutable environment containing market, intent, order, and result tables.
Get new events since the previous exchange run
sim_exchange_new_events(exchange)sim_exchange_new_events(exchange)
exchange |
A |
A data.table of newly observed simulation events.
Get simulated exchange orders
sim_exchange_orders(exchange)sim_exchange_orders(exchange)
exchange |
A |
A data.table of accepted/cancelled intent-level orders.
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.
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_ )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_ )
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. |
The generated order id.
Get simulated exchange positions
sim_exchange_positions(exchange)sim_exchange_positions(exchange)
exchange |
A |
A one-row data.table with the latest position snapshot.
Converts pending append-only order request and cancellation commands into exchange orders and cancellation attempts.
sim_exchange_process_commands(exchange)sim_exchange_process_commands(exchange)
exchange |
A |
A data.table of processed command rows.
Run or refresh a simulated exchange replay
sim_exchange_run(exchange)sim_exchange_run(exchange)
exchange |
A |
A simulation result returned by sim_backtest().
Export exchange events and state
sim_exchange_save(exchange, path, format = c("csv", "fst"))sim_exchange_save(exchange, path, format = c("csv", "fst"))
exchange |
A |
path |
Output directory. |
format |
File format, either |
Invisibly returns written file paths.
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.
sim_exchange_set_carry_rates( exchange, borrow_rates = numeric(), cash_interest_rates = numeric() )sim_exchange_set_carry_rates( exchange, borrow_rates = numeric(), cash_interest_rates = numeric() )
exchange |
A |
borrow_rates |
Named numeric annualized rates keyed by symbol. |
cash_interest_rates |
Named numeric annualized rates keyed by currency. |
Invisibly returns the configured rates.
Settle due profile-aware cash movements
sim_exchange_settle(exchange, timestamp = Sys.time())sim_exchange_settle(exchange, timestamp = Sys.time())
exchange |
A |
timestamp |
Settlement cutoff. |
A data.table of settled ledger rows.
Step a simulated exchange with one or more bars
sim_exchange_step(exchange, bars)sim_exchange_step(exchange, bars)
exchange |
A |
bars |
Market bars coercible by |
The incremental simulation snapshots.
Validate registered-asset bar cadence
sim_exchange_validate_cadence(exchange, bars, strict = FALSE)sim_exchange_validate_cadence(exchange, bars, strict = FALSE)
exchange |
A |
bars |
Market bars. |
strict |
Whether cadence violations should error. |
A data.table with calendar_open and cadence_ok columns.
Export simulation tables to durable files
sim_export( sim, path, format = c("csv", "fst"), tables = c("simulation", "market_events", "events", "orders", "fills", "positions", "cash_ledger", "account", "risk") )sim_export( sim, path, format = c("csv", "fst"), tables = c("simulation", "market_events", "events", "orders", "fills", "positions", "cash_ledger", "account", "risk") )
sim |
A simulation result returned by |
path |
Output directory. |
format |
File format, either |
tables |
Names of tables to export. |
Invisibly returns a named character vector of written file paths.
Default live feed configuration
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() )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() )
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
|
A list suitable for sim_feed_configure().
Configure a live exchange feed
sim_feed_configure(exchange, config = sim_feed_config())sim_feed_configure(exchange, config = sim_feed_config())
exchange |
A |
config |
Feed configuration list. A list with |
The feed configuration, invisibly.
Start a configured live feed
sim_feed_start(exchange, now = Sys.time(), symbol = NULL, asset_id = NULL)sim_feed_start(exchange, now = Sys.time(), symbol = NULL, asset_id = NULL)
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. |
Feed status.
Get live feed status
sim_feed_status(exchange)sim_feed_status(exchange)
exchange |
A |
A list describing feed state.
Generates or fetches all completed bars after the last processed feed
boundary and appends them through sim_exchange_step().
sim_feed_step( exchange, now = Sys.time(), max_bars = Inf, symbol = NULL, asset_id = NULL )sim_feed_step( exchange, now = Sys.time(), max_bars = Inf, symbol = NULL, asset_id = NULL )
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. |
A data.table of bars appended by this call.
Stop a configured live feed
sim_feed_stop(exchange, symbol = NULL, asset_id = NULL)sim_feed_stop(exchange, symbol = NULL, asset_id = NULL)
exchange |
A |
symbol, asset_id
|
Optional feed asset selector. If omitted, all configured active asset feeds are stopped. |
Feed status.
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.
sim_feed_warmup( exchange, n_bars = 100L, now = Sys.time(), symbol = NULL, asset_id = NULL )sim_feed_warmup( exchange, n_bars = 100L, now = Sys.time(), symbol = NULL, asset_id = NULL )
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. |
A data.table of appended market bars.
Extract fill events from a simulation
sim_fills(sim)sim_fills(sim)
sim |
A simulation result returned by |
A data.table of filled trade events.
Marks inventory, settles futures/perpetual variation margin, and evaluates a normalized order batch without mutating the supplied R input tables.
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() )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() )
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. |
Updated account state, typed events, fills, and group outcomes.
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.
sim_heterogeneous_order_batch_schema()sim_heterogeneous_order_batch_schema()
A typed empty data.table accepted by
sim_heterogeneous_account_step().
Import exported simulation tables
sim_import(path)sim_import(path)
path |
Export directory created by |
A named list containing manifest, simulation, and available
durable tables.
Resolve an instrument profile
sim_instrument_profile(instrument_profile)sim_instrument_profile(instrument_profile)
instrument_profile |
Supported profile name. |
A one-row data.table of profile defaults.
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.
sim_instrument_profiles()sim_instrument_profiles()
A data.table of supported profiles and their defaults.
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.
sim_live_service(exchange = sim_exchange_new())sim_live_service(exchange = sim_exchange_new())
exchange |
A |
A plumber router.
Run a local live exchange service
sim_live_service_run( exchange = sim_exchange_new(), host = "127.0.0.1", port = 8080 )sim_live_service_run( exchange = sim_exchange_new(), host = "127.0.0.1", port = 8080 )
exchange |
A |
host |
Host interface. |
port |
Port. |
The result of plumber's run() method.
Open a live-state dashboard
sim_live_state_dashboard_open( exchange = sim_exchange_new(), path = tempfile("tradesimr-live-state-") )sim_live_state_dashboard_open( exchange = sim_exchange_new(), path = tempfile("tradesimr-live-state-") )
exchange |
A |
path |
Output directory. |
Invisibly returns the dashboard index path.
Build an export manifest
sim_manifest(paths, tables, format, config = list())sim_manifest(paths, tables, format, config = list())
paths |
Named character vector of exported files. |
tables |
Named list of exported tables. |
format |
Export file format. |
config |
Optional simulation configuration. |
A data.table manifest.
Extract market bars from a simulation
sim_market_events(sim)sim_market_events(sim)
sim |
A simulation result returned by |
A data.table with timestamp, open, high, low, and close.
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.
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" )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" )
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. |
A sim_market_model_config() list with calibration metadata.
Configure an exchange market model from historical bars
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" )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" )
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. |
The calibrated market model config, invisibly.
Configure market-level multi-asset simulation
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 )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 )
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. |
A market model configuration list.
Configure a market-level simulation model
sim_market_model_configure(exchange, config = sim_market_model_config())sim_market_model_configure(exchange, config = sim_market_model_config())
exchange |
A |
config |
A list from |
The market model configuration, invisibly.
Get market-level simulation model status
sim_market_model_status(exchange)sim_market_model_status(exchange)
exchange |
A |
A list describing the market-level simulation model.
Calculate core performance metrics from a simulation result
sim_metrics(sim)sim_metrics(sim)
sim |
A simulation result from |
A one-row data.table with return, drawdown, and event counts.
Convert a simulation recorder into an order/event table
sim_orders(x)sim_orders(x)
x |
A simulation result returned by |
A data.table of recorded execution events.
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.
sim_portfolio_decision_policy( mode = c("complete_universe", "as_of_valuation", "per_asset_decision"), max_staleness = Inf )sim_portfolio_decision_policy( mode = c("complete_universe", "as_of_valuation", "per_asset_decision"), max_staleness = Inf )
mode |
Decision policy. |
max_staleness |
Maximum age in seconds of a carried valuation for
|
A validated decision-policy list.
Build execution assumptions for a target-weight portfolio replay
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 )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 )
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. |
A named execution configuration list.
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.
sim_portfolio_execution_quality(exchange, agent_id = NULL, summary = FALSE)sim_portfolio_execution_quality(exchange, agent_id = NULL, summary = FALSE)
exchange |
A |
agent_id |
Optional account identifier used to filter the projection. |
summary |
If |
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
sim_portfolio_export(exchange, agent_id, path, format = "json")sim_portfolio_export(exchange, agent_id, path, format = "json")
exchange |
A |
agent_id |
Agent identifier. |
path |
Output directory. |
format |
Export format. Phase 1 supports JSON. |
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.
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.
sim_portfolio_market_step( exchange, bars, execution = sim_portfolio_execution() )sim_portfolio_market_step( exchange, bars, execution = sim_portfolio_execution() )
exchange |
A |
bars |
One timestamped batch of registered, completed OHLC bars. |
execution |
Execution assumptions from |
A public-safe list with bars, fills, events, positions,
account, and outcomes.
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.
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 )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 )
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. |
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.
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().
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 )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 )
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 |
A list with the exchange, durable orders/fills/positions/accounts, targets/rebalances, execution quality, optional export paths, and timings.
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.
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() )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() )
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
|
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.
A list containing orders, fills, positions, account,
targets, realized_weights, and outcomes.
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.
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() )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() )
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
|
A list containing orders, fills, positions, account,
targets, realized_weights, and outcomes.
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.
sim_portfolio_target_submit_batch( exchange, bars, decisions, execution = sim_portfolio_execution(), decision_policy = sim_portfolio_decision_policy() )sim_portfolio_target_submit_batch( exchange, bars, decisions, execution = sim_portfolio_execution(), decision_policy = sim_portfolio_decision_policy() )
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. |
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
sim_positions(sim)sim_positions(sim)
sim |
A simulation result returned by |
A data.table of bar-level position snapshots.
Read exported account snapshots
sim_read_account(path)sim_read_account(path)
path |
Export directory created by |
A data.table of account snapshots.
Read exported simulation events
sim_read_events(path)sim_read_events(path)
path |
Export directory created by |
A data.table of events.
Read an export manifest
sim_read_manifest(path)sim_read_manifest(path)
path |
Export directory or manifest file path. |
A data.table manifest.
Read an exported simulation table
sim_read_table(path, table, format = NULL)sim_read_table(path, table, format = NULL)
path |
Export directory or table file path. |
table |
Table name when |
format |
Optional format. Inferred from manifest or file extension when absent. |
A data.table.
Alias for sim_backtest() reserved for replay-oriented workflows.
sim_replay(data, ...)sim_replay(data, ...)
data |
A data frame/data.table with timestamp, open, high, low, close, and target-position columns. |
... |
Additional arguments passed to |
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.
sim_replay_dashboard_export(sim, path)sim_replay_dashboard_export(sim, path)
sim |
A simulation result returned by |
path |
Output directory. |
Invisibly returns a named character vector of written files.
Extract risk snapshots from a simulation
sim_risk(sim)sim_risk(sim)
sim |
A simulation result returned by |
A data.table of bar-level risk snapshots.
Reconstruct simulation views from exported events
sim_run_from_events(path)sim_run_from_events(path)
path |
Export directory created by |
A data.table simulation result when a simulation table exists,
otherwise event-level account state reconstructed from events.
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.
sim_schema_migrate(tables, from_version = NULL)sim_schema_migrate(tables, from_version = NULL)
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. |
A named list upgraded to sim_schema_version().
Get the tradesimr schema version
sim_schema_version()sim_schema_version()
A scalar character schema version.
Simulation table schemas
sim_schemas()sim_schemas()
A named list of empty data.tables representing durable simulation table schemas.
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.
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 )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 )
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. |
A list containing cash, units, average cost, market value, equity, P&L, fees, corporate-action cash, and execution status.
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.
sim_spot_target_submit(exchange, agent_id, bars, target_weights, fee_rt = 0)sim_spot_target_submit(exchange, agent_id, bars, target_weights, fee_rt = 0)
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. |
A list of accepted orders and planned target quantities.
Create a simulation state object
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 )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 )
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. |
A list suitable for sim_step().
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.
sim_state_dashboard_export(exchange, path)sim_state_dashboard_export(exchange, path)
exchange |
A |
path |
Output directory. |
Invisibly returns a named character vector of written files.
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.
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 )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 )
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. |
A list with state and events.
List registered strategy ids
sim_strategy_list(exchange)sim_strategy_list(exchange)
exchange |
A |
Character vector of registered strategy ids.
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.
sim_strategy_register(exchange, strategy_id, strategy_fn)sim_strategy_register(exchange, strategy_id, strategy_fn)
exchange |
A |
strategy_id |
Strategy identifier used by agent config. |
strategy_fn |
Function returning target positions, strategyr action plans, or order-intent rows. |
The strategy id, invisibly.
Unregister a strategy function
sim_strategy_unregister(exchange, strategy_id)sim_strategy_unregister(exchange, strategy_id)
exchange |
A |
strategy_id |
Strategy identifier used by agent config. |
Invisibly returns TRUE when a strategy was removed.
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 ....
sim_strategy_validate_config(exchange, config)sim_strategy_validate_config(exchange, config)
exchange |
A |
config |
Agent config list. |
A list with valid, message, strategy_id, strategy_fun, and
params.
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().
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 )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 )
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. |
The generated command id.
List built-in trading calendars
sim_trading_calendars()sim_trading_calendars()
A data.table describing the deterministic built-in session rules.
Heterogeneous account schema version
TRADESIMR_ACCOUNT_SCHEMA_VERSIONTRADESIMR_ACCOUNT_SCHEMA_VERSION
An object of class character of length 1.
tradesimr durable schema version
TRADESIMR_SCHEMA_VERSIONTRADESIMR_SCHEMA_VERSION
An object of class character of length 1.
Validate target-position intent columns
validate_intents(data, tgt_pos_col = "tgt_pos", tol_pos_col = NULL)validate_intents(data, tgt_pos_col = "tgt_pos", tol_pos_col = NULL)
data |
A table-like object. |
tgt_pos_col |
Target-position column name. |
tol_pos_col |
Optional tolerance column name. |
Invisibly returns TRUE on success.
Validate core market-bar columns
validate_market_data( data, timestamp_col = "timestamp", open_col = "open", high_col = "high", low_col = "low", close_col = "close" )validate_market_data( data, timestamp_col = "timestamp", open_col = "open", high_col = "high", low_col = "low", close_col = "close" )
data |
A table-like object. |
timestamp_col, open_col, high_col, low_col, close_col
|
Column names. |
Invisibly returns TRUE on success.
Legacy helper that loads candle data through strategyr and applies signal strategies before forming long, short, and both-side position series.
vec_batch_run_simulations( inst_ids, bar, signal_strategies, root_path = Sys.getenv("OKX_Candle_Data_Path"), bg_time = NULL, ed_time = NULL )vec_batch_run_simulations( inst_ids, bar, signal_strategies, root_path = Sys.getenv("OKX_Candle_Data_Path"), bg_time = NULL, ed_time = NULL )
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. |
A named list of data.tables.
Plot vectorized simulation results
vec_sim_gen_plot(vec_sim_res, report_mode = c("simple", "full"))vec_sim_gen_plot(vec_sim_res, report_mode = c("simple", "full"))
vec_sim_res |
Result from |
report_mode |
Plot report mode. |
Summarize vectorized simulation results
vec_sim_gen_summary( vec_sim_res, report_mode = c("short_txt", "long_txt", "dt") )vec_sim_gen_summary( vec_sim_res, report_mode = c("short_txt", "long_txt", "dt") )
vec_sim_res |
Result from |
report_mode |
Summary mode. |
Text or a one-row data.table depending on report_mode.
Summarize a batch of vectorized simulations
vec_sim_gen_summary_table(DTs)vec_sim_gen_summary_table(DTs)
DTs |
List of vectorized simulation data.tables. |
A data.table of summaries.
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().
vec_sim_run_backtest(DT)vec_sim_run_backtest(DT)
DT |
A data.table containing at least |
A list containing equity series and summary statistics.