The program learns its own parameter: it tries thresholds on training episodes, keeps the best, then tests it on episodes it never saw — training and testing in nine languages, no library.
Training is choosing a policy's parameters from experience. The simplest real training is a search: try values, score each on training episodes, keep the best. This guide trains the momentum rule's threshold that way — in any language, with no library — and then does what matters most: tests the result on episodes it never trained on.
| Episodes | Used for | |
|---|---|---|
| training | seeds 1, 2, 3 | choosing the threshold |
| test | seeds 101, 102, 103 | judging the choice — never for choosing |
The thresholds tried are 0, 0.001, 0.002 and 0.003. Each is scored by the money it made over the three training episodes.
01Step 1 — the workbench and the environment
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)
made = client.strategy.env_make(gym_bench, episode="window", episode_bars=24, interval="H1", reward="pnl@1", window=8)
env_id = made["env"]JavaScript
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;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);
}
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>() ?? "";Go
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"))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);
}
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");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));
}
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());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
made = client.strategy.env_make(gym_bench; episode = "window", episode_bars = 24, interval = "H1", reward = "pnl@1", window = 8)
env_id = made["env"]R
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$envRust
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();02Step 2 — training: try each threshold, keep the best
For each threshold, three training episodes; their rewards — money, with pnl@1 — add up to its score. A higher score replaces the best so far.
Python
theta = 0.0
best_theta = 0.0
best_score = -1000000000.0
action = 0
for _ in range(4):
score = 0.0
seed = 1
for _ in range(3):
now = client.strategy.env_reset(env_id, seed=seed)
for _ in range(1000):
drift = now["obs"]["market"][0][3]
up = drift + theta
down = drift - theta
action = 0
if up < 0:
action = 1
if down > 0:
action = 2
now = client.strategy.env_step(env_id, action)
r = now["reward"]
score += r
if now["terminated"] or now["truncated"]: break
seed += 1
print("threshold", theta)
print(" scored", score)
better = score - best_score
if better > 0:
best_score = score
best_theta = theta
theta += 0.001
print("trained threshold:", best_theta)JavaScript
let theta = 0.0;
let best_theta = 0.0;
let best_score = -1000000000.0;
let action = 0;
for (let i0 = 0; i0 < 4; i0++) {
let score = 0.0;
let seed = 1;
for (let i1 = 0; i1 < 3; i1++) {
let now = await client.strategy.envReset({ env: env_id, seed });
for (let i2 = 0; i2 < 1000; i2++) {
const drift = now.obs.market[0][3];
const up = drift + theta;
const down = drift - theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = await client.strategy.envStep({ env: env_id, action });
const r = now.reward;
score += r;
if (now.terminated || now.truncated) break;
}
seed += 1;
}
console.log("threshold", theta);
console.log(" scored", score);
const better = score - best_score;
if (better > 0) {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
console.log("trained threshold:", best_theta);C#
var theta = 0.0;
var best_theta = 0.0;
var best_score = -1000000000.0;
var action = 0;
for (var i0 = 0; i0 < 4; i0++)
{
var score = 0.0;
var seed = 1;
for (var i1 = 0; i1 < 3; i1++)
{
var now = await client.Strategy.EnvReset(env_id, seed: seed);
for (var i2 = 0; i2 < 1000; i2++)
{
var drift = now!["obs"]!["market"]![0]![3]!.GetValue<double>();
var up = drift + theta;
var down = drift - theta;
action = 0;
if (up < 0)
{
action = 1;
}
if (down > 0)
{
action = 2;
}
now = await client.Strategy.EnvStep(env_id, action);
var r = now!["reward"]!.GetValue<double>();
score += r;
if (now!["terminated"]!.GetValue<bool>() || now!["truncated"]!.GetValue<bool>()) break;
}
seed += 1;
}
Console.WriteLine($"threshold {theta}");
Console.WriteLine($" scored {score}");
var better = score - best_score;
if (better > 0)
{
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
Console.WriteLine($"trained threshold: {best_theta}");Go
theta := float64(0.0)
best_theta := float64(0.0)
best_score := float64(-1000000000.0)
action := int64(0)
for i0 := 0; i0 < 4; i0++ {
score := float64(0.0)
seed := int64(1)
for i1 := 0; i1 < 3; i1++ {
var now any = must(client.Strategy.EnvReset(ctx, mcp.StrategyEnvResetArgs{Env: env_id, Seed: mcp.Ptr[int64](seed)}))
for i2 := 0; i2 < 1000; i2++ {
drift := num(at(now, "obs", "market", 0, 3))
up := drift + theta
down := drift - theta
action = int64(0)
if up < 0 {
action = int64(1)
}
if down > 0 {
action = int64(2)
}
now = must(client.Strategy.EnvStep(ctx, mcp.StrategyEnvStepArgs{Env: env_id, Action: action}))
r := num(at(now, "reward"))
score += r
if at(now, "terminated") == true || at(now, "truncated") == true {
break
}
}
seed += int64(1)
}
fmt.Println("threshold", theta)
fmt.Println(" scored", score)
better := score - best_score
if better > 0 {
best_score = score
best_theta = theta
}
theta += 0.001
}
fmt.Println("trained threshold:", best_theta)Java
double theta = 0.0;
double best_theta = 0.0;
double best_score = -1000000000.0;
long action = 0L;
for (int i0 = 0; i0 < 4; i0++) {
double score = 0.0;
long seed = 1L;
for (int i1 = 0; i1 < 3; i1++) {
Object now = client.strategy.envReset(new Bentrix.StrategyApi.EnvResetArgs(env_id).seed(seed));
for (int i2 = 0; i2 < 1000; i2++) {
double drift = ((Number) at(now, "obs", "market", 0, 3)).doubleValue();
double up = drift + theta;
double down = drift - theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.envStep(new Bentrix.StrategyApi.EnvStepArgs(env_id, action));
double r = ((Number) at(now, "reward")).doubleValue();
score += r;
if (Boolean.TRUE.equals(at(now, "terminated")) || Boolean.TRUE.equals(at(now, "truncated"))) break;
}
seed += 1;
}
System.out.println("threshold" + " " + theta);
System.out.println(" scored" + " " + score);
double better = score - best_score;
if (better > 0) {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
System.out.println("trained threshold:" + " " + best_theta);C++
double theta = 0.0;
double best_theta = 0.0;
double best_score = -1000000000.0;
int64_t action = 0;
for (int i0 = 0; i0 < 4; i0++) {
double score = 0.0;
int64_t seed = 1;
for (int i1 = 0; i1 < 3; i1++) {
Json now = client.strategy.env_reset(StrategyApi::EnvResetArgs(env_id).seed(seed));
for (int i2 = 0; i2 < 1000; i2++) {
auto drift = now["obs"]["market"][0u][3u].num();
auto up = drift + theta;
auto down = drift - theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.env_step(StrategyApi::EnvStepArgs(env_id, action));
auto r = now["reward"].num();
score += r;
if (now["terminated"] == Json(true) || now["truncated"] == Json(true)) break;
}
seed += 1;
}
std::cout << "threshold" << " " << theta << std::endl;
std::cout << " scored" << " " << score << std::endl;
auto better = score - best_score;
if (better > 0) {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
std::cout << "trained threshold:" << " " << best_theta << std::endl;Julia
theta = 0.0
best_theta = 0.0
best_score = -1000000000.0
action = 0
for _ in 1:4
score = 0.0
seed = 1
for _ in 1:3
now = client.strategy.env_reset(env_id; seed = seed)
for _ in 1:1000
drift = now["obs"]["market"][1][4]
up = drift + theta
down = drift - theta
global action = 0
if up < 0
global action = 1
end
if down > 0
global action = 2
end
now = client.strategy.env_step(env_id, action)
r = now["reward"]
score += r
(now["terminated"] || now["truncated"]) && break
end
seed += 1
end
println("threshold", " ", theta)
println(" scored", " ", score)
better = score - best_score
if better > 0
global best_score = score
global best_theta = theta
end
global theta += 0.001
end
println("trained threshold:", " ", best_theta)R
theta <- 0.0
best_theta <- 0.0
best_score <- -1000000000.0
action <- 0
for (k in seq_len(4)) {
score <- 0.0
seed <- 1
for (k in seq_len(3)) {
now <- client$strategy$env_reset(env_id, seed = seed)
for (k in seq_len(1000)) {
drift <- now$obs$market[[1]][[4]]
up <- drift + theta
down <- drift - theta
action <- 0
if (up < 0) {
action <- 1
}
if (down > 0) {
action <- 2
}
now <- client$strategy$env_step(env_id, action)
r <- now$reward
score <- score + r
if (isTRUE(now$terminated) || isTRUE(now$truncated)) break
}
seed <- seed + 1
}
cat("threshold", format(theta), "\n")
cat(" scored", format(score), "\n")
better <- score - best_score
if (better > 0) {
best_score <- score
best_theta <- theta
}
theta <- theta + 0.001
}
cat("trained threshold:", format(best_theta), "\n")Rust
let mut theta: f64 = 0.0;
let mut best_theta: f64 = 0.0;
let mut best_score: f64 = -1000000000.0;
let mut action: i64 = 0;
for _ in 0..4 {
let mut score: f64 = 0.0;
let mut seed: i64 = 1;
for _ in 0..3 {
let mut now = client.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env_id.clone()).seed(seed.clone()))?;
for _ in 0..1000 {
let drift = now["obs"]["market"][0][3].as_f64().unwrap_or(f64::NAN);
let up = drift + theta;
let down = drift - theta;
action = 0;
if up < 0.0 {
action = 1;
}
if down > 0.0 {
action = 2;
}
now = client.strategy().env_step(mcp::StrategyEnvStepArgs::new(env_id.clone(), action.clone()))?;
let r = now["reward"].as_f64().unwrap_or(f64::NAN);
score += r;
if now["terminated"] == true || now["truncated"] == true { break; }
}
seed += 1;
}
println!("threshold {}", theta);
println!(" scored {}", score);
let better = score - best_score;
if better > 0.0 {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
println!("trained threshold: {}", best_theta);03Step 3 — the test: episodes the training never saw
The trained threshold, on seeds 101 to 103.
Python
test_score = 0.0
test_seed = 101
for _ in range(3):
now = client.strategy.env_reset(env_id, seed=test_seed)
for _ in range(1000):
drift = now["obs"]["market"][0][3]
up = drift + best_theta
down = drift - best_theta
action = 0
if up < 0:
action = 1
if down > 0:
action = 2
now = client.strategy.env_step(env_id, action)
r = now["reward"]
test_score += r
if now["terminated"] or now["truncated"]: break
test_seed += 1
print("on the training episodes:", best_score)
print("on the test episodes:", test_score)
client.strategy.env_close(env_id)JavaScript
let test_score = 0.0;
let test_seed = 101;
for (let i0 = 0; i0 < 3; i0++) {
let now = await client.strategy.envReset({ env: env_id, seed: test_seed });
for (let i1 = 0; i1 < 1000; i1++) {
const drift = now.obs.market[0][3];
const up = drift + best_theta;
const down = drift - best_theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = await client.strategy.envStep({ env: env_id, action });
const r = now.reward;
test_score += r;
if (now.terminated || now.truncated) break;
}
test_seed += 1;
}
console.log("on the training episodes:", best_score);
console.log("on the test episodes:", test_score);
await client.strategy.envClose({ env: env_id });C#
var test_score = 0.0;
var test_seed = 101;
for (var i0 = 0; i0 < 3; i0++)
{
var now = await client.Strategy.EnvReset(env_id, seed: test_seed);
for (var i1 = 0; i1 < 1000; i1++)
{
var drift = now!["obs"]!["market"]![0]![3]!.GetValue<double>();
var up = drift + best_theta;
var down = drift - best_theta;
action = 0;
if (up < 0)
{
action = 1;
}
if (down > 0)
{
action = 2;
}
now = await client.Strategy.EnvStep(env_id, action);
var r = now!["reward"]!.GetValue<double>();
test_score += r;
if (now!["terminated"]!.GetValue<bool>() || now!["truncated"]!.GetValue<bool>()) break;
}
test_seed += 1;
}
Console.WriteLine($"on the training episodes: {best_score}");
Console.WriteLine($"on the test episodes: {test_score}");
await client.Strategy.EnvClose(env_id);Go
test_score := float64(0.0)
test_seed := int64(101)
for i0 := 0; i0 < 3; i0++ {
var now any = must(client.Strategy.EnvReset(ctx, mcp.StrategyEnvResetArgs{Env: env_id, Seed: mcp.Ptr[int64](test_seed)}))
for i1 := 0; i1 < 1000; i1++ {
drift := num(at(now, "obs", "market", 0, 3))
up := drift + best_theta
down := drift - best_theta
action = int64(0)
if up < 0 {
action = int64(1)
}
if down > 0 {
action = int64(2)
}
now = must(client.Strategy.EnvStep(ctx, mcp.StrategyEnvStepArgs{Env: env_id, Action: action}))
r := num(at(now, "reward"))
test_score += r
if at(now, "terminated") == true || at(now, "truncated") == true {
break
}
}
test_seed += int64(1)
}
fmt.Println("on the training episodes:", best_score)
fmt.Println("on the test episodes:", test_score)
_ = must(client.Strategy.EnvClose(ctx, mcp.StrategyEnvCloseArgs{Env: env_id}))Java
double test_score = 0.0;
long test_seed = 101L;
for (int i0 = 0; i0 < 3; i0++) {
Object now = client.strategy.envReset(new Bentrix.StrategyApi.EnvResetArgs(env_id).seed(test_seed));
for (int i1 = 0; i1 < 1000; i1++) {
double drift = ((Number) at(now, "obs", "market", 0, 3)).doubleValue();
double up = drift + best_theta;
double down = drift - best_theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.envStep(new Bentrix.StrategyApi.EnvStepArgs(env_id, action));
double r = ((Number) at(now, "reward")).doubleValue();
test_score += r;
if (Boolean.TRUE.equals(at(now, "terminated")) || Boolean.TRUE.equals(at(now, "truncated"))) break;
}
test_seed += 1;
}
System.out.println("on the training episodes:" + " " + best_score);
System.out.println("on the test episodes:" + " " + test_score);
client.strategy.envClose(new Bentrix.StrategyApi.EnvCloseArgs(env_id));C++
double test_score = 0.0;
int64_t test_seed = 101;
for (int i0 = 0; i0 < 3; i0++) {
Json now = client.strategy.env_reset(StrategyApi::EnvResetArgs(env_id).seed(test_seed));
for (int i1 = 0; i1 < 1000; i1++) {
auto drift = now["obs"]["market"][0u][3u].num();
auto up = drift + best_theta;
auto down = drift - best_theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.env_step(StrategyApi::EnvStepArgs(env_id, action));
auto r = now["reward"].num();
test_score += r;
if (now["terminated"] == Json(true) || now["truncated"] == Json(true)) break;
}
test_seed += 1;
}
std::cout << "on the training episodes:" << " " << best_score << std::endl;
std::cout << "on the test episodes:" << " " << test_score << std::endl;
client.strategy.env_close(StrategyApi::EnvCloseArgs(env_id));Julia
test_score = 0.0
test_seed = 101
for _ in 1:3
now = client.strategy.env_reset(env_id; seed = test_seed)
for _ in 1:1000
drift = now["obs"]["market"][1][4]
up = drift + best_theta
down = drift - best_theta
global action = 0
if up < 0
global action = 1
end
if down > 0
global action = 2
end
now = client.strategy.env_step(env_id, action)
r = now["reward"]
global test_score += r
(now["terminated"] || now["truncated"]) && break
end
global test_seed += 1
end
println("on the training episodes:", " ", best_score)
println("on the test episodes:", " ", test_score)
client.strategy.env_close(env_id)R
test_score <- 0.0
test_seed <- 101
for (k in seq_len(3)) {
now <- client$strategy$env_reset(env_id, seed = test_seed)
for (k in seq_len(1000)) {
drift <- now$obs$market[[1]][[4]]
up <- drift + best_theta
down <- drift - best_theta
action <- 0
if (up < 0) {
action <- 1
}
if (down > 0) {
action <- 2
}
now <- client$strategy$env_step(env_id, action)
r <- now$reward
test_score <- test_score + r
if (isTRUE(now$terminated) || isTRUE(now$truncated)) break
}
test_seed <- test_seed + 1
}
cat("on the training episodes:", format(best_score), "\n")
cat("on the test episodes:", format(test_score), "\n")
client$strategy$env_close(env_id)Rust
let mut test_score: f64 = 0.0;
let mut test_seed: i64 = 101;
for _ in 0..3 {
let mut now = client.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env_id.clone()).seed(test_seed.clone()))?;
for _ in 0..1000 {
let drift = now["obs"]["market"][0][3].as_f64().unwrap_or(f64::NAN);
let up = drift + best_theta;
let down = drift - best_theta;
action = 0;
if up < 0.0 {
action = 1;
}
if down > 0.0 {
action = 2;
}
now = client.strategy().env_step(mcp::StrategyEnvStepArgs::new(env_id.clone(), action.clone()))?;
let r = now["reward"].as_f64().unwrap_or(f64::NAN);
test_score += r;
if now["terminated"] == true || now["truncated"] == true { break; }
}
test_seed += 1;
}
println!("on the training episodes: {}", best_score);
println!("on the test episodes: {}", test_score);
client.strategy().env_close(mcp::StrategyEnvCloseArgs::new(env_id.clone()))?;04The 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"]
theta = 0.0
best_theta = 0.0
best_score = -1000000000.0
action = 0
for _ in range(4):
score = 0.0
seed = 1
for _ in range(3):
now = client.strategy.env_reset(env_id, seed=seed)
for _ in range(1000):
drift = now["obs"]["market"][0][3]
up = drift + theta
down = drift - theta
action = 0
if up < 0:
action = 1
if down > 0:
action = 2
now = client.strategy.env_step(env_id, action)
r = now["reward"]
score += r
if now["terminated"] or now["truncated"]: break
seed += 1
print("threshold", theta)
print(" scored", score)
better = score - best_score
if better > 0:
best_score = score
best_theta = theta
theta += 0.001
print("trained threshold:", best_theta)
test_score = 0.0
test_seed = 101
for _ in range(3):
now = client.strategy.env_reset(env_id, seed=test_seed)
for _ in range(1000):
drift = now["obs"]["market"][0][3]
up = drift + best_theta
down = drift - best_theta
action = 0
if up < 0:
action = 1
if down > 0:
action = 2
now = client.strategy.env_step(env_id, action)
r = now["reward"]
test_score += r
if now["terminated"] or now["truncated"]: break
test_seed += 1
print("on the training episodes:", best_score)
print("on the test episodes:", test_score)
client.strategy.env_close(env_id)JavaScript
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;
let theta = 0.0;
let best_theta = 0.0;
let best_score = -1000000000.0;
let action = 0;
for (let i0 = 0; i0 < 4; i0++) {
let score = 0.0;
let seed = 1;
for (let i1 = 0; i1 < 3; i1++) {
let now = await client.strategy.envReset({ env: env_id, seed });
for (let i2 = 0; i2 < 1000; i2++) {
const drift = now.obs.market[0][3];
const up = drift + theta;
const down = drift - theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = await client.strategy.envStep({ env: env_id, action });
const r = now.reward;
score += r;
if (now.terminated || now.truncated) break;
}
seed += 1;
}
console.log("threshold", theta);
console.log(" scored", score);
const better = score - best_score;
if (better > 0) {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
console.log("trained threshold:", best_theta);
let test_score = 0.0;
let test_seed = 101;
for (let i0 = 0; i0 < 3; i0++) {
let now = await client.strategy.envReset({ env: env_id, seed: test_seed });
for (let i1 = 0; i1 < 1000; i1++) {
const drift = now.obs.market[0][3];
const up = drift + best_theta;
const down = drift - best_theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = await client.strategy.envStep({ env: env_id, action });
const r = now.reward;
test_score += r;
if (now.terminated || now.truncated) break;
}
test_seed += 1;
}
console.log("on the training episodes:", best_score);
console.log("on the test episodes:", test_score);
await client.strategy.envClose({ env: env_id });
})();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>() ?? "";
var theta = 0.0;
var best_theta = 0.0;
var best_score = -1000000000.0;
var action = 0;
for (var i0 = 0; i0 < 4; i0++)
{
var score = 0.0;
var seed = 1;
for (var i1 = 0; i1 < 3; i1++)
{
var now = await client.Strategy.EnvReset(env_id, seed: seed);
for (var i2 = 0; i2 < 1000; i2++)
{
var drift = now!["obs"]!["market"]![0]![3]!.GetValue<double>();
var up = drift + theta;
var down = drift - theta;
action = 0;
if (up < 0)
{
action = 1;
}
if (down > 0)
{
action = 2;
}
now = await client.Strategy.EnvStep(env_id, action);
var r = now!["reward"]!.GetValue<double>();
score += r;
if (now!["terminated"]!.GetValue<bool>() || now!["truncated"]!.GetValue<bool>()) break;
}
seed += 1;
}
Console.WriteLine($"threshold {theta}");
Console.WriteLine($" scored {score}");
var better = score - best_score;
if (better > 0)
{
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
Console.WriteLine($"trained threshold: {best_theta}");
var test_score = 0.0;
var test_seed = 101;
for (var i0 = 0; i0 < 3; i0++)
{
var now = await client.Strategy.EnvReset(env_id, seed: test_seed);
for (var i1 = 0; i1 < 1000; i1++)
{
var drift = now!["obs"]!["market"]![0]![3]!.GetValue<double>();
var up = drift + best_theta;
var down = drift - best_theta;
action = 0;
if (up < 0)
{
action = 1;
}
if (down > 0)
{
action = 2;
}
now = await client.Strategy.EnvStep(env_id, action);
var r = now!["reward"]!.GetValue<double>();
test_score += r;
if (now!["terminated"]!.GetValue<bool>() || now!["truncated"]!.GetValue<bool>()) break;
}
test_seed += 1;
}
Console.WriteLine($"on the training episodes: {best_score}");
Console.WriteLine($"on the test episodes: {test_score}");
await client.Strategy.EnvClose(env_id);Go
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"))
theta := float64(0.0)
best_theta := float64(0.0)
best_score := float64(-1000000000.0)
action := int64(0)
for i0 := 0; i0 < 4; i0++ {
score := float64(0.0)
seed := int64(1)
for i1 := 0; i1 < 3; i1++ {
var now any = must(client.Strategy.EnvReset(ctx, mcp.StrategyEnvResetArgs{Env: env_id, Seed: mcp.Ptr[int64](seed)}))
for i2 := 0; i2 < 1000; i2++ {
drift := num(at(now, "obs", "market", 0, 3))
up := drift + theta
down := drift - theta
action = int64(0)
if up < 0 {
action = int64(1)
}
if down > 0 {
action = int64(2)
}
now = must(client.Strategy.EnvStep(ctx, mcp.StrategyEnvStepArgs{Env: env_id, Action: action}))
r := num(at(now, "reward"))
score += r
if at(now, "terminated") == true || at(now, "truncated") == true {
break
}
}
seed += int64(1)
}
fmt.Println("threshold", theta)
fmt.Println(" scored", score)
better := score - best_score
if better > 0 {
best_score = score
best_theta = theta
}
theta += 0.001
}
fmt.Println("trained threshold:", best_theta)
test_score := float64(0.0)
test_seed := int64(101)
for i0 := 0; i0 < 3; i0++ {
var now any = must(client.Strategy.EnvReset(ctx, mcp.StrategyEnvResetArgs{Env: env_id, Seed: mcp.Ptr[int64](test_seed)}))
for i1 := 0; i1 < 1000; i1++ {
drift := num(at(now, "obs", "market", 0, 3))
up := drift + best_theta
down := drift - best_theta
action = int64(0)
if up < 0 {
action = int64(1)
}
if down > 0 {
action = int64(2)
}
now = must(client.Strategy.EnvStep(ctx, mcp.StrategyEnvStepArgs{Env: env_id, Action: action}))
r := num(at(now, "reward"))
test_score += r
if at(now, "terminated") == true || at(now, "truncated") == true {
break
}
}
test_seed += int64(1)
}
fmt.Println("on the training episodes:", best_score)
fmt.Println("on the test episodes:", test_score)
_ = must(client.Strategy.EnvClose(ctx, mcp.StrategyEnvCloseArgs{Env: env_id}))
_ = []any{state, gym_bench, made, env_id, theta, best_theta, best_score, action, test_score, test_seed}
}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");
double theta = 0.0;
double best_theta = 0.0;
double best_score = -1000000000.0;
long action = 0L;
for (int i0 = 0; i0 < 4; i0++) {
double score = 0.0;
long seed = 1L;
for (int i1 = 0; i1 < 3; i1++) {
Object now = client.strategy.envReset(new Bentrix.StrategyApi.EnvResetArgs(env_id).seed(seed));
for (int i2 = 0; i2 < 1000; i2++) {
double drift = ((Number) at(now, "obs", "market", 0, 3)).doubleValue();
double up = drift + theta;
double down = drift - theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.envStep(new Bentrix.StrategyApi.EnvStepArgs(env_id, action));
double r = ((Number) at(now, "reward")).doubleValue();
score += r;
if (Boolean.TRUE.equals(at(now, "terminated")) || Boolean.TRUE.equals(at(now, "truncated"))) break;
}
seed += 1;
}
System.out.println("threshold" + " " + theta);
System.out.println(" scored" + " " + score);
double better = score - best_score;
if (better > 0) {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
System.out.println("trained threshold:" + " " + best_theta);
double test_score = 0.0;
long test_seed = 101L;
for (int i0 = 0; i0 < 3; i0++) {
Object now = client.strategy.envReset(new Bentrix.StrategyApi.EnvResetArgs(env_id).seed(test_seed));
for (int i1 = 0; i1 < 1000; i1++) {
double drift = ((Number) at(now, "obs", "market", 0, 3)).doubleValue();
double up = drift + best_theta;
double down = drift - best_theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.envStep(new Bentrix.StrategyApi.EnvStepArgs(env_id, action));
double r = ((Number) at(now, "reward")).doubleValue();
test_score += r;
if (Boolean.TRUE.equals(at(now, "terminated")) || Boolean.TRUE.equals(at(now, "truncated"))) break;
}
test_seed += 1;
}
System.out.println("on the training episodes:" + " " + best_score);
System.out.println("on the test episodes:" + " " + test_score);
client.strategy.envClose(new Bentrix.StrategyApi.EnvCloseArgs(env_id));
}
}
}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());
double theta = 0.0;
double best_theta = 0.0;
double best_score = -1000000000.0;
int64_t action = 0;
for (int i0 = 0; i0 < 4; i0++) {
double score = 0.0;
int64_t seed = 1;
for (int i1 = 0; i1 < 3; i1++) {
Json now = client.strategy.env_reset(StrategyApi::EnvResetArgs(env_id).seed(seed));
for (int i2 = 0; i2 < 1000; i2++) {
auto drift = now["obs"]["market"][0u][3u].num();
auto up = drift + theta;
auto down = drift - theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.env_step(StrategyApi::EnvStepArgs(env_id, action));
auto r = now["reward"].num();
score += r;
if (now["terminated"] == Json(true) || now["truncated"] == Json(true)) break;
}
seed += 1;
}
std::cout << "threshold" << " " << theta << std::endl;
std::cout << " scored" << " " << score << std::endl;
auto better = score - best_score;
if (better > 0) {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
std::cout << "trained threshold:" << " " << best_theta << std::endl;
double test_score = 0.0;
int64_t test_seed = 101;
for (int i0 = 0; i0 < 3; i0++) {
Json now = client.strategy.env_reset(StrategyApi::EnvResetArgs(env_id).seed(test_seed));
for (int i1 = 0; i1 < 1000; i1++) {
auto drift = now["obs"]["market"][0u][3u].num();
auto up = drift + best_theta;
auto down = drift - best_theta;
action = 0;
if (up < 0) {
action = 1;
}
if (down > 0) {
action = 2;
}
now = client.strategy.env_step(StrategyApi::EnvStepArgs(env_id, action));
auto r = now["reward"].num();
test_score += r;
if (now["terminated"] == Json(true) || now["truncated"] == Json(true)) break;
}
test_seed += 1;
}
std::cout << "on the training episodes:" << " " << best_score << std::endl;
std::cout << "on the test episodes:" << " " << test_score << 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"]
theta = 0.0
best_theta = 0.0
best_score = -1000000000.0
action = 0
for _ in 1:4
score = 0.0
seed = 1
for _ in 1:3
now = client.strategy.env_reset(env_id; seed = seed)
for _ in 1:1000
drift = now["obs"]["market"][1][4]
up = drift + theta
down = drift - theta
global action = 0
if up < 0
global action = 1
end
if down > 0
global action = 2
end
now = client.strategy.env_step(env_id, action)
r = now["reward"]
score += r
(now["terminated"] || now["truncated"]) && break
end
seed += 1
end
println("threshold", " ", theta)
println(" scored", " ", score)
better = score - best_score
if better > 0
global best_score = score
global best_theta = theta
end
global theta += 0.001
end
println("trained threshold:", " ", best_theta)
test_score = 0.0
test_seed = 101
for _ in 1:3
now = client.strategy.env_reset(env_id; seed = test_seed)
for _ in 1:1000
drift = now["obs"]["market"][1][4]
up = drift + best_theta
down = drift - best_theta
global action = 0
if up < 0
global action = 1
end
if down > 0
global action = 2
end
now = client.strategy.env_step(env_id, action)
r = now["reward"]
global test_score += r
(now["terminated"] || now["truncated"]) && break
end
global test_seed += 1
end
println("on the training episodes:", " ", best_score)
println("on the test episodes:", " ", test_score)
client.strategy.env_close(env_id)R
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
theta <- 0.0
best_theta <- 0.0
best_score <- -1000000000.0
action <- 0
for (k in seq_len(4)) {
score <- 0.0
seed <- 1
for (k in seq_len(3)) {
now <- client$strategy$env_reset(env_id, seed = seed)
for (k in seq_len(1000)) {
drift <- now$obs$market[[1]][[4]]
up <- drift + theta
down <- drift - theta
action <- 0
if (up < 0) {
action <- 1
}
if (down > 0) {
action <- 2
}
now <- client$strategy$env_step(env_id, action)
r <- now$reward
score <- score + r
if (isTRUE(now$terminated) || isTRUE(now$truncated)) break
}
seed <- seed + 1
}
cat("threshold", format(theta), "\n")
cat(" scored", format(score), "\n")
better <- score - best_score
if (better > 0) {
best_score <- score
best_theta <- theta
}
theta <- theta + 0.001
}
cat("trained threshold:", format(best_theta), "\n")
test_score <- 0.0
test_seed <- 101
for (k in seq_len(3)) {
now <- client$strategy$env_reset(env_id, seed = test_seed)
for (k in seq_len(1000)) {
drift <- now$obs$market[[1]][[4]]
up <- drift + best_theta
down <- drift - best_theta
action <- 0
if (up < 0) {
action <- 1
}
if (down > 0) {
action <- 2
}
now <- client$strategy$env_step(env_id, action)
r <- now$reward
test_score <- test_score + r
if (isTRUE(now$terminated) || isTRUE(now$truncated)) break
}
test_seed <- test_seed + 1
}
cat("on the training episodes:", format(best_score), "\n")
cat("on the test episodes:", format(test_score), "\n")
client$strategy$env_close(env_id)Rust
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();
let mut theta: f64 = 0.0;
let mut best_theta: f64 = 0.0;
let mut best_score: f64 = -1000000000.0;
let mut action: i64 = 0;
for _ in 0..4 {
let mut score: f64 = 0.0;
let mut seed: i64 = 1;
for _ in 0..3 {
let mut now = client.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env_id.clone()).seed(seed.clone()))?;
for _ in 0..1000 {
let drift = now["obs"]["market"][0][3].as_f64().unwrap_or(f64::NAN);
let up = drift + theta;
let down = drift - theta;
action = 0;
if up < 0.0 {
action = 1;
}
if down > 0.0 {
action = 2;
}
now = client.strategy().env_step(mcp::StrategyEnvStepArgs::new(env_id.clone(), action.clone()))?;
let r = now["reward"].as_f64().unwrap_or(f64::NAN);
score += r;
if now["terminated"] == true || now["truncated"] == true { break; }
}
seed += 1;
}
println!("threshold {}", theta);
println!(" scored {}", score);
let better = score - best_score;
if better > 0.0 {
best_score = score;
best_theta = theta;
}
theta += 0.001;
}
println!("trained threshold: {}", best_theta);
let mut test_score: f64 = 0.0;
let mut test_seed: i64 = 101;
for _ in 0..3 {
let mut now = client.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env_id.clone()).seed(test_seed.clone()))?;
for _ in 0..1000 {
let drift = now["obs"]["market"][0][3].as_f64().unwrap_or(f64::NAN);
let up = drift + best_theta;
let down = drift - best_theta;
action = 0;
if up < 0.0 {
action = 1;
}
if down > 0.0 {
action = 2;
}
now = client.strategy().env_step(mcp::StrategyEnvStepArgs::new(env_id.clone(), action.clone()))?;
let r = now["reward"].as_f64().unwrap_or(f64::NAN);
test_score += r;
if now["terminated"] == true || now["truncated"] == true { break; }
}
test_seed += 1;
}
println!("on the training episodes: {}", best_score);
println!("on the test episodes: {}", test_score);
client.strategy().env_close(mcp::StrategyEnvCloseArgs::new(env_id.clone()))?;
Ok(())
}05Reading the result
- The training score flatters. The best of four was chosen because it did best on those episodes, so part of its score is luck that will not repeat. Only the test score says what the threshold is worth.
- A test score far below the training score means the choice fitted the training episodes rather than the market — try more training episodes, fewer candidate values, or a simpler rule.
- This is the same loop a learning library runs. PPO or DQN replace "try four values" with a gradient step on a neural network's thousands of parameters, and score with the rewards of every step rather than a total — but it is still experience in, a better policy out, and a test it never trained on. With Gymnasium and Stable-Baselines3 does it in Python.
06Going further, in any language
- Search two parameters — the threshold and the window the rule reads (
market[k][3]for an older or newer candle). - Replace the search with a learner of your own: a table of action values per state (tabular Q-learning), or a small network. Every learner needs only what each step already answers:
obs,reward,terminatedandtruncated. - Change the reward to
dsr_dd_penalty@1and see whether the trained threshold changes.