cmdtyView Desktop API
The cmdtyView Desktop API provides localhost access to cmdtyView market data through two interfaces:
- WebSocket endpoint for real-time streaming market data
- HTTP endpoint for historical OHLC data
Instead of connecting directly to Barchart infrastructure, your application connects to localhost, while cmdtyView Desktop handles authentication, permissions, and the upstream connection.
For JavaScript and TypeScript, the cmdtyView Desktop SDK (@barchart/desktop-sdk-js) is the easiest way to connect. It handles login, subscriptions, snapshots, and updates for you, and gives you ready-to-use quotes, order books, and cumulative volume, with prices already scaled and formatted.
This guide walks you through enabling the Desktop API, confirming that the local server is running, and testing both real-time streaming and historical data retrieval.
Setup
-
Download and install cmdtyView Desktop
If you haven’t already, download the application from:
barchart.com/cmdty/trading/cmdtyview/desktop
The desktop app is required for the localhost proxy to work.
-
Open the app and log in
Launch cmdtyView Desktop, log into an account with Desktop API privileges, and keep it running.
The localhost proxy requires an active session with the appropriate permissions.
-
Enable the localhost proxy
Navigate to the Settings menu in cmdtyView Desktop:
- Click the Settings icon, the gear icon, in the application
- Go to the Desktop API section
- Toggle the switch to On to enable the proxy server
-
Confirm the port
The default port is 9000. You can change this in the Desktop API settings if needed.
⚠️ Important
If your account does not have Desktop API privileges, the Desktop API section will not appear in Settings and you will not be able to start the local cmdtyView Desktop API. Contact your administrator or Barchart support to request access.
Note
After making any changes to the Desktop API settings, click the Apply button for the changes to take effect.
Health check
Open the health endpoint in your browser or fetch it from your app.
This is a simple HTTP request to verify that the localhost proxy is up and running. The actual data connection to cmdtyView uses WebSocket. See the Live example section below.
http://localhost:9000/healthExpected JSON response:
{ "status": "ok", "message": "openfeed proxy is running on port: 9000"}Note
If you changed the port in Settings, make sure to update the port number in the URL.
Live example
Check the server first, then connect the WebSocket.
Historical Data API
The cmdtyView Desktop API provides an HTTP endpoint for fetching historical OHLC data.
Unlike real-time streaming, which uses WebSocket, historical data is retrieved via a simple HTTP GET request.
Endpoint
GET http://localhost:9000/api/historyQuery parameters
Either symbol or expression is required. All other parameters control the data range and aggregation.
| Parameter | Type | Required | Description |
|---|---|---|---|
symbol | string | * | The market symbol, for example AAPL or ESM26 |
expression | string | * | Calculated expression, for example {ZC*1}-{ZC*2} |
aggregation | string | ✓ | Data aggregation: tick, 1m, 5m, 15m, 60m, daily, weekly, monthly, etc. |
rangeType | string | ✓ | One of: recordsback, daysback, daterange |
records | number | if recordsback | Number of records to return, max 5000 |
days | number | if daysback | Number of days back |
start | string | if daterange | Start date, for example 2024-01-01 |
end | string | if daterange | End date, for example 2024-06-01 |
* Either symbol or expression is required. At least one must be provided.
Response format
The response is a JSON object containing metadata about the symbol and a columnar data structure with timestamps and field values.
{ "symbol": "AAPL", "aggregation": "daily", "metadata": { "unitCode": "2", "hasOpenInterest": false }, "fields": ["open", "high", "low", "close", "volume"], "data": { "timestamps": [1716768000000, 1716854400000, 1716940800000], "open": [189.5, 190.25, 191.0], "high": [192.0, 193.5, 194.25], "low": [188.75, 189.5, 190.0], "close": [191.25, 192.75, 193.5], "volume": [52000000, 48500000, 55000000] }}Timestamps are in epoch milliseconds, UTC. The fields array lists which data arrays are included in the response.
Example request
// Fetch last 50 daily bars for AAPLconst response = await fetch( "http://localhost:9000/api/history?symbol=AAPL&aggregation=daily&rangeType=recordsback&records=50",);
const data = await response.json();
console.log("Records:", data.data.timestamps.length);console.log("Fields:", data.fields);
// Access the close pricesconst closePrices = data.data.close;console.log("Latest close:", closePrices[closePrices.length - 1]);Note
For expression symbols containing special characters like{ZC*1}-{ZC*2}, use theexpressionparameter instead ofsymbol. The curly brackets will be URL-encoded automatically by your HTTP client.
Historical data demo
SDK Installation
Before using the code snippets below, you’ll need to install an SDK for your programming language. There are two SDKs to choose from, and you can use either one. Both are open source.
cmdtyView Desktop SDK (recommended for JavaScript and TypeScript). The cmdtyView Desktop SDK is the easier, more opinionated way to get market data. You subscribe to a symbol and get ready-to-use quotes, order books, and cumulative volume, with prices already scaled and formatted. The SDK applies snapshots and updates for you, so you never process Openfeed messages yourself. It is open source and available on GitHub.
Openfeed SDKs (lower level). The Openfeed SDKs give you the raw Openfeed messages: instrument definitions, snapshots, and updates. You decide how to process them and keep your own market state. They are open source and available for JavaScript, Python, Go, Java, and C#.
You don’t lose access to raw data by choosing the Desktop SDK. It runs on top of the Openfeed JavaScript client and also has an API for subscribing to raw Openfeed messages, for anything it doesn’t model itself. See Raw market data for both ways to get raw messages in JavaScript.
Note
The Desktop SDK is currently available for JavaScript and TypeScript only. Versions for other languages are in development. Until they are released, use the Openfeed SDK for your language.
On this page, the JavaScript streaming snippet uses the Desktop SDK, and the streaming snippets for other languages use the Openfeed SDKs.
Choose your language and follow the installation steps:
Install via npm:
npm install @barchart/desktop-sdk-js @openfeed/sdk-js long@openfeed/sdk-js and long are peer dependencies, so your application and the SDK share one Openfeed client.
The Python SDK is published to PyPI. Install via pip:
pip install openfeedInstall via go get:
go get github.com/openfeed-org/sdk-go/openfeedThe Java SDK is published on Github and Maven. Add the dependency to your pom.xml (Maven):
<dependency> <groupId>org.openfeed</groupId> <artifactId>openfeed</artifactId> <version>LATEST</version></dependency>Alternatively, build from source:
git clone git@github.com:openfeed-org/sdk-java.gitcd sdk-java && mvn clean installThe C# SDK is published to NuGet. Install via .NET CLI:
dotnet add package openfeed.netSnippets
Use these as a starting point for your own integration.
- Streaming: the JavaScript snippet uses the cmdtyView Desktop SDK. The other languages use their Openfeed SDK. To see raw Openfeed messages in JavaScript instead, see Raw market data.
- Health check and historical data: these are plain HTTP requests and don’t need an SDK.
Minimal health check
const response = await fetch("http://localhost:9000/health");const health = await response.json();
console.log("Local proxy health:", health);import requests
response = requests.get("http://localhost:9000/health")health = response.json()
print("Local proxy health:", health)package main
import ( "encoding/json" "fmt" "io" "log" "net/http")
func main() { resp, err := http.Get("http://localhost:9000/health") if err != nil { log.Fatal("Error:", err) } defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) if err != nil { log.Fatal("Error reading response:", err) }
var health map[string]interface{} if err := json.Unmarshal(body, &health); err != nil { log.Fatal("Error parsing JSON:", err) }
fmt.Println("Local proxy health:", health)}package com.example.openfeed;
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;
public class HealthCheck { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:9000/health")) .GET() .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Local proxy health: " + response.body()); }}using System;using System.Net.Http;using System.Threading.Tasks;
class HealthCheck{ static async Task Main() { using var client = new HttpClient();
var response = await client.GetStringAsync("http://localhost:9000/health");
Console.WriteLine("Local proxy health: " + response); }}Minimal Desktop API connection using the SDK
Sign in with the same username and password that cmdtyView Desktop is signed in with. Other credentials are rejected.
import { DesktopSdk } from "@barchart/desktop-sdk-js";
// Replace with your cmdtyView Desktop API credentialsconst wsUrl = "ws://localhost:9000";const username = "YOUR_USERNAME";const password = "YOUR_PASSWORD";
const sdk = new DesktopSdk();sdk.login({ url: wsUrl, username, password });
const symbol = "ESZ26";sdk.subscribeQuote(symbol, { onEvent({ kind, instrument, quote, formatted }) { console.log(kind, instrument.symbol, formatted.session.last, quote.session.volume); }, onError(error) { console.error(error.symbol, error.message); },});
await sdk.whenConnected();console.log("Connected to the WebSocket server");import openfeed
# Connection credentials (replace with your own)username = "{username-placeholder}"password = "{password-placeholder}"server = "localhost:9000" # connect to local OpenFeed instance; change port if using a different one
# Create clientclient = openfeed.OpenfeedClient(username, password, server)
# Connection state handlersclient.on_connected = lambda _: print("Connected to OpenFeed")client.on_disconnected = lambda _: print("Disconnected from OpenFeed")client.on_error = lambda err: print(f"Error: {err}")
# Global state variablesmarket_state = {} # Dictionary to store state by symbol (includes price denominator)marketid_to_symbol = {} # Maps marketId to symbol (updates use marketId, not symbol)
def on_message(msg): """ Callback for market data messages.
Message flow after subscribing: 1. subscriptionResponse - confirmation of subscription 2. instrumentDefinition - metadata about the instrument 3. marketSnapshot - complete current state of the market 4. marketUpdate(s) - real-time incremental changes """ global market_state, marketid_to_symbol
msg_type = msg.WhichOneof('data')
# Subscription confirmation if msg_type == 'subscriptionResponse': response = msg.subscriptionResponse print(f"Subscription confirmed: {response.symbol}") return
# Instrument metadata elif msg_type == 'instrumentDefinition': instrument = msg.instrumentDefinition symbol = instrument.subscriptionSymbol
# Initialize state with price denominator market_state[symbol] = { 'price_denominator': instrument.priceDenominator, 'last_price': None, }
marketid_to_symbol[instrument.marketId] = symbol print(f"\n[Definition] {symbol} - {instrument.description}") print(f" Price Denominator: {instrument.priceDenominator}") return
# Initial market state - Populate state object elif msg_type == 'marketSnapshot': snapshot = msg.marketSnapshot symbol = marketid_to_symbol.get(snapshot.marketId, f"Unknown({snapshot.marketId})")
# Make sure state exists if symbol not in market_state: return
# Populate initial values if snapshot.HasField('last') and snapshot.last.price: price_denom = market_state[symbol]['price_denominator'] market_state[symbol]['last_price'] = snapshot.last.price / price_denom
print(f"[Snapshot] {symbol} initialized - Last: {market_state[symbol]['last_price']}") return
# Real-time updates - Update existing state elif msg_type == 'marketUpdate': update = msg.marketUpdate symbol = marketid_to_symbol.get(update.marketId, f"Unknown({update.marketId})")
# Make sure state exists (definition and snapshot must arrive first) if symbol not in market_state: return # Silently ignore updates before state is initialized
# Track if state changed old_price = market_state[symbol]['last_price'] price_denom = market_state[symbol]['price_denominator']
# Update state with new data if update.HasField("trades") and update.HasField('session'): market_state[symbol]['last_price'] = update.session.last.price / price_denom
elif update.HasField('last'): market_state[symbol]['last_price'] = update.last.price / price_denom
# Only print if price changed new_price = market_state[symbol]['last_price'] if new_price is not None and new_price != old_price: print(f"[Update] {symbol} - Last: {new_price}")
# Subscribe to market data (see SDK documentation for available options)client.add_symbol_subscription( symbol=["ZCN26", "ZLN26", "AAPL"], # Corn, Soybean Oil, Apple stock callback=on_message, service="REAL_TIME", subscription_type=["ALL"])
# Start receiving data (blocking call)client.start()package main
import ( "log" "os" "time"
"github.com/openfeed-org/sdk-go/openfeed")
var esm26Price float64
// MessageHandler handles incoming OpenFeed messagestype MessageHandler struct{}
func (h *MessageHandler) NewHeartbeat(msg *openfeed.HeartBeat) { t := time.Unix(0, msg.GetTransactionTime()) log.Printf("Heartbeat: %v", t)}
func (h *MessageHandler) NewMessage(msg *openfeed.Message) { /* Message flow after subscribing: 1. InstrumentDefinition - metadata about the instrument 2. MarketSnapshot - complete current state of all market data 3. Stream of MarketUpdate(s) - incremental changes as they occur */
switch msg.MessageType { case openfeed.MessageType_INSTRUMENT_DEFINITION: log.Printf("Instrument Definition: %v", msg.Message)
case openfeed.MessageType_MARKET_SNAPSHOT: snapshot := msg.Message2.GetMarketSnapshot() if snapshot != nil && snapshot.Last != nil { esm26Price = float64(snapshot.Last.GetPrice()) log.Printf("Snapshot - Last: %.2f", esm26Price) }
case openfeed.MessageType_MARKET_UPDATE: update := msg.Message2.GetMarketUpdate() if update != nil { // Handle last price updates if update.Session.Last != nil { esm26Price = float64(update.Session.Last.GetPrice()) log.Printf("Last Update: %.2f", esm26Price) }
// Handle trade updates with session data last := update.GetLast() if last != nil { esm26Price = float64(last.GetPrice()) log.Printf("Trade Update - Last: %.2f", esm26Price) }
// Handle BBO (Best Bid/Offer) updates bbo := update.GetBbo() if bbo != nil { log.Printf("BBO - Bid: %d, Ask: %d", bbo.GetBidPrice(), bbo.GetOfferPrice()) } }
case openfeed.MessageType_OHLC: log.Printf("OHLC: %v", msg.Message)
case openfeed.MessageType_SUBSCRIPTION_RESPONSE: log.Printf("Subscription Response: %v", msg.Message)
default: log.Printf("Unhandled message type: %d", msg.MessageType) }}
func main() { log.SetOutput(os.Stdout)
username := "{username-placeholder}" password := "{password-placeholder}" server := "localhost:9000" // Use "demo.openfeed.barchart.com" for demo
log.Printf("Connecting to %s as %s", server, username)
// Create connection with credentials conn := openfeed.NewConnection(openfeed.Credentials{ Username: username, Password: password, }, server)
// Set up message handler messageHandler := &MessageHandler{} hnd := openfeed.MessageHandler(messageHandler)
// Subscribe to real-time quotes for E-mini S&P 500 June 2026 // Available services: "REAL_TIME", "DELAYED" // For subscription types, use: // - conn.AddSymbolSubscription() for quotes (includes trades) // - conn.AddSymbolOHLCSubscription() for OHLC data subRequest := openfeed.SubRequest{ Service: "REAL_TIME", Symbols: []string{"ESM26"}, } conn.AddSymbolSubscription(subRequest.Symbols, &hnd, &subRequest)
// Add heartbeat handler hb := openfeed.HeartbeatHandler(messageHandler) conn.AddHeartbeatSubscription(&hb)
// Start connection (blocking) err := conn.Start() if err != nil { log.Printf("Error: %v", err) }}package com.example.openfeed;
import org.openfeed.ExchangeResponse;import org.openfeed.HeartBeat;import org.openfeed.InstrumentAction;import org.openfeed.InstrumentDefinition;import org.openfeed.InstrumentReferenceResponse;import org.openfeed.InstrumentResponse;import org.openfeed.ListSubscriptionsResponse;import org.openfeed.LoginResponse;import org.openfeed.LogoutResponse;import org.openfeed.MarketSnapshot;import org.openfeed.MarketStatus;import org.openfeed.MarketUpdate;import org.openfeed.Ohlc;import org.openfeed.Service;import org.openfeed.SubscriptionResponse;import org.openfeed.SubscriptionType;import org.openfeed.VolumeAtPrice;import org.openfeed.client.api.OpenfeedClient;import org.openfeed.client.api.OpenfeedClientEventHandler;import org.openfeed.client.api.OpenfeedClientHandler;import org.openfeed.client.api.OpenfeedEvent;import org.openfeed.client.api.impl.ConnectionStats;import org.openfeed.client.api.impl.OpenfeedClientConfigImpl;import org.openfeed.client.api.impl.websocket.OpenfeedClientWebSocket;
import io.netty.channel.ChannelPromise;
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.HashMap;import java.util.Map;
/** * OpenFeed Start Guide - Java Edition * * Demonstrates market data consumption with state management. * Tracks price changes and logs only when prices actually change. * * OpenFeed Streaming Example * * Maven dependency: * <dependency> * <groupId>org.openfeed</groupId> * <artifactId>openfeed-client</artifactId> * <version>LATEST</version> * </dependency> */public class StartGuide implements OpenfeedClientEventHandler, OpenfeedClientHandler {
private static class MarketState { int priceDenominator = 1; BigDecimal lastPrice = null; }
private final OpenfeedClientWebSocket client; // Global state management private final Map<String, MarketState> marketState = new HashMap<>(); private final Map<Long, String> marketIdToSymbol = new HashMap<>();
public static void main(String[] args) { new StartGuide(); }
public StartGuide() { final OpenfeedClientConfigImpl config = new OpenfeedClientConfigImpl();
// Read credentials from environment or use defaults String username = "{username-placeholder}"; String password = "{password-placeholder}";
config.setUserName(username); config.setPassword(password);
config.setHost("localhost"); config.setPort(9000);
client = new OpenfeedClientWebSocket(config, this, this); client.connectAndLogin();
System.out.println("Client started. Press Ctrl+C to exit."); registerShutdownHook(); keepAlive(); }
private void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("\nShutting down..."); if (client != null) { client.disconnect(); } })); }
private void keepAlive() { try { Thread.currentThread().join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
@Override public void onLoginResponse(LoginResponse loginResponse) { System.out.println("\n LOGIN SUCCESSFUL");
String[] symbols = { "ZCN26", "ZLN26", "AAPL" }; System.out.println("Subscribing to: " + String.join(", ", symbols)); client.subscribe(Service.REAL_TIME, SubscriptionType.ALL, symbols); }
@Override public void onLogoutResponse(LogoutResponse logoutResponse) { System.out.println("[LOGOUT] " + logoutResponse.getStatus()); }
@Override public void onSubscriptionResponse(SubscriptionResponse response) { System.out.println("[SUBSCRIPTION] " + response.getSymbol() + " - " + response.getStatus()); }
@Override public void onInstrumentDefinition(InstrumentDefinition definition) { String symbol = definition.getSubscriptionSymbol();
// Initialize state with price denominator MarketState state = new MarketState(); state.priceDenominator = definition.getPriceDenominator(); marketState.put(symbol, state);
// Map marketId to symbol for updates (updates use marketId, not symbol) marketIdToSymbol.put(definition.getMarketId(), symbol);
System.out.println("\n[Definition] " + symbol + " - " + definition.getDescription()); System.out.println(" Price Denominator: " + definition.getPriceDenominator()); }
@Override public void onMarketSnapshot(MarketSnapshot snapshot) { String symbol = marketIdToSymbol.get(snapshot.getMarketId());
// Make sure state exists if (symbol == null || !marketState.containsKey(symbol)) { return; }
MarketState state = marketState.get(symbol);
// Populate initial last price if (snapshot.hasLast() && snapshot.getLast().getPrice() != 0) { long priceRaw = snapshot.getLast().getPrice(); state.lastPrice = BigDecimal.valueOf(priceRaw) .divide(BigDecimal.valueOf(state.priceDenominator), 6, RoundingMode.HALF_UP);
System.out.println("[Snapshot] " + symbol + " initialized - Last: " + state.lastPrice); } }
@Override public void onMarketUpdate(MarketUpdate update) { String symbol = marketIdToSymbol.get(update.getMarketId());
// Make sure state exists (definition and snapshot must arrive first) if (symbol == null || !marketState.containsKey(symbol)) { return; // Silently ignore updates before state is initialized }
MarketState state = marketState.get(symbol); BigDecimal oldPrice = state.lastPrice; BigDecimal newPrice = oldPrice;
// Update state with new data // Check for trades with session data first if (update.hasTrades() && update.hasSession() && update.getSession().hasLast() && update.getSession().getLast().getPrice() != 0) { long priceRaw = update.getSession().getLast().getPrice(); newPrice = BigDecimal.valueOf(priceRaw) .divide(BigDecimal.valueOf(state.priceDenominator), 6, RoundingMode.HALF_UP); state.lastPrice = newPrice; } // Otherwise check for direct last price else if (update.hasLast() && update.getLast().getPrice() != 0) { long priceRaw = update.getLast().getPrice(); newPrice = BigDecimal.valueOf(priceRaw) .divide(BigDecimal.valueOf(state.priceDenominator), 6, RoundingMode.HALF_UP); state.lastPrice = newPrice; }
// Only log if price changed if (newPrice != null && !newPrice.equals(oldPrice)) { System.out.println("[Update] " + symbol + " - Last: " + newPrice); } }
// Minimal implementations for unused handlers @Override public void onInstrumentResponse(InstrumentResponse response) { }
@Override public void onInstrumentReferenceResponse(InstrumentReferenceResponse response) { }
@Override public void onListSubscriptionsResponse(ListSubscriptionsResponse response) { }
@Override public void setInstrumentPromise(ChannelPromise promise) { }
@Override public void onExchangeResponse(ExchangeResponse response) { }
@Override public void onMarketStatus(MarketStatus status) { }
@Override public void onHeartBeat(HeartBeat hb) { }
@Override public void onVolumeAtPrice(VolumeAtPrice volume) { }
@Override public void onOhlc(Ohlc ohlc) { }
@Override public void onInstrumentAction(InstrumentAction action) { }
@Override public ConnectionStats getConnectionStats() { return null; }
@Override public void onEvent(OpenfeedClient client, OpenfeedEvent event) { if (event.getType() == OpenfeedEvent.EventType.Connected) { System.out.println("Connected to OpenFeed"); } else if (event.getType() == OpenfeedEvent.EventType.Disconnected) { System.out.println("Disconnected from OpenFeed"); } }}using System;using System.Collections.Generic;using System.Threading.Tasks;using Org.Openfeed;using Org.Openfeed.Client;
namespace OpenFeedStartGuide{ class Program { private const string OpenfeedUrl = "ws://localhost:9000"; private const string OpenfeedUsername = "{username-placeholder}"; private const string OpenfeedPassword = "{password-placeholder}";
// Global state management - Store state by symbol private static readonly Dictionary<string, MarketState> MarketStateBySymbol = new();
class MarketState { public long PriceDenominator { get; set; } = 1; public decimal? LastPrice { get; set; } }
static async Task Main(string[] args) { Console.WriteLine("Connecting to OpenFeed...");
var listeners = new OpenfeedListeners { OnConnected = _ => { Console.WriteLine("Connected to OpenFeed"); return ValueTask.CompletedTask; }, OnDisconnected = () => { Console.WriteLine("Disconnected from OpenFeed"); return ValueTask.CompletedTask; }, OnCredentialsRejected = () => { Console.WriteLine("Invalid credentials - check username/password"); return ValueTask.CompletedTask; }, OnConnectFailed = exception => { Console.WriteLine($"Connection failed: {exception.Message}"); return ValueTask.CompletedTask; }, OnMessageWithMetadata = (message, definition, symbols) => { HandleMessage(message, definition, symbols); return ValueTask.CompletedTask; } };
var client = OpenfeedFactory.CreateClient( new Uri(OpenfeedUrl), OpenfeedUsername, OpenfeedPassword, listeners, clientId: null );
await client.GetConnectionAsync(default);
client.Subscribe( Service.RealTime, SubscriptionType.All, snapshotIntervalSeconds: 1, symbols: new[] { "ZCN26", "ZLN26" }, marketIds: null, exchanges: null, channels: null );
Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
private static void HandleMessage(OpenfeedGatewayMessage message, InstrumentDefinition? definition, string[] symbols) { // Get the symbol from the provided list var symbol = symbols.Length > 0 ? symbols[0] : "unknown";
// Handle subscription response if (message.SubscriptionResponse != null) { Console.WriteLine($"[Subscription] {message.SubscriptionResponse.Symbol}"); return; }
// Handle instrument definition - Initialize state with metadata if (message.InstrumentDefinition != null) { var def = message.InstrumentDefinition;
// Initialize state with price denominator MarketStateBySymbol[symbol] = new MarketState { PriceDenominator = def.PriceDenominator == 0 ? 1 : def.PriceDenominator };
Console.WriteLine($"\n[Definition] {symbol} - {def.Description}"); Console.WriteLine($" Price Denominator: {def.PriceDenominator}"); return; }
// Handle market snapshot - Populate initial state if (message.MarketSnapshot != null) { // Make sure state exists if (!MarketStateBySymbol.ContainsKey(symbol)) return;
// Populate initial values if (message.MarketSnapshot.Last != null) { var price = message.MarketSnapshot.Last.Price; var denominator = MarketStateBySymbol[symbol].PriceDenominator; MarketStateBySymbol[symbol].LastPrice = (decimal)price / denominator;
Console.WriteLine($"[Snapshot] {symbol} initialized - Last: {MarketStateBySymbol[symbol].LastPrice}"); } return; }
// Handle market update - Update existing state and log only on change if (message.MarketUpdate != null) { var update = message.MarketUpdate;
// Make sure state exists (definition and snapshot must arrive first) if (!MarketStateBySymbol.ContainsKey(symbol)) return; // Silently ignore updates before state is initialized
// Track if state changed var oldPrice = MarketStateBySymbol[symbol].LastPrice; var denominator = MarketStateBySymbol[symbol].PriceDenominator; decimal? newPrice = null;
// Update state with new data if (update.Trades != null && update.Session?.Last != null) { newPrice = (decimal)update.Session.Last.Price / denominator; } else if (update.Last != null) { newPrice = (decimal)update.Last.Price / denominator; }
if (newPrice != null && newPrice != oldPrice) { MarketStateBySymbol[symbol].LastPrice = newPrice; Console.WriteLine($"[Update] {symbol} - Last: {newPrice}"); } return; } } }}Minimal historical data fetch
const response = await fetch( "http://localhost:9000/api/history?symbol=ESM26&aggregation=daily&rangeType=recordsback&records=50");
const data = await response.json();
console.log(`Fetched ${data.data.timestamps.length} records`);console.log("Latest close:", data.data.close[data.data.close.length - 1]);import requests
response = requests.get( "http://localhost:9000/api/history", params={ "symbol": "ESM26", "aggregation": "daily", "rangeType": "recordsback", "records": 50, },)
data = response.json()
print(f"Fetched {len(data['data']['timestamps'])} records")print("Latest close:", data["data"]["close"][-1])package main
import ( "encoding/json" "fmt" "io" "log" "net/http" "net/url")
type HistoryData struct { Timestamps []int64 `json:"timestamps"` Open []float64 `json:"open"` High []float64 `json:"high"` Low []float64 `json:"low"` Close []float64 `json:"close"` Volume []float64 `json:"volume"`}
type HistoryResponse struct { Data HistoryData `json:"data"`}
func main() { baseURL := "http://localhost:9000/api/history"
params := url.Values{} params.Add("symbol", "ESM26") params.Add("aggregation", "daily") params.Add("rangeType", "recordsback") params.Add("records", "50")
resp, err := http.Get(baseURL + "?" + params.Encode()) if err != nil { log.Fatal("Error:", err) } defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) if err != nil { log.Fatal("Error reading response:", err) }
var history HistoryResponse if err := json.Unmarshal(body, &history); err != nil { log.Fatal("Error parsing JSON:", err) }
fmt.Printf("Fetched %d records\n", len(history.Data.Timestamps)) if len(history.Data.Close) > 0 { fmt.Println("Latest close:", history.Data.Close[len(history.Data.Close)-1]) }}package com.example.openfeed;
import java.net.URI;import java.net.URLEncoder;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
// For JSON parsing, use your preferred library (Jackson, Gson, etc.)// This example uses simple string parsing for demonstrationimport com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;
public class History { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient();
// Build query parameters String baseUrl = "http://localhost:9000/api/history"; String params = String.format("?symbol=%s&aggregation=%s&rangeType=%s&records=%d", URLEncoder.encode("ESM26", StandardCharsets.UTF_8), URLEncoder.encode("daily", StandardCharsets.UTF_8), URLEncoder.encode("recordsback", StandardCharsets.UTF_8), 50 );
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl + params)) .GET() .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Parse JSON response using Jackson ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(response.body()); JsonNode data = root.get("data"); JsonNode timestamps = data.get("timestamps"); JsonNode closes = data.get("close");
System.out.println("Fetched " + timestamps.size() + " records"); if (closes.size() > 0) { System.out.println("Latest close: " + closes.get(closes.size() - 1).asDouble()); } }}using System;using System.Net.Http;using System.Text.Json;using System.Threading.Tasks;using System.Web;
class History{ static async Task Main() { using var client = new HttpClient();
// Build query parameters var query = HttpUtility.ParseQueryString(string.Empty); query["symbol"] = "ESM26"; query["aggregation"] = "daily"; query["rangeType"] = "recordsback"; query["records"] = "50";
var url = $"http://localhost:9000/api/history?{query}";
var response = await client.GetStringAsync(url);
// Parse JSON response using var doc = JsonDocument.Parse(response); var data = doc.RootElement.GetProperty("data"); var timestamps = data.GetProperty("timestamps"); var closes = data.GetProperty("close");
Console.WriteLine($"Fetched {timestamps.GetArrayLength()} records"); if (closes.GetArrayLength() > 0) { // Get the last element var closeArray = closes.EnumerateArray(); double lastClose = 0; foreach (var item in closeArray) { lastClose = item.GetDouble(); } Console.WriteLine($"Latest close: {lastClose}"); } }}Next steps
After you confirm that the local Desktop API server is running and that you can receive data through the demo, the next step is to build your integration using one of the supported SDKs.
- JavaScript: see the cmdtyView Desktop SDK README, its reference, and its examples for quotes, order books, cumulative volume, and connection handling.
- Other languages: the cmdtyView Desktop API uses the same message model and SDK patterns as Openfeed, so the Openfeed SDK documentation covers the implementation details, including message formats, subscriptions, and real-time data handling.