A Gymnasium environment written by you on Bentrix's engine — your observation, your actions, your reward, your episodes — with none of the ready-made environment's choices, in about ninety lines.
The ready-made environment, TradingEnv, decides what an observation holds, what an action means and how a reward is computed. That is a good start and a poor fit for an agent with its own design: one that manages several positions at once, reads several timeframes, or is rewarded for something other than the equity's change.
You do not have to use it. A Gymnasium environment is a small piece of Python with two methods, reset and step. Write it yourself, and let Bentrix do only what it is for: replay the market, fill the orders, keep the account. This page builds one from an empty file.
01Who does what
| Yours | Bentrix's |
|---|---|
| The observation: which numbers, in what shape | The candles and ticks, never past the clock |
| The actions: what each one means | The orders: filled at the bid or the ask on the next tick, or refused in words |
| The reward | The account: balance, equity, margin, commission, swap |
| When an episode starts and ends | The clock, and undoing an episode's deals |
| The policy and the training loop | Nothing: no algorithm is built in or required |
02The environment
This one manages legs: up to five separate positions, opened and closed one at a time. Its observation mixes two timeframes with the account's exposure and drawdown. Its reward is the equity's change with a charge for new drawdown. Every one of those choices is a few lines you can replace.
Install the package with Gymnasium — pip install "bentrix[gym]" — and save this as my_env.py:
import tempfile
import gymnasium as gym
import numpy as np
from gymnasium import spaces
from bentrix import _native
from bentrix.local import Local
HOUR = 3_600_000
class LegsEnv(gym.Env):
"""Bentrix's venue under an environment of your own: your observation, your actions, your reward.
Actions: 0 hold, 1 open a long leg, 2 open a short leg, 3 close the oldest leg, 4 close every leg.
One step is five minutes of the recording."""
metadata = {"render_modes": []}
def __init__(self, engine, bench, symbol, leg_lots=0.01, max_legs=5, episode_steps=120):
self.engine, self.bench, self.symbol = engine, bench, symbol
self.leg_lots, self.max_legs, self.episode_steps = leg_lots, max_legs, episode_steps
home, owner, _, name = bench.removeprefix("bentrix://").split("/")
self._where = dict(home=home, owner=owner, bench=name)
engine.arm(bench)
bounds = engine.state(bench)["bounds"]
self.first, self.last = bounds["from_ms"] + 6 * HOUR, bounds["to_ms"] - 12 * HOUR
self.origin = engine.snapshot(bench) # the untouched workbench, kept in memory
self.observation_space = spaces.Box(-1e3, 1e3, shape=(16 + 4 + 4,), dtype=np.float32)
self.action_space = spaces.Discrete(5)
# ---- what the agent sees: yours to design ------------------------------------------------
def _observe(self):
got = self.engine.call("bars_window", bench=self.bench, symbol=self.symbol, frames=["M5", "H1"], limit=17)
frames = got["markets"][self.symbol]
m5 = np.array([row[4] for row in frames["M5"]["rows"]]) # closes of CLOSED candles only
h1 = np.array([row[4] for row in frames["H1"]["rows"]][-5:])
book = self.engine.book(self.bench)
legs = book["positions"]
long_lots = sum(p["volume"] for p in legs if p["side"] == "buy")
short_lots = sum(p["volume"] for p in legs if p["side"] == "sell")
account = self.engine.read("trade_account", **self._where)
self.equity = account["equity"]
self.peak = max(self.peak, self.equity)
cap = self.leg_lots * self.max_legs
mine = [
(long_lots - short_lots) / cap, # net exposure, in units of the cap
(long_lots + short_lots) / cap, # gross exposure
self.equity / self.opening - 1.0,
self.equity / self.peak - 1.0, # drawdown from the episode's peak
]
obs = np.concatenate([np.diff(np.log(m5)) * 1e3, np.diff(np.log(h1)) * 1e3, mine]).astype(np.float32)
return obs, legs
# ---- Gymnasium's two methods --------------------------------------------------------------
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
self.engine.restore(self.bench, self.origin) # every order and deal undone
hours = (self.last - self.first) // HOUR
start = self.first + int(self.np_random.integers(hours)) * HOUR # the seed draws the start
self.engine.advance(self.bench, start)
self.steps = 0
self.opening = self.peak = self.engine.read("trade_account", **self._where)["equity"]
obs, _ = self._observe()
return obs, {"start_ms": start}
def step(self, action):
_, legs = self._observe()
refused = None
if action in (1, 2) and len(legs) < self.max_legs:
side = "buy" if action == 1 else "sell"
answer = self.engine.call("order_market", bench=self.bench, symbol=self.symbol, side=side, volume=self.leg_lots)
refused = answer["last_answer"].get("reason")
elif action == 3 and legs:
self.engine.call("order_close", bench=self.bench, ticket=min(p["ticket"] for p in legs))
elif action == 4 and legs:
self.engine.call("order_close_all", bench=self.bench)
before, peak_before = self.equity, self.peak
closed = self.engine.next_close(self.bench, "M5", [self.symbol]) # five minutes, tick by tick
obs, legs = self._observe()
self.steps += 1
# ---- the reward: yours to design. Here: the equity's change, less new drawdown. ------
new_drawdown = max(0.0, (peak_before - self.equity) - (peak_before - before))
reward = (self.equity - before) - 0.5 * new_drawdown
terminated = self.equity <= 0.5 * self.opening
truncated = closed is None or self.steps >= self.episode_steps
info = {"equity": self.equity, "legs": len(legs), "refused": refused}
return obs, float(reward), bool(terminated), bool(truncated), info
if __name__ == "__main__":
from gymnasium.utils.env_checker import check_env
workspace, store = _native.make_tape(tempfile.mkdtemp(prefix="bentrix-practice-"))
with Local(workspace=workspace, store=store) as engine:
bench = engine.call("get_state")["laboratories"][0]["benches"][0]["uri"]
env = LegsEnv(engine, bench, "XAUUSD")
check_env(env, skip_render_check=True) # Gymnasium's own contract check
print("Gymnasium's check passed")
def episode(seed):
rng = np.random.default_rng(seed)
obs, info = env.reset(seed=seed)
total, done = 0.0, False
while not done:
obs, reward, terminated, truncated, info = env.step(int(rng.integers(5)))
total += reward
done = terminated or truncated
return round(total, 4), round(info["equity"], 2), info["legs"]
print("seed 1:", episode(1))
print("seed 2:", episode(2))
print("seed 1 again:", episode(1))
Run it — python my_env.py — and it prints:
Gymnasium's check passed
seed 1: (-27.261, 9985.16, 2)
seed 2: (-27.649, 9987.62, 2)
seed 1 again: (-27.261, 9985.16, 2)
Three things are shown there. Gymnasium's own checker accepts the environment, so any library written for Gymnasium will too. Two seeds give two different episodes. And the same seed gives the same episode, to the cent: the start is drawn from the seed, the venue is deterministic, and a reset undoes everything the episode before it did.
The policy in that test picks actions at random, so its rewards are those of random trading with costs: negative.
03How it works, piece by piece
The observation is built from closed candles only. bars_window answers several timeframes cut at one instant — the workbench's clock. A candle is in rows only if it had closed by then; the candle still forming is never among them. So an observation cannot contain a price from the future, whatever you compute from it. Several timeframes without look-ahead shows this with a test.
An action becomes orders. Action 1 sends order_market; action 3 closes one position by its ticket; action 4 closes all. Because each leg is a position of its own, the agent can hold longs and shorts together and close them in any order. The whole list of operations is on orders, legs and exposure.
The order fills during the step, not before it. step sends the order and then calls next_close, which moves the clock five minutes, tick by tick. The order fills on the first tick of those five minutes. The agent decided on a closed candle and was filled on the next price: the same order of events as in a live market.
A refused order is not hidden. If the venue refuses an order — not enough margin, for instance — last_answer carries the reason, and this environment passes it on in info["refused"]. Your reward function may charge for it, or ignore it.
The reward is plain arithmetic on the account. trade_account gives the balance, equity, margin and free margin after every step. Anything you can compute from those, the legs and the deals can be a reward: a risk-adjusted return, a penalty on exposure, a bonus for closing a leg early. Bentrix computes none of it for you here, and does not need to know what it is.
A reset is a restore. engine.snapshot(bench) in the constructor keeps the untouched workbench in memory; engine.restore at each reset brings it back in about a millisecond, with every order and deal of the previous episode gone. Then engine.advance runs the clock to the start the seed drew.
An episode ends your way. terminated is yours to define — here, half the opening equity lost. truncated here means the episode's length or the end of the recording, where next_close answers None.
04Train on it
The environment is an ordinary Gymnasium environment, so a library's trainer takes it as it is. With Stable-Baselines3 (pip install stable-baselines3), save this beside my_env.py as train_my_env.py:
import tempfile
from stable_baselines3 import PPO
from bentrix import _native
from bentrix.local import Local
from my_env import LegsEnv
workspace, store = _native.make_tape(tempfile.mkdtemp(prefix="bentrix-practice-"))
with Local(workspace=workspace, store=store) as engine:
bench = engine.call("get_state")["laboratories"][0]["benches"][0]["uri"]
env = LegsEnv(engine, bench, "XAUUSD")
model = PPO("MlpPolicy", env, n_steps=240, batch_size=60, seed=0, verbose=0)
model.learn(total_timesteps=1_200)
obs, info = env.reset(seed=100)
action, _ = model.predict(obs, deterministic=True)
print("trained for 1,200 steps; first action on a new seed:", int(action))
trained for 1,200 steps; first action on a new seed: 1
It took about 25 seconds on a desktop computer without a graphics card. Any other library written for Gymnasium, or a loop you write yourself with PyTorch or TensorFlow, takes it the same way: none of them needs anything from Bentrix beyond reset and step. Only Stable-Baselines3 was run for this page.
Twelve hundred steps teach a policy nothing worth having; the point is that the loop runs. For what makes a training result believable — test seeds the training never saw, at least ten of them, a baseline to beat — read evaluating a policy honestly.
05Make it yours
- Another observation. Add frames to
bars_window("M1","M15","H4","D1", or a custom interval such as"M12"), read an indicator's values withbentrix.data.indicator, or add features from your own files. The shape inobservation_spacemust match what_observereturns. - Other actions. A
Boxfor a continuous size, aMultiDiscretefor a market and a side, aDictwith a stop distance. Translate each into the order tools. - Several markets. One workbench holds many markets under one account. Pass them all to
next_closeandbars_window(symbols=[…]); margin and equity are shared, as on a real account. - Other conditions. Train on a workbench with slippage, latency and a wider spread: slippage, latency and spread.
- Many at once. One environment per workbench, stepped together: many environments at once.
06Good to know
- One step of this environment took about 12 milliseconds on a desktop computer: it reads the candles twice (before acting, to count the legs, and after) and sends an order. Reading the candles once a step, and the book alone before acting, is the first thing to try when training speed matters.
- An environment holds its workbench for itself. Two environments on one workbench would undo each other's episodes.
- The engine is used from one thread — the one that opened it.