Bentrix Docs
HomePricingDashboard

8. Bentrix's indicators

Attach any of Bentrix's indicators to a chart, change its settings, and read its values — computed by Bentrix exactly as the chart draws them.

Bentrix computes 227 indicators; a program uses them two ways. On a chart: attach one, as the indicator menu does, and change its settings as its settings card does. As numbers: ask for its values over a market and an interval, up to the clock — the same values the chart draws, without your program computing anything.

01Step 1 — the workbench, a chart, some history

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)
wb = client.agent.resource_read(bench)
market = wb["markets"][0]
client.replay.step(bench, n=200, timeframe="H1", unit="candle")
opened = client.chart.open(bench, market, timeframe="H1")
chart = opened["uri"]

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));
}
const wb = await client.agent.resourceRead({ uri: bench });
const market = wb.markets[0];
await client.replay.step({ bench, n: 200, timeframe: "H1", unit: "candle" });
const opened = await client.chart.open({ bench, symbol: market, timeframe: "H1" });
const chart = opened.uri;

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);
}
var wb = await client.Agent.ResourceRead(bench);
var market = wb!["markets"]![0]?.GetValue<string>() ?? "";
await client.Replay.Step(bench, n: 200, timeframe: "H1", unit: "candle");
var opened = await client.Chart.Open(bench, market, timeframe: "H1");
var chart = opened!["uri"]?.GetValue<string>() ?? "";

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)
}
wb := must(client.Agent.ResourceRead(ctx, mcp.AgentResourceReadArgs{Uri: bench}))
market := text(at(wb, "markets", 0))
_ = must(client.Replay.Step(ctx, mcp.ReplayStepArgs{Bench: bench, N: mcp.Ptr[int64](200), Timeframe: mcp.Ptr[string]("H1"), Unit: mcp.Ptr[string]("candle")}))
opened := must(client.Chart.Open(ctx, mcp.ChartOpenArgs{Bench: bench, Symbol: market, Timeframe: mcp.Ptr[string]("H1")}))
chart := text(at(opened, "uri"))

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);
}
Object wb = client.agent.resourceRead(new Bentrix.AgentApi.ResourceReadArgs(bench));
String market = (String) at(wb, "markets", 0);
client.replay.step(new Bentrix.ReplayApi.StepArgs(bench).n(200L).timeframe("H1").unit("candle"));
Object opened = client.chart.open(new Bentrix.ChartApi.OpenArgs(bench, market).timeframe("H1"));
String chart = (String) at(opened, "uri");

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));
}
auto wb = client.agent.resource_read(AgentApi::ResourceReadArgs(bench));
auto market = (wb["markets"][0u].is_string() ? wb["markets"][0u].str() : std::string());
client.replay.step(ReplayApi::StepArgs(bench).n(200).timeframe("H1").unit("candle"));
auto opened = client.chart.open(ChartApi::OpenArgs(bench, market).timeframe("H1"));
auto chart = (opened["uri"].is_string() ? opened["uri"].str() : std::string());

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
wb = client.agent.resource_read(bench)
market = wb["markets"][1]
client.replay.step(bench; n = 200, timeframe = "H1", unit = "candle")
opened = client.chart.open(bench, market; timeframe = "H1")
chart = opened["uri"]

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)
}
wb <- client$agent$resource_read(bench)
market <- wb$markets[[1]]
client$replay$step(bench, n = 200, timeframe = "H1", unit = "candle")
opened <- client$chart$open(bench, market, timeframe = "H1")
chart <- opened$uri

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));
}
let wb = client.agent().resource_read(mcp::AgentResourceReadArgs::new(bench.clone()))?;
let market = wb["markets"][0].as_str().unwrap_or_default().to_string();
client.replay().step(mcp::ReplayStepArgs::new(bench.clone()).n(200).timeframe("H1").unit("candle"))?;
let opened = client.chart().open(mcp::ChartOpenArgs::new(bench.clone(), market.clone()).timeframe("H1"))?;
let chart = opened["uri"].as_str().unwrap_or_default().to_string();

02Step 2 — attach an RSI

study_attach puts an indicator on a chart by its kind — its name in the indicator reference, such as rsi, ema, macd, bollinger. It answers the chart, whose setup.studies lists every indicator on it with its id; the one just attached is the newest of its kind.

Python

with_rsi = client.study.attach(chart, "rsi")
rsi_id = max(s["id"] for s in with_rsi["setup"]["studies"] if s["kind"] == "rsi")
print("the RSI's id on the chart:", rsi_id)

JSJavaScript

const with_rsi = await client.study.attach({ chart, kind: "rsi" });
const rsi_id = Math.max(...with_rsi.setup.studies.filter((s) => s.kind === "rsi").map((s) => s.id));
console.log("the RSI's id on the chart:", rsi_id);

C#C#

var with_rsi = await client.Study.Attach(chart, "rsi");
var rsi_id = with_rsi!["setup"]!["studies"]!.AsArray().Where(s => s!["kind"]!.GetValue<string>() == "rsi").Max(s => s!["id"]!.GetValue<long>());
Console.WriteLine($"the RSI's id on the chart: {rsi_id}");

GOGo

with_rsi := must(client.Study.Attach(ctx, mcp.StudyAttachArgs{Chart: chart, Kind: "rsi"}))
rsi_id := studyID(with_rsi, "rsi")
fmt.Println("the RSI's id on the chart:", rsi_id)

Java

Object with_rsi = client.study.attach(new Bentrix.StudyApi.AttachArgs(chart, "rsi"));
long rsi_id = studyId(with_rsi, "rsi");
System.out.println("the RSI's id on the chart:" + " " + rsi_id);

C++C++

auto with_rsi = client.study.attach(StudyApi::AttachArgs(chart, "rsi"));
auto rsi_id = study_id(with_rsi, "rsi");
std::cout << "the RSI's id on the chart:" << " " << rsi_id << std::endl;

Julia

with_rsi = client.study.attach(chart, "rsi")
rsi_id = maximum(s["id"] for s in with_rsi["setup"]["studies"] if s["kind"] == "rsi")
println("the RSI's id on the chart:", " ", rsi_id)

RR

with_rsi <- client$study$attach(chart, "rsi")
rsi_id <- max(vapply(Filter(function(s) s$kind == "rsi", with_rsi$setup$studies), function(s) s$id, numeric(1)))
cat("the RSI's id on the chart:", format(rsi_id), "\n")

RRust

let with_rsi = client.study().attach(mcp::StudyAttachArgs::new(chart.clone(), "rsi"))?;
let rsi_id = with_rsi["setup"]["studies"].as_array().into_iter().flatten().filter(|s| s["kind"] == "rsi").filter_map(|s| s["id"].as_i64()).max().unwrap_or(-1);
println!("the RSI's id on the chart: {:?}", rsi_id);

03Step 3 — change its period

study_set_inputs changes what the Inputs tab of its settings card holds: here its settings, a period of 21.

Python

client.study.set_inputs(chart, rsi_id, {"settings": {"shape": "period", "period": 21}})

JSJavaScript

await client.study.setInputs({ chart, study: rsi_id, patch: { "settings": { "shape": "period", "period": 21 } } });

C#C#

await client.Study.SetInputs(chart, rsi_id, new Dictionary<string, object?> { ["settings"] = new Dictionary<string, object?> { ["shape"] = "period", ["period"] = 21 } });

GOGo

_ = must(client.Study.SetInputs(ctx, mcp.StudySetInputsArgs{Chart: chart, Study: rsi_id, Patch: map[string]any{"settings": map[string]any{"shape": "period", "period": 21}}}))

Java

client.study.setInputs(new Bentrix.StudyApi.SetInputsArgs(chart, rsi_id, obj("settings", obj("shape", "period", "period", 21))));

C++C++

client.study.set_inputs(StudyApi::SetInputsArgs(chart, rsi_id, Json::Object{{"settings", Json::Object{{"shape", "period"}, {"period", 21}}}}));

Julia

client.study.set_inputs(chart, rsi_id, Dict{String,Any}("settings" => Dict{String,Any}("shape" => "period", "period" => 21)))

RR

client$study$set_inputs(chart, rsi_id, list(settings = list(shape = "period", period = 21)))

RRust

client.study().set_inputs(mcp::StudySetInputsArgs::new(chart.clone(), rsi_id.clone(), serde_json::json!({"settings": {"shape": "period", "period": 21}})))?;

The chart redraws the RSI at once.

04Step 4 — read its values

study_values computes an indicator over a workbench's candles at the clock and answers each of its lines by name, with the newest limit values beside their candles' times. The indicator is given as the chart files it: its kind, its convention (mt5 or talib, where the two calculate differently), the price it reads (applied) and its settings.

Python

values = client.study.values(bench, market, "H1", {"kind": "rsi", "convention": "mt5", "applied": "close", "settings": {"shape": "period", "period": 21}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
    print("line:", line["line"])
    print("  values:", line["values"])
rsi_now = values["lines"][0]["values"][-1]
print("RSI at the clock:", rsi_now)

JSJavaScript

const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "kind": "rsi", "convention": "mt5", "applied": "close", "settings": { "shape": "period", "period": 21 } }, limit: 5 });
console.log("times:", values.times);
for (const line of values.lines) {
  console.log("line:", line.line);
  console.log("  values:", line.values);
}
const rsi_now = values.lines[0].values.at(-1);
console.log("RSI at the clock:", rsi_now);

C#C#

var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["kind"] = "rsi", ["convention"] = "mt5", ["applied"] = "close", ["settings"] = new Dictionary<string, object?> { ["shape"] = "period", ["period"] = 21 } }, limit: 5);
Console.WriteLine($"times: {values!["times"]!}");
foreach (var line in values!["lines"]!.AsArray())
{
    Console.WriteLine($"line: {line!["line"]!}");
    Console.WriteLine($"  values: {line!["values"]!}");
}
var rsi_now = values!["lines"]![0]!["values"]!.AsArray().Last()!.GetValue<double>();
Console.WriteLine($"RSI at the clock: {rsi_now}");

GOGo

values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"kind": "rsi", "convention": "mt5", "applied": "close", "settings": map[string]any{"shape": "period", "period": 21}}, Limit: mcp.Ptr[int64](5)}))
fmt.Println("times:", at(values, "times"))
for _, line := range at(values, "lines").([]any) {
	fmt.Println("line:", at(line, "line"))
	fmt.Println("  values:", at(line, "values"))
}
rsi_now := num(at(values, "lines", 0, "values").([]any)[len(at(values, "lines", 0, "values").([]any))-1])
fmt.Println("RSI at the clock:", rsi_now)

Java

Object values = client.study.values(new Bentrix.StudyApi.ValuesArgs(bench, market, "H1", obj("kind", "rsi", "convention", "mt5", "applied", "close", "settings", obj("shape", "period", "period", 21))).limit(5L));
System.out.println("times:" + " " + at(values, "times"));
for (Object line : (List<Object>) at(values, "lines")) {
    System.out.println("line:" + " " + at(line, "line"));
    System.out.println("  values:" + " " + at(line, "values"));
}
double rsi_now = ((Number) ((List<?>) at(values, "lines", 0, "values")).get(((List<?>) at(values, "lines", 0, "values")).size() - 1)).doubleValue();
System.out.println("RSI at the clock:" + " " + rsi_now);

C++C++

auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"kind", "rsi"}, {"convention", "mt5"}, {"applied", "close"}, {"settings", Json::Object{{"shape", "period"}, {"period", 21}}}}).limit(5));
std::cout << "times:" << " " << values["times"].dump() << std::endl;
for (const Json &line : values["lines"].arr()) {
    std::cout << "line:" << " " << line["line"].dump() << std::endl;
    std::cout << "  values:" << " " << line["values"].dump() << std::endl;
}
auto rsi_now = values["lines"][0u]["values"].arr().back().num();
std::cout << "RSI at the clock:" << " " << rsi_now << std::endl;

Julia

values = client.study.values(bench, market, "H1", Dict{String,Any}("kind" => "rsi", "convention" => "mt5", "applied" => "close", "settings" => Dict{String,Any}("shape" => "period", "period" => 21)); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
    println("line:", " ", line["line"])
    println("  values:", " ", line["values"])
end
rsi_now = values["lines"][1]["values"][end]
println("RSI at the clock:", " ", rsi_now)

RR

values <- client$study$values(bench, market, "H1", list(kind = "rsi", convention = "mt5", applied = "close", settings = list(shape = "period", period = 21)), limit = 5)
cat("times:", format(values$times), "\n")
for (line in values$lines) {
  cat("line:", format(line$line), "\n")
  cat("  values:", format(line$values), "\n")
}
rsi_now <- tail(values$lines[[1]]$values, 1)[[1]]
cat("RSI at the clock:", format(rsi_now), "\n")

RRust

let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"kind": "rsi", "convention": "mt5", "applied": "close", "settings": {"shape": "period", "period": 21}})).limit(5))?;
println!("times: {}", values["times"]);
for line in values["lines"].as_array().into_iter().flatten() {
    println!("line: {}", line["line"]);
    println!("  values: {}", line["values"]);
}
let rsi_now = values["lines"][0]["values"].as_array().and_then(|a| a.last()).and_then(|v| v.as_f64()).unwrap_or(f64::NAN);
println!("RSI at the clock: {}", rsi_now);

No chart is needed for study_values: a program can read an indicator it never draws.

05Step 5 — an overlay too

An overlay such as an exponential moving average draws over the prices. Its period is set the same way.

Python

with_ema = client.study.attach(chart, "ema")
ema_id = max(s["id"] for s in with_ema["setup"]["studies"] if s["kind"] == "ema")
client.study.set_inputs(chart, ema_id, {"settings": {"shape": "period", "period": 50}})

JSJavaScript

const with_ema = await client.study.attach({ chart, kind: "ema" });
const ema_id = Math.max(...with_ema.setup.studies.filter((s) => s.kind === "ema").map((s) => s.id));
await client.study.setInputs({ chart, study: ema_id, patch: { "settings": { "shape": "period", "period": 50 } } });

C#C#

var with_ema = await client.Study.Attach(chart, "ema");
var ema_id = with_ema!["setup"]!["studies"]!.AsArray().Where(s => s!["kind"]!.GetValue<string>() == "ema").Max(s => s!["id"]!.GetValue<long>());
await client.Study.SetInputs(chart, ema_id, new Dictionary<string, object?> { ["settings"] = new Dictionary<string, object?> { ["shape"] = "period", ["period"] = 50 } });

GOGo

with_ema := must(client.Study.Attach(ctx, mcp.StudyAttachArgs{Chart: chart, Kind: "ema"}))
ema_id := studyID(with_ema, "ema")
_ = must(client.Study.SetInputs(ctx, mcp.StudySetInputsArgs{Chart: chart, Study: ema_id, Patch: map[string]any{"settings": map[string]any{"shape": "period", "period": 50}}}))

Java

Object with_ema = client.study.attach(new Bentrix.StudyApi.AttachArgs(chart, "ema"));
long ema_id = studyId(with_ema, "ema");
client.study.setInputs(new Bentrix.StudyApi.SetInputsArgs(chart, ema_id, obj("settings", obj("shape", "period", "period", 50))));

C++C++

auto with_ema = client.study.attach(StudyApi::AttachArgs(chart, "ema"));
auto ema_id = study_id(with_ema, "ema");
client.study.set_inputs(StudyApi::SetInputsArgs(chart, ema_id, Json::Object{{"settings", Json::Object{{"shape", "period"}, {"period", 50}}}}));

Julia

with_ema = client.study.attach(chart, "ema")
ema_id = maximum(s["id"] for s in with_ema["setup"]["studies"] if s["kind"] == "ema")
client.study.set_inputs(chart, ema_id, Dict{String,Any}("settings" => Dict{String,Any}("shape" => "period", "period" => 50)))

RR

with_ema <- client$study$attach(chart, "ema")
ema_id <- max(vapply(Filter(function(s) s$kind == "ema", with_ema$setup$studies), function(s) s$id, numeric(1)))
client$study$set_inputs(chart, ema_id, list(settings = list(shape = "period", period = 50)))

RRust

let with_ema = client.study().attach(mcp::StudyAttachArgs::new(chart.clone(), "ema"))?;
let ema_id = with_ema["setup"]["studies"].as_array().into_iter().flatten().filter(|s| s["kind"] == "ema").filter_map(|s| s["id"].as_i64()).max().unwrap_or(-1);
client.study().set_inputs(mcp::StudySetInputsArgs::new(chart.clone(), ema_id.clone(), serde_json::json!({"settings": {"shape": "period", "period": 50}})))?;

06The 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)
wb = client.agent.resource_read(bench)
market = wb["markets"][0]
client.replay.step(bench, n=200, timeframe="H1", unit="candle")
opened = client.chart.open(bench, market, timeframe="H1")
chart = opened["uri"]
with_rsi = client.study.attach(chart, "rsi")
rsi_id = max(s["id"] for s in with_rsi["setup"]["studies"] if s["kind"] == "rsi")
print("the RSI's id on the chart:", rsi_id)
client.study.set_inputs(chart, rsi_id, {"settings": {"shape": "period", "period": 21}})
values = client.study.values(bench, market, "H1", {"kind": "rsi", "convention": "mt5", "applied": "close", "settings": {"shape": "period", "period": 21}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
    print("line:", line["line"])
    print("  values:", line["values"])
rsi_now = values["lines"][0]["values"][-1]
print("RSI at the clock:", rsi_now)
with_ema = client.study.attach(chart, "ema")
ema_id = max(s["id"] for s in with_ema["setup"]["studies"] if s["kind"] == "ema")
client.study.set_inputs(chart, ema_id, {"settings": {"shape": "period", "period": 50}})

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 wb = await client.agent.resourceRead({ uri: bench });
  const market = wb.markets[0];
  await client.replay.step({ bench, n: 200, timeframe: "H1", unit: "candle" });
  const opened = await client.chart.open({ bench, symbol: market, timeframe: "H1" });
  const chart = opened.uri;
  const with_rsi = await client.study.attach({ chart, kind: "rsi" });
  const rsi_id = Math.max(...with_rsi.setup.studies.filter((s) => s.kind === "rsi").map((s) => s.id));
  console.log("the RSI's id on the chart:", rsi_id);
  await client.study.setInputs({ chart, study: rsi_id, patch: { "settings": { "shape": "period", "period": 21 } } });
  const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "kind": "rsi", "convention": "mt5", "applied": "close", "settings": { "shape": "period", "period": 21 } }, limit: 5 });
  console.log("times:", values.times);
  for (const line of values.lines) {
    console.log("line:", line.line);
    console.log("  values:", line.values);
  }
  const rsi_now = values.lines[0].values.at(-1);
  console.log("RSI at the clock:", rsi_now);
  const with_ema = await client.study.attach({ chart, kind: "ema" });
  const ema_id = Math.max(...with_ema.setup.studies.filter((s) => s.kind === "ema").map((s) => s.id));
  await client.study.setInputs({ chart, study: ema_id, patch: { "settings": { "shape": "period", "period": 50 } } });
})();

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 wb = await client.Agent.ResourceRead(bench);
var market = wb!["markets"]![0]?.GetValue<string>() ?? "";
await client.Replay.Step(bench, n: 200, timeframe: "H1", unit: "candle");
var opened = await client.Chart.Open(bench, market, timeframe: "H1");
var chart = opened!["uri"]?.GetValue<string>() ?? "";
var with_rsi = await client.Study.Attach(chart, "rsi");
var rsi_id = with_rsi!["setup"]!["studies"]!.AsArray().Where(s => s!["kind"]!.GetValue<string>() == "rsi").Max(s => s!["id"]!.GetValue<long>());
Console.WriteLine($"the RSI's id on the chart: {rsi_id}");
await client.Study.SetInputs(chart, rsi_id, new Dictionary<string, object?> { ["settings"] = new Dictionary<string, object?> { ["shape"] = "period", ["period"] = 21 } });
var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["kind"] = "rsi", ["convention"] = "mt5", ["applied"] = "close", ["settings"] = new Dictionary<string, object?> { ["shape"] = "period", ["period"] = 21 } }, limit: 5);
Console.WriteLine($"times: {values!["times"]!}");
foreach (var line in values!["lines"]!.AsArray())
{
    Console.WriteLine($"line: {line!["line"]!}");
    Console.WriteLine($"  values: {line!["values"]!}");
}
var rsi_now = values!["lines"]![0]!["values"]!.AsArray().Last()!.GetValue<double>();
Console.WriteLine($"RSI at the clock: {rsi_now}");
var with_ema = await client.Study.Attach(chart, "ema");
var ema_id = with_ema!["setup"]!["studies"]!.AsArray().Where(s => s!["kind"]!.GetValue<string>() == "ema").Max(s => s!["id"]!.GetValue<long>());
await client.Study.SetInputs(chart, ema_id, new Dictionary<string, object?> { ["settings"] = new Dictionary<string, object?> { ["shape"] = "period", ["period"] = 50 } });

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
}

// studyID is the id of the newest study of this kind in a chart's answer.
func studyID(chart any, kind string) int64 {
	var id int64 = -1
	for _, s := range at(chart, "setup", "studies").([]any) {
		if at(s, "kind") == kind {
			n := int64(num(at(s, "id")))
			if n > id {
				id = n
			}
		}
	}
	return id
}

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)
	}
	wb := must(client.Agent.ResourceRead(ctx, mcp.AgentResourceReadArgs{Uri: bench}))
	market := text(at(wb, "markets", 0))
	_ = must(client.Replay.Step(ctx, mcp.ReplayStepArgs{Bench: bench, N: mcp.Ptr[int64](200), Timeframe: mcp.Ptr[string]("H1"), Unit: mcp.Ptr[string]("candle")}))
	opened := must(client.Chart.Open(ctx, mcp.ChartOpenArgs{Bench: bench, Symbol: market, Timeframe: mcp.Ptr[string]("H1")}))
	chart := text(at(opened, "uri"))
	with_rsi := must(client.Study.Attach(ctx, mcp.StudyAttachArgs{Chart: chart, Kind: "rsi"}))
	rsi_id := studyID(with_rsi, "rsi")
	fmt.Println("the RSI's id on the chart:", rsi_id)
	_ = must(client.Study.SetInputs(ctx, mcp.StudySetInputsArgs{Chart: chart, Study: rsi_id, Patch: map[string]any{"settings": map[string]any{"shape": "period", "period": 21}}}))
	values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"kind": "rsi", "convention": "mt5", "applied": "close", "settings": map[string]any{"shape": "period", "period": 21}}, Limit: mcp.Ptr[int64](5)}))
	fmt.Println("times:", at(values, "times"))
	for _, line := range at(values, "lines").([]any) {
		fmt.Println("line:", at(line, "line"))
		fmt.Println("  values:", at(line, "values"))
	}
	rsi_now := num(at(values, "lines", 0, "values").([]any)[len(at(values, "lines", 0, "values").([]any))-1])
	fmt.Println("RSI at the clock:", rsi_now)
	with_ema := must(client.Study.Attach(ctx, mcp.StudyAttachArgs{Chart: chart, Kind: "ema"}))
	ema_id := studyID(with_ema, "ema")
	_ = must(client.Study.SetInputs(ctx, mcp.StudySetInputsArgs{Chart: chart, Study: ema_id, Patch: map[string]any{"settings": map[string]any{"shape": "period", "period": 50}}}))
	_ = []any{state, bench, wb, market, opened, chart, with_rsi, rsi_id, values, rsi_now, with_ema, ema_id}
}

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

    // studyId is the id of the newest study of this kind in a chart's answer.
    @SuppressWarnings("unchecked")
    static long studyId(Object chart, String kind) {
        long id = -1;
        for (Object s : (List<Object>) at(chart, "setup", "studies")) {
            if (kind.equals(at(s, "kind"))) {
                id = Math.max(id, ((Number) at(s, "id")).longValue());
            }
        }
        return id;
    }

    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 wb = client.agent.resourceRead(new Bentrix.AgentApi.ResourceReadArgs(bench));
            String market = (String) at(wb, "markets", 0);
            client.replay.step(new Bentrix.ReplayApi.StepArgs(bench).n(200L).timeframe("H1").unit("candle"));
            Object opened = client.chart.open(new Bentrix.ChartApi.OpenArgs(bench, market).timeframe("H1"));
            String chart = (String) at(opened, "uri");
            Object with_rsi = client.study.attach(new Bentrix.StudyApi.AttachArgs(chart, "rsi"));
            long rsi_id = studyId(with_rsi, "rsi");
            System.out.println("the RSI's id on the chart:" + " " + rsi_id);
            client.study.setInputs(new Bentrix.StudyApi.SetInputsArgs(chart, rsi_id, obj("settings", obj("shape", "period", "period", 21))));
            Object values = client.study.values(new Bentrix.StudyApi.ValuesArgs(bench, market, "H1", obj("kind", "rsi", "convention", "mt5", "applied", "close", "settings", obj("shape", "period", "period", 21))).limit(5L));
            System.out.println("times:" + " " + at(values, "times"));
            for (Object line : (List<Object>) at(values, "lines")) {
                System.out.println("line:" + " " + at(line, "line"));
                System.out.println("  values:" + " " + at(line, "values"));
            }
            double rsi_now = ((Number) ((List<?>) at(values, "lines", 0, "values")).get(((List<?>) at(values, "lines", 0, "values")).size() - 1)).doubleValue();
            System.out.println("RSI at the clock:" + " " + rsi_now);
            Object with_ema = client.study.attach(new Bentrix.StudyApi.AttachArgs(chart, "ema"));
            long ema_id = studyId(with_ema, "ema");
            client.study.setInputs(new Bentrix.StudyApi.SetInputsArgs(chart, ema_id, obj("settings", obj("shape", "period", "period", 50))));
        }
    }
}

C++C++

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

// study_id is the id of the newest study of this kind in a chart's answer.
static int64_t study_id(const Json &chart, const std::string &kind) {
    int64_t id = -1;
    for (const Json &s : chart["setup"]["studies"].arr()) {
        if (s["kind"].str() == kind) id = std::max(id, int64_t(s["id"].num()));
    }
    return id;
}

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 wb = client.agent.resource_read(AgentApi::ResourceReadArgs(bench));
    auto market = (wb["markets"][0u].is_string() ? wb["markets"][0u].str() : std::string());
    client.replay.step(ReplayApi::StepArgs(bench).n(200).timeframe("H1").unit("candle"));
    auto opened = client.chart.open(ChartApi::OpenArgs(bench, market).timeframe("H1"));
    auto chart = (opened["uri"].is_string() ? opened["uri"].str() : std::string());
    auto with_rsi = client.study.attach(StudyApi::AttachArgs(chart, "rsi"));
    auto rsi_id = study_id(with_rsi, "rsi");
    std::cout << "the RSI's id on the chart:" << " " << rsi_id << std::endl;
    client.study.set_inputs(StudyApi::SetInputsArgs(chart, rsi_id, Json::Object{{"settings", Json::Object{{"shape", "period"}, {"period", 21}}}}));
    auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"kind", "rsi"}, {"convention", "mt5"}, {"applied", "close"}, {"settings", Json::Object{{"shape", "period"}, {"period", 21}}}}).limit(5));
    std::cout << "times:" << " " << values["times"].dump() << std::endl;
    for (const Json &line : values["lines"].arr()) {
        std::cout << "line:" << " " << line["line"].dump() << std::endl;
        std::cout << "  values:" << " " << line["values"].dump() << std::endl;
    }
    auto rsi_now = values["lines"][0u]["values"].arr().back().num();
    std::cout << "RSI at the clock:" << " " << rsi_now << std::endl;
    auto with_ema = client.study.attach(StudyApi::AttachArgs(chart, "ema"));
    auto ema_id = study_id(with_ema, "ema");
    client.study.set_inputs(StudyApi::SetInputsArgs(chart, ema_id, Json::Object{{"settings", Json::Object{{"shape", "period"}, {"period", 50}}}}));
}

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
wb = client.agent.resource_read(bench)
market = wb["markets"][1]
client.replay.step(bench; n = 200, timeframe = "H1", unit = "candle")
opened = client.chart.open(bench, market; timeframe = "H1")
chart = opened["uri"]
with_rsi = client.study.attach(chart, "rsi")
rsi_id = maximum(s["id"] for s in with_rsi["setup"]["studies"] if s["kind"] == "rsi")
println("the RSI's id on the chart:", " ", rsi_id)
client.study.set_inputs(chart, rsi_id, Dict{String,Any}("settings" => Dict{String,Any}("shape" => "period", "period" => 21)))
values = client.study.values(bench, market, "H1", Dict{String,Any}("kind" => "rsi", "convention" => "mt5", "applied" => "close", "settings" => Dict{String,Any}("shape" => "period", "period" => 21)); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
    println("line:", " ", line["line"])
    println("  values:", " ", line["values"])
end
rsi_now = values["lines"][1]["values"][end]
println("RSI at the clock:", " ", rsi_now)
with_ema = client.study.attach(chart, "ema")
ema_id = maximum(s["id"] for s in with_ema["setup"]["studies"] if s["kind"] == "ema")
client.study.set_inputs(chart, ema_id, Dict{String,Any}("settings" => Dict{String,Any}("shape" => "period", "period" => 50)))

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)
}
wb <- client$agent$resource_read(bench)
market <- wb$markets[[1]]
client$replay$step(bench, n = 200, timeframe = "H1", unit = "candle")
opened <- client$chart$open(bench, market, timeframe = "H1")
chart <- opened$uri
with_rsi <- client$study$attach(chart, "rsi")
rsi_id <- max(vapply(Filter(function(s) s$kind == "rsi", with_rsi$setup$studies), function(s) s$id, numeric(1)))
cat("the RSI's id on the chart:", format(rsi_id), "\n")
client$study$set_inputs(chart, rsi_id, list(settings = list(shape = "period", period = 21)))
values <- client$study$values(bench, market, "H1", list(kind = "rsi", convention = "mt5", applied = "close", settings = list(shape = "period", period = 21)), limit = 5)
cat("times:", format(values$times), "\n")
for (line in values$lines) {
  cat("line:", format(line$line), "\n")
  cat("  values:", format(line$values), "\n")
}
rsi_now <- tail(values$lines[[1]]$values, 1)[[1]]
cat("RSI at the clock:", format(rsi_now), "\n")
with_ema <- client$study$attach(chart, "ema")
ema_id <- max(vapply(Filter(function(s) s$kind == "ema", with_ema$setup$studies), function(s) s$id, numeric(1)))
client$study$set_inputs(chart, ema_id, list(settings = list(shape = "period", period = 50)))

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 wb = client.agent().resource_read(mcp::AgentResourceReadArgs::new(bench.clone()))?;
    let market = wb["markets"][0].as_str().unwrap_or_default().to_string();
    client.replay().step(mcp::ReplayStepArgs::new(bench.clone()).n(200).timeframe("H1").unit("candle"))?;
    let opened = client.chart().open(mcp::ChartOpenArgs::new(bench.clone(), market.clone()).timeframe("H1"))?;
    let chart = opened["uri"].as_str().unwrap_or_default().to_string();
    let with_rsi = client.study().attach(mcp::StudyAttachArgs::new(chart.clone(), "rsi"))?;
    let rsi_id = with_rsi["setup"]["studies"].as_array().into_iter().flatten().filter(|s| s["kind"] == "rsi").filter_map(|s| s["id"].as_i64()).max().unwrap_or(-1);
    println!("the RSI's id on the chart: {:?}", rsi_id);
    client.study().set_inputs(mcp::StudySetInputsArgs::new(chart.clone(), rsi_id.clone(), serde_json::json!({"settings": {"shape": "period", "period": 21}})))?;
    let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"kind": "rsi", "convention": "mt5", "applied": "close", "settings": {"shape": "period", "period": 21}})).limit(5))?;
    println!("times: {}", values["times"]);
    for line in values["lines"].as_array().into_iter().flatten() {
        println!("line: {}", line["line"]);
        println!("  values: {}", line["values"]);
    }
    let rsi_now = values["lines"][0]["values"].as_array().and_then(|a| a.last()).and_then(|v| v.as_f64()).unwrap_or(f64::NAN);
    println!("RSI at the clock: {}", rsi_now);
    let with_ema = client.study().attach(mcp::StudyAttachArgs::new(chart.clone(), "ema"))?;
    let ema_id = with_ema["setup"]["studies"].as_array().into_iter().flatten().filter(|s| s["kind"] == "ema").filter_map(|s| s["id"].as_i64()).max().unwrap_or(-1);
    client.study().set_inputs(mcp::StudySetInputsArgs::new(chart.clone(), ema_id.clone(), serde_json::json!({"settings": {"shape": "period", "period": 50}})))?;
    Ok(())
}

07What else a study can change

The same card's other tabs have their own tools: study_set_style (colours, widths, line types), study_set_slope (colour by slope), study_set_bands (bands around a line), study_set_visibility (on which intervals it shows), and study_remove. Each indicator's page in the indicator reference lists its settings and their names.

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