Bentrix Docs
HomePricingDashboard

Your first episode

Make an environment, run one whole episode, add up its reward, and prove with the ledger hash that the same seed gives the same deals.

This guide runs one episode from start to end: the loop every learning agent is built on. The "policy" here only ever chooses long — the next guides choose better.

You need Bentrix open, the SDK of your language connected (start in your language), and a laboratory workbench kept for training, selected in Bentrix. Each episode rewinds that workbench and undoes its deals.

01Step 1 — the workbench

The program takes the workbench selected in Bentrix and waits until its engine is ready.

Python

state = client.workspace.get_state(depth="benches")
gym_bench = state["selected"]
for _ in range(120):
    if client.agent.resource_read(gym_bench)["engine"] == "ready":
        break
    time.sleep(0.5)

JSJavaScript

const state = await client.workspace.getState({ depth: "benches" });
const gym_bench = state.selected;
for (let w = 0; w < 120; w++) {
  if ((await client.agent.resourceRead({ uri: gym_bench })).engine === 'ready') break;
  await new Promise((r) => setTimeout(r, 500));
}

C#C#

var state = await client.Workspace.GetState(depth: "benches");
var gym_bench = state!["selected"]?.GetValue<string>() ?? "";
for (var w = 0; w < 120; w++)
{
    if ((await client.Agent.ResourceRead(gym_bench))!["engine"]!.GetValue<string>() == "ready") break;
    await Task.Delay(500);
}

GOGo

state := must(client.Workspace.GetState(ctx, mcp.WorkspaceGetStateArgs{Depth: mcp.Ptr[string]("benches")}))
gym_bench := text(at(state, "selected"))
for w := 0; w < 120; w++ {
	if at(must(client.Agent.ResourceRead(ctx, mcp.AgentResourceReadArgs{Uri: gym_bench})), "engine") == "ready" {
		break
	}
	time.Sleep(500 * time.Millisecond)
}

Java

Object state = client.workspace.getState(new Bentrix.WorkspaceApi.GetStateArgs().depth("benches"));
String gym_bench = (String) at(state, "selected");
for (int w = 0; w < 120; w++) {
    if ("ready".equals(at(client.agent.resourceRead(new Bentrix.AgentApi.ResourceReadArgs(gym_bench)), "engine"))) break;
    Thread.sleep(500);
}

C++C++

auto state = client.workspace.get_state(WorkspaceApi::GetStateArgs().depth("benches"));
auto gym_bench = (state["selected"].is_string() ? state["selected"].str() : std::string());
for (int w = 0; w < 120; w++) {
    if (client.agent.resource_read(AgentApi::ResourceReadArgs(gym_bench))["engine"].str() == "ready") break;
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
}

Julia

state = client.workspace.get_state(; depth = "benches")
gym_bench = state["selected"]
for _ in 1:120
    client.agent.resource_read(gym_bench)["engine"] == "ready" && break
    sleep(0.5)
end

RR

state <- client$workspace$get_state(depth = "benches")
gym_bench <- state$selected
for (w in 1:120) {
  if (client$agent$resource_read(gym_bench)$engine == "ready") break
  Sys.sleep(0.5)
}

RRust

let state = client.workspace().get_state(mcp::WorkspaceGetStateArgs::new().depth("benches"))?;
let gym_bench = state["selected"].as_str().unwrap_or_default().to_string();
for _ in 0..120 {
    if client.agent().resource_read(mcp::AgentResourceReadArgs::new(gym_bench.clone()))?["engine"] == "ready" {
        break;
    }
    std::thread::sleep(std::time::Duration::from_millis(500));
}

02Step 2 — the environment

A step of one hour, an observation of the last 8 candles, episodes of 24 steps, and the reward in money (pnl@1) so it is easy to read.

Python

made = client.strategy.env_make(gym_bench, episode="window", episode_bars=24, interval="H1", reward="pnl@1", window=8)
env_id = made["env"]
print("market:", made["symbol"])
print("actions:", made["action_space"])

JSJavaScript

const made = await client.strategy.envMake({ bench: gym_bench, episode: "window", episode_bars: 24, interval: "H1", reward: "pnl@1", window: 8 });
const env_id = made.env;
console.log("market:", made.symbol);
console.log("actions:", made.action_space);

C#C#

var made = await client.Strategy.EnvMake(gym_bench, episode: "window", episodeBars: 24, interval: "H1", reward: "pnl@1", window: 8);
var env_id = made!["env"]?.GetValue<string>() ?? "";
Console.WriteLine($"market: {made!["symbol"]!}");
Console.WriteLine($"actions: {made!["action_space"]!}");

GOGo

made := must(client.Strategy.EnvMake(ctx, mcp.StrategyEnvMakeArgs{Bench: gym_bench, Episode: mcp.Ptr[string]("window"), EpisodeBars: mcp.Ptr[int64](24), Interval: mcp.Ptr[string]("H1"), Reward: mcp.Ptr[string]("pnl@1"), Window: mcp.Ptr[int64](8)}))
env_id := text(at(made, "env"))
fmt.Println("market:", at(made, "symbol"))
fmt.Println("actions:", at(made, "action_space"))

Java

Object made = client.strategy.envMake(new Bentrix.StrategyApi.EnvMakeArgs(gym_bench).episode("window").episodeBars(24L).interval("H1").reward("pnl@1").window(8L));
String env_id = (String) at(made, "env");
System.out.println("market:" + " " + at(made, "symbol"));
System.out.println("actions:" + " " + at(made, "action_space"));

C++C++

auto made = client.strategy.env_make(StrategyApi::EnvMakeArgs(gym_bench).episode("window").episode_bars(24).interval("H1").reward("pnl@1").window(8));
auto env_id = (made["env"].is_string() ? made["env"].str() : std::string());
std::cout << "market:" << " " << made["symbol"].dump() << std::endl;
std::cout << "actions:" << " " << made["action_space"].dump() << std::endl;

Julia

made = client.strategy.env_make(gym_bench; episode = "window", episode_bars = 24, interval = "H1", reward = "pnl@1", window = 8)
env_id = made["env"]
println("market:", " ", made["symbol"])
println("actions:", " ", made["action_space"])

RR

made <- client$strategy$env_make(gym_bench, episode = "window", episode_bars = 24, interval = "H1", reward = "pnl@1", window = 8)
env_id <- made$env
cat("market:", format(made$symbol), "\n")
cat("actions:", format(made$action_space), "\n")

RRust

let made = client.strategy().env_make(mcp::StrategyEnvMakeArgs::new(gym_bench.clone()).episode("window").episode_bars(24).interval("H1").reward("pnl@1").window(8))?;
let env_id = made["env"].as_str().unwrap_or_default().to_string();
println!("market: {}", made["symbol"]);
println!("actions: {}", made["action_space"]);

03Step 3 — one whole episode

env_reset starts the episode; the loop calls env_step until the episode says it is over — terminated (ruin) or truncated (its 24 steps are done). Each step's reward is added to a total.

Python

now = client.strategy.env_reset(env_id, seed=7)
print("the episode starts at:", now["info"]["start_ms"])
print("opening equity:", now["info"]["opening"])
total = 0.0
steps = 0
for _ in range(1000):
    now = client.strategy.env_step(env_id, 1)
    r = now["reward"]
    total += r
    steps += 1
    if now["terminated"] or now["truncated"]: break
print("steps:", steps)
print("total reward:", total)
print("closing equity:", now["info"]["equity"])

JSJavaScript

let now = await client.strategy.envReset({ env: env_id, seed: 7 });
console.log("the episode starts at:", now.info.start_ms);
console.log("opening equity:", now.info.opening);
let total = 0.0;
let steps = 0;
for (let i0 = 0; i0 < 1000; i0++) {
  now = await client.strategy.envStep({ env: env_id, action: 1 });
  const r = now.reward;
  total += r;
  steps += 1;
  if (now.terminated || now.truncated) break;
}
console.log("steps:", steps);
console.log("total reward:", total);
console.log("closing equity:", now.info.equity);

C#C#

var now = await client.Strategy.EnvReset(env_id, seed: 7);
Console.WriteLine($"the episode starts at: {now!["info"]!["start_ms"]!}");
Console.WriteLine($"opening equity: {now!["info"]!["opening"]!}");
var total = 0.0;
var steps = 0;
for (var i0 = 0; i0 < 1000; i0++)
{
    now = await client.Strategy.EnvStep(env_id, 1);
    var r = now!["reward"]!.GetValue<double>();
    total += r;
    steps += 1;
    if (now!["terminated"]!.GetValue<bool>() || now!["truncated"]!.GetValue<bool>()) break;
}
Console.WriteLine($"steps: {steps}");
Console.WriteLine($"total reward: {total}");
Console.WriteLine($"closing equity: {now!["info"]!["equity"]!}");

GOGo

var now any = must(client.Strategy.EnvReset(ctx, mcp.StrategyEnvResetArgs{Env: env_id, Seed: mcp.Ptr[int64](7)}))
fmt.Println("the episode starts at:", at(now, "info", "start_ms"))
fmt.Println("opening equity:", at(now, "info", "opening"))
total := float64(0.0)
steps := int64(0)
for i0 := 0; i0 < 1000; i0++ {
	now = must(client.Strategy.EnvStep(ctx, mcp.StrategyEnvStepArgs{Env: env_id, Action: 1}))
	r := num(at(now, "reward"))
	total += r
	steps += int64(1)
	if at(now, "terminated") == true || at(now, "truncated") == true {
		break
	}
}
fmt.Println("steps:", steps)
fmt.Println("total reward:", total)
fmt.Println("closing equity:", at(now, "info", "equity"))

Java

Object now = client.strategy.envReset(new Bentrix.StrategyApi.EnvResetArgs(env_id).seed(7L));
System.out.println("the episode starts at:" + " " + at(now, "info", "start_ms"));
System.out.println("opening equity:" + " " + at(now, "info", "opening"));
double total = 0.0;
long steps = 0L;
for (int i0 = 0; i0 < 1000; i0++) {
    now = client.strategy.envStep(new Bentrix.StrategyApi.EnvStepArgs(env_id, 1));
    double r = ((Number) at(now, "reward")).doubleValue();
    total += r;
    steps += 1;
    if (Boolean.TRUE.equals(at(now, "terminated")) || Boolean.TRUE.equals(at(now, "truncated"))) break;
}
System.out.println("steps:" + " " + steps);
System.out.println("total reward:" + " " + total);
System.out.println("closing equity:" + " " + at(now, "info", "equity"));

C++C++

Json now = client.strategy.env_reset(StrategyApi::EnvResetArgs(env_id).seed(7));
std::cout << "the episode starts at:" << " " << now["info"]["start_ms"].dump() << std::endl;
std::cout << "opening equity:" << " " << now["info"]["opening"].dump() << std::endl;
double total = 0.0;
int64_t steps = 0;
for (int i0 = 0; i0 < 1000; i0++) {
    now = client.strategy.env_step(StrategyApi::EnvStepArgs(env_id, 1));
    auto r = now["reward"].num();
    total += r;
    steps += 1;
    if (now["terminated"] == Json(true) || now["truncated"] == Json(true)) break;
}
std::cout << "steps:" << " " << steps << std::endl;
std::cout << "total reward:" << " " << total << std::endl;
std::cout << "closing equity:" << " " << now["info"]["equity"].dump() << std::endl;

Julia

now = client.strategy.env_reset(env_id; seed = 7)
println("the episode starts at:", " ", now["info"]["start_ms"])
println("opening equity:", " ", now["info"]["opening"])
total = 0.0
steps = 0
for _ in 1:1000
    global now = client.strategy.env_step(env_id, 1)
    r = now["reward"]
    global total += r
    global steps += 1
    (now["terminated"] || now["truncated"]) && break
end
println("steps:", " ", steps)
println("total reward:", " ", total)
println("closing equity:", " ", now["info"]["equity"])

RR

now <- client$strategy$env_reset(env_id, seed = 7)
cat("the episode starts at:", format(now$info$start_ms), "\n")
cat("opening equity:", format(now$info$opening), "\n")
total <- 0.0
steps <- 0
for (k in seq_len(1000)) {
  now <- client$strategy$env_step(env_id, 1)
  r <- now$reward
  total <- total + r
  steps <- steps + 1
  if (isTRUE(now$terminated) || isTRUE(now$truncated)) break
}
cat("steps:", format(steps), "\n")
cat("total reward:", format(total), "\n")
cat("closing equity:", format(now$info$equity), "\n")

RRust

let mut now = client.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env_id.clone()).seed(7))?;
println!("the episode starts at: {}", now["info"]["start_ms"]);
println!("opening equity: {}", now["info"]["opening"]);
let mut total: f64 = 0.0;
let mut steps: i64 = 0;
for _ in 0..1000 {
    now = client.strategy().env_step(mcp::StrategyEnvStepArgs::new(env_id.clone(), 1))?;
    let r = now["reward"].as_f64().unwrap_or(f64::NAN);
    total += r;
    steps += 1;
    if now["terminated"] == true || now["truncated"] == true { break; }
}
println!("steps: {}", steps);
println!("total reward: {}", total);
println!("closing equity: {}", now["info"]["equity"]);

With pnl@1 the total reward is the money the episode made or lost — the closing equity minus the opening equity, after the spread and the commission.

04Step 4 — the same seed, the same deals

The ledger hash fingerprints every deal. Run the same seed and the same actions again — here in one call, run_episode, with 24 longs — and the hash is the same.

Python

first_hash = now["info"]["ledger_hash"]
again = client.strategy.run_episode(env_id, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], seed=7)
second_hash = again["ledger_hash"]
print("first run: ", first_hash)
print("second run:", second_hash)
client.strategy.env_close(env_id)

JSJavaScript

const first_hash = now.info.ledger_hash;
const again = await client.strategy.runEpisode({ env: env_id, actions: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], seed: 7 });
const second_hash = again.ledger_hash;
console.log("first run: ", first_hash);
console.log("second run:", second_hash);
await client.strategy.envClose({ env: env_id });

C#C#

var first_hash = now!["info"]!["ledger_hash"]?.GetValue<string>() ?? "";
var again = await client.Strategy.RunEpisode(env_id, new object?[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, seed: 7);
var second_hash = again!["ledger_hash"]?.GetValue<string>() ?? "";
Console.WriteLine($"first run:  {first_hash}");
Console.WriteLine($"second run: {second_hash}");
await client.Strategy.EnvClose(env_id);

GOGo

first_hash := text(at(now, "info", "ledger_hash"))
again := must(client.Strategy.RunEpisode(ctx, mcp.StrategyRunEpisodeArgs{Env: env_id, Actions: []any{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, Seed: mcp.Ptr[int64](7)}))
second_hash := text(at(again, "ledger_hash"))
fmt.Println("first run: ", first_hash)
fmt.Println("second run:", second_hash)
_ = must(client.Strategy.EnvClose(ctx, mcp.StrategyEnvCloseArgs{Env: env_id}))

Java

String first_hash = (String) at(now, "info", "ledger_hash");
Object again = client.strategy.runEpisode(new Bentrix.StrategyApi.RunEpisodeArgs(env_id, java.util.Arrays.asList(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)).seed(7L));
String second_hash = (String) at(again, "ledger_hash");
System.out.println("first run: " + " " + first_hash);
System.out.println("second run:" + " " + second_hash);
client.strategy.envClose(new Bentrix.StrategyApi.EnvCloseArgs(env_id));

C++C++

auto first_hash = (now["info"]["ledger_hash"].is_string() ? now["info"]["ledger_hash"].str() : std::string());
auto again = client.strategy.run_episode(StrategyApi::RunEpisodeArgs(env_id, Json::Array{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}).seed(7));
auto second_hash = (again["ledger_hash"].is_string() ? again["ledger_hash"].str() : std::string());
std::cout << "first run: " << " " << first_hash << std::endl;
std::cout << "second run:" << " " << second_hash << std::endl;
client.strategy.env_close(StrategyApi::EnvCloseArgs(env_id));

Julia

first_hash = now["info"]["ledger_hash"]
again = client.strategy.run_episode(env_id, Any[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; seed = 7)
second_hash = again["ledger_hash"]
println("first run: ", " ", first_hash)
println("second run:", " ", second_hash)
client.strategy.env_close(env_id)

RR

first_hash <- now$info$ledger_hash
again <- client$strategy$run_episode(env_id, list(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), seed = 7)
second_hash <- again$ledger_hash
cat("first run: ", format(first_hash), "\n")
cat("second run:", format(second_hash), "\n")
client$strategy$env_close(env_id)

RRust

let first_hash = now["info"]["ledger_hash"].as_str().unwrap_or_default().to_string();
let again = client.strategy().run_episode(mcp::StrategyRunEpisodeArgs::new(env_id.clone(), serde_json::json!([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])).seed(7))?;
let second_hash = again["ledger_hash"].as_str().unwrap_or_default().to_string();
println!("first run:  {}", first_hash);
println!("second run: {}", second_hash);
client.strategy().env_close(mcp::StrategyEnvCloseArgs::new(env_id.clone()))?;

The two lines print the same hash. Change one action, or the seed, and it changes.

05The whole program

Python

import time
import bentrix

client = bentrix.connect(name="my-agent")

state = client.workspace.get_state(depth="benches")
gym_bench = state["selected"]
for _ in range(120):
    if client.agent.resource_read(gym_bench)["engine"] == "ready":
        break
    time.sleep(0.5)
made = client.strategy.env_make(gym_bench, episode="window", episode_bars=24, interval="H1", reward="pnl@1", window=8)
env_id = made["env"]
print("market:", made["symbol"])
print("actions:", made["action_space"])
now = client.strategy.env_reset(env_id, seed=7)
print("the episode starts at:", now["info"]["start_ms"])
print("opening equity:", now["info"]["opening"])
total = 0.0
steps = 0
for _ in range(1000):
    now = client.strategy.env_step(env_id, 1)
    r = now["reward"]
    total += r
    steps += 1
    if now["terminated"] or now["truncated"]: break
print("steps:", steps)
print("total reward:", total)
print("closing equity:", now["info"]["equity"])
first_hash = now["info"]["ledger_hash"]
again = client.strategy.run_episode(env_id, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], seed=7)
second_hash = again["ledger_hash"]
print("first run: ", first_hash)
print("second run:", second_hash)
client.strategy.env_close(env_id)

JSJavaScript

const { connect } = require('bentrix/mcp');

(async () => {
  const client = await connect({ name: 'my-agent' });

  const state = await client.workspace.getState({ depth: "benches" });
  const gym_bench = state.selected;
  for (let w = 0; w < 120; w++) {
    if ((await client.agent.resourceRead({ uri: gym_bench })).engine === 'ready') break;
    await new Promise((r) => setTimeout(r, 500));
  }
  const made = await client.strategy.envMake({ bench: gym_bench, episode: "window", episode_bars: 24, interval: "H1", reward: "pnl@1", window: 8 });
  const env_id = made.env;
  console.log("market:", made.symbol);
  console.log("actions:", made.action_space);
  let now = await client.strategy.envReset({ env: env_id, seed: 7 });
  console.log("the episode starts at:", now.info.start_ms);
  console.log("opening equity:", now.info.opening);
  let total = 0.0;
  let steps = 0;
  for (let i0 = 0; i0 < 1000; i0++) {
    now = await client.strategy.envStep({ env: env_id, action: 1 });
    const r = now.reward;
    total += r;
    steps += 1;
    if (now.terminated || now.truncated) break;
  }
  console.log("steps:", steps);
  console.log("total reward:", total);
  console.log("closing equity:", now.info.equity);
  const first_hash = now.info.ledger_hash;
  const again = await client.strategy.runEpisode({ env: env_id, actions: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], seed: 7 });
  const second_hash = again.ledger_hash;
  console.log("first run: ", first_hash);
  console.log("second run:", second_hash);
  await client.strategy.envClose({ env: env_id });
})();

C#C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bentrix.Mcp;

using var client = await BentrixClient.ConnectAsync("my-agent");

var state = await client.Workspace.GetState(depth: "benches");
var gym_bench = state!["selected"]?.GetValue<string>() ?? "";
for (var w = 0; w < 120; w++)
{
    if ((await client.Agent.ResourceRead(gym_bench))!["engine"]!.GetValue<string>() == "ready") break;
    await Task.Delay(500);
}
var made = await client.Strategy.EnvMake(gym_bench, episode: "window", episodeBars: 24, interval: "H1", reward: "pnl@1", window: 8);
var env_id = made!["env"]?.GetValue<string>() ?? "";
Console.WriteLine($"market: {made!["symbol"]!}");
Console.WriteLine($"actions: {made!["action_space"]!}");
var now = await client.Strategy.EnvReset(env_id, seed: 7);
Console.WriteLine($"the episode starts at: {now!["info"]!["start_ms"]!}");
Console.WriteLine($"opening equity: {now!["info"]!["opening"]!}");
var total = 0.0;
var steps = 0;
for (var i0 = 0; i0 < 1000; i0++)
{
    now = await client.Strategy.EnvStep(env_id, 1);
    var r = now!["reward"]!.GetValue<double>();
    total += r;
    steps += 1;
    if (now!["terminated"]!.GetValue<bool>() || now!["truncated"]!.GetValue<bool>()) break;
}
Console.WriteLine($"steps: {steps}");
Console.WriteLine($"total reward: {total}");
Console.WriteLine($"closing equity: {now!["info"]!["equity"]!}");
var first_hash = now!["info"]!["ledger_hash"]?.GetValue<string>() ?? "";
var again = await client.Strategy.RunEpisode(env_id, new object?[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, seed: 7);
var second_hash = again!["ledger_hash"]?.GetValue<string>() ?? "";
Console.WriteLine($"first run:  {first_hash}");
Console.WriteLine($"second run: {second_hash}");
await client.Strategy.EnvClose(env_id);

GOGo

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"bentrix/mcp"
)

// at reads a field or an element of an answer: at(v, "laboratories", 0, "uri").
func at(v any, path ...any) any {
	for _, p := range path {
		switch k := p.(type) {
		case string:
			m, _ := v.(map[string]any)
			v = m[k]
		case int:
			a, _ := v.([]any)
			if k >= len(a) {
				return nil
			}
			v = a[k]
		}
	}
	return v
}

// must stops the program with Bentrix's own sentence when a call is refused.
func must[T any](v T, err error) T {
	if err != nil {
		panic(err)
	}
	return v
}

// num reads a number of an answer, however the client decoded it.
func num(v any) float64 {
	switch n := v.(type) {
	case json.Number:
		f, _ := n.Float64()
		return f
	case float64:
		return n
	}
	return 0
}

// text reads a text of an answer; nothing is "".
func text(v any) string {
	s, _ := v.(string)
	return s
}

func main() {
	ctx := context.Background()
	client, err := mcp.Connect(ctx, "my-agent")
	if err != nil {
		panic(err)
	}

	state := must(client.Workspace.GetState(ctx, mcp.WorkspaceGetStateArgs{Depth: mcp.Ptr[string]("benches")}))
	gym_bench := text(at(state, "selected"))
	for w := 0; w < 120; w++ {
		if at(must(client.Agent.ResourceRead(ctx, mcp.AgentResourceReadArgs{Uri: gym_bench})), "engine") == "ready" {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}
	made := must(client.Strategy.EnvMake(ctx, mcp.StrategyEnvMakeArgs{Bench: gym_bench, Episode: mcp.Ptr[string]("window"), EpisodeBars: mcp.Ptr[int64](24), Interval: mcp.Ptr[string]("H1"), Reward: mcp.Ptr[string]("pnl@1"), Window: mcp.Ptr[int64](8)}))
	env_id := text(at(made, "env"))
	fmt.Println("market:", at(made, "symbol"))
	fmt.Println("actions:", at(made, "action_space"))
	var now any = must(client.Strategy.EnvReset(ctx, mcp.StrategyEnvResetArgs{Env: env_id, Seed: mcp.Ptr[int64](7)}))
	fmt.Println("the episode starts at:", at(now, "info", "start_ms"))
	fmt.Println("opening equity:", at(now, "info", "opening"))
	total := float64(0.0)
	steps := int64(0)
	for i0 := 0; i0 < 1000; i0++ {
		now = must(client.Strategy.EnvStep(ctx, mcp.StrategyEnvStepArgs{Env: env_id, Action: 1}))
		r := num(at(now, "reward"))
		total += r
		steps += int64(1)
		if at(now, "terminated") == true || at(now, "truncated") == true {
			break
		}
	}
	fmt.Println("steps:", steps)
	fmt.Println("total reward:", total)
	fmt.Println("closing equity:", at(now, "info", "equity"))
	first_hash := text(at(now, "info", "ledger_hash"))
	again := must(client.Strategy.RunEpisode(ctx, mcp.StrategyRunEpisodeArgs{Env: env_id, Actions: []any{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, Seed: mcp.Ptr[int64](7)}))
	second_hash := text(at(again, "ledger_hash"))
	fmt.Println("first run: ", first_hash)
	fmt.Println("second run:", second_hash)
	_ = must(client.Strategy.EnvClose(ctx, mcp.StrategyEnvCloseArgs{Env: env_id}))
	_ = []any{state, gym_bench, made, env_id, now, total, steps, first_hash, again, second_hash}
}

Java

import bentrix.mcp.Bentrix;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public final class MyAgent {
    // at reads a field or an element of an answer: at(v, "laboratories", 0, "uri").
    @SuppressWarnings("unchecked")
    static Object at(Object v, Object... path) {
        for (Object p : path) {
            v = p instanceof Integer i ? ((List<Object>) v).get(i) : ((Map<String, Object>) v).get(p);
        }
        return v;
    }

    public static void main(String[] argv) throws Exception {
        try (Bentrix client = Bentrix.connect("my-agent")) {

            Object state = client.workspace.getState(new Bentrix.WorkspaceApi.GetStateArgs().depth("benches"));
            String gym_bench = (String) at(state, "selected");
            for (int w = 0; w < 120; w++) {
                if ("ready".equals(at(client.agent.resourceRead(new Bentrix.AgentApi.ResourceReadArgs(gym_bench)), "engine"))) break;
                Thread.sleep(500);
            }
            Object made = client.strategy.envMake(new Bentrix.StrategyApi.EnvMakeArgs(gym_bench).episode("window").episodeBars(24L).interval("H1").reward("pnl@1").window(8L));
            String env_id = (String) at(made, "env");
            System.out.println("market:" + " " + at(made, "symbol"));
            System.out.println("actions:" + " " + at(made, "action_space"));
            Object now = client.strategy.envReset(new Bentrix.StrategyApi.EnvResetArgs(env_id).seed(7L));
            System.out.println("the episode starts at:" + " " + at(now, "info", "start_ms"));
            System.out.println("opening equity:" + " " + at(now, "info", "opening"));
            double total = 0.0;
            long steps = 0L;
            for (int i0 = 0; i0 < 1000; i0++) {
                now = client.strategy.envStep(new Bentrix.StrategyApi.EnvStepArgs(env_id, 1));
                double r = ((Number) at(now, "reward")).doubleValue();
                total += r;
                steps += 1;
                if (Boolean.TRUE.equals(at(now, "terminated")) || Boolean.TRUE.equals(at(now, "truncated"))) break;
            }
            System.out.println("steps:" + " " + steps);
            System.out.println("total reward:" + " " + total);
            System.out.println("closing equity:" + " " + at(now, "info", "equity"));
            String first_hash = (String) at(now, "info", "ledger_hash");
            Object again = client.strategy.runEpisode(new Bentrix.StrategyApi.RunEpisodeArgs(env_id, java.util.Arrays.asList(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)).seed(7L));
            String second_hash = (String) at(again, "ledger_hash");
            System.out.println("first run: " + " " + first_hash);
            System.out.println("second run:" + " " + second_hash);
            client.strategy.envClose(new Bentrix.StrategyApi.EnvCloseArgs(env_id));
        }
    }
}

C++C++

#include <algorithm>
#include <chrono>
#include <iostream>
#include <thread>
#include "bentrix_mcp_generated.hpp"
using namespace bentrix::mcp;

int main() {
    auto client = Bentrix::connect("my-agent");

    auto state = client.workspace.get_state(WorkspaceApi::GetStateArgs().depth("benches"));
    auto gym_bench = (state["selected"].is_string() ? state["selected"].str() : std::string());
    for (int w = 0; w < 120; w++) {
        if (client.agent.resource_read(AgentApi::ResourceReadArgs(gym_bench))["engine"].str() == "ready") break;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    auto made = client.strategy.env_make(StrategyApi::EnvMakeArgs(gym_bench).episode("window").episode_bars(24).interval("H1").reward("pnl@1").window(8));
    auto env_id = (made["env"].is_string() ? made["env"].str() : std::string());
    std::cout << "market:" << " " << made["symbol"].dump() << std::endl;
    std::cout << "actions:" << " " << made["action_space"].dump() << std::endl;
    Json now = client.strategy.env_reset(StrategyApi::EnvResetArgs(env_id).seed(7));
    std::cout << "the episode starts at:" << " " << now["info"]["start_ms"].dump() << std::endl;
    std::cout << "opening equity:" << " " << now["info"]["opening"].dump() << std::endl;
    double total = 0.0;
    int64_t steps = 0;
    for (int i0 = 0; i0 < 1000; i0++) {
        now = client.strategy.env_step(StrategyApi::EnvStepArgs(env_id, 1));
        auto r = now["reward"].num();
        total += r;
        steps += 1;
        if (now["terminated"] == Json(true) || now["truncated"] == Json(true)) break;
    }
    std::cout << "steps:" << " " << steps << std::endl;
    std::cout << "total reward:" << " " << total << std::endl;
    std::cout << "closing equity:" << " " << now["info"]["equity"].dump() << std::endl;
    auto first_hash = (now["info"]["ledger_hash"].is_string() ? now["info"]["ledger_hash"].str() : std::string());
    auto again = client.strategy.run_episode(StrategyApi::RunEpisodeArgs(env_id, Json::Array{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}).seed(7));
    auto second_hash = (again["ledger_hash"].is_string() ? again["ledger_hash"].str() : std::string());
    std::cout << "first run: " << " " << first_hash << std::endl;
    std::cout << "second run:" << " " << second_hash << std::endl;
    client.strategy.env_close(StrategyApi::EnvCloseArgs(env_id));
}

Julia

using BentrixMCP

client = BentrixMCP.connect("my-agent")

state = client.workspace.get_state(; depth = "benches")
gym_bench = state["selected"]
for _ in 1:120
    client.agent.resource_read(gym_bench)["engine"] == "ready" && break
    sleep(0.5)
end
made = client.strategy.env_make(gym_bench; episode = "window", episode_bars = 24, interval = "H1", reward = "pnl@1", window = 8)
env_id = made["env"]
println("market:", " ", made["symbol"])
println("actions:", " ", made["action_space"])
now = client.strategy.env_reset(env_id; seed = 7)
println("the episode starts at:", " ", now["info"]["start_ms"])
println("opening equity:", " ", now["info"]["opening"])
total = 0.0
steps = 0
for _ in 1:1000
    global now = client.strategy.env_step(env_id, 1)
    r = now["reward"]
    global total += r
    global steps += 1
    (now["terminated"] || now["truncated"]) && break
end
println("steps:", " ", steps)
println("total reward:", " ", total)
println("closing equity:", " ", now["info"]["equity"])
first_hash = now["info"]["ledger_hash"]
again = client.strategy.run_episode(env_id, Any[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; seed = 7)
second_hash = again["ledger_hash"]
println("first run: ", " ", first_hash)
println("second run:", " ", second_hash)
client.strategy.env_close(env_id)

RR

library(bentrixmcp)

client <- connect("my-agent")

state <- client$workspace$get_state(depth = "benches")
gym_bench <- state$selected
for (w in 1:120) {
  if (client$agent$resource_read(gym_bench)$engine == "ready") break
  Sys.sleep(0.5)
}
made <- client$strategy$env_make(gym_bench, episode = "window", episode_bars = 24, interval = "H1", reward = "pnl@1", window = 8)
env_id <- made$env
cat("market:", format(made$symbol), "\n")
cat("actions:", format(made$action_space), "\n")
now <- client$strategy$env_reset(env_id, seed = 7)
cat("the episode starts at:", format(now$info$start_ms), "\n")
cat("opening equity:", format(now$info$opening), "\n")
total <- 0.0
steps <- 0
for (k in seq_len(1000)) {
  now <- client$strategy$env_step(env_id, 1)
  r <- now$reward
  total <- total + r
  steps <- steps + 1
  if (isTRUE(now$terminated) || isTRUE(now$truncated)) break
}
cat("steps:", format(steps), "\n")
cat("total reward:", format(total), "\n")
cat("closing equity:", format(now$info$equity), "\n")
first_hash <- now$info$ledger_hash
again <- client$strategy$run_episode(env_id, list(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), seed = 7)
second_hash <- again$ledger_hash
cat("first run: ", format(first_hash), "\n")
cat("second run:", format(second_hash), "\n")
client$strategy$env_close(env_id)

RRust

use bentrix as mcp;

fn main() -> Result<(), mcp::Error> {
    let client = mcp::connect(Some("my-agent"))?;

    let state = client.workspace().get_state(mcp::WorkspaceGetStateArgs::new().depth("benches"))?;
    let gym_bench = state["selected"].as_str().unwrap_or_default().to_string();
    for _ in 0..120 {
        if client.agent().resource_read(mcp::AgentResourceReadArgs::new(gym_bench.clone()))?["engine"] == "ready" {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    let made = client.strategy().env_make(mcp::StrategyEnvMakeArgs::new(gym_bench.clone()).episode("window").episode_bars(24).interval("H1").reward("pnl@1").window(8))?;
    let env_id = made["env"].as_str().unwrap_or_default().to_string();
    println!("market: {}", made["symbol"]);
    println!("actions: {}", made["action_space"]);
    let mut now = client.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env_id.clone()).seed(7))?;
    println!("the episode starts at: {}", now["info"]["start_ms"]);
    println!("opening equity: {}", now["info"]["opening"]);
    let mut total: f64 = 0.0;
    let mut steps: i64 = 0;
    for _ in 0..1000 {
        now = client.strategy().env_step(mcp::StrategyEnvStepArgs::new(env_id.clone(), 1))?;
        let r = now["reward"].as_f64().unwrap_or(f64::NAN);
        total += r;
        steps += 1;
        if now["terminated"] == true || now["truncated"] == true { break; }
    }
    println!("steps: {}", steps);
    println!("total reward: {}", total);
    println!("closing equity: {}", now["info"]["equity"]);
    let first_hash = now["info"]["ledger_hash"].as_str().unwrap_or_default().to_string();
    let again = client.strategy().run_episode(mcp::StrategyRunEpisodeArgs::new(env_id.clone(), serde_json::json!([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])).seed(7))?;
    let second_hash = again["ledger_hash"].as_str().unwrap_or_default().to_string();
    println!("first run:  {}", first_hash);
    println!("second run: {}", second_hash);
    client.strategy().env_close(mcp::StrategyEnvCloseArgs::new(env_id.clone()))?;
    Ok(())
}

06What to try

  • "seed": 8 — another window of history, another result.
  • "action": 2 in the loop — always short.
  • "reward": "dsr_dd_penalty@1" — the default reward: the total is no longer money, but a risk-aware score.

Next: a rule to beat makes the action depend on the observation.

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