Bentrix Docs
HomePricingDashboard

Many environments at once

Step several environments together — one workbench each, with its own account, clock, seed and fill conditions — inside one program, or run several programs side by side over one set of recordings.

Most training algorithms collect experience from several environments at once: PPO steps eight or sixteen of them together and learns from the batch. Each environment must be independent — its own account, its own position, its own place in time — or one episode's trades would leak into another's.

In Bentrix the unit of independence is the workbench. Each has its own account, clock and book. So the rule is short: one environment, one workbench.

01Several workbenches in one program

bentrix.gym.make_vec takes a list of workbenches and returns Gymnasium's own vector environment, with one TradingEnv on each:

import tempfile
import time

import numpy as np

from bentrix import _native
from bentrix.gym import make_vec
from bentrix.local import Local

workspace, store = _native.make_tape(tempfile.mkdtemp(prefix="bentrix-practice-"))
engine = Local(workspace=workspace, store=store)
first = engine.call("get_state")["laboratories"][0]["benches"][0]["uri"]
engine.arm(first)

# Four workbenches over the same days, each with its own account, clock and book - and each with its
# own seed for the slippage its fills draw (up to 5 points against the order).
benches = [first] + [
    engine.call("bench_create_alike", bench=first, slippage={"random": {"up_to_points": 5}}, seed=seed)["uri"]
    for seed in (1, 2, 3)
]
envs = make_vec(benches, local=engine, interval="M15", window=16, episode="window", episode_bars=96, reward="pnl@1")

obs, info = envs.reset(seed=[11, 12, 13, 14])                 # one seed per environment
print("market:", obs["market"].shape, "account:", obs["account"].shape)

rng = np.random.default_rng(0)
steps, started = 0, time.perf_counter()
totals = np.zeros(len(benches))
for _ in range(96):
    obs, rewards, terminated, truncated, info = envs.step(rng.integers(0, 3, size=len(benches)))
    totals += rewards
    steps += len(benches)
print("steps:", steps, "in", round(time.perf_counter() - started, 2), "s")
print("each environment's own reward sum:", np.round(totals, 2))
envs.close()
engine.close()
market: (4, 16, 4) account: (4, 3)
steps: 384 in 1.64 s
each environment's own reward sum: [ -6.19 -21.73 -10.72 -14.6 ]

The observation now has a leading dimension of four — market is 4 × 16 candles × 4 prices — and step takes four actions and answers four rewards. The four reward sums differ because each environment drew its own episode from its own seed and was filled under its own slippage seed.

The three extra workbenches are made alike the first: the same days, markets and account, each with its own seed for a small random slippage. That is the common arrangement — the same market, independent execution. bench_create_alike asks for at least one spread or fill setting, so a small random slippage with a different seed per workbench is the natural way to get siblings.

An environment of your own works the same way with Gymnasium's own tools:

import gymnasium as gym
from my_env import LegsEnv   # the class from "An environment of your own"

envs = gym.vector.SyncVectorEnv([lambda b=b: LegsEnv(engine, b, "XAUUSD") for b in benches])

02What is shared and what is not

One per environmentShared by all
The account: balance, equity, marginThe recordings on disk (store): replaying never changes them
The clock and the episodeThe engine library, loaded once per program
Positions, orders, deals
The fill model and its seed

03One program, one thread

The engine is used from the thread that opened it, and make_vec steps its environments one after another in that thread (SyncVectorEnv). That is simple and deterministic, and it is why 384 steps above took about two seconds: the same per-step cost as a single environment, four times over.

Gymnasium's AsyncVectorEnv, which puts each environment in its own process, cannot share one Local: a workspace has one writer.

04More speed: several programs side by side

To use several processor cores, run several programs, each with a workspace of its own, over the same recordings:

  1. Make the workspace once and set up its workbenches.
  2. With no program holding it, copy the workspace folder once per worker: ws_1, ws_2, …
  3. Start each worker with Local(workspace="ws_N", store="the same store").

Each worker opens its own copy; all of them read the one store. On the practice tape three workers started together each replayed 3,000 one-minute closes in about a second, as fast as one alone.

Opening the same workspace from two programs is refused, with a sentence naming the process that holds it — so a mistake here stops at once instead of corrupting a run.

With a library that manages worker processes for you (Stable-Baselines3's SubprocVecEnv, RLlib's workers), give each worker's environment constructor its own workspace copy and let it open its own Local inside the worker, not before the processes are started.

05Good to know

  • Seeds: envs.reset(seed=[…]) gives each environment its own seed; a single number gives them consecutive seeds, as in Gymnasium.
  • An environment that finishes its episode is reset by the vector environment itself; Gymnasium's documentation describes which observation you then receive.
  • Evaluate on workbenches the training never used, over at least ten seeds: evaluating a policy honestly.

Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed