Skip to content

About

OpenAlgo Java SDK

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenAlgo Java SDK

OpenAlgo Java SDK for algorithmic trading - Java client library for OpenAlgo API. Supports order placement, market data, options trading, and real-time WebSocket streaming.

Installation

Maven

Add the following dependency to your pom.xml:

<dependency>
    <groupId>in.openalgo</groupId>
    <artifactId>openalgo</artifactId>
    <version>1.0.1</version>
</dependency>

Gradle

Add the following to your build.gradle:

implementation 'in.openalgo:openalgo:1.0.1'

Compatibility

Java Version Support
Java 11 LTS (Long Term Support)
Java 17 LTS (Long Term Support)
Java 21 LTS (Long Term Support) - Recommended

Get the OpenAlgo apikey

Make Sure that your OpenAlgo Application is running. Login to OpenAlgo Application with valid credentials and get the OpenAlgo apikey

For detailed function parameters refer to the API Documentation

Getting Started with OpenAlgo Java SDK

First, import the OpenAlgo class and initialize it with your API key:

import in.openalgo.OpenAlgo;
import com.google.gson.JsonObject;

// Replace 'your_api_key_here' with your actual API key
// Specify the host URL with your hosted domain or ngrok domain.
// If running locally in windows then use the default host value.
OpenAlgo client = new OpenAlgo("your_api_key_here");

// Or with custom host
OpenAlgo client = new OpenAlgo("your_api_key_here", "http://127.0.0.1:5000");

Examples

Please refer to the documentation on order constants, and consult the API reference for details on optional parameters


API Reference

PlaceOrder Example

To place a new market order (simplest form):

// Minimal - uses defaults (MARKET, MIS, qty=1)
JsonObject response = client.placeorder("YESBANK", "BUY", "NSE");

// With quantity
JsonObject response = client.placeorder("YESBANK", "BUY", "NSE", 10);

// With priceType, product, quantity
JsonObject response = client.placeorder("YESBANK", "BUY", "NSE", "MARKET", "CNC", 1);

// With strategy
JsonObject response = client.placeorder("YESBANK", "BUY", "NSE", "MARKET", "CNC", 1, "MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());
System.out.println("OrderId: " + response.get("orderid").getAsString());

Place Market Order Response

{
  "mode": "analyze",
  "orderid": "25122301278383",
  "status": "success"
}

To place a new limit order:

// LIMIT order with price
JsonObject response = client.placeorder("YESBANK", "BUY", "NSE", "CNC", 1, "16");

System.out.println("Status: " + response.get("status").getAsString());
System.out.println("OrderId: " + response.get("orderid").getAsString());

Place Limit Order Response

{
  "status": "success",
  "orderid": "250408001003813"
}

PlaceSmartOrder Example

To place a smart order considering the current position size:

// Minimal - uses defaults (MARKET, MIS, qty=1)
JsonObject response = client.placesmartorder("TATAMOTORS", "SELL", "NSE", 5);

// With priceType, product, quantity
JsonObject response = client.placesmartorder("TATAMOTORS", "SELL", "NSE", 5, "MARKET", "MIS", 1);

// With strategy
JsonObject response = client.placesmartorder("TATAMOTORS", "SELL", "NSE", 5, "MARKET", "MIS", 1, "MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());
System.out.println("OrderId: " + response.get("orderid").getAsString());

Place Smart Market Order Response

{
  "status": "success",
  "orderid": "250408000997543"
}

BasketOrder Example

To place a new basket order:

List<Map<String, Object>> orders = new ArrayList<>();
orders.add(Map.of(
    "symbol", "BHEL",
    "exchange", "NSE",
    "action", "BUY",
    "quantity", 1,
    "pricetype", "MARKET",
    "product", "MIS"
));
orders.add(Map.of(
    "symbol", "ZOMATO",
    "exchange", "NSE",
    "action", "SELL",
    "quantity", 1,
    "pricetype", "MARKET",
    "product", "MIS"
));

// Without strategy (uses default "Java")
JsonObject response = client.basketorder(orders);

// With strategy
JsonObject response = client.basketorder(orders, "MyStrategy");
System.out.println("Status: " + response.get("status").getAsString());

Basket Order Response

{
  "status": "success",
  "results": [
    {"orderid": "250408000999544", "status": "success", "symbol": "BHEL"},
    {"orderid": "250408000997545", "status": "success", "symbol": "ZOMATO"}
  ]
}

SplitOrder Example

To place a new split order:

// Minimal - uses defaults (MARKET, MIS)
JsonObject response = client.splitorder("YESBANK", "SELL", "NSE", 105, 20);

System.out.println("Status: " + response.get("status").getAsString());

SplitOrder Response

{
  "status": "success",
  "split_size": "20",
  "total_quantity": 105,
  "results": [
    {"order_num": 1, "orderid": "250408001021467", "quantity": 20, "status": "success"},
    {"order_num": 2, "orderid": "250408001021459", "quantity": 20, "status": "success"},
    {"order_num": 3, "orderid": "250408001021466", "quantity": 20, "status": "success"},
    {"order_num": 4, "orderid": "250408001021470", "quantity": 20, "status": "success"},
    {"order_num": 5, "orderid": "250408001021471", "quantity": 20, "status": "success"},
    {"order_num": 6, "orderid": "250408001021472", "quantity": 5, "status": "success"}
  ]
}

ModifyOrder Example

To modify an existing order:

JsonObject response = client.modifyorder(
    "250408001002736",  // orderId
    "YESBANK",          // symbol
    "BUY",              // action
    "NSE",              // exchange
    "CNC",              // product
    1,                  // quantity
    "16.5"              // price
);
System.out.println("Status: " + response.get("status").getAsString());
System.out.println("OrderId: " + response.get("orderid").getAsString());

Modify Order Response

{
  "status": "success",
  "orderid": "250408001002736"
}

CancelOrder Example

To cancel an existing order:

// Without strategy (uses default)
JsonObject response = client.cancelorder("250408001002736");

// With strategy
JsonObject response = client.cancelorder("250408001002736", "MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());
System.out.println("OrderId: " + response.get("orderid").getAsString());

CancelOrder Response

{
  "status": "success",
  "orderid": "250408001002736"
}

CancelAllOrder Example

To cancel all open orders and trigger pending orders:

// Without strategy (uses default)
JsonObject response = client.cancelallorder();

// With strategy
JsonObject response = client.cancelallorder("MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());

CancelAllOrder Response

{
  "status": "success",
  "message": "Canceled 5 orders. Failed to cancel 0 orders.",
  "canceled_orders": ["250408001042620", "250408001042667", "250408001042642"]
}

ClosePosition Example

To close all open positions across various exchanges:

// Without strategy (uses default)
JsonObject response = client.closeposition();

// With strategy
JsonObject response = client.closeposition("MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());

ClosePosition Response

{
  "status": "success",
  "message": "All Open Positions Squared Off"
}

OrderStatus Example

To get the current order status:

// Without strategy (uses default)
JsonObject response = client.orderstatus("250828000185002");

// With strategy
JsonObject response = client.orderstatus("250828000185002", "MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());
if (response.has("data")) {
    JsonObject data = response.getAsJsonObject("data");
    System.out.println("Order Status: " + data.get("order_status").getAsString());
    System.out.println("Symbol: " + data.get("symbol").getAsString());
}

OrderStatus Response

{
  "status": "success",
  "data": {
    "action": "BUY",
    "exchange": "NSE",
    "order_status": "complete",
    "orderid": "250828000185002",
    "price": 18.95,
    "quantity": 1,
    "symbol": "YESBANK",
    "timestamp": "28-Aug-2025 09:59:10"
  }
}

OpenPosition Example

To get the current open position:

// Without strategy (uses default)
JsonObject response = client.openposition("YESBANK", "NSE", "MIS");

// With strategy
JsonObject response = client.openposition("YESBANK", "NSE", "MIS", "MyStrategy");

System.out.println("Status: " + response.get("status").getAsString());
System.out.println("Quantity: " + response.get("quantity").getAsInt());

OpenPosition Response

{
  "status": "success",
  "quantity": -10
}

Quotes Example

JsonObject response = client.quotes("RELIANCE", "NSE");
System.out.println("Status: " + response.get("status").getAsString());
if (response.has("data")) {
    JsonObject data = response.getAsJsonObject("data");
    System.out.println("Open: " + data.get("open").getAsDouble());
    System.out.println("High: " + data.get("high").getAsDouble());
    System.out.println("Low: " + data.get("low").getAsDouble());
    System.out.println("LTP: " + data.get("ltp").getAsDouble());
    System.out.println("Volume: " + data.get("volume").getAsLong());
}

Quotes Response

{
  "status": "success",
  "data": {
    "ask": 1575.4,
    "bid": 0.0,
    "high": 1577.5,
    "low": 1565.3,
    "ltp": 1575.4,
    "oi": 179211500,
    "open": 1573.5,
    "prev_close": 1565.1,
    "volume": 10184852
  }
}

Depth Example

JsonObject response = client.depth("SBIN", "NSE");
System.out.println("Status: " + response.get("status").getAsString());

Depth Response

{
  "status": "success",
  "data": {
    "ltp": 827.45,
    "open": 825.00,
    "high": 829.35,
    "low": 824.55,
    "volume": 9362799,
    "totalbuyqty": 591351,
    "totalsellqty": 835701,
    "bids": [
      {"price": 827.40, "quantity": 886},
      {"price": 827.35, "quantity": 212}
    ],
    "asks": [
      {"price": 827.45, "quantity": 767},
      {"price": 827.50, "quantity": 115}
    ]
  }
}

History Example

// Default source ("api") - fetches directly from the broker API
JsonObject response = client.history("SBIN", "NSE", "5m", "2025-12-20", "2025-12-22");

// Explicit source: "db" fetches from OpenAlgo's DuckDB/Historify database instead.
// The "db" source stores 1m and D intervals physically and computes all other
// intervals on-the-fly via SQL aggregation. Custom intraday intervals
// (2m, 3m, 4m, 6m, 7m, 2h, 3h, 4h, etc.) and daily-based intervals (W, M, Q, Y
// with multiples like 2W, 3M) are only available with source = "db".
JsonObject dbResponse = client.history("SBIN", "NSE", "2h", "2025-12-01", "2025-12-22", "db");

System.out.println("Status: " + response.get("status").getAsString());
if (response.has("data")) {
    JsonArray data = response.getAsJsonArray("data");
    System.out.println("Total Candles: " + data.size());
    // Print first candle
    JsonObject candle = data.get(0).getAsJsonObject();
    System.out.println("Open: " + candle.get("open").getAsDouble());
    System.out.println("High: " + candle.get("high").getAsDouble());
    System.out.println("Low: " + candle.get("low").getAsDouble());
    System.out.println("Close: " + candle.get("close").getAsDouble());
    System.out.println("Volume: " + candle.get("volume").getAsLong());
}

History Response

{
  "status": "success",
  "data": [
    {
      "close": 981.5,
      "high": 982.0,
      "low": 980.0,
      "open": 981.1,
      "timestamp": 1766375100,
      "volume": 131984
    },
    {
      "close": 981.75,
      "high": 982.6,
      "low": 981.15,
      "open": 981.5,
      "timestamp": 1766375400,
      "volume": 122471
    }
  ]
}

Intervals Example

JsonObject response = client.intervals();
System.out.println("Status: " + response.get("status").getAsString());

Intervals Response

{
  "status": "success",
  "data": {
    "days": ["D"],
    "hours": ["1h"],
    "minutes": ["1m", "3m", "5m", "10m", "15m", "30m"]
  }
}

Symbol Example

JsonObject response = client.symbol("NIFTY30DEC25FUT", "NFO");
System.out.println("Status: " + response.get("status").getAsString());

Symbol Response

{
  "status": "success",
  "data": {
    "symbol": "NIFTY30DEC25FUT",
    "name": "NIFTY",
    "exchange": "NFO",
    "instrumenttype": "FUT",
    "lotsize": 75,
    "expiry": "30-DEC-25",
    "freeze_qty": 1800
  }
}

Search Example

JsonObject response = client.search("NIFTY 26000 DEC CE", "NFO");
System.out.println("Status: " + response.get("status").getAsString());

Search Response

{
  "status": "success",
  "message": "Found 7 matching symbols",
  "data": [
    {
      "symbol": "NIFTY30DEC2526000CE",
      "exchange": "NFO",
      "expiry": "30-DEC-25",
      "lotsize": 75
    }
  ]
}

Instruments Example

// Download instruments for a single exchange
JsonObject nseResponse = client.instruments("NSE");
System.out.println("Status: " + nseResponse.get("status").getAsString());

// Download instruments for ALL exchanges (NSE, BSE, NFO, BFO, MCX, CDS, BCD,
// NSE_INDEX, BSE_INDEX) combined into a single response
JsonObject allResponse = client.instruments();
System.out.println("Total instruments: " + allResponse.getAsJsonArray("data").size());

Instruments Response

{
  "status": "success",
  "data": [
    {
      "symbol": "RELIANCE",
      "brsymbol": "RELIANCE-EQ",
      "name": "RELIANCE INDUSTRIES LTD",
      "exchange": "NSE",
      "token": "2885",
      "lotsize": 1,
      "instrumenttype": "EQ",
      "tick_size": 0.05
    }
  ]
}

OptionsOrder Example

To place ATM options order:

JsonObject response = client.optionsorder(
    "NIFTY",      // underlying
    "NSE_INDEX",  // exchange
    "ATM",        // offset
    "CE",         // optionType
    "BUY",        // action
    75            // quantity
);
System.out.println("Status: " + response.get("status").getAsString());
System.out.println("OrderId: " + response.get("orderid").getAsString());

OptionsOrder Response

{
  "status": "success",
  "orderid": "25102800000006",
  "symbol": "NIFTY30DEC2526200CE",
  "exchange": "NFO",
  "underlying": "NIFTY",
  "underlying_ltp": 26215.55
}

OptionsMultiOrder Example

To place multi-leg options strategy (e.g., Bull Call Spread):

List<Map<String, Object>> legs = new ArrayList<>();

// Leg 1: Buy ATM CE
Map<String, Object> leg1 = new HashMap<>();
leg1.put("offset", "ATM");
leg1.put("option_type", "CE");
leg1.put("action", "BUY");
leg1.put("quantity", 75);
leg1.put("product", "NRML");
legs.add(leg1);

// Leg 2: Sell OTM1 CE
Map<String, Object> leg2 = new HashMap<>();
leg2.put("offset", "OTM1");
leg2.put("option_type", "CE");
leg2.put("action", "SELL");
leg2.put("quantity", 75);
leg2.put("product", "NRML");
legs.add(leg2);

// Place multi-leg order with expiry
JsonObject response = client.optionsmultiorder("MyStrategy", "NIFTY", "NFO", legs, "30DEC25");

// Or without expiry (uses nearest expiry)
JsonObject response = client.optionsmultiorder("MyStrategy", "NIFTY", "NFO", legs);

System.out.println("Status: " + response.get("status").getAsString());

OptionsMultiOrder Response

{
  "status": "success",
  "mode": "analyze",
  "underlying": "NIFTY",
  "underlying_ltp": 26172.4,
  "results": [
    {
      "leg": 1,
      "action": "BUY",
      "offset": "ATM",
      "option_type": "CE",
      "symbol": "NIFTY30DEC2526150CE",
      "exchange": "NFO",
      "orderid": "25122337669355",
      "status": "success"
    },
    {
      "leg": 2,
      "action": "SELL",
      "offset": "OTM1",
      "option_type": "CE",
      "symbol": "NIFTY30DEC2526200CE",
      "exchange": "NFO",
      "orderid": "25122347595003",
      "status": "success"
    }
  ]
}

OptionChain Example

JsonObject response = client.optionchain("NIFTY", "NSE_INDEX", "30DEC25", 10);
System.out.println("Status: " + response.get("status").getAsString());
System.out.println("Underlying: " + response.get("underlying").getAsString());
System.out.println("ATM Strike: " + response.get("atm_strike").getAsInt());

OptionChain Response

{
  "status": "success",
  "underlying": "NIFTY",
  "underlying_ltp": 26215.55,
  "expiry_date": "30DEC25",
  "atm_strike": 26200,
  "chain": [
    {
      "strike": 26100,
      "ce": {"symbol": "NIFTY30DEC2526100CE", "label": "ITM2", "ltp": 490},
      "pe": {"symbol": "NIFTY30DEC2526100PE", "label": "OTM2", "ltp": 193}
    }
  ]
}

OptionGreeks Example

JsonObject response = client.optiongreeks("NIFTY25NOV2526000CE", "NFO");
System.out.println("Status: " + response.get("status").getAsString());

OptionGreeks Response

{
  "status": "success",
  "symbol": "NIFTY25NOV2526000CE",
  "spot_price": 25966.05,
  "option_price": 435,
  "implied_volatility": 15.6,
  "days_to_expiry": 28.51,
  "greeks": {
    "delta": 0.4967,
    "gamma": 0.000352,
    "theta": -7.919,
    "vega": 28.9489
  }
}

Funds Example

JsonObject response = client.funds();
System.out.println("Status: " + response.get("status").getAsString());
if (response.has("data")) {
    JsonObject data = response.getAsJsonObject("data");
    System.out.println("Available Cash: " + data.get("availablecash").getAsString());
}

Funds Response

{
  "status": "success",
  "data": {
    "availablecash": "320.66",
    "collateral": "0.00",
    "m2mrealized": "3.27",
    "m2munrealized": "-7.88",
    "utiliseddebits": "679.34"
  }
}

OrderBook Example

JsonObject response = client.orderbook();
System.out.println("Status: " + response.get("status").getAsString());

OrderBook Response

{
  "status": "success",
  "data": {
    "orders": [
      {
        "action": "BUY",
        "exchange": "NSE",
        "order_status": "complete",
        "orderid": "250408000989443",
        "symbol": "RELIANCE"
      }
    ],
    "statistics": {
      "total_buy_orders": 2,
      "total_completed_orders": 1
    }
  }
}

TradeBook Example

JsonObject response = client.tradebook();
System.out.println("Status: " + response.get("status").getAsString());

TradeBook Response

{
  "status": "success",
  "data": [
    {
      "action": "BUY",
      "average_price": "1180.1",
      "exchange": "NSE",
      "orderid": "250408000989443",
      "symbol": "RELIANCE",
      "trade_value": "1180.1"
    }
  ]
}

PositionBook Example

JsonObject response = client.positionbook();
System.out.println("Status: " + response.get("status").getAsString());

PositionBook Response

{
  "status": "success",
  "data": [
    {
      "symbol": "NHPC",
      "exchange": "NSE",
      "quantity": -1,
      "ltp": 83.72,
      "pnl": 0.02
    }
  ]
}

Holdings Example

JsonObject response = client.holdings();
System.out.println("Status: " + response.get("status").getAsString());

Holdings Response

{
  "status": "success",
  "data": {
    "holdings": [
      {
        "symbol": "RELIANCE",
        "exchange": "NSE",
        "quantity": 1,
        "pnl": -149,
        "pnlpercent": -11.1
      }
    ],
    "statistics": {
      "totalholdingvalue": 1768,
      "totalprofitandloss": -233.15,
      "totalpnlpercentage": -11.65
    }
  }
}

Telegram Alert Example

JsonObject response = client.telegram("<openalgo_loginid>", "NIFTY crossed 26000!", 5);
System.out.println("Status: " + response.get("status").getAsString());

Telegram Alert Response

{
  "status": "success",
  "message": "Notification sent successfully"
}

WhatsApp Alert Example

Send a message via the OpenAlgo paired WhatsApp device. Prerequisite: the device must already be paired from the OpenAlgo /whatsapp admin page (pairing itself is not exposed via the API).

// Send to self (the paired device's own number) - simplest form
JsonObject response = client.whatsapp("Build #482 deployed. P&L: +1.2%");

// Send to a single phone number (E.164 digits, no '+')
JsonObject response = client.whatsapp("Order placed: BUY RELIANCE x 10", "919876543210");

// Small broadcast (max 5 recipients)
List<String> phones = List.of("919876543210", "919812345678");
JsonObject response = client.whatsapp("Server maintenance in 10 minutes", phones);

// Send to a linked OpenAlgo user by username
JsonObject response = client.whatsappToUser("alice", "Daily summary attached");

// Full control: username/phone/phones, image, document, caption, filename, wait_for_delivery
JsonObject response = client.whatsapp(
    "NIFTY end-of-day chart",   // message
    null,                        // username
    "919876543210",              // phone
    null,                        // phones (broadcast list)
    "/srv/charts/nifty_eod.png", // image
    null,                        // document
    null,                        // caption
    null,                        // filename
    true                          // waitForDelivery
);

System.out.println("Status: " + response.get("status").getAsString());

WhatsApp Alert Response

{
  "status": "success",
  "message": "Delivered to 1, failed 0",
  "data": {
    "sent": ["919876543210@s.whatsapp.net"],
    "failed": [],
    "skipped": 0
  }
}

Holidays Example

// Explicit year
JsonObject response = client.holidays(2025);

// No argument - defaults to the current year
JsonObject currentYearResponse = client.holidays();

System.out.println("Status: " + response.get("status").getAsString());

Holidays Response

{
  "status": "success",
  "data": [
    {"date": "2025-02-26", "description": "Maha Shivaratri", "holiday_type": "TRADING_HOLIDAY"},
    {"date": "2025-03-14", "description": "Holi", "holiday_type": "TRADING_HOLIDAY"}
  ]
}

Timings Example

// Explicit date
JsonObject response = client.timings("2025-12-19");

// No argument - defaults to today's date
JsonObject todayResponse = client.timings();

System.out.println("Status: " + response.get("status").getAsString());

Timings Response

{
  "status": "success",
  "data": [
    {"exchange": "NSE", "start_time": 1734584100000, "end_time": 1734606600000},
    {"exchange": "BSE", "start_time": 1734584100000, "end_time": 1734606600000}
  ]
}

Analyzer Status Example

JsonObject response = client.analyzerstatus();
System.out.println("Status: " + response.get("status").getAsString());

Analyzer Status Response

{
  "status": "success",
  "data": {
    "analyze_mode": true,
    "mode": "analyze",
    "total_logs": 2
  }
}

Analyzer Toggle Example

// Switch to analyze mode (simulated responses)
JsonObject response = client.analyzertoggle(true);
System.out.println("Status: " + response.get("status").getAsString());

Analyzer Toggle Response

{
  "status": "success",
  "data": {
    "analyze_mode": true,
    "mode": "analyze",
    "message": "Analyzer mode switched to analyze",
    "total_logs": 2
  }
}

Strategy Webhook (TradingView Integration)

The Strategy class is a standalone webhook client for TradingView-style integrations. Unlike OpenAlgo, it is not initialized with an API key — instead it posts signed order signals to a per-strategy webhook URL that you configure in OpenAlgo. The strategy mode (LONG_ONLY, SHORT_ONLY, BOTH) is configured on the OpenAlgo server side, not by this client.

import in.openalgo.Strategy;
import com.google.gson.JsonObject;

// host_url is your OpenAlgo server, webhook_id comes from the strategy's
// webhook settings page in OpenAlgo
Strategy strategy = new Strategy("http://127.0.0.1:5000", "your-webhook-id");

// Simple BUY/SELL signal
JsonObject response = strategy.strategyorder("RELIANCE", "BUY");

// With an explicit position size (required for BOTH mode strategies)
JsonObject response2 = strategy.strategyorder("NIFTY", "SELL", 75);

System.out.println("Status: " + response.get("status").getAsString());

// Release the pooled HTTP connection when done
strategy.close();

Strategy Order Response

{
  "status": "success",
  "message": "Order placed successfully"
}

WebSocket Streaming

LTP Data (Streaming WebSocket)

import in.openalgo.OpenAlgo;
import java.util.*;

// Initialize OpenAlgo client with WebSocket URL
OpenAlgo client = new OpenAlgo.Builder("your_api_key")
    .host("http://127.0.0.1:5000")
    .wsUrl("ws://127.0.0.1:8765")
    .build();

// Define instruments to subscribe for LTP
List<Map<String, String>> instruments = new ArrayList<>();
instruments.add(Map.of("exchange", "MCX", "symbol", "CRUDEOIL16JAN26FUT"));

// Connect and subscribe
client.connect();
client.subscribeLtp(instruments, data -> {
    System.out.println("LTP Update: " + data);
});

// Wait for data
Thread.sleep(3000);

// Get cached LTP data
Map<String, Object> ltpData = client.getLtp("MCX", "CRUDEOIL16JAN26FUT");
System.out.println("LTP Data: " + ltpData);

// Unsubscribe and disconnect
client.unsubscribeLtp(instruments);
client.disconnect();

LTP Response

{
  "ltp": {
    "MCX": {
      "CRUDEOIL16JAN26FUT": {
        "ltp": 5218.0,
        "timestamp": 1703328453123
      }
    }
  }
}

Quotes (Streaming WebSocket)

// Subscribe to quote stream
client.connect();
client.subscribeQuote(instruments, data -> {
    System.out.println("Quote Update: " + data);
});

// Get cached Quote data
Map<String, Object> quoteData = client.getQuotes("MCX", "CRUDEOIL16JAN26FUT");

Quote Response

{
  "quote": {
    "MCX": {
      "CRUDEOIL16JAN26FUT": {
        "open": 5124.0,
        "high": 5246.0,
        "low": 5114.0,
        "ltp": 5218.0,
        "volume": 14537,
        "timestamp": 1703328453123
      }
    }
  }
}

Depth (Streaming WebSocket)

// Subscribe to depth stream
client.connect();
client.subscribeDepth(instruments, data -> {
    System.out.println("Depth Update: " + data);
});

// Get cached Depth data
Map<String, Object> depthData = client.getDepth("MCX", "CRUDEOIL16JAN26FUT");

Depth Response

{
  "depth": {
    "MCX": {
      "CRUDEOIL16JAN26FUT": {
        "ltp": 5218.0,
        "timestamp": 1703328453123,
        "depth": {
          "buy": [
            {"price": 5217.0, "quantity": 2, "orders": 2},
            {"price": 5216.0, "quantity": 16, "orders": 8}
          ],
          "sell": [
            {"price": 5218.0, "quantity": 5, "orders": 3},
            {"price": 5219.0, "quantity": 13, "orders": 7}
          ]
        }
      }
    }
  }
}

Note on subscribe/unsubscribe wire format: subscribeLtp() / subscribeQuote() / subscribeDepth() (and their unsubscribe* counterparts) each send a single bulk WebSocket frame containing every instrument in the list ({"action": "subscribe", "symbols":[{"exchange","symbol"}, ...], "mode": N, "depth": N}), matching the OpenAlgo WebSocket proxy's contract. This makes subscribing to a large list (e.g. a 200-symbol option chain) a single fast round trip instead of one frame per instrument.


Error Handling

JsonObject response = client.placeorder("INVALID", "BUY", "NSE");

if (!"success".equals(response.get("status").getAsString())) {
    System.out.println("Error: " + response.get("message").getAsString());
}

Complete API Reference

Order Management

Method Description
placeorder() Place a new order
placesmartorder() Place a smart order with position sizing
modifyorder() Modify an existing order
cancelorder() Cancel a specific order
cancelallorder() Cancel all open orders
closeposition() Close all open positions
orderstatus() Get status of a specific order
openposition() Get current open position quantity

Basket & Split Orders

Method Description
basketorder() Place multiple orders in a single request
splitorder() Split large order into smaller chunks

Options Trading

Method Description
optionsorder() Place ATM/ITM/OTM option order
optionsmultiorder() Place multi-leg option strategy
optionsymbol() Get option symbol by offset
optionchain() Get full option chain data
optiongreeks() Calculate option Greeks
syntheticfuture() Calculate synthetic future price
expiry() Get expiry dates for symbol

Market Data

Method Description
quotes() Get real-time quotes for a symbol
multiquotes() Get quotes for multiple symbols
depth() Get market depth (order book)
history() Get historical OHLCV data (optional source: "api" default, or "db" for DuckDB/Historify)
intervals() Get supported time intervals

Symbol & Search

Method Description
symbol() Get symbol details
search() Search for symbols
instruments() Download instruments for a specific exchange, or all exchanges combined when omitted

Account & Portfolio

Method Description
funds() Get funds and margin details
margin() Calculate margin requirements
orderbook() Get order book
tradebook() Get trade book
positionbook() Get position book
holdings() Get stock holdings

Utilities

Method Description
holidays() Get trading holidays for a year (defaults to the current year when omitted)
timings() Get exchange timings for a date (defaults to today when omitted)
telegram() Send Telegram alert message
whatsapp() Send a WhatsApp alert message (self, single number, small broadcast, or linked username)
whatsappToUser() Send a WhatsApp alert to a linked OpenAlgo user by username
analyzerstatus() Get analyzer mode status
analyzertoggle() Toggle analyze/live mode

Strategy Webhook

Method Description
new Strategy(hostUrl, webhookId) Create a standalone TradingView-style webhook client (no API key)
strategyorder() Send a BUY/SELL signal (with optional position size) to the strategy's webhook
close() Release the underlying pooled HTTP connection

WebSocket Streaming

Method Description
connect() Connect to WebSocket server
disconnect() Disconnect from WebSocket
subscribeLtp() Subscribe to LTP updates
unsubscribeLtp() Unsubscribe from LTP
subscribeQuote() Subscribe to Quote updates
unsubscribeQuote() Unsubscribe from Quote
subscribeDepth() Subscribe to Depth updates
unsubscribeDepth() Unsubscribe from Depth
getLtp() Get cached LTP data
getQuotes() Get cached Quote data
getDepth() Get cached Depth data

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links

About

OpenAlgo Java SDK

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages