Java · REST + WebSocket · NinjaTrader 8

Java NinjaTrader 8 API examples

NinjaTrader 8 integration for the JVM. java.net.http.HttpClient for REST, java.net.http.WebSocket for streaming. Zero external dependencies on Java 11+.

Before running the examples

Connect Java to the right account route

These examples use the NinjaTrader 8 surface. Keep NT8 and the CrossTrade Add-On connected, store your Bearer token outside browser-delivered code, and first verify access with GET /v1/api/accounts. The webhook Secret Key is a different credential. REST access requires Pro.

For accounts linked directly to Tradovate, start with GET /v1/api/tv/accounts and the Tradovate API reference. Do not assume the same order fields, symbol handling or response shape simply by changing a route prefix.

Handle HTTP and endpoint-level errors, then inspect returned order state. An accepted request is not a fill. Use a dated native futures contract for direct NT8 requests and keep exits tied to the original contract. See authentication and the external API versus NinjaScript comparison before building a live client.

Why Java

Using Java against the CrossTrade NinjaTrader API

Java 11+ ships native HTTP and WebSocket clients in java.net.http. No Apache HttpClient, no OkHttp, no third-party WebSocket library needed. Good fit for enterprise trading infrastructure that needs the JVM ecosystem.

REST java.net.http.HttpClient (Java 11+)
WebSocket java.net.http.WebSocket (Java 11+)
REST · animated

Watch the request get written

A pseudo-developer types out a real GET GetAccountSummary call against your NinjaTrader 8 account. The animation runs on a loop; the static snippet below is yours to copy.

getaccountsummary.java
Copy this

Complete Java GetAccountSummary example

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder()
    .uri(URI.create("https://app.crosstrade.io/v1/api/accounts/Sim101/summary"))
    .header("Authorization", "Bearer YOUR_TOKEN")
    .GET()
    .build();

var res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode() + " " + res.body());
WebSocket · animated

Streaming data with java.net.http.WebSocket (Java 11+)

Same flow on a persistent connection: open the socket, send a subscribe message, receive market data or P&L pushes in real time. CrossTrade's WebSocket is at wss://app.crosstrade.io/ws/stream with the same Bearer token in the request header.

stream.java
Copy this

Complete Java WebSocket example

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;

var ws = HttpClient.newHttpClient()
    .newWebSocketBuilder()
    .header("Authorization", "Bearer YOUR_TOKEN")
    .buildAsync(
        URI.create("wss://app.crosstrade.io/ws/stream"),
        new WebSocket.Listener() {
            public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
                System.out.println(data);
                return WebSocket.Listener.super.onText(ws, data, last);
            }
        }
    )
    .join();

ws.sendText("{\"action\":\"subscribe\",\"instruments\":[\"ES 12-25\"]}", true);

The full Java-compatible API surface

Every endpoint documented with request/response schemas, error codes, rate-limit notes, and language-specific code samples.

FAQ

Common questions

Is Java a good language for algorithmic trading?

Yes. Java is widely used in institutional trading for the same reasons it's used in enterprise: strong typing, mature concurrency primitives (CompletableFuture, virtual threads in Java 21+), JVM observability, and zero-allocation hot paths when written carefully. CrossTrade fits naturally — Bearer-token HTTP, JSON bodies, WebSocket frames.

Does this work with Java 8?

Yes! The example above uses java.net.http.HttpClient (Java 11+) for zero-dependency simplicity, but Java 8 is fully supported. For Java 8, use Apache HttpClient 5, OkHttp, or Spring's RestTemplate — same Authorization: Bearer header, same JSON body. For WebSocket on Java 8, the Tyrus JSR-356 reference implementation or the Eclipse Jetty WebSocket client both work cleanly.

Spring Boot integration?

Yes, very natural fit. Use WebClient (reactive) or RestTemplate (legacy) for REST; either flows the Bearer token via headers. For WebSocket, Spring's WebSocketClient (built on Jetty or Tyrus) works. Wrap the CrossTrade client as a @Service bean and inject it where needed. Put the token in application.yml or Spring Cloud Config, not in code.

Performance vs Python or JavaScript?

JVM bytecode is JIT-compiled to native and typically beats Python by 10-30x on CPU-bound work. For pure I/O (sending REST orders, parsing JSON responses), the difference is smaller — both finish well under CrossTrade's ~50ms round-trip. The JVM advantage shines when you're running complex backtest engines or indicator calculations alongside the live trading code.

Kotlin support?

Yes — Kotlin compiles to the same JVM bytecode and can call java.net.http.HttpClient directly. Kotlin's coroutines pair beautifully with the WebSocket; you can write a tight async loop that's shorter than the equivalent Java code. Same Bearer pattern, same JSON shapes.

Virtual threads (Java 21+) for trading concurrency?

Excellent fit. Each Java virtual thread is cheap enough to dedicate one per instrument subscription or per backtest worker. Wrap HttpClient calls in a virtual-thread executor and you get clean, blocking-style code with async-like scalability. CrossTrade's rate limit (3 req/sec per token) is shared, so concurrency is about correctness more than throughput.

Maven or Gradle?

Either. The example uses zero dependencies (java.net.http is in the stdlib), so the choice only matters when you add JSON binding (Jackson, Gson), logging (SLF4J), or testing (JUnit). Both are well-understood by anyone joining your trading project.

Running inside NinjaTrader itself?

NinjaTrader is C# / .NET, not Java — so if your strategy logic must run inside NT8's strategy engine, port it to NinjaScript C# (see our C# examples). Java is for the external bot, dashboard, or service side of trading. Most teams run Java services alongside NT8 rather than inside it.

Testing strategy with mocked CrossTrade calls?

Use WireMock or MockWebServer to stub HTTP responses in unit tests. For integration tests, hit Sim101 against a dedicated test bearer token. The CrossTrade error shapes ({ "error": "..." }) make happy-path and error-path tests straightforward.

Build your first NinjaTrader 8 trading bot in Java

One bearer token, one URL, every NinjaTrader endpoint. Ship to Sim101 first.