Bentrix Docs
HomePricingDashboard

18. Test a strategy honestly

Run a grid and read it against chance, count every trial, walk it forward, test one run's robustness, compare with another engine, judge a MetaTrader optimisation, test a family of candidates, and let Bentrix's own engine prove itself on your data.

A backtest lies most easily to the person who wants it to be true. Bentrix's validation layer is a set of instruments for finding that out before money does. Each is described in Testing a strategy honestly. This guide uses each from a program, on guide 12's strategy, rsi pullback, on the selected laboratory workbench.

01Step 1 — the workbench

Python

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

JSJavaScript

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

C#C#

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

GOGo

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

Java

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

C++C++

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

Julia

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

RR

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

RRust

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

02Step 2 — a batch, and its statistics against chance

strategy_batch runs the strategy once per combination of the grid's values, each cell on a workbench of its own made over the same conditions, at machine speed. batch_get answers its cells as they settle. Once every one has, its record is written and its statistics say what the best cell is worth against chance:

  • the deflated Sharpe ratio: the probability that its Sharpe ratio beats what the best of that many trials would reach by luck;
  • the probability of backtest overfitting over the cells;
  • the minimum backtest length the result would need;
  • the Harvey–Liu haircut on its Sharpe ratio;
  • the cells' interquartile mean, with a bootstrap interval;
  • the market's own price change as the baseline.

The program waits until record is set.

Python

made = client.strategy.batch("rsi pullback", bench, {"studies.rsi.settings.period": [10, 14], "exits.stop.atr.times": [1.0, 2.0]})
batch = made["uri"]
b = client.strategy.batch_get(batch)
for _ in range(1200):
    b = client.strategy.batch_get(batch)
    if b["record"] is not None:
        break
    time.sleep(0.5)
print("cells settled:", b["settled"])
print("against chance:", b["statistics"])

JSJavaScript

const made = await client.strategy.batch({ strategy: "rsi pullback", bench, grid: { "studies.rsi.settings.period": [10, 14], "exits.stop.atr.times": [1.0, 2.0] } });
const batch = made.uri;
let b = await client.strategy.batchGet({ batch });
for (let w = 0; w < 1200; w++) {
  b = await client.strategy.batchGet({ batch });
  if (b.record != null) break;
  await new Promise((r) => setTimeout(r, 500));
}
console.log("cells settled:", b.settled);
console.log("against chance:", b.statistics);

C#C#

var made = await client.Strategy.Batch("rsi pullback", bench, new Dictionary<string, object?> { ["studies.rsi.settings.period"] = new object?[] { 10, 14 }, ["exits.stop.atr.times"] = new object?[] { 1.0, 2.0 } });
var batch = made!["uri"]?.GetValue<string>() ?? "";
var b = await client.Strategy.BatchGet(batch);
for (var w = 0; w < 1200; w++)
{
    b = await client.Strategy.BatchGet(batch);
    if (b!["record"]! is not null) break;
    await Task.Delay(500);
}
Console.WriteLine($"cells settled: {b!["settled"]!}");
Console.WriteLine($"against chance: {b!["statistics"]!}");

GOGo

made := must(client.Strategy.Batch(ctx, mcp.StrategyBatchArgs{Strategy: "rsi pullback", Bench: bench, Grid: map[string]any{"studies.rsi.settings.period": []any{10, 14}, "exits.stop.atr.times": []any{1.0, 2.0}}}))
batch := text(at(made, "uri"))
var b any = must(client.Strategy.BatchGet(ctx, mcp.StrategyBatchGetArgs{Batch: batch}))
for w := 0; w < 1200; w++ {
	b = must(client.Strategy.BatchGet(ctx, mcp.StrategyBatchGetArgs{Batch: batch}))
	if at(b, "record") != nil {
		break
	}
	time.Sleep(500 * time.Millisecond)
}
fmt.Println("cells settled:", at(b, "settled"))
fmt.Println("against chance:", at(b, "statistics"))

Java

Object made = client.strategy.batch(new Bentrix.StrategyApi.BatchArgs("rsi pullback", bench, obj("studies.rsi.settings.period", java.util.Arrays.asList(10, 14), "exits.stop.atr.times", java.util.Arrays.asList(1.0, 2.0))));
String batch = (String) at(made, "uri");
Object b = client.strategy.batchGet(new Bentrix.StrategyApi.BatchGetArgs(batch));
for (int w = 0; w < 1200; w++) {
    b = client.strategy.batchGet(new Bentrix.StrategyApi.BatchGetArgs(batch));
    if (at(b, "record") != null) break;
    Thread.sleep(500);
}
System.out.println("cells settled:" + " " + at(b, "settled"));
System.out.println("against chance:" + " " + at(b, "statistics"));

C++C++

auto made = client.strategy.batch(StrategyApi::BatchArgs("rsi pullback", bench, Json::Object{{"studies.rsi.settings.period", Json::Array{10, 14}}, {"exits.stop.atr.times", Json::Array{1.0, 2.0}}}));
auto batch = (made["uri"].is_string() ? made["uri"].str() : std::string());
Json b = client.strategy.batch_get(StrategyApi::BatchGetArgs(batch));
for (int w = 0; w < 1200; w++) {
    b = client.strategy.batch_get(StrategyApi::BatchGetArgs(batch));
    if (!b["record"].is_null()) break;
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "cells settled:" << " " << b["settled"].dump() << std::endl;
std::cout << "against chance:" << " " << b["statistics"].dump() << std::endl;

Julia

made = client.strategy.batch("rsi pullback", bench, Dict{String,Any}("studies.rsi.settings.period" => Any[10, 14], "exits.stop.atr.times" => Any[1.0, 2.0]))
batch = made["uri"]
b = client.strategy.batch_get(batch)
for _ in 1:1200
    global b = client.strategy.batch_get(batch)
    b["record"] !== nothing && break
    sleep(0.5)
end
println("cells settled:", " ", b["settled"])
println("against chance:", " ", b["statistics"])

RR

made <- client$strategy$batch("rsi pullback", bench, list(studies.rsi.settings.period = list(10, 14), exits.stop.atr.times = list(1.0, 2.0)))
batch <- made$uri
b <- client$strategy$batch_get(batch)
for (w in 1:1200) {
  b <- client$strategy$batch_get(batch)
  if (!is.null(b$record)) break
  Sys.sleep(0.5)
}
cat("cells settled:", format(b$settled), "\n")
cat("against chance:", format(b$statistics), "\n")

RRust

let made = client.strategy().batch(mcp::StrategyBatchArgs::new("rsi pullback", bench.clone(), serde_json::json!({"studies.rsi.settings.period": [10, 14], "exits.stop.atr.times": [1.0, 2.0]})))?;
let batch = made["uri"].as_str().unwrap_or_default().to_string();
let mut b = client.strategy().batch_get(mcp::StrategyBatchGetArgs::new(batch.clone()))?;
for _ in 0..1200 {
    b = client.strategy().batch_get(mcp::StrategyBatchGetArgs::new(batch.clone()))?;
    if !b["record"].is_null() {
        break;
    }
    std::thread::sleep(std::time::Duration::from_millis(500));
}
println!("cells settled: {}", b["settled"]);
println!("against chance: {}", b["statistics"]);

A grid may also vary two things the document does not hold: tick_model (real, every-tick, ohlc-m1, open-only) and spread_multiplier (1 is the spread as recorded). The record then compares the results under each, and flags a result whose sign flips.

03Step 3 — every trial, counted

Every run, batch cell and re-run is written to the trial ledger before its result is shown, and the ledger has no door that removes a line. ledger_query with strategy answers that strategy's trials and their results, and trials counts them. That count is the N every correction for multiple testing needs: the batch's statistics above are taken over every trial the ledger counts for the strategy, not over this batch alone.

Python

l = client.strategy.ledger_query(limit=5, strategy="rsi pullback")
print("trials of rsi pullback:", l["trials"])
print("trials of everything:", l["union"])

JSJavaScript

const l = await client.strategy.ledgerQuery({ limit: 5, strategy: "rsi pullback" });
console.log("trials of rsi pullback:", l.trials);
console.log("trials of everything:", l.union);

C#C#

var l = await client.Strategy.LedgerQuery(limit: 5, strategy: "rsi pullback");
Console.WriteLine($"trials of rsi pullback: {l!["trials"]!}");
Console.WriteLine($"trials of everything: {l!["union"]!}");

GOGo

l := must(client.Strategy.LedgerQuery(ctx, mcp.StrategyLedgerQueryArgs{Limit: mcp.Ptr[int64](5), Strategy: mcp.Ptr[string]("rsi pullback")}))
fmt.Println("trials of rsi pullback:", at(l, "trials"))
fmt.Println("trials of everything:", at(l, "union"))

Java

Object l = client.strategy.ledgerQuery(new Bentrix.StrategyApi.LedgerQueryArgs().limit(5L).strategy("rsi pullback"));
System.out.println("trials of rsi pullback:" + " " + at(l, "trials"));
System.out.println("trials of everything:" + " " + at(l, "union"));

C++C++

auto l = client.strategy.ledger_query(StrategyApi::LedgerQueryArgs().limit(5).strategy("rsi pullback"));
std::cout << "trials of rsi pullback:" << " " << l["trials"].dump() << std::endl;
std::cout << "trials of everything:" << " " << l["union"].dump() << std::endl;

Julia

l = client.strategy.ledger_query(; limit = 5, strategy = "rsi pullback")
println("trials of rsi pullback:", " ", l["trials"])
println("trials of everything:", " ", l["union"])

RR

l <- client$strategy$ledger_query(limit = 5, strategy = "rsi pullback")
cat("trials of rsi pullback:", format(l$trials), "\n")
cat("trials of everything:", format(l$union), "\n")

RRust

let l = client.strategy().ledger_query(mcp::StrategyLedgerQueryArgs::new().limit(5).strategy("rsi pullback"))?;
println!("trials of rsi pullback: {}", l["trials"]);
println!("trials of everything: {}", l["union"]);

A search you ran in your own code counts too. ledger_record writes it as one family with its count, before you look at its result, and it joins the union:

Python

fam = client.strategy.ledger_record("trial", count=50, description="50 moving-average pairs tried in my own notebook", family="my-grid-search")
print("line:", fam["seq"])
print("the union now:", fam["union"])

JSJavaScript

const fam = await client.strategy.ledgerRecord({ kind: "trial", count: 50, description: "50 moving-average pairs tried in my own notebook", family: "my-grid-search" });
console.log("line:", fam.seq);
console.log("the union now:", fam.union);

C#C#

var fam = await client.Strategy.LedgerRecord("trial", count: 50, description: "50 moving-average pairs tried in my own notebook", family: "my-grid-search");
Console.WriteLine($"line: {fam!["seq"]!}");
Console.WriteLine($"the union now: {fam!["union"]!}");

GOGo

fam := must(client.Strategy.LedgerRecord(ctx, mcp.StrategyLedgerRecordArgs{Kind: "trial", Count: mcp.Ptr[int64](50), Description: mcp.Ptr[string]("50 moving-average pairs tried in my own notebook"), Family: mcp.Ptr[string]("my-grid-search")}))
fmt.Println("line:", at(fam, "seq"))
fmt.Println("the union now:", at(fam, "union"))

Java

Object fam = client.strategy.ledgerRecord(new Bentrix.StrategyApi.LedgerRecordArgs("trial").count(50L).description("50 moving-average pairs tried in my own notebook").family("my-grid-search"));
System.out.println("line:" + " " + at(fam, "seq"));
System.out.println("the union now:" + " " + at(fam, "union"));

C++C++

auto fam = client.strategy.ledger_record(StrategyApi::LedgerRecordArgs("trial").count(50).description("50 moving-average pairs tried in my own notebook").family("my-grid-search"));
std::cout << "line:" << " " << fam["seq"].dump() << std::endl;
std::cout << "the union now:" << " " << fam["union"].dump() << std::endl;

Julia

fam = client.strategy.ledger_record("trial"; count = 50, description = "50 moving-average pairs tried in my own notebook", family = "my-grid-search")
println("line:", " ", fam["seq"])
println("the union now:", " ", fam["union"])

RR

fam <- client$strategy$ledger_record("trial", count = 50, description = "50 moving-average pairs tried in my own notebook", family = "my-grid-search")
cat("line:", format(fam$seq), "\n")
cat("the union now:", format(fam$union), "\n")

RRust

let fam = client.strategy().ledger_record(mcp::StrategyLedgerRecordArgs::new("trial").count(50).description("50 moving-average pairs tried in my own notebook").family("my-grid-search"))?;
println!("line: {}", fam["seq"]);
println!("the union now: {}", fam["union"]);

04Step 4 — one run's robustness

run_robustness tests an ended run, every draw from one fixed seed:

  • its maximum drawdown with the trades drawn again in another order;
  • its net with a tenth of the trades left out;
  • its net with every fill made worse;
  • its random-entry percentile: the share of random runs with as many trades, each held as long, whose result is below this one's;
  • its trades on quiet, middle and busy days;
  • Van Tharp's SQN and its expectancy.

Each answer comes with its definition. Here, the first cell of the batch:

Python

run = b["cells"][0]["state"]["run"]
r = client.strategy.run_robustness(run)
print("drawdown reshuffled:", r["reshuffle_max_drawdown"])
print("random entry:", r["random_entry"])
print("metrics:", r["metrics"])

JSJavaScript

const run = b.cells[0].state.run;
const r = await client.strategy.runRobustness({ run });
console.log("drawdown reshuffled:", r.reshuffle_max_drawdown);
console.log("random entry:", r.random_entry);
console.log("metrics:", r.metrics);

C#C#

var run = b!["cells"]![0]!["state"]!["run"]?.GetValue<string>() ?? "";
var r = await client.Strategy.RunRobustness(run);
Console.WriteLine($"drawdown reshuffled: {r!["reshuffle_max_drawdown"]!}");
Console.WriteLine($"random entry: {r!["random_entry"]!}");
Console.WriteLine($"metrics: {r!["metrics"]!}");

GOGo

run := text(at(b, "cells", 0, "state", "run"))
r := must(client.Strategy.RunRobustness(ctx, mcp.StrategyRunRobustnessArgs{Run: run}))
fmt.Println("drawdown reshuffled:", at(r, "reshuffle_max_drawdown"))
fmt.Println("random entry:", at(r, "random_entry"))
fmt.Println("metrics:", at(r, "metrics"))

Java

String run = (String) at(b, "cells", 0, "state", "run");
Object r = client.strategy.runRobustness(new Bentrix.StrategyApi.RunRobustnessArgs(run));
System.out.println("drawdown reshuffled:" + " " + at(r, "reshuffle_max_drawdown"));
System.out.println("random entry:" + " " + at(r, "random_entry"));
System.out.println("metrics:" + " " + at(r, "metrics"));

C++C++

auto run = (b["cells"][0u]["state"]["run"].is_string() ? b["cells"][0u]["state"]["run"].str() : std::string());
auto r = client.strategy.run_robustness(StrategyApi::RunRobustnessArgs(run));
std::cout << "drawdown reshuffled:" << " " << r["reshuffle_max_drawdown"].dump() << std::endl;
std::cout << "random entry:" << " " << r["random_entry"].dump() << std::endl;
std::cout << "metrics:" << " " << r["metrics"].dump() << std::endl;

Julia

run = b["cells"][1]["state"]["run"]
r = client.strategy.run_robustness(run)
println("drawdown reshuffled:", " ", r["reshuffle_max_drawdown"])
println("random entry:", " ", r["random_entry"])
println("metrics:", " ", r["metrics"])

RR

run <- b$cells[[1]]$state$run
r <- client$strategy$run_robustness(run)
cat("drawdown reshuffled:", format(r$reshuffle_max_drawdown), "\n")
cat("random entry:", format(r$random_entry), "\n")
cat("metrics:", format(r$metrics), "\n")

RRust

let run = b["cells"][0]["state"]["run"].as_str().unwrap_or_default().to_string();
let r = client.strategy().run_robustness(mcp::StrategyRunRobustnessArgs::new(run.clone()))?;
println!("drawdown reshuffled: {}", r["reshuffle_max_drawdown"]);
println!("random entry: {}", r["random_entry"]);
println!("metrics: {}", r["metrics"]);

05Step 5 — against another engine

run_parity compares a run's closed trades with a trade list another engine produced: MetaTrader's tester, another backtester, an earlier run. Each list is put in one canonical form (one line a closed trade: its close time, long or short, its net to the cent) and hashed. The answer says whether the two are the same list, and if not, the first trade where they part. Pass the other list's file as text. Here it is a made-up list of two trades, so it parts at the first:

Python

p = client.strategy.run_parity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]")
print("the same list:", p["parity"])
print("they part at:", p["first_difference"])

JSJavaScript

const p = await client.strategy.runParity({ run, list: "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]" });
console.log("the same list:", p.parity);
console.log("they part at:", p.first_difference);

C#C#

var p = await client.Strategy.RunParity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]");
Console.WriteLine($"the same list: {p!["parity"]!}");
Console.WriteLine($"they part at: {p!["first_difference"]!}");

GOGo

p := must(client.Strategy.RunParity(ctx, mcp.StrategyRunParityArgs{Run: run, List: "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"}))
fmt.Println("the same list:", at(p, "parity"))
fmt.Println("they part at:", at(p, "first_difference"))

Java

Object p = client.strategy.runParity(new Bentrix.StrategyApi.RunParityArgs(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"));
System.out.println("the same list:" + " " + at(p, "parity"));
System.out.println("they part at:" + " " + at(p, "first_difference"));

C++C++

auto p = client.strategy.run_parity(StrategyApi::RunParityArgs(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"));
std::cout << "the same list:" << " " << p["parity"].dump() << std::endl;
std::cout << "they part at:" << " " << p["first_difference"].dump() << std::endl;

Julia

p = client.strategy.run_parity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]")
println("the same list:", " ", p["parity"])
println("they part at:", " ", p["first_difference"])

RR

p <- client$strategy$run_parity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]")
cat("the same list:", format(p$parity), "\n")
cat("they part at:", format(p$first_difference), "\n")

RRust

let p = client.strategy().run_parity(mcp::StrategyRunParityArgs::new(run.clone(), "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"))?;
println!("the same list: {}", p["parity"]);
println!("they part at: {}", p["first_difference"]);

06Step 6 — a MetaTrader optimisation, judged

optimisation_import reads the results table of an optimisation run in MetaTrader's tester: its Export to XML file's text, or the table as CSV with its header row. It writes every pass to the trial ledger under the expert's name, then judges the best pass by its Sharpe ratio over every pass the ledger counts for that name. It answers the best pass's probabilistic and deflated Sharpe ratio and the Harvey–Liu haircut. The table holds no return series, so the answer says what it assumed instead.

Python

opt = client.strategy.optimisation_import("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n")
print("passes in the ledger:", opt["trials_in_ledger"])
print("best pass:", opt["best"]["pass"])
print("its Sharpe ratio:", opt["best"]["sharpe"])
print("probabilistic:", opt["psr"])
print("deflated:", opt["dsr"])
print("assumed:", opt["assumed"])

JSJavaScript

const opt = await client.strategy.optimisationImport({ name: "MyCrossEA", table: "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n" });
console.log("passes in the ledger:", opt.trials_in_ledger);
console.log("best pass:", opt.best.pass);
console.log("its Sharpe ratio:", opt.best.sharpe);
console.log("probabilistic:", opt.psr);
console.log("deflated:", opt.dsr);
console.log("assumed:", opt.assumed);

C#C#

var opt = await client.Strategy.OptimisationImport("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n");
Console.WriteLine($"passes in the ledger: {opt!["trials_in_ledger"]!}");
Console.WriteLine($"best pass: {opt!["best"]!["pass"]!}");
Console.WriteLine($"its Sharpe ratio: {opt!["best"]!["sharpe"]!}");
Console.WriteLine($"probabilistic: {opt!["psr"]!}");
Console.WriteLine($"deflated: {opt!["dsr"]!}");
Console.WriteLine($"assumed: {opt!["assumed"]!}");

GOGo

opt := must(client.Strategy.OptimisationImport(ctx, mcp.StrategyOptimisationImportArgs{Name: "MyCrossEA", Table: "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"}))
fmt.Println("passes in the ledger:", at(opt, "trials_in_ledger"))
fmt.Println("best pass:", at(opt, "best", "pass"))
fmt.Println("its Sharpe ratio:", at(opt, "best", "sharpe"))
fmt.Println("probabilistic:", at(opt, "psr"))
fmt.Println("deflated:", at(opt, "dsr"))
fmt.Println("assumed:", at(opt, "assumed"))

Java

Object opt = client.strategy.optimisationImport(new Bentrix.StrategyApi.OptimisationImportArgs("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"));
System.out.println("passes in the ledger:" + " " + at(opt, "trials_in_ledger"));
System.out.println("best pass:" + " " + at(opt, "best", "pass"));
System.out.println("its Sharpe ratio:" + " " + at(opt, "best", "sharpe"));
System.out.println("probabilistic:" + " " + at(opt, "psr"));
System.out.println("deflated:" + " " + at(opt, "dsr"));
System.out.println("assumed:" + " " + at(opt, "assumed"));

C++C++

auto opt = client.strategy.optimisation_import(StrategyApi::OptimisationImportArgs("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"));
std::cout << "passes in the ledger:" << " " << opt["trials_in_ledger"].dump() << std::endl;
std::cout << "best pass:" << " " << opt["best"]["pass"].dump() << std::endl;
std::cout << "its Sharpe ratio:" << " " << opt["best"]["sharpe"].dump() << std::endl;
std::cout << "probabilistic:" << " " << opt["psr"].dump() << std::endl;
std::cout << "deflated:" << " " << opt["dsr"].dump() << std::endl;
std::cout << "assumed:" << " " << opt["assumed"].dump() << std::endl;

Julia

opt = client.strategy.optimisation_import("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n")
println("passes in the ledger:", " ", opt["trials_in_ledger"])
println("best pass:", " ", opt["best"]["pass"])
println("its Sharpe ratio:", " ", opt["best"]["sharpe"])
println("probabilistic:", " ", opt["psr"])
println("deflated:", " ", opt["dsr"])
println("assumed:", " ", opt["assumed"])

RR

opt <- client$strategy$optimisation_import("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n")
cat("passes in the ledger:", format(opt$trials_in_ledger), "\n")
cat("best pass:", format(opt$best$pass), "\n")
cat("its Sharpe ratio:", format(opt$best$sharpe), "\n")
cat("probabilistic:", format(opt$psr), "\n")
cat("deflated:", format(opt$dsr), "\n")
cat("assumed:", format(opt$assumed), "\n")

RRust

let opt = client.strategy().optimisation_import(mcp::StrategyOptimisationImportArgs::new("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"))?;
println!("passes in the ledger: {}", opt["trials_in_ledger"]);
println!("best pass: {}", opt["best"]["pass"]);
println!("its Sharpe ratio: {}", opt["best"]["sharpe"]);
println!("probabilistic: {}", opt["psr"]);
println!("deflated: {}", opt["dsr"]);
println!("assumed: {}", opt["assumed"]);

07Step 7 — a family of candidates, tested at once

stats_family_test asks whether the best of several candidates really beats a benchmark, or only looks as if it does because it was the best of several. It runs Hansen's test for superior predictive ability (with the conservative p-value, which is White's reality check) and gives each candidate its Romano–Wolf adjusted p-value. Give each candidate's performance less the benchmark's, period by period, one row a candidate. It reads and writes nothing, and the same series and seed give the same answer.

Python

fam_test = client.strategy.stats_family_test([[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], [0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], [-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]], resamples=1000, seed=7)
print("superior predictive ability:", fam_test["spa"])
print("Romano-Wolf:", fam_test["romano_wolf"])

JSJavaScript

const fam_test = await client.strategy.statsFamilyTest({ series: [[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], [0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], [-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]], resamples: 1000, seed: 7 });
console.log("superior predictive ability:", fam_test.spa);
console.log("Romano-Wolf:", fam_test.romano_wolf);

C#C#

var fam_test = await client.Strategy.StatsFamilyTest(new object?[] { new object?[] { 0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2 }, new object?[] { 0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1 }, new object?[] { -0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1 } }, resamples: 1000, seed: 7);
Console.WriteLine($"superior predictive ability: {fam_test!["spa"]!}");
Console.WriteLine($"Romano-Wolf: {fam_test!["romano_wolf"]!}");

GOGo

fam_test := must(client.Strategy.StatsFamilyTest(ctx, mcp.StrategyStatsFamilyTestArgs{Series: []any{[]any{0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2}, []any{0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1}, []any{-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1}}, Resamples: mcp.Ptr[int64](1000), Seed: mcp.Ptr[int64](7)}))
fmt.Println("superior predictive ability:", at(fam_test, "spa"))
fmt.Println("Romano-Wolf:", at(fam_test, "romano_wolf"))

Java

Object fam_test = client.strategy.statsFamilyTest(new Bentrix.StrategyApi.StatsFamilyTestArgs(java.util.Arrays.asList(java.util.Arrays.asList(0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2), java.util.Arrays.asList(0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1), java.util.Arrays.asList(-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1))).resamples(1000L).seed(7L));
System.out.println("superior predictive ability:" + " " + at(fam_test, "spa"));
System.out.println("Romano-Wolf:" + " " + at(fam_test, "romano_wolf"));

C++C++

auto fam_test = client.strategy.stats_family_test(StrategyApi::StatsFamilyTestArgs(Json::Array{Json::Array{0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2}, Json::Array{0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1}, Json::Array{-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1}}).resamples(1000).seed(7));
std::cout << "superior predictive ability:" << " " << fam_test["spa"].dump() << std::endl;
std::cout << "Romano-Wolf:" << " " << fam_test["romano_wolf"].dump() << std::endl;

Julia

fam_test = client.strategy.stats_family_test(Any[Any[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], Any[0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], Any[-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]]; resamples = 1000, seed = 7)
println("superior predictive ability:", " ", fam_test["spa"])
println("Romano-Wolf:", " ", fam_test["romano_wolf"])

RR

fam_test <- client$strategy$stats_family_test(list(list(0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2), list(0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1), list(-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1)), resamples = 1000, seed = 7)
cat("superior predictive ability:", format(fam_test$spa), "\n")
cat("Romano-Wolf:", format(fam_test$romano_wolf), "\n")

RRust

let fam_test = client.strategy().stats_family_test(mcp::StrategyStatsFamilyTestArgs::new(serde_json::json!([[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], [0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], [-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]])).resamples(1000).seed(7))?;
println!("superior predictive ability: {}", fam_test["spa"]);
println!("Romano-Wolf: {}", fam_test["romano_wolf"]);

08Step 8 — Bentrix's own engine, proved on your data

battery_run runs sixteen checks of Bentrix's engine on the workbench's own recording. A reference strategy (EMA 8 crossing EMA 21, hourly) runs on workbenches made alike this one: as it is, again, on twice the spread, on one-minute OHLC ticks, and over the first half of its days. Scripted orders run on three more. Each check answers pass, fail, measured (a figure with no threshold) or not run, with what it found. The workbenches it makes stay in the laboratory, to open or remove.

Python

client.strategy.battery_run(bench)
bat = client.strategy.battery_get()
for _ in range(1800):
    bat = client.strategy.battery_get()
    if bat["checks"] is not None:
        break
    time.sleep(0.5)
print("passed:", bat["passed"])
print("failed:", bat["failed_checks"])
for c in bat["checks"]:
    print("check:", c["name"])
    print("  ", c["verdict"])
    print("  found:", c["said"])

JSJavaScript

await client.strategy.batteryRun({ bench });
let bat = await client.strategy.batteryGet();
for (let w = 0; w < 1800; w++) {
  bat = await client.strategy.batteryGet();
  if (bat.checks != null) break;
  await new Promise((r) => setTimeout(r, 500));
}
console.log("passed:", bat.passed);
console.log("failed:", bat.failed_checks);
for (const c of bat.checks) {
  console.log("check:", c.name);
  console.log("  ", c.verdict);
  console.log("  found:", c.said);
}

C#C#

await client.Strategy.BatteryRun(bench);
var bat = await client.Strategy.BatteryGet();
for (var w = 0; w < 1800; w++)
{
    bat = await client.Strategy.BatteryGet();
    if (bat!["checks"]! is not null) break;
    await Task.Delay(500);
}
Console.WriteLine($"passed: {bat!["passed"]!}");
Console.WriteLine($"failed: {bat!["failed_checks"]!}");
foreach (var c in bat!["checks"]!.AsArray())
{
    Console.WriteLine($"check: {c!["name"]!}");
    Console.WriteLine($"   {c!["verdict"]!}");
    Console.WriteLine($"  found: {c!["said"]!}");
}

GOGo

_ = must(client.Strategy.BatteryRun(ctx, mcp.StrategyBatteryRunArgs{Bench: bench}))
var bat any = must(client.Strategy.BatteryGet(ctx))
for w := 0; w < 1800; w++ {
	bat = must(client.Strategy.BatteryGet(ctx))
	if at(bat, "checks") != nil {
		break
	}
	time.Sleep(500 * time.Millisecond)
}
fmt.Println("passed:", at(bat, "passed"))
fmt.Println("failed:", at(bat, "failed_checks"))
for _, c := range at(bat, "checks").([]any) {
	fmt.Println("check:", at(c, "name"))
	fmt.Println("  ", at(c, "verdict"))
	fmt.Println("  found:", at(c, "said"))
}

Java

client.strategy.batteryRun(new Bentrix.StrategyApi.BatteryRunArgs(bench));
Object bat = client.strategy.batteryGet();
for (int w = 0; w < 1800; w++) {
    bat = client.strategy.batteryGet();
    if (at(bat, "checks") != null) break;
    Thread.sleep(500);
}
System.out.println("passed:" + " " + at(bat, "passed"));
System.out.println("failed:" + " " + at(bat, "failed_checks"));
for (Object c : (List<Object>) at(bat, "checks")) {
    System.out.println("check:" + " " + at(c, "name"));
    System.out.println("  " + " " + at(c, "verdict"));
    System.out.println("  found:" + " " + at(c, "said"));
}

C++C++

client.strategy.battery_run(StrategyApi::BatteryRunArgs(bench));
Json bat = client.strategy.battery_get();
for (int w = 0; w < 1800; w++) {
    bat = client.strategy.battery_get();
    if (!bat["checks"].is_null()) break;
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "passed:" << " " << bat["passed"].dump() << std::endl;
std::cout << "failed:" << " " << bat["failed_checks"].dump() << std::endl;
for (const Json &c : bat["checks"].arr()) {
    std::cout << "check:" << " " << c["name"].dump() << std::endl;
    std::cout << "  " << " " << c["verdict"].dump() << std::endl;
    std::cout << "  found:" << " " << c["said"].dump() << std::endl;
}

Julia

client.strategy.battery_run(bench)
bat = client.strategy.battery_get()
for _ in 1:1800
    global bat = client.strategy.battery_get()
    bat["checks"] !== nothing && break
    sleep(0.5)
end
println("passed:", " ", bat["passed"])
println("failed:", " ", bat["failed_checks"])
for c in bat["checks"]
    println("check:", " ", c["name"])
    println("  ", " ", c["verdict"])
    println("  found:", " ", c["said"])
end

RR

client$strategy$battery_run(bench)
bat <- client$strategy$battery_get()
for (w in 1:1800) {
  bat <- client$strategy$battery_get()
  if (!is.null(bat$checks)) break
  Sys.sleep(0.5)
}
cat("passed:", format(bat$passed), "\n")
cat("failed:", format(bat$failed_checks), "\n")
for (c in bat$checks) {
  cat("check:", format(c$name), "\n")
  cat("  ", format(c$verdict), "\n")
  cat("  found:", format(c$said), "\n")
}

RRust

client.strategy().battery_run(mcp::StrategyBatteryRunArgs::new(bench.clone()))?;
let mut bat = client.strategy().battery_get()?;
for _ in 0..1800 {
    bat = client.strategy().battery_get()?;
    if !bat["checks"].is_null() {
        break;
    }
    std::thread::sleep(std::time::Duration::from_millis(500));
}
println!("passed: {}", bat["passed"]);
println!("failed: {}", bat["failed_checks"]);
for c in bat["checks"].as_array().into_iter().flatten() {
    println!("check: {}", c["name"]);
    println!("   {}", c["verdict"]);
    println!("  found: {}", c["said"]);
}

09The whole program

Python

import time
import bentrix

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

state = client.workspace.get_state(depth="benches")
bench = state["selected"]
for _ in range(120):
    if client.agent.resource_read(bench)["engine"] == "ready":
        break
    time.sleep(0.5)
made = client.strategy.batch("rsi pullback", bench, {"studies.rsi.settings.period": [10, 14], "exits.stop.atr.times": [1.0, 2.0]})
batch = made["uri"]
b = client.strategy.batch_get(batch)
for _ in range(1200):
    b = client.strategy.batch_get(batch)
    if b["record"] is not None:
        break
    time.sleep(0.5)
print("cells settled:", b["settled"])
print("against chance:", b["statistics"])
l = client.strategy.ledger_query(limit=5, strategy="rsi pullback")
print("trials of rsi pullback:", l["trials"])
print("trials of everything:", l["union"])
fam = client.strategy.ledger_record("trial", count=50, description="50 moving-average pairs tried in my own notebook", family="my-grid-search")
print("line:", fam["seq"])
print("the union now:", fam["union"])
run = b["cells"][0]["state"]["run"]
r = client.strategy.run_robustness(run)
print("drawdown reshuffled:", r["reshuffle_max_drawdown"])
print("random entry:", r["random_entry"])
print("metrics:", r["metrics"])
p = client.strategy.run_parity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]")
print("the same list:", p["parity"])
print("they part at:", p["first_difference"])
opt = client.strategy.optimisation_import("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n")
print("passes in the ledger:", opt["trials_in_ledger"])
print("best pass:", opt["best"]["pass"])
print("its Sharpe ratio:", opt["best"]["sharpe"])
print("probabilistic:", opt["psr"])
print("deflated:", opt["dsr"])
print("assumed:", opt["assumed"])
fam_test = client.strategy.stats_family_test([[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], [0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], [-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]], resamples=1000, seed=7)
print("superior predictive ability:", fam_test["spa"])
print("Romano-Wolf:", fam_test["romano_wolf"])
client.strategy.battery_run(bench)
bat = client.strategy.battery_get()
for _ in range(1800):
    bat = client.strategy.battery_get()
    if bat["checks"] is not None:
        break
    time.sleep(0.5)
print("passed:", bat["passed"])
print("failed:", bat["failed_checks"])
for c in bat["checks"]:
    print("check:", c["name"])
    print("  ", c["verdict"])
    print("  found:", c["said"])

JSJavaScript

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

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

  const state = await client.workspace.getState({ depth: "benches" });
  const bench = state.selected;
  for (let w = 0; w < 120; w++) {
    if ((await client.agent.resourceRead({ uri: bench })).engine === 'ready') break;
    await new Promise((r) => setTimeout(r, 500));
  }
  const made = await client.strategy.batch({ strategy: "rsi pullback", bench, grid: { "studies.rsi.settings.period": [10, 14], "exits.stop.atr.times": [1.0, 2.0] } });
  const batch = made.uri;
  let b = await client.strategy.batchGet({ batch });
  for (let w = 0; w < 1200; w++) {
    b = await client.strategy.batchGet({ batch });
    if (b.record != null) break;
    await new Promise((r) => setTimeout(r, 500));
  }
  console.log("cells settled:", b.settled);
  console.log("against chance:", b.statistics);
  const l = await client.strategy.ledgerQuery({ limit: 5, strategy: "rsi pullback" });
  console.log("trials of rsi pullback:", l.trials);
  console.log("trials of everything:", l.union);
  const fam = await client.strategy.ledgerRecord({ kind: "trial", count: 50, description: "50 moving-average pairs tried in my own notebook", family: "my-grid-search" });
  console.log("line:", fam.seq);
  console.log("the union now:", fam.union);
  const run = b.cells[0].state.run;
  const r = await client.strategy.runRobustness({ run });
  console.log("drawdown reshuffled:", r.reshuffle_max_drawdown);
  console.log("random entry:", r.random_entry);
  console.log("metrics:", r.metrics);
  const p = await client.strategy.runParity({ run, list: "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]" });
  console.log("the same list:", p.parity);
  console.log("they part at:", p.first_difference);
  const opt = await client.strategy.optimisationImport({ name: "MyCrossEA", table: "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n" });
  console.log("passes in the ledger:", opt.trials_in_ledger);
  console.log("best pass:", opt.best.pass);
  console.log("its Sharpe ratio:", opt.best.sharpe);
  console.log("probabilistic:", opt.psr);
  console.log("deflated:", opt.dsr);
  console.log("assumed:", opt.assumed);
  const fam_test = await client.strategy.statsFamilyTest({ series: [[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], [0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], [-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]], resamples: 1000, seed: 7 });
  console.log("superior predictive ability:", fam_test.spa);
  console.log("Romano-Wolf:", fam_test.romano_wolf);
  await client.strategy.batteryRun({ bench });
  let bat = await client.strategy.batteryGet();
  for (let w = 0; w < 1800; w++) {
    bat = await client.strategy.batteryGet();
    if (bat.checks != null) break;
    await new Promise((r) => setTimeout(r, 500));
  }
  console.log("passed:", bat.passed);
  console.log("failed:", bat.failed_checks);
  for (const c of bat.checks) {
    console.log("check:", c.name);
    console.log("  ", c.verdict);
    console.log("  found:", c.said);
  }
})();

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 bench = state!["selected"]?.GetValue<string>() ?? "";
for (var w = 0; w < 120; w++)
{
    if ((await client.Agent.ResourceRead(bench))!["engine"]!.GetValue<string>() == "ready") break;
    await Task.Delay(500);
}
var made = await client.Strategy.Batch("rsi pullback", bench, new Dictionary<string, object?> { ["studies.rsi.settings.period"] = new object?[] { 10, 14 }, ["exits.stop.atr.times"] = new object?[] { 1.0, 2.0 } });
var batch = made!["uri"]?.GetValue<string>() ?? "";
var b = await client.Strategy.BatchGet(batch);
for (var w = 0; w < 1200; w++)
{
    b = await client.Strategy.BatchGet(batch);
    if (b!["record"]! is not null) break;
    await Task.Delay(500);
}
Console.WriteLine($"cells settled: {b!["settled"]!}");
Console.WriteLine($"against chance: {b!["statistics"]!}");
var l = await client.Strategy.LedgerQuery(limit: 5, strategy: "rsi pullback");
Console.WriteLine($"trials of rsi pullback: {l!["trials"]!}");
Console.WriteLine($"trials of everything: {l!["union"]!}");
var fam = await client.Strategy.LedgerRecord("trial", count: 50, description: "50 moving-average pairs tried in my own notebook", family: "my-grid-search");
Console.WriteLine($"line: {fam!["seq"]!}");
Console.WriteLine($"the union now: {fam!["union"]!}");
var run = b!["cells"]![0]!["state"]!["run"]?.GetValue<string>() ?? "";
var r = await client.Strategy.RunRobustness(run);
Console.WriteLine($"drawdown reshuffled: {r!["reshuffle_max_drawdown"]!}");
Console.WriteLine($"random entry: {r!["random_entry"]!}");
Console.WriteLine($"metrics: {r!["metrics"]!}");
var p = await client.Strategy.RunParity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]");
Console.WriteLine($"the same list: {p!["parity"]!}");
Console.WriteLine($"they part at: {p!["first_difference"]!}");
var opt = await client.Strategy.OptimisationImport("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n");
Console.WriteLine($"passes in the ledger: {opt!["trials_in_ledger"]!}");
Console.WriteLine($"best pass: {opt!["best"]!["pass"]!}");
Console.WriteLine($"its Sharpe ratio: {opt!["best"]!["sharpe"]!}");
Console.WriteLine($"probabilistic: {opt!["psr"]!}");
Console.WriteLine($"deflated: {opt!["dsr"]!}");
Console.WriteLine($"assumed: {opt!["assumed"]!}");
var fam_test = await client.Strategy.StatsFamilyTest(new object?[] { new object?[] { 0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2 }, new object?[] { 0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1 }, new object?[] { -0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1 } }, resamples: 1000, seed: 7);
Console.WriteLine($"superior predictive ability: {fam_test!["spa"]!}");
Console.WriteLine($"Romano-Wolf: {fam_test!["romano_wolf"]!}");
await client.Strategy.BatteryRun(bench);
var bat = await client.Strategy.BatteryGet();
for (var w = 0; w < 1800; w++)
{
    bat = await client.Strategy.BatteryGet();
    if (bat!["checks"]! is not null) break;
    await Task.Delay(500);
}
Console.WriteLine($"passed: {bat!["passed"]!}");
Console.WriteLine($"failed: {bat!["failed_checks"]!}");
foreach (var c in bat!["checks"]!.AsArray())
{
    Console.WriteLine($"check: {c!["name"]!}");
    Console.WriteLine($"   {c!["verdict"]!}");
    Console.WriteLine($"  found: {c!["said"]!}");
}

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")}))
	bench := text(at(state, "selected"))
	for w := 0; w < 120; w++ {
		if at(must(client.Agent.ResourceRead(ctx, mcp.AgentResourceReadArgs{Uri: bench})), "engine") == "ready" {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}
	made := must(client.Strategy.Batch(ctx, mcp.StrategyBatchArgs{Strategy: "rsi pullback", Bench: bench, Grid: map[string]any{"studies.rsi.settings.period": []any{10, 14}, "exits.stop.atr.times": []any{1.0, 2.0}}}))
	batch := text(at(made, "uri"))
	var b any = must(client.Strategy.BatchGet(ctx, mcp.StrategyBatchGetArgs{Batch: batch}))
	for w := 0; w < 1200; w++ {
		b = must(client.Strategy.BatchGet(ctx, mcp.StrategyBatchGetArgs{Batch: batch}))
		if at(b, "record") != nil {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}
	fmt.Println("cells settled:", at(b, "settled"))
	fmt.Println("against chance:", at(b, "statistics"))
	l := must(client.Strategy.LedgerQuery(ctx, mcp.StrategyLedgerQueryArgs{Limit: mcp.Ptr[int64](5), Strategy: mcp.Ptr[string]("rsi pullback")}))
	fmt.Println("trials of rsi pullback:", at(l, "trials"))
	fmt.Println("trials of everything:", at(l, "union"))
	fam := must(client.Strategy.LedgerRecord(ctx, mcp.StrategyLedgerRecordArgs{Kind: "trial", Count: mcp.Ptr[int64](50), Description: mcp.Ptr[string]("50 moving-average pairs tried in my own notebook"), Family: mcp.Ptr[string]("my-grid-search")}))
	fmt.Println("line:", at(fam, "seq"))
	fmt.Println("the union now:", at(fam, "union"))
	run := text(at(b, "cells", 0, "state", "run"))
	r := must(client.Strategy.RunRobustness(ctx, mcp.StrategyRunRobustnessArgs{Run: run}))
	fmt.Println("drawdown reshuffled:", at(r, "reshuffle_max_drawdown"))
	fmt.Println("random entry:", at(r, "random_entry"))
	fmt.Println("metrics:", at(r, "metrics"))
	p := must(client.Strategy.RunParity(ctx, mcp.StrategyRunParityArgs{Run: run, List: "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"}))
	fmt.Println("the same list:", at(p, "parity"))
	fmt.Println("they part at:", at(p, "first_difference"))
	opt := must(client.Strategy.OptimisationImport(ctx, mcp.StrategyOptimisationImportArgs{Name: "MyCrossEA", Table: "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"}))
	fmt.Println("passes in the ledger:", at(opt, "trials_in_ledger"))
	fmt.Println("best pass:", at(opt, "best", "pass"))
	fmt.Println("its Sharpe ratio:", at(opt, "best", "sharpe"))
	fmt.Println("probabilistic:", at(opt, "psr"))
	fmt.Println("deflated:", at(opt, "dsr"))
	fmt.Println("assumed:", at(opt, "assumed"))
	fam_test := must(client.Strategy.StatsFamilyTest(ctx, mcp.StrategyStatsFamilyTestArgs{Series: []any{[]any{0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2}, []any{0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1}, []any{-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1}}, Resamples: mcp.Ptr[int64](1000), Seed: mcp.Ptr[int64](7)}))
	fmt.Println("superior predictive ability:", at(fam_test, "spa"))
	fmt.Println("Romano-Wolf:", at(fam_test, "romano_wolf"))
	_ = must(client.Strategy.BatteryRun(ctx, mcp.StrategyBatteryRunArgs{Bench: bench}))
	var bat any = must(client.Strategy.BatteryGet(ctx))
	for w := 0; w < 1800; w++ {
		bat = must(client.Strategy.BatteryGet(ctx))
		if at(bat, "checks") != nil {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}
	fmt.Println("passed:", at(bat, "passed"))
	fmt.Println("failed:", at(bat, "failed_checks"))
	for _, c := range at(bat, "checks").([]any) {
		fmt.Println("check:", at(c, "name"))
		fmt.Println("  ", at(c, "verdict"))
		fmt.Println("  found:", at(c, "said"))
	}
	_ = []any{state, bench, made, batch, b, l, fam, run, r, p, opt, fam_test, bat}
}

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;
    }

    // obj makes an object of name, value pairs: obj("period", 14).
    static Map<String, Object> obj(Object... kv) {
        Map<String, Object> m = new LinkedHashMap<>();
        for (int i = 0; i < kv.length; i += 2) {
            m.put((String) kv[i], kv[i + 1]);
        }
        return m;
    }

    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 bench = (String) at(state, "selected");
            for (int w = 0; w < 120; w++) {
                if ("ready".equals(at(client.agent.resourceRead(new Bentrix.AgentApi.ResourceReadArgs(bench)), "engine"))) break;
                Thread.sleep(500);
            }
            Object made = client.strategy.batch(new Bentrix.StrategyApi.BatchArgs("rsi pullback", bench, obj("studies.rsi.settings.period", java.util.Arrays.asList(10, 14), "exits.stop.atr.times", java.util.Arrays.asList(1.0, 2.0))));
            String batch = (String) at(made, "uri");
            Object b = client.strategy.batchGet(new Bentrix.StrategyApi.BatchGetArgs(batch));
            for (int w = 0; w < 1200; w++) {
                b = client.strategy.batchGet(new Bentrix.StrategyApi.BatchGetArgs(batch));
                if (at(b, "record") != null) break;
                Thread.sleep(500);
            }
            System.out.println("cells settled:" + " " + at(b, "settled"));
            System.out.println("against chance:" + " " + at(b, "statistics"));
            Object l = client.strategy.ledgerQuery(new Bentrix.StrategyApi.LedgerQueryArgs().limit(5L).strategy("rsi pullback"));
            System.out.println("trials of rsi pullback:" + " " + at(l, "trials"));
            System.out.println("trials of everything:" + " " + at(l, "union"));
            Object fam = client.strategy.ledgerRecord(new Bentrix.StrategyApi.LedgerRecordArgs("trial").count(50L).description("50 moving-average pairs tried in my own notebook").family("my-grid-search"));
            System.out.println("line:" + " " + at(fam, "seq"));
            System.out.println("the union now:" + " " + at(fam, "union"));
            String run = (String) at(b, "cells", 0, "state", "run");
            Object r = client.strategy.runRobustness(new Bentrix.StrategyApi.RunRobustnessArgs(run));
            System.out.println("drawdown reshuffled:" + " " + at(r, "reshuffle_max_drawdown"));
            System.out.println("random entry:" + " " + at(r, "random_entry"));
            System.out.println("metrics:" + " " + at(r, "metrics"));
            Object p = client.strategy.runParity(new Bentrix.StrategyApi.RunParityArgs(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"));
            System.out.println("the same list:" + " " + at(p, "parity"));
            System.out.println("they part at:" + " " + at(p, "first_difference"));
            Object opt = client.strategy.optimisationImport(new Bentrix.StrategyApi.OptimisationImportArgs("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"));
            System.out.println("passes in the ledger:" + " " + at(opt, "trials_in_ledger"));
            System.out.println("best pass:" + " " + at(opt, "best", "pass"));
            System.out.println("its Sharpe ratio:" + " " + at(opt, "best", "sharpe"));
            System.out.println("probabilistic:" + " " + at(opt, "psr"));
            System.out.println("deflated:" + " " + at(opt, "dsr"));
            System.out.println("assumed:" + " " + at(opt, "assumed"));
            Object fam_test = client.strategy.statsFamilyTest(new Bentrix.StrategyApi.StatsFamilyTestArgs(java.util.Arrays.asList(java.util.Arrays.asList(0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2), java.util.Arrays.asList(0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1), java.util.Arrays.asList(-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1))).resamples(1000L).seed(7L));
            System.out.println("superior predictive ability:" + " " + at(fam_test, "spa"));
            System.out.println("Romano-Wolf:" + " " + at(fam_test, "romano_wolf"));
            client.strategy.batteryRun(new Bentrix.StrategyApi.BatteryRunArgs(bench));
            Object bat = client.strategy.batteryGet();
            for (int w = 0; w < 1800; w++) {
                bat = client.strategy.batteryGet();
                if (at(bat, "checks") != null) break;
                Thread.sleep(500);
            }
            System.out.println("passed:" + " " + at(bat, "passed"));
            System.out.println("failed:" + " " + at(bat, "failed_checks"));
            for (Object c : (List<Object>) at(bat, "checks")) {
                System.out.println("check:" + " " + at(c, "name"));
                System.out.println("  " + " " + at(c, "verdict"));
                System.out.println("  found:" + " " + at(c, "said"));
            }
        }
    }
}

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 bench = (state["selected"].is_string() ? state["selected"].str() : std::string());
    for (int w = 0; w < 120; w++) {
        if (client.agent.resource_read(AgentApi::ResourceReadArgs(bench))["engine"].str() == "ready") break;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    auto made = client.strategy.batch(StrategyApi::BatchArgs("rsi pullback", bench, Json::Object{{"studies.rsi.settings.period", Json::Array{10, 14}}, {"exits.stop.atr.times", Json::Array{1.0, 2.0}}}));
    auto batch = (made["uri"].is_string() ? made["uri"].str() : std::string());
    Json b = client.strategy.batch_get(StrategyApi::BatchGetArgs(batch));
    for (int w = 0; w < 1200; w++) {
        b = client.strategy.batch_get(StrategyApi::BatchGetArgs(batch));
        if (!b["record"].is_null()) break;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    std::cout << "cells settled:" << " " << b["settled"].dump() << std::endl;
    std::cout << "against chance:" << " " << b["statistics"].dump() << std::endl;
    auto l = client.strategy.ledger_query(StrategyApi::LedgerQueryArgs().limit(5).strategy("rsi pullback"));
    std::cout << "trials of rsi pullback:" << " " << l["trials"].dump() << std::endl;
    std::cout << "trials of everything:" << " " << l["union"].dump() << std::endl;
    auto fam = client.strategy.ledger_record(StrategyApi::LedgerRecordArgs("trial").count(50).description("50 moving-average pairs tried in my own notebook").family("my-grid-search"));
    std::cout << "line:" << " " << fam["seq"].dump() << std::endl;
    std::cout << "the union now:" << " " << fam["union"].dump() << std::endl;
    auto run = (b["cells"][0u]["state"]["run"].is_string() ? b["cells"][0u]["state"]["run"].str() : std::string());
    auto r = client.strategy.run_robustness(StrategyApi::RunRobustnessArgs(run));
    std::cout << "drawdown reshuffled:" << " " << r["reshuffle_max_drawdown"].dump() << std::endl;
    std::cout << "random entry:" << " " << r["random_entry"].dump() << std::endl;
    std::cout << "metrics:" << " " << r["metrics"].dump() << std::endl;
    auto p = client.strategy.run_parity(StrategyApi::RunParityArgs(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"));
    std::cout << "the same list:" << " " << p["parity"].dump() << std::endl;
    std::cout << "they part at:" << " " << p["first_difference"].dump() << std::endl;
    auto opt = client.strategy.optimisation_import(StrategyApi::OptimisationImportArgs("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"));
    std::cout << "passes in the ledger:" << " " << opt["trials_in_ledger"].dump() << std::endl;
    std::cout << "best pass:" << " " << opt["best"]["pass"].dump() << std::endl;
    std::cout << "its Sharpe ratio:" << " " << opt["best"]["sharpe"].dump() << std::endl;
    std::cout << "probabilistic:" << " " << opt["psr"].dump() << std::endl;
    std::cout << "deflated:" << " " << opt["dsr"].dump() << std::endl;
    std::cout << "assumed:" << " " << opt["assumed"].dump() << std::endl;
    auto fam_test = client.strategy.stats_family_test(StrategyApi::StatsFamilyTestArgs(Json::Array{Json::Array{0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2}, Json::Array{0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1}, Json::Array{-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1}}).resamples(1000).seed(7));
    std::cout << "superior predictive ability:" << " " << fam_test["spa"].dump() << std::endl;
    std::cout << "Romano-Wolf:" << " " << fam_test["romano_wolf"].dump() << std::endl;
    client.strategy.battery_run(StrategyApi::BatteryRunArgs(bench));
    Json bat = client.strategy.battery_get();
    for (int w = 0; w < 1800; w++) {
        bat = client.strategy.battery_get();
        if (!bat["checks"].is_null()) break;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    std::cout << "passed:" << " " << bat["passed"].dump() << std::endl;
    std::cout << "failed:" << " " << bat["failed_checks"].dump() << std::endl;
    for (const Json &c : bat["checks"].arr()) {
        std::cout << "check:" << " " << c["name"].dump() << std::endl;
        std::cout << "  " << " " << c["verdict"].dump() << std::endl;
        std::cout << "  found:" << " " << c["said"].dump() << std::endl;
    }
}

Julia

using BentrixMCP

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

state = client.workspace.get_state(; depth = "benches")
bench = state["selected"]
for _ in 1:120
    client.agent.resource_read(bench)["engine"] == "ready" && break
    sleep(0.5)
end
made = client.strategy.batch("rsi pullback", bench, Dict{String,Any}("studies.rsi.settings.period" => Any[10, 14], "exits.stop.atr.times" => Any[1.0, 2.0]))
batch = made["uri"]
b = client.strategy.batch_get(batch)
for _ in 1:1200
    global b = client.strategy.batch_get(batch)
    b["record"] !== nothing && break
    sleep(0.5)
end
println("cells settled:", " ", b["settled"])
println("against chance:", " ", b["statistics"])
l = client.strategy.ledger_query(; limit = 5, strategy = "rsi pullback")
println("trials of rsi pullback:", " ", l["trials"])
println("trials of everything:", " ", l["union"])
fam = client.strategy.ledger_record("trial"; count = 50, description = "50 moving-average pairs tried in my own notebook", family = "my-grid-search")
println("line:", " ", fam["seq"])
println("the union now:", " ", fam["union"])
run = b["cells"][1]["state"]["run"]
r = client.strategy.run_robustness(run)
println("drawdown reshuffled:", " ", r["reshuffle_max_drawdown"])
println("random entry:", " ", r["random_entry"])
println("metrics:", " ", r["metrics"])
p = client.strategy.run_parity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]")
println("the same list:", " ", p["parity"])
println("they part at:", " ", p["first_difference"])
opt = client.strategy.optimisation_import("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n")
println("passes in the ledger:", " ", opt["trials_in_ledger"])
println("best pass:", " ", opt["best"]["pass"])
println("its Sharpe ratio:", " ", opt["best"]["sharpe"])
println("probabilistic:", " ", opt["psr"])
println("deflated:", " ", opt["dsr"])
println("assumed:", " ", opt["assumed"])
fam_test = client.strategy.stats_family_test(Any[Any[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], Any[0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], Any[-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]]; resamples = 1000, seed = 7)
println("superior predictive ability:", " ", fam_test["spa"])
println("Romano-Wolf:", " ", fam_test["romano_wolf"])
client.strategy.battery_run(bench)
bat = client.strategy.battery_get()
for _ in 1:1800
    global bat = client.strategy.battery_get()
    bat["checks"] !== nothing && break
    sleep(0.5)
end
println("passed:", " ", bat["passed"])
println("failed:", " ", bat["failed_checks"])
for c in bat["checks"]
    println("check:", " ", c["name"])
    println("  ", " ", c["verdict"])
    println("  found:", " ", c["said"])
end

RR

library(bentrixmcp)

client <- connect("my-agent")

state <- client$workspace$get_state(depth = "benches")
bench <- state$selected
for (w in 1:120) {
  if (client$agent$resource_read(bench)$engine == "ready") break
  Sys.sleep(0.5)
}
made <- client$strategy$batch("rsi pullback", bench, list(studies.rsi.settings.period = list(10, 14), exits.stop.atr.times = list(1.0, 2.0)))
batch <- made$uri
b <- client$strategy$batch_get(batch)
for (w in 1:1200) {
  b <- client$strategy$batch_get(batch)
  if (!is.null(b$record)) break
  Sys.sleep(0.5)
}
cat("cells settled:", format(b$settled), "\n")
cat("against chance:", format(b$statistics), "\n")
l <- client$strategy$ledger_query(limit = 5, strategy = "rsi pullback")
cat("trials of rsi pullback:", format(l$trials), "\n")
cat("trials of everything:", format(l$union), "\n")
fam <- client$strategy$ledger_record("trial", count = 50, description = "50 moving-average pairs tried in my own notebook", family = "my-grid-search")
cat("line:", format(fam$seq), "\n")
cat("the union now:", format(fam$union), "\n")
run <- b$cells[[1]]$state$run
r <- client$strategy$run_robustness(run)
cat("drawdown reshuffled:", format(r$reshuffle_max_drawdown), "\n")
cat("random entry:", format(r$random_entry), "\n")
cat("metrics:", format(r$metrics), "\n")
p <- client$strategy$run_parity(run, "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]")
cat("the same list:", format(p$parity), "\n")
cat("they part at:", format(p$first_difference), "\n")
opt <- client$strategy$optimisation_import("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n")
cat("passes in the ledger:", format(opt$trials_in_ledger), "\n")
cat("best pass:", format(opt$best$pass), "\n")
cat("its Sharpe ratio:", format(opt$best$sharpe), "\n")
cat("probabilistic:", format(opt$psr), "\n")
cat("deflated:", format(opt$dsr), "\n")
cat("assumed:", format(opt$assumed), "\n")
fam_test <- client$strategy$stats_family_test(list(list(0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2), list(0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1), list(-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1)), resamples = 1000, seed = 7)
cat("superior predictive ability:", format(fam_test$spa), "\n")
cat("Romano-Wolf:", format(fam_test$romano_wolf), "\n")
client$strategy$battery_run(bench)
bat <- client$strategy$battery_get()
for (w in 1:1800) {
  bat <- client$strategy$battery_get()
  if (!is.null(bat$checks)) break
  Sys.sleep(0.5)
}
cat("passed:", format(bat$passed), "\n")
cat("failed:", format(bat$failed_checks), "\n")
for (c in bat$checks) {
  cat("check:", format(c$name), "\n")
  cat("  ", format(c$verdict), "\n")
  cat("  found:", format(c$said), "\n")
}

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 bench = state["selected"].as_str().unwrap_or_default().to_string();
    for _ in 0..120 {
        if client.agent().resource_read(mcp::AgentResourceReadArgs::new(bench.clone()))?["engine"] == "ready" {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    let made = client.strategy().batch(mcp::StrategyBatchArgs::new("rsi pullback", bench.clone(), serde_json::json!({"studies.rsi.settings.period": [10, 14], "exits.stop.atr.times": [1.0, 2.0]})))?;
    let batch = made["uri"].as_str().unwrap_or_default().to_string();
    let mut b = client.strategy().batch_get(mcp::StrategyBatchGetArgs::new(batch.clone()))?;
    for _ in 0..1200 {
        b = client.strategy().batch_get(mcp::StrategyBatchGetArgs::new(batch.clone()))?;
        if !b["record"].is_null() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    println!("cells settled: {}", b["settled"]);
    println!("against chance: {}", b["statistics"]);
    let l = client.strategy().ledger_query(mcp::StrategyLedgerQueryArgs::new().limit(5).strategy("rsi pullback"))?;
    println!("trials of rsi pullback: {}", l["trials"]);
    println!("trials of everything: {}", l["union"]);
    let fam = client.strategy().ledger_record(mcp::StrategyLedgerRecordArgs::new("trial").count(50).description("50 moving-average pairs tried in my own notebook").family("my-grid-search"))?;
    println!("line: {}", fam["seq"]);
    println!("the union now: {}", fam["union"]);
    let run = b["cells"][0]["state"]["run"].as_str().unwrap_or_default().to_string();
    let r = client.strategy().run_robustness(mcp::StrategyRunRobustnessArgs::new(run.clone()))?;
    println!("drawdown reshuffled: {}", r["reshuffle_max_drawdown"]);
    println!("random entry: {}", r["random_entry"]);
    println!("metrics: {}", r["metrics"]);
    let p = client.strategy().run_parity(mcp::StrategyRunParityArgs::new(run.clone(), "[{\"time_ms\": 1704182400000, \"long\": true, \"net\": 12.5}, {\"time_ms\": 1704268800000, \"long\": false, \"net\": -4.1}]"))?;
    println!("the same list: {}", p["parity"]);
    println!("they part at: {}", p["first_difference"]);
    let opt = client.strategy().optimisation_import(mcp::StrategyOptimisationImportArgs::new("MyCrossEA", "Pass,Result,Profit,Sharpe Ratio,Trades,Fast,Slow\n1,10420.5,420.5,1.10,118,8,21\n2,9919.8,-80.2,-0.20,131,10,21\n3,10610.0,610.0,1.45,96,8,34\n4,10150.3,150.3,0.40,104,12,34\n"))?;
    println!("passes in the ledger: {}", opt["trials_in_ledger"]);
    println!("best pass: {}", opt["best"]["pass"]);
    println!("its Sharpe ratio: {}", opt["best"]["sharpe"]);
    println!("probabilistic: {}", opt["psr"]);
    println!("deflated: {}", opt["dsr"]);
    println!("assumed: {}", opt["assumed"]);
    let fam_test = client.strategy().stats_family_test(mcp::StrategyStatsFamilyTestArgs::new(serde_json::json!([[0.4, -0.1, 0.3, 0.2, -0.2, 0.5, 0.1, -0.3, 0.2, 0.4, 0.0, 0.3, -0.1, 0.2, 0.1, 0.3, -0.2, 0.4, 0.1, 0.2], [0.1, 0.0, -0.2, 0.1, 0.2, -0.1, 0.0, 0.1, -0.1, 0.2, 0.1, -0.2, 0.0, 0.1, 0.0, -0.1, 0.2, 0.0, -0.1, 0.1], [-0.3, 0.2, 0.1, -0.4, 0.3, 0.0, -0.2, 0.2, 0.1, -0.3, 0.2, 0.0, -0.1, 0.3, -0.2, 0.1, 0.0, -0.2, 0.2, -0.1]])).resamples(1000).seed(7))?;
    println!("superior predictive ability: {}", fam_test["spa"]);
    println!("Romano-Wolf: {}", fam_test["romano_wolf"]);
    client.strategy().battery_run(mcp::StrategyBatteryRunArgs::new(bench.clone()))?;
    let mut bat = client.strategy().battery_get()?;
    for _ in 0..1800 {
        bat = client.strategy().battery_get()?;
        if !bat["checks"].is_null() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    println!("passed: {}", bat["passed"]);
    println!("failed: {}", bat["failed_checks"]);
    for c in bat["checks"].as_array().into_iter().flatten() {
        println!("check: {}", c["name"]);
        println!("   {}", c["verdict"]);
        println!("  found: {}", c["said"]);
    }
    Ok(())
}

None of these says a strategy will work. Each is a way of finding out that it probably will not, cheaply, in the laboratory.

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