Bentrix Docs
HomePricingDashboard

The C# SDK

.NET: BentrixClient.ConnectAsync, and every tool is an async method with typed parameters.

The client is the project Bentrix.Mcp (.NET). It finds the Bentrix running on this computer through the agents folder Bentrix writes at every start, pairs with it under the name you give — the name the person sees in ☰ › Settings › Agents, where the pairing's scopes are set — and talks to it over MCP. Nothing is typed: no address, no key.

01What you need

The .NET SDK 8 or later, and Bentrix open on the same computer.

02Install

Two ways, the same client either way.

From NuGet. The client is the package Bentrix.Mcp, its version the application's:

dotnet new console -o MyAgent
cd MyAgent
dotnet add package Bentrix.Mcp

The engine in your own process is the package Bentrix beside it (dotnet add package Bentrix).

From its source on your computer. Its source is github.com/bentrixhq/bentrix-dotnet, under the MIT licence; a clone of it is the SDK on your computer, and your project references the client in it:

git clone https://github.com/bentrixhq/bentrix-dotnet
dotnet new console -o MyAgent
cd MyAgent
dotnet add reference ../bentrix-dotnet/mcp/Bentrix.Mcp.csproj

03Connect

using Bentrix.Mcp;

using var b = await BentrixClient.ConnectAsync("my-agent");
var state = await b.Workspace.GetState();
var bench = state!["laboratories"]![0]!["benches"]![0]!["uri"]!.GetValue<string>();
var p = bench.Replace("bentrix://", "").Split('/');
var book = await b.Trade.Book(p[0], p[1], p[3]);
Console.WriteLine(book!["positions"]!.AsArray().Count);

04How a call looks

Every tool of the catalogue is a method, grouped by its domain: b.Workspace, b.Chart, b.Study, b.Trade … in Pascal case. A method takes the tool's arguments as method parameters — the required ones first, the optional ones as optional parameters, and answers the tool's answer as a JsonNode. The whole list is at the end of this page; each method links to its tool's full entry — the arguments with their types and defaults, the scope a pairing must grant, and the plan.

05When Bentrix says no

A tool that runs and refuses throws a BentrixException carrying the product's own sentence. The client also checks, when it connects, that the catalogue it was generated from is the one the running Bentrix serves: a different major version is refused before any call, so a program never calls a tool with arguments that no longer fit.

Busy is waited out, not raised. Bentrix answers one program at most 20 calls a second (a burst of 60), and answers a call past that busy (-40001, with the wait in retryAfterMs) before running anything. The client waits that long and sends the call again — so an order is never sent twice by it — up to ten times, each wait at most five seconds, and only then raises the refusal: Client.Busy (-40001), Client.BusyRetries (10) and Client.BusyWaitMaxMs (5000); RpcException.RetryAfterMs carries the wait.

06Long work and streams

A tool that starts long work — a strategy run, a batch, a question put to the person in Bentrix's own window — answers a job; its handle is read with job_get until it ends. A stream (bars as they close, ticks, quotes, deals, the Journal) is followed with wait_for, which answers what came after the cursor it is given and the cursor to give next.

Your first program

Save this as a file, with Bentrix open on this computer. It connects, lists your laboratories and their workbenches, and prints the selected workbench’s markets.

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

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

// Every laboratory, and the workbenches in it.
var state = await client.Workspace.GetState(depth: "benches");
foreach (var lab in state!["laboratories"]!.AsArray())
{
    Console.WriteLine($"laboratory: {lab!["name"]!}");
    foreach (var bench in lab!["benches"]!.AsArray())
    {
        Console.WriteLine($"  workbench: {bench!["uri"]!}");
    }
}

Run it

dotnet run

The first run pairs the program: it appears in ☰ › Settings › Agents under the name it gave (my-agent), with the scopes read, lab and paper. If it says Bentrix is not running, open Bentrix and run it again.

A larger program, the one the tests run

This is the program Bentrix’s own tests run in C# against a running Bentrix: it reads the workspace and a workbench’s book, is refused in the product’s words, and runs a reinforcement-learning episode through the tools.

using System.Text.Json.Nodes;
using Bentrix.Mcp;

static void Check(bool held, string what)
{
    if (!held)
    {
        throw new BentrixException($"FAILED: {what}");
    }
}

try
{
    using var b = await BentrixClient.ConnectAsync("dotnet-walk");
    var state = await b.Workspace.GetState();
    var bench = state!["laboratories"]![0]!["benches"]![0]!["uri"]!.GetValue<string>();
    var p = bench.Replace("bentrix://", "").Split('/');
    var book = await b.Trade.Book(p[0], p[1], p[3]);
    Check(book?["positions"] is JsonArray, $"the book did not read: {book}");
    var said = "";
    try
    {
        await b.Call("no_such_tool");
    }
    catch (BentrixException e)
    {
        said = e.Message;
    }
    Check(said.Contains("no_such_tool"), $"a refusal did not say its tool: {said}");

    var made = await b.Strategy.EnvMake(bench, interval: "H1", window: 8, episode: "window", episodeBars: 12);
    var env = made!["env"]!.GetValue<string>();
    var start = await b.Strategy.EnvReset(env, seed: 5);
    Check(start!["obs"]!["market"]!.AsArray().Count == 8, "the observation is not shaped as declared");
    var rewards = new List<double>();
    var hashes = new List<string> { start["info"]!["ledger_hash"]!.GetValue<string>() };
    foreach (var a in new[] { 1, 1, 2, 0, 2, 2, 1, 0, 1, 2, 0, 1 })
    {
        var s = await b.Strategy.EnvStep(env, a);
        rewards.Add(s!["reward"]!.GetValue<double>());
        hashes.Add(s["info"]!["ledger_hash"]!.GetValue<string>());
        if (s["terminated"]!.GetValue<bool>() || s["truncated"]!.GetValue<bool>())
        {
            break;
        }
    }
    await b.Strategy.EnvClose(env);
    // A tool's own refusal (isError), not a request the wire refused.
    Exception? refusal = null;
    try
    {
        await b.Strategy.EnvStep(env, 0);
    }
    catch (Exception e)
    {
        refusal = e;
    }
    Check(refusal is ToolException && refusal.Message.Contains("No environment"), $"a closed environment's step was not refused in its words: {refusal}");
    Check(hashes.Distinct().Count() > 1, "the episode traded nothing");
    // System.Text.Json writes a double in the shortest digits that read back as the same double.
    var episode = new JsonObject
    {
        ["start_ms"] = start["info"]!["start_ms"]!.GetValue<long>(),
        ["rewards"] = new JsonArray(rewards.Select(r => (JsonNode)JsonValue.Create(r)).ToArray()),
        ["hashes"] = new JsonArray(hashes.Select(h => (JsonNode)JsonValue.Create(h)).ToArray()),
    };
    Console.WriteLine(episode.ToJsonString());
    Console.WriteLine("PASS");
    return 0;
}
catch (BentrixException e)
{
    Console.Error.WriteLine(e.Message);
    return 1;
}

Next

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