### Get and Display Mutual Fund Instruments Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieves a list of all available mutual fund instruments and prints their details. Ensure you have initialized KiteConnect and logged in. ```java import com.zerodhatech.models.MFInstrument; import java.util.List; // Get all mutual fund instruments List mfInstruments = kiteConnect.getMFInstruments(); System.out.println("Total MF Instruments: " + mfInstruments.size()); for (MFInstrument mf : mfInstruments) { System.out.println("Trading Symbol: " + mf.tradingsymbol); System.out.println("AMC: " + mf.amc); System.out.println("Name: " + mf.name); System.out.println("Purchase Allowed: " + mf.purchase_allowed); System.out.println("Min Purchase: " + mf.minimum_purchase_amount); System.out.println("Last Price: " + mf.last_price); System.out.println("---"); } ``` -------------------------------- ### Get Margin Details Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Retrieve margin details for a specific segment, such as 'equity' or 'commodity'. This provides information on available and utilized margins. ```java // Get margins returns margin model, you can pass equity or commodity as arguments to get margins of respective segments. Margin margins = kiteSdk.getMargins("equity"); System.out.println(margins.available.cash); System.out.println(margins.utilised.debits); ``` -------------------------------- ### Get Positions - Java KiteConnect Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieves both net (overnight + day) and day-only positions. Iterates through net positions to display details like symbol, exchange, product, quantity, average price, P&L, and day buy/sell quantities. Also prints the count of day positions. ```java // Get positions (day and net) Map> positions = kiteConnect.getPositions(); // Net positions (overnight + today) List netPositions = positions.get("net"); for (Position position : netPositions) { System.out.println("Symbol: " + position.tradingSymbol); System.out.println("Exchange: " + position.exchange); System.out.println("Product: " + position.product); System.out.println("Quantity: " + position.quantity); System.out.println("Average Price: " + position.averagePrice); System.out.println("P&L: " + position.pnl); System.out.println("Day Buy Qty: " + position.dayBuyQuantity); System.out.println("Day Sell Qty: " + position.daySellQuantity); } // Day positions (intraday only) List dayPositions = positions.get("day"); System.out.println("Day Positions Count: " + dayPositions.size()); ``` -------------------------------- ### Place Mutual Fund SIP Source: https://context7.com/zerodha/javakiteconnect/llms.txt Places a Systematic Investment Plan (SIP) for a mutual fund. Configure frequency, day, instalments, initial amount, and monthly amount. ```java import com.zerodhatech.models.MFSIP; // Place a SIP MFSIP sip = kiteConnect.placeMFSIP( "INF174K01LS2", // Trading symbol "monthly", // Frequency: weekly, monthly, quarterly 1, // Day of month (1, 5, 10, 15, 20, 25) -1, // Instalments (-1 for perpetual) 5000, // Initial amount 1000 // Monthly amount ); System.out.println("SIP ID: " + sip.sipId); System.out.println("First Order ID: " + sip.orderId); ``` -------------------------------- ### Get All Mutual Fund SIPs Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieves a list of all active and inactive Systematic Investment Plans (SIPs). This function iterates through the SIPs and prints key details for each. ```java import com.zerodhatech.models.MFSIP; import java.util.List; // Get all SIPs List sips = kiteConnect.getMFSIPs(); for (MFSIP s : sips) { System.out.println("SIP ID: " + s.sipId); System.out.println("Fund: " + s.tradingsymbol); System.out.println("Amount: " + s.instalmentAmount); System.out.println("Frequency: " + s.frequency); System.out.println("Status: " + s.status); } ``` -------------------------------- ### Get and Display Mutual Fund Holdings Source: https://context7.com/zerodha/javakiteconnect/llms.txt Fetches and displays details of your current mutual fund holdings. This requires an active KiteConnect session. ```java import com.zerodhatech.models.MFHolding; import java.util.List; // Get mutual fund holdings List mfHoldings = kiteConnect.getMFHoldings(); for (MFHolding holding : mfHoldings) { System.out.println("Fund: " + holding.fund); System.out.println("Folio: " + holding.folio); System.out.println("Units: " + holding.quantity); System.out.println("Average Price: " + holding.averagePrice); System.out.println("Last Price: " + holding.lastPrice); System.out.println("P&L: " + holding.pnl); } ``` -------------------------------- ### Get Holdings - Java KiteConnect Source: https://context7.com/zerodha/javakiteconnect/llms.txt Fetches all holdings associated with the user's account. Iterates through the holdings to print details like trading symbol, ISIN, quantity, prices, P&L, and day change. Also handles MTF holdings if applicable. ```java import com.zerodhatech.models.Holding; import com.zerodhatech.models.Position; import org.json.JSONObject; import java.util.List; import java.util.Map; // Get holdings List holdings = kiteConnect.getHoldings(); for (Holding holding : holdings) { System.out.println("Symbol: " + holding.tradingSymbol); System.out.println("ISIN: " + holding.isin); System.out.println("Quantity: " + holding.quantity); System.out.println("Average Price: " + holding.averagePrice); System.out.println("Last Price: " + holding.lastPrice); System.out.println("P&L: " + holding.pnl); System.out.println("Day Change: " + holding.dayChange); System.out.println("Day Change %: " + holding.dayChangePercentage); // MTF holdings (if applicable) if (holding.mtf != null && holding.mtf.quantity > 0) { System.out.println("MTF Quantity: " + holding.mtf.quantity); System.out.println("MTF Average Price: " + holding.mtf.averagePrice); } System.out.println("---"); } ``` -------------------------------- ### Get All Mutual Fund Orders Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieves a list of all mutual fund orders placed. This function requires an active session and returns the total count of orders. ```java import com.zerodhatech.models.MFOrder; import java.util.List; // Get all mutual fund orders List mfOrders = kiteConnect.getMFOrders(); System.out.println("Total MF Orders: " + mfOrders.size()); ``` -------------------------------- ### Get Specific Mutual Fund SIP Source: https://context7.com/zerodha/javakiteconnect/llms.txt Fetches details for a specific mutual fund SIP using its SIP ID. This allows you to inspect the configuration and status of a particular SIP. ```java import com.zerodhatech.models.MFSIP; // Get specific SIP MFSIP mySip = kiteConnect.getMFSIP("291156521960679"); System.out.println("SIP Instalments: " + mySip.instalments); ``` -------------------------------- ### Modify Mutual Fund SIP Source: https://context7.com/zerodha/javakiteconnect/llms.txt Modifies an existing mutual fund SIP. You can change the frequency, day, number of instalments, amount, and status (active/paused) of the SIP. ```java // Modify a SIP kiteConnect.modifyMFSIP( "weekly", // New frequency 1, // Day 12, // Instalments 1500, // New amount "paused", // Status: active or paused "504341441825418" // SIP ID ); System.out.println("SIP modified successfully"); ``` -------------------------------- ### Get Specific Mutual Fund Order Source: https://context7.com/zerodha/javakiteconnect/llms.txt Fetches details for a specific mutual fund order using its unique order ID. This is useful for checking the status of a particular transaction. ```java import com.zerodhatech.models.MFOrder; // Get specific mutual fund order MFOrder order = kiteConnect.getMFOrder("106580291331583"); System.out.println("Order Symbol: " + order.tradingsymbol); System.out.println("Order Status: " + order.status); ``` -------------------------------- ### Place Various Order Types in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Demonstrates how to configure and place different order types using the OrderParams object and the kiteConnect.placeOrder method. Includes handling for auto-sliced child orders. ```java import com.zerodhatech.kiteconnect.utils.Constants; import com.zerodhatech.models.OrderParams; import com.zerodhatech.models.OrderResponse; import com.zerodhatech.models.BulkOrderResponse; // Place a regular limit order OrderParams orderParams = new OrderParams(); orderParams.quantity = 1; orderParams.orderType = Constants.ORDER_TYPE_LIMIT; orderParams.tradingsymbol = "INFY"; orderParams.product = Constants.PRODUCT_CNC; orderParams.exchange = Constants.EXCHANGE_NSE; orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; orderParams.validity = Constants.VALIDITY_DAY; orderParams.price = 1450.0; orderParams.triggerPrice = 0.0; orderParams.tag = "myTag123"; // Optional: max 8 alphanumeric chars OrderResponse response = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR); System.out.println("Order ID: " + response.orderId); // Place a market order OrderParams marketOrder = new OrderParams(); marketOrder.quantity = 1; marketOrder.orderType = Constants.ORDER_TYPE_MARKET; marketOrder.tradingsymbol = "RELIANCE"; marketOrder.product = Constants.PRODUCT_MIS; marketOrder.exchange = Constants.EXCHANGE_NSE; marketOrder.transactionType = Constants.TRANSACTION_TYPE_BUY; marketOrder.validity = Constants.VALIDITY_DAY; OrderResponse marketResponse = kiteConnect.placeOrder(marketOrder, Constants.VARIETY_REGULAR); System.out.println("Market Order ID: " + marketResponse.orderId); // Place a cover order (CO) OrderParams coOrder = new OrderParams(); coOrder.quantity = 1; coOrder.price = 0.0; coOrder.orderType = Constants.ORDER_TYPE_MARKET; coOrder.tradingsymbol = "SBIN"; coOrder.exchange = Constants.EXCHANGE_NSE; coOrder.transactionType = Constants.TRANSACTION_TYPE_BUY; coOrder.validity = Constants.VALIDITY_DAY; coOrder.triggerPrice = 580.0; // Stop-loss trigger coOrder.product = Constants.PRODUCT_MIS; OrderResponse coResponse = kiteConnect.placeOrder(coOrder, Constants.VARIETY_CO); System.out.println("Cover Order ID: " + coResponse.orderId); // Place an iceberg order with TTL validity OrderParams icebergOrder = new OrderParams(); icebergOrder.quantity = 100; icebergOrder.orderType = Constants.ORDER_TYPE_LIMIT; icebergOrder.price = 1440.0; icebergOrder.transactionType = Constants.TRANSACTION_TYPE_BUY; icebergOrder.tradingsymbol = "INFY"; icebergOrder.exchange = Constants.EXCHANGE_NSE; icebergOrder.validity = Constants.VALIDITY_TTL; icebergOrder.product = Constants.PRODUCT_MIS; icebergOrder.validityTTL = 10; // Minutes icebergOrder.icebergLegs = 5; // 2-10 legs allowed icebergOrder.icebergQuantity = 20; // Quantity per leg OrderResponse icebergResponse = kiteConnect.placeOrder(icebergOrder, Constants.VARIETY_ICEBERG); System.out.println("Iceberg Order ID: " + icebergResponse.orderId); // Place order with auto-slice (for large orders) OrderParams sliceOrder = new OrderParams(); sliceOrder.price = 146.55; sliceOrder.quantity = 5925; sliceOrder.transactionType = Constants.TRANSACTION_TYPE_BUY; sliceOrder.orderType = Constants.ORDER_TYPE_LIMIT; sliceOrder.tradingsymbol = "NIFTY2632423000PE"; sliceOrder.exchange = Constants.EXCHANGE_NFO; sliceOrder.validity = Constants.VALIDITY_DAY; sliceOrder.product = Constants.PRODUCT_MIS; sliceOrder.autoslice = true; OrderResponse sliceResponse = kiteConnect.placeOrder(sliceOrder, Constants.VARIETY_REGULAR); System.out.println("Parent Order ID: " + sliceResponse.orderId); // Handle child orders from auto-slice if (sliceResponse.children != null) { for (BulkOrderResponse child : sliceResponse.children) { if (child.orderId != null) { System.out.println("Child Order ID: " + child.orderId); } else if (child.bulkOrderError != null) { System.out.println("Child Error: " + child.bulkOrderError.message); } } } // Place an auction order OrderParams auctionOrder = new OrderParams(); auctionOrder.price = 365.5; auctionOrder.quantity = 1; auctionOrder.transactionType = Constants.TRANSACTION_TYPE_SELL; auctionOrder.orderType = Constants.ORDER_TYPE_LIMIT; auctionOrder.tradingsymbol = "ITC"; auctionOrder.exchange = Constants.EXCHANGE_NSE; auctionOrder.validity = Constants.VALIDITY_DAY; auctionOrder.product = Constants.PRODUCT_CNC; auctionOrder.auctionNumber = "2559"; OrderResponse auctionResponse = kiteConnect.placeOrder(auctionOrder, Constants.VARIETY_AUCTION); System.out.println("Auction Order ID: " + auctionResponse.orderId); ``` -------------------------------- ### Initialize KiteConnect SDK (Version 2) Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md This is the initialization method for the KiteConnect SDK in version 2. It requires your API key. ```java KiteConnect kiteSdk = new KiteConnect("your_apiKey"); ``` -------------------------------- ### Initialize and Connect KiteTicker Source: https://context7.com/zerodha/javakiteconnect/llms.txt Initializes the KiteTicker with access token and API key, sets up listeners for connection, ticks, and errors, and then connects to the WebSocket server. Ensure you have valid credentials and network connectivity. ```java import com.zerodhatech.ticker.*; import com.zerodhatech.models.Tick; import com.zerodhatech.models.Order; import com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; // Initialize ticker with access token and API key KiteTicker ticker = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey()); // Prepare tokens to subscribe ArrayList tokens = new ArrayList<>(); tokens.add(256265L); // NIFTY 50 tokens.add(260105L); // NIFTY BANK tokens.add(738561L); // RELIANCE tokens.add(408065L); // INFY // Set connection listener ticker.setOnConnectedListener(new OnConnect() { @Override public void onConnected() { System.out.println("Connected to ticker"); // Subscribe to tokens (default mode: quote) ticker.subscribe(tokens); // Set mode to full for complete depth data ticker.setMode(tokens, KiteTicker.modeFull); } }); // Set disconnection listener ticker.setOnDisconnectedListener(new OnDisconnect() { @Override public void onDisconnected() { System.out.println("Disconnected from ticker"); } }); // Set tick arrival listener ticker.setOnTickerArrivalListener(new OnTicks() { @Override public void onTicks(ArrayList ticks) { NumberFormat formatter = new DecimalFormat("#.#\n"); for (Tick tick : ticks) { System.out.println("Token: " + tick.getInstrumentToken()); System.out.println("LTP: " + formatter.format(tick.getLastTradedPrice())); System.out.println("Change: " + formatter.format(tick.getChange()) + "%\n"); System.out.println("Volume: " + tick.getVolumeTradedToday()); System.out.println("Open: " + tick.getOpenPrice()); System.out.println("High: " + tick.getHighPrice()); System.out.println("Low: " + tick.getLowPrice()); System.out.println("Close: " + tick.getClosePrice()); System.out.println("OI: " + formatter.format(tick.getOi())); System.out.println("OI Day High: " + tick.getOpenInterestDayHigh()); System.out.println("OI Day Low: " + tick.getOpenInterestDayLow()); System.out.println("Last Traded Time: " + tick.getLastTradedTime()); System.out.println("Tick Timestamp: " + tick.getTickTimestamp()); // Market depth (in full mode) if (tick.getMarketDepth() != null) { System.out.println("Buy Depth Levels: " + tick.getMarketDepth().get("buy").size()); System.out.println("Sell Depth Levels: " + tick.getMarketDepth().get("sell").size()); } System.out.println("---\n"); } } }); // Set order update listener (for postback updates) ticker.setOnOrderUpdateListener(new OnOrderUpdate() { @Override public void onOrderUpdate(Order order) { System.out.println("Order Update - ID: " + order.orderId); System.out.println("Status: " + order.status); System.out.println("Symbol: " + order.tradingSymbol); } }); // Set error listener ticker.setOnErrorListener(new OnError() { @Override public void onError(Exception e) { System.out.println("Error: " + e.getMessage()); } @Override public void onError(KiteException ke) { System.out.println("Kite Error: " + ke.message); } @Override public void onError(String error) { System.out.println("Error: " + error); } }); // Configure reconnection ticker.setTryReconnection(true); ticker.setMaximumRetries(10); ticker.setMaximumRetryInterval(30); // seconds // Connect to ticker ticker.connect(); // Check connection status boolean isConnected = ticker.isConnectionOpen(); System.out.println("Ticker Connected: " + isConnected); // Change mode for specific tokens // modeLTP - Only last traded price // modeQuote - LTP, LTQ, average price, volume, OHLC, change // modeFull - All data including depth and OI ticker.setMode(tokens, KiteTicker.modeLTP); // Unsubscribe from specific tokens ArrayList unsubTokens = new ArrayList<>(); unsubTokens.add(738561L); ticker.unsubscribe(unsubTokens); // Disconnect when done ticker.disconnect(); ``` -------------------------------- ### Initialize KiteTicker (Version 3) Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md This is the initialization method for the KiteTicker in version 3. It requires user ID, access token, and API key for authentication. ```java KiteTicker tickerProvider = new KiteTicker(kiteConnect.getUserId(), kiteConnect.getAccessToken(), kiteConnect.getApiKey()); ``` -------------------------------- ### Initialize KiteConnect Client and Authenticate User Source: https://context7.com/zerodha/javakiteconnect/llms.txt Initialize the KiteConnect client with your API key and authenticate users via OAuth to obtain access tokens. Includes optional debug logging, proxy support, and session expiry handling. ```java import com.zerodhatech.kiteconnect.KiteConnect; import com.zerodhatech.kiteconnect.kitehttp.SessionExpiryHook; import com.zerodhatech.models.User; // Initialize with API key KiteConnect kiteConnect = new KiteConnect("your_api_key"); // Enable debug logging (optional) KiteConnect kiteConnectDebug = new KiteConnect("your_api_key", true); // Initialize with proxy support (optional) Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.host", 8080)); KiteConnect kiteConnectProxy = new KiteConnect("your_api_key", proxy, false); // Set user ID kiteConnect.setUserId("AB1234"); // Get login URL - redirect user to this URL for authentication String loginUrl = kiteConnect.getLoginURL(); System.out.println("Login URL: " + loginUrl); // Output: https://kite.zerodha.com/connect/login?api_key=your_api_key&v=3 // After user login, exchange request_token for access_token User user = kiteConnect.generateSession("request_token_from_callback", "your_api_secret"); System.out.println("Access Token: " + user.accessToken); System.out.println("User ID: " + user.userId); // Set the tokens for subsequent requests kiteConnect.setAccessToken(user.accessToken); kiteConnect.setPublicToken(user.publicToken); // Set session expiry hook for automatic session management kiteConnect.setSessionExpiryHook(new SessionExpiryHook() { @Override public void sessionExpired() { System.out.println("Session expired - re-authenticate user"); // Implement re-authentication logic here } }); // Renew access token using refresh token TokenSet tokenSet = kiteConnect.renewAccessToken("refresh_token", "your_api_secret"); System.out.println("New Access Token: " + tokenSet.accessToken); ``` -------------------------------- ### Fetch Market Data and Quotes in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieves real-time quotes, OHLC data, and last traded prices for specified instruments. Use getQuote for full depth, getOHLC for lighter data, and getLTP for the lightest call. ```java import com.zerodhatech.models.Quote; import com.zerodhatech.models.OHLCQuote; import com.zerodhatech.models.LTPQuote; import java.util.Map; // Get full quote data (includes depth) String[] instruments = {"NSE:INFY", "NSE:RELIANCE", "BSE:SBIN", "256265"}; Map quotes = kiteConnect.getQuote(instruments); Quote infyQuote = quotes.get("NSE:INFY"); System.out.println("Symbol: " + infyQuote.instrumentToken); System.out.println("Last Price: " + infyQuote.lastPrice); System.out.println("Open: " + infyQuote.ohlc.open); System.out.println("High: " + infyQuote.ohlc.high); System.out.println("Low: " + infyQuote.ohlc.low); System.out.println("Close: " + infyQuote.ohlc.close); System.out.println("Volume: " + infyQuote.volume); System.out.println("Average Price: " + infyQuote.averagePrice); System.out.println("Open Interest: " + infyQuote.oi); System.out.println("OI Day High: " + infyQuote.oiDayHigh); System.out.println("OI Day Low: " + infyQuote.oiDayLow); System.out.println("Upper Circuit: " + infyQuote.upperCircuitLimit); System.out.println("Lower Circuit: " + infyQuote.lowerCircuitLimit); System.out.println("Timestamp: " + infyQuote.timestamp); // Market depth (bid/ask) System.out.println("Top Bid: " + infyQuote.depth.buy.get(0).getPrice() + " x " + infyQuote.depth.buy.get(0).getQuantity()); System.out.println("Top Ask: " + infyQuote.depth.sell.get(0).getPrice() + " x " + infyQuote.depth.sell.get(0).getQuantity()); // Get OHLC data (lighter than full quote) String[] ohlcInstruments = {"NSE:NIFTY 50", "NSE:BANKNIFTY", "256265"}; Map ohlcData = kiteConnect.getOHLC(ohlcInstruments); OHLCQuote nifty = ohlcData.get("NSE:NIFTY 50"); System.out.println("NIFTY Open: " + nifty.ohlc.open); System.out.println("NIFTY High: " + nifty.ohlc.high); System.out.println("NIFTY Low: " + nifty.ohlc.low); System.out.println("NIFTY Close: " + nifty.ohlc.close); System.out.println("NIFTY LTP: " + nifty.lastPrice); // Get LTP only (lightest call) String[] ltpInstruments = {"NSE:INFY", "NSE:TCS", "NSE:WIPRO"}; Map ltpData = kiteConnect.getLTP(ltpInstruments); System.out.println("INFY LTP: " + ltpData.get("NSE:INFY").lastPrice); System.out.println("TCS LTP: " + ltpData.get("NSE:TCS").lastPrice); System.out.println("WIPRO LTP: " + ltpData.get("NSE:WIPRO").lastPrice); ``` -------------------------------- ### Initialize Kite Connect and Set User ID Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Initialize the KiteConnect SDK with your API key and set the user ID for subsequent operations. ```java // Initialize Kiteconnect using apiKey. KiteConnect kiteSdk = new KiteConnect("your_apiKey"); // Set userId. kiteSdk.setUserId("your_userId"); ``` -------------------------------- ### Set Access and Public Tokens Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Configure the KiteConnect SDK with the obtained access token and public token after a successful login. ```java // Set request token and public token which are obtained from login process. kiteSdk.setAccessToken(userModel.accessToken); kiteSdk.setPublicToken(userModel.publicToken); ``` -------------------------------- ### Generate Virtual Contract Note in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Use this snippet to calculate trade charges by providing order parameters to the getVirtualContractNote method. ```java import com.zerodhatech.models.ContractNoteParams; import com.zerodhatech.models.ContractNote; import java.util.ArrayList; import java.util.List; // Create contract note parameters List contractParams = new ArrayList<>(); ContractNoteParams param = new ContractNoteParams(); param.orderID = "230727202226518"; param.tradingSymbol = "ITC"; param.exchange = Constants.EXCHANGE_NSE; param.product = Constants.PRODUCT_CNC; param.orderType = Constants.ORDER_TYPE_MARKET; param.variety = Constants.VARIETY_REGULAR; param.transactionType = Constants.TRANSACTION_TYPE_SELL; param.quantity = 100; param.averagePrice = 470.05; contractParams.add(param); // Get virtual contract note List contractNotes = kiteConnect.getVirtualContractNote(contractParams); ContractNote note = contractNotes.get(0); System.out.println("Order ID: " + note.orderId); System.out.println("Total Charges: " + note.charges.total); System.out.println("Brokerage: " + note.charges.brokerage); System.out.println("STT: " + note.charges.stt); System.out.println("Exchange Charges: " + note.charges.exchangeCharges); System.out.println("SEBI Charges: " + note.charges.sebiCharges); System.out.println("Stamp Duty: " + note.charges.stampDuty); System.out.println("GST: " + note.charges.gst); ``` -------------------------------- ### Place a Single-Leg GTT Order in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Creates and places a single-leg GTT order. This involves defining the GTT parameters, including the trigger type, trading symbol, exchange, last price, trigger price, and the specific order details (type, price, product, transaction type, quantity). ```java // Place a single-leg GTT order GTTParams singleGTT = new GTTParams(); singleGTT.triggerType = Constants.SINGLE; singleGTT.exchange = "NSE"; singleGTT.tradingsymbol = "SBIN"; singleGTT.lastPrice = 600.0; List singleTrigger = new ArrayList<>(); singleTrigger.add(580.0); // Buy when price falls to 580 singleGTT.triggerPrices = singleTrigger; GTTParams.GTTOrderParams singleOrder = singleGTT.new GTTOrderParams(); singleOrder.orderType = Constants.ORDER_TYPE_LIMIT; singleOrder.price = 580; singleOrder.product = Constants.PRODUCT_CNC; singleOrder.transactionType = Constants.TRANSACTION_TYPE_BUY; singleOrder.quantity = 1; List singleOrders = new ArrayList<>(); singleOrders.add(singleOrder); singleGTT.orders = singleOrders; GTT placedSingleGTT = kiteConnect.placeGTT(singleGTT); System.out.println("Single GTT ID: " + placedSingleGTT.id); ``` -------------------------------- ### Fetch Historical Data in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieves historical OHLCV candle data for instruments. Requires a date range, instrument token, and interval specification. ```java import com.zerodhatech.models.HistoricalData; import java.text.SimpleDateFormat; import java.util.Date; // Fetch 15-minute candles for an instrument SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date from = formatter.parse("2024-01-15 09:15:00"); Date to = formatter.parse("2024-01-15 15:30:00"); HistoricalData historicalData = kiteConnect.getHistoricalData( from, to, "256265", // Instrument token (NIFTY 50) "15minute", // Interval: minute, 3minute, 5minute, 10minute, 15minute, 30minute, 60minute, day false, // Continuous (for expired F&O) true // Include Open Interest ); System.out.println("Total Candles: " + historicalData.dataArrayList.size()); for (HistoricalData.Data candle : historicalData.dataArrayList) { System.out.println("Time: " + candle.timeStamp); System.out.println("Open: " + candle.open); System.out.println("High: " + candle.high); System.out.println("Low: " + candle.low); System.out.println("Close: " + candle.close); System.out.println("Volume: " + candle.volume); System.out.println("OI: " + candle.oi); System.out.println("---"); } // Fetch daily candles for historical analysis Date dailyFrom = formatter.parse("2024-01-01 00:00:00"); Date dailyTo = formatter.parse("2024-01-31 23:59:59"); HistoricalData dailyData = kiteConnect.getHistoricalData( dailyFrom, dailyTo, "738561", // RELIANCE instrument token "day", // Daily candles false, false ); System.out.println("Daily Candles: " + dailyData.dataArrayList.size()); ``` -------------------------------- ### Generate Session with Access Token Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Generate a user session by providing the request token, public token, and API secret obtained during the login process. ```java // Get accessToken as follows, User user = kiteSdk.generateSession("request_token", "your_apiSecret"); ``` -------------------------------- ### Fetch User Profile and Margins Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieve user profile details and account margin information for equity and commodity segments. Supports fetching margins for individual segments or all segments combined. ```java import com.zerodhatech.models.Profile; import com.zerodhatech.models.Margin; import java.util.Map; // Get user profile Profile profile = kiteConnect.getProfile(); System.out.println("User Name: " + profile.userName); System.out.println("Email: " + profile.email); System.out.println("Broker: " + profile.broker); System.out.println("Products: " + profile.products); System.out.println("Exchanges: " + profile.exchanges); // Get margins for equity segment Margin equityMargin = kiteConnect.getMargins("equity"); System.out.println("Available Cash: " + equityMargin.available.cash); System.out.println("Available Collateral: " + equityMargin.available.collateral); System.out.println("Utilised Debits: " + equityMargin.utilised.debits); System.out.println("M2M Unrealised: " + equityMargin.utilised.m2mUnrealised); // Get margins for commodity segment Margin commodityMargin = kiteConnect.getMargins("commodity"); System.out.println("Commodity Cash: " + commodityMargin.available.cash); // Get margins for all segments Map allMargins = kiteConnect.getMargins(); System.out.println("Equity Cash: " + allMargins.get("equity").available.cash); System.out.println("Commodity Cash: " + allMargins.get("commodity").available.cash); ``` -------------------------------- ### Place a Limit Order Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Place a limit order by configuring OrderParams with necessary details like trading symbol, exchange, quantity, order type, and price. The 'tag' parameter is optional and has length restrictions. ```java /** Place order method requires a orderParams argument which contains, * tradingsymbol, exchange, transaction_type, order_type, quantity, product, price, trigger_price, disclosed_quantity, validity * squareoff_value, stoploss_value, trailing_stoploss * and variety (value can be regular, bo, co, amo) * place order will return order model which will have only orderId in the order model * Following is an example param for LIMIT order, * if a call fails then KiteException will have error message in it * Success of this call implies only order has been placed successfully, not order execution. */ OrderParams orderParams = new OrderParams(); orderParams.quantity = 1; orderParams.orderType = Constants.ORDER_TYPE_LIMIT; orderParams.tradingsymbol = "ASHOKLEY"; orderParams.product = Constants.PRODUCT_CNC; orderParams.exchange = Constants.EXCHANGE_NSE; orderParams.transactionType = Constants.TRANSACTION_TYPE_BUY; orderParams.validity = Constants.VALIDITY_DAY; orderParams.price = 122.2; orderParams.triggerPrice = 0.0; orderParams.tag = "myTag"; //tag is optional and it cannot be more than 8 characters and only alphanumeric is allowed Order order = kiteConnect.placeOrder(orderParams, Constants.VARIETY_REGULAR); System.out.println(order.orderId); ``` -------------------------------- ### WebSocket Live Streaming Data with KiteTicker Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Use the KiteTicker class for live price data via WebSocket. It's recommended to maintain only one connection and close it when the user exits the app. This snippet shows how to connect, subscribe to tokens, set modes (Quote, LTP, Full), handle order updates, and process incoming ticks. Ensure to disconnect the ticker when done. ```java /** To get live price use websocket connection. * It is recommended to use only one websocket connection at any point of time and make sure you stop connection, once user goes out of app. * custom url points to new endpoint which can be used till complete Kite Connect 3 migration is done. */ KiteTicker tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey()); tickerProvider.setOnConnectedListener(new OnConnect() { @Override public void onConnected() { /** Subscribe ticks for token. * By default, all tokens are subscribed for modeQuote. * */ tickerProvider.subscribe(tokens); tickerProvider.setMode(tokens, KiteTicker.modeFull); } }); tickerProvider.setOnDisconnectedListener(new OnDisconnect() { @Override public void onDisconnected() { // your code goes here } }); /** Set listener to get order updates.*/ tickerProvider.setOnOrderUpdateListener(new OnOrderUpdate() { @Override public void onOrderUpdate(Order order) { System.out.println("order update "+order.orderId); } }); tickerProvider.setOnTickerArrivalListener(new OnTicks() { @Override public void onTicks(ArrayList ticks) { NumberFormat formatter = new DecimalFormat(); System.out.println("ticks size "+ticks.size()); if(ticks.size() > 0) { System.out.println("last price "+ticks.get(0).getLastTradedPrice()); System.out.println("open interest "+formatter.format(ticks.get(0).getOi())); System.out.println("day high OI "+formatter.format(ticks.get(0).getOpenInterestDayHigh())); System.out.println("day low OI "+formatter.format(ticks.get(0).getOpenInterestDayLow())); System.out.println("change "+formatter.format(ticks.get(0).getChange())); System.out.println("tick timestamp "+ticks.get(0).getTickTimestamp()); System.out.println("tick timestamp date "+ticks.get(0).getTickTimestamp()); System.out.println("last traded time "+ticks.get(0).getLastTradedTime()); System.out.println(ticks.get(0).getMarketDepth().get("buy").size()); } } }); tickerProvider.setTryReconnection(true); //maximum retries and should be greater than 0 tickerProvider.setMaximumRetries(10); //set maximum retry interval in seconds tickerProvider.setMaximumRetryInterval(30); /** connects to com.zerodhatech.com.zerodhatech.ticker server for getting live quotes*/ tickerProvider.connect(); /** You can check, if websocket connection is open or not using the following method. */ boolean isConnected = tickerProvider.isConnectionOpen(); System.out.println(isConnected); /** set mode is used to set mode in which you need tick for list of tokens. * Ticker allows three modes, modeFull, modeQuote, modeLTP. * For getting only last traded price, use modeLTP * For getting last traded price, last traded quantity, average price, volume traded today, total sell quantity and total buy quantity, open, high, low, close, change, use modeQuote * For getting all data with depth, use modeFull*/ tickerProvider.setMode(tokens, KiteTicker.modeLTP); // Unsubscribe for a token. tickerProvider.unsubscribe(tokens); // After using com.zerodhatech.com.zerodhatech.ticker, close websocket connection. tickerProvider.disconnect(); ``` -------------------------------- ### Fetch Instruments and Auction Data Source: https://context7.com/zerodha/javakiteconnect/llms.txt Retrieve the complete instrument list or filter by exchange. Auction instruments can also be fetched separately. ```java import com.zerodhatech.models.Instrument; import java.util.List; // Get all instruments (large download - cache locally) List allInstruments = kiteConnect.getInstruments(); System.out.println("Total Instruments: " + allInstruments.size()); // Get instruments for a specific exchange List nseInstruments = kiteConnect.getInstruments("NSE"); System.out.println("NSE Instruments: " + nseInstruments.size()); List nfoInstruments = kiteConnect.getInstruments("NFO"); System.out.println("NFO Instruments: " + nfoInstruments.size()); // Filter and display instrument details for (Instrument instrument : nseInstruments) { if (instrument.tradingsymbol.equals("INFY")) { System.out.println("Instrument Token: " + instrument.instrument_token); System.out.println("Exchange Token: " + instrument.exchange_token); System.out.println("Trading Symbol: " + instrument.tradingsymbol); System.out.println("Name: " + instrument.name); System.out.println("Last Price: " + instrument.last_price); System.out.println("Tick Size: " + instrument.tick_size); System.out.println("Lot Size: " + instrument.lot_size); System.out.println("Instrument Type: " + instrument.instrument_type); System.out.println("Segment: " + instrument.segment); System.out.println("Exchange: " + instrument.exchange); System.out.println("Expiry: " + instrument.expiry); break; } } // Get auction instruments List auctionInstruments = kiteConnect.getAuctionInstruments(); for (AuctionInstrument auction : auctionInstruments) { System.out.println("Auction Symbol: " + auction.tradingSymbol); System.out.println("Quantity: " + auction.quantity); } ``` -------------------------------- ### Place a Two-Leg OCO GTT Order in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Creates and places a two-leg OCO (One Cancels Other) GTT order. This requires defining two distinct orders (e.g., stop-loss and target) that are linked by a common trigger condition. Only one of the orders will be executed, and the other will be automatically canceled. ```java // Place a two-leg OCO (One Cancels Other) GTT order GTTParams ocoGTT = new GTTParams(); ocoGTT.triggerType = Constants.OCO; ocoGTT.exchange = "NSE"; ocoGTT.tradingsymbol = "SBIN"; ocoGTT.lastPrice = 600.0; List ocoTriggers = new ArrayList<>(); ocoTriggers.add(580.0); // Stop-loss trigger (lower) ocoTriggers.add(650.0); // Target trigger (upper) ocoGTT.triggerPrices = ocoTriggers; // Stop-loss order (lower trigger) GTTParams.GTTOrderParams stopLoss = ocoGTT.new GTTOrderParams(); stopLoss.orderType = Constants.ORDER_TYPE_LIMIT; stopLoss.price = 580; stopLoss.product = Constants.PRODUCT_CNC; stopLoss.transactionType = Constants.TRANSACTION_TYPE_SELL; stopLoss.quantity = 1; // Target order (upper trigger) GTTParams.GTTOrderParams target = ocoGTT.new GTTOrderParams(); target.orderType = Constants.ORDER_TYPE_LIMIT; target.price = 650; target.product = Constants.PRODUCT_CNC; target.transactionType = Constants.TRANSACTION_TYPE_SELL; target.quantity = 1; List ocoOrders = new ArrayList<>(); ocoOrders.add(stopLoss); ocoOrders.add(target); ocoGTT.orders = ocoOrders; GTT placedOCO = kiteConnect.placeGTT(ocoGTT); System.out.println("OCO GTT ID: " + placedOCO.id); ``` -------------------------------- ### Retrieve All Orders (Order Book) Source: https://context7.com/zerodha/javakiteconnect/llms.txt Fetches the complete list of orders. Iterates through the orders to print details like ID, symbol, status, type, quantity, price, and timestamps. ```java import com.zerodhatech.models.Order; import com.zerodhatech.models.Trade; import java.util.List; // Get all orders (order book) List orders = kiteConnect.getOrders(); for (Order order : orders) { System.out.println("Order ID: " + order.orderId); System.out.println("Symbol: " + order.tradingSymbol); System.out.println("Status: " + order.status); System.out.println("Type: " + order.orderType); System.out.println("Quantity: " + order.quantity); System.out.println("Price: " + order.price); System.out.println("Average Price: " + order.averagePrice); System.out.println("Exchange Timestamp: " + order.exchangeTimestamp); System.out.println("---"); } ``` -------------------------------- ### Retrieve All GTT Orders in Java Source: https://context7.com/zerodha/javakiteconnect/llms.txt Fetches a list of all existing GTT orders. Iterates through the list to print details of each GTT, including its ID, type, associated symbol and exchange, status, and creation timestamp. ```java import com.zerodhatech.models.GTT; import com.zerodhatech.models.GTTParams; import java.util.ArrayList; import java.util.List; // Get all GTT orders List gtts = kiteConnect.getGTTs(); for (GTT gtt : gtts) { System.out.println("GTT ID: " + gtt.id); System.out.println("Type: " + gtt.triggerType); System.out.println("Symbol: " + gtt.condition.tradingSymbol); System.out.println("Exchange: " + gtt.condition.exchange); System.out.println("Status: " + gtt.status); System.out.println("Created: " + gtt.createdAt); } ``` -------------------------------- ### Calculate Order Margins Source: https://context7.com/zerodha/javakiteconnect/llms.txt Calculate margin requirements for individual orders or combined hedged positions. ```java import com.zerodhatech.models.MarginCalculationParams; import com.zerodhatech.models.MarginCalculationData; import com.zerodhatech.models.CombinedMarginData; import java.util.ArrayList; import java.util.List; // Calculate margin for a single order MarginCalculationParams param = new MarginCalculationParams(); param.exchange = "NSE"; param.tradingSymbol = "INFY"; param.orderType = "MARKET"; param.quantity = 100; param.product = "MIS"; param.variety = "regular"; param.transactionType = Constants.TRANSACTION_TYPE_BUY; param.price = 0; param.triggerPrice = 0; List params = new ArrayList<>(); params.add(param); List marginData = kiteConnect.getMarginCalculation(params); MarginCalculationData result = marginData.get(0); System.out.println("Total Margin: " + result.total); System.out.println("Leverage: " + result.leverage); System.out.println("SPAN: " + result.span); System.out.println("Exposure: " + result.exposure); // Calculate combined margin for hedged positions List basketParams = new ArrayList<>(); MarginCalculationParams futureParam = new MarginCalculationParams(); futureParam.exchange = "NFO"; futureParam.tradingSymbol = "NIFTY24JANFUT"; futureParam.orderType = "LIMIT"; futureParam.quantity = 50; futureParam.product = "MIS"; futureParam.variety = "regular"; futureParam.transactionType = "BUY"; futureParam.price = 21500; basketParams.add(futureParam); MarginCalculationParams optionParam = new MarginCalculationParams(); optionParam.exchange = "NFO"; optionParam.tradingSymbol = "NIFTY24JAN21500PE"; optionParam.orderType = "LIMIT"; optionParam.quantity = 50; optionParam.product = "MIS"; optionParam.variety = "regular"; optionParam.transactionType = "BUY"; optionParam.price = 200; basketParams.add(optionParam); CombinedMarginData combinedMargin = kiteConnect.getCombinedMarginCalculation( basketParams, true, // Consider existing positions false // Compact mode ); System.out.println("Initial Margin: " + combinedMargin.initialMargin.total); System.out.println("Final Margin: " + combinedMargin.finalMargin.total); System.out.println("Margin Benefit: " + (combinedMargin.initialMargin.total - combinedMargin.finalMargin.total)); ``` -------------------------------- ### Profile API Source: https://github.com/zerodha/javakiteconnect/blob/master/README.md Provides an API call to fetch user details. ```APIDOC ## Profile API ### Description Fetches user details. ### Method GET ### Endpoint /profile ### Parameters #### Query Parameters N/A #### Request Body N/A ### Response #### Success Response (200) - **userDetails** (Object) - Contains user-specific information. ### Response Example ```json { "userDetails": { "userId": "XYZ123", "name": "John Doe", "email": "john.doe@example.com" } } ``` ```