Bentrix Docs
HomePricingDashboard

With Gymnasium and Stable-Baselines3

The environment as a Gymnasium environment, trained with PPO from Stable-Baselines3, then evaluated on seeds it never saw — one Python program, start to end.

In Python the environment is also a ready Gymnasium environment — bentrix.gym.TradingEnv — so any library written for Gymnasium trains on it: Stable-Baselines3, CleanRL, RLlib, your own. It is the same environment the other languages call, not a copy: every step goes to Bentrix and is filled on the workbench's venue.

01Install

The Python SDK with the Gym's libraries, then Stable-Baselines3 (PyTorch's CPU build is enough to start):

pip install "bentrix[gym]"
pip install stable-baselines3

02The pieces

PieceWhat it does
bentrix.connect(name=…)pairs with the Bentrix open on this computer
bentrix.live.Remote(b)lets TradingEnv call that Bentrix
TradingEnv(bench, …, local=Remote(b))the environment: reset() → (obs, info), step(a) → (obs, reward, terminated, truncated, info)
gymnasium.wrappers.FlattenObservationthe observation's two arrays as one vector, for an MLP policy
bentrix.gym.evaluate(policy, env, seeds)one episode per seed; the interquartile mean of the scores with a bootstrap interval

TradingEnv takes the same settings as env_make (every setting), with the same defaults: window=32, action="discrete", reward="dsr_dd_penalty@1", episode="window", episode_bars=200 and the rest.

03The program

It trains PPO for 1,500 steps on short episodes, then scores the trained policy and flat — the policy that never trades — on ten test seeds it never trained on. Save it as train_ppo.py and run python train_ppo.py with Bentrix open and a training workbench selected.

import time

import gymnasium as gym
from stable_baselines3 import PPO

import bentrix
from bentrix.gym import TradingEnv, evaluate
from bentrix.live import Remote


b = bentrix.connect(name="my-trainer")
door = Remote(b)
bench = b.workspace.get_state(depth="benches")["selected"]

# A new workbench's engine takes a few seconds to arm.
for _ in range(120):
    if b.agent.resource_read(bench)["engine"] == "ready":
        break
    time.sleep(0.5)

# The environment: hour steps, the last 8 candles, episodes of 24 steps, the default reward.
settings = dict(interval="H1", window=8, episode="window", episode_bars=24)
env = TradingEnv(bench, local=door, **settings)
print("observation:", env.observation_space)
print("actions:", env.action_space)

# Train: PPO on the flattened observation. Seed 1 starts the training episodes' draws.
flat = gym.wrappers.FlattenObservation(env)
flat.reset(seed=1)
model = PPO("MlpPolicy", flat, seed=1, n_steps=256, batch_size=64, n_epochs=4, verbose=0)
model.learn(total_timesteps=1500)
model.save("ppo_bentrix")

# Test on ten seeds the training never used: the trained policy against flat, one episode each.
def trained(obs):
    action, _ = model.predict(gym.spaces.flatten(env.observation_space, obs), deterministic=True)
    return int(action)


test_seeds = range(101, 111)
report = evaluate(trained, env, seeds=test_seeds)
baseline = evaluate(lambda obs: 0, env, seeds=test_seeds)
print("trained PPO, IQM of the log return:", round(report["iqm"], 6), "interval", [round(x, 6) for x in report["interval"]])
print("flat, IQM of the log return:", round(baseline["iqm"], 6))
print("every test score:", [round(x, 6) for x in report["scores"]])
print("the first test episode's ledger hash:", report["ledger_hashes"][0])
env.close()

04What it prints

On a test machine the whole program — 1,500 training steps and twenty test episodes — took about six minutes; most of it is Bentrix replaying each step's hour tick by tick on its venue.

  • the spaces — a Dict of account (3 numbers) and market (8 × 4), and Discrete(3);
  • the trained policy's IQM (interquartile mean) of the test episodes' log returns, with a 95 % interval;
  • flat's, which is 0 — flat never trades and pays nothing;
  • every test score, so the spread is visible and not only the centre;
  • one ledger hash, to replay that test episode exactly.

1,500 steps is a demonstration, not a training run: a policy worth testing usually needs hundreds of thousands. Raise total_timesteps, lengthen episode_bars, and save the model as you go.

05Making the run faster and fairer

  • Several workbenches at once. bentrix.gym.make_vec([bench_a, bench_b, …]) steps one environment per workbench together, as a Gymnasium vector environment — make the workbenches alike (the same laboratory, markets and account) so they are the same conditions.
  • Keep the score honest. Train on some seeds, choose on others, report on a third set — and never choose a model by its test score (evaluating honestly).
  • Record the run. bentrix.track.log_run(identity(ledger_hash=…, reward=…, seed=…, bench=…), params, metrics) writes the identity to MLflow or Weights & Biases when one is installed, so a number on a dashboard leads back to its deals.
  • Another action kind. action="continuous" suits SAC and TD3; action="order" gives a Dict action space for policies that set a stop and a target.

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