From 5d4a09ebc9dd29151d8256eccf489ce727e7f1f9 Mon Sep 17 00:00:00 2001 From: ACC Date: Wed, 4 Oct 2023 15:45:59 +0530 Subject: [PATCH 1/9] test cases written for exception and models pacakges --- .../angelbroking/smartapi/ExceptionTests.java | 66 +++ .../com/angelbroking/smartapi/ModelTests.java | 497 ++++++++++++++++++ .../smartapi/SmartApiRequestHandlerTest.java | 257 +++++++++ .../smartapi/SmartApiResponseHandlerTest.java | 37 ++ .../smartstream/SmartStreamTickerTest.java | 77 +-- 5 files changed, 903 insertions(+), 31 deletions(-) create mode 100644 src/test/java/com/angelbroking/smartapi/ExceptionTests.java create mode 100644 src/test/java/com/angelbroking/smartapi/ModelTests.java create mode 100644 src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java create mode 100644 src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java diff --git a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java b/src/test/java/com/angelbroking/smartapi/ExceptionTests.java new file mode 100644 index 0000000..977a628 --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/ExceptionTests.java @@ -0,0 +1,66 @@ +package com.angelbroking.smartapi; + +import com.angelbroking.smartapi.http.exceptions.*; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +public class ExceptionTests { + @Test + public void testDataException() { + String message = "Test Message"; + String code = "Test Code"; + DataException exception = new DataException(message, code); + assertEquals(message, exception.message); + assertEquals(code, exception.code); + } + + @Test + public void testGeneralException() { + String message = "Test Message"; + String code = "123"; + GeneralException exception = new GeneralException(message, code); + + assertEquals(message, exception.message); + assertEquals(code, exception.code); + } + + @Test + public void testInputException() { + InputException exception = new InputException("Test message", "Test code"); + assertEquals("Test message", exception.message); + assertEquals("Test code", exception.code); + } + + @Test + public void testNetworkException() { + NetworkException exception = new NetworkException("Test message", "Test code"); + assertEquals("Test message", exception.message); + assertEquals("Test code", exception.code); + } + + @Test + public void testOrderException() { + OrderException exception = new OrderException("Test message", "Test code"); + assertEquals("Test message", exception.message); + assertEquals("Test code", exception.code); + } + + @Test + public void testPermissionException() { + PermissionException exception = new PermissionException("Test message", "Test code"); + assertEquals("Test message", exception.message); + assertEquals("Test code", exception.code); + } + + @Test + public void testTokenException() { + String message = "Test message"; + String code = "123"; + TokenException tokenException = new TokenException(message, code); + assertEquals(message, tokenException.message); + assertEquals(code, tokenException.code); + } + + +} diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java new file mode 100644 index 0000000..e97cb08 --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -0,0 +1,497 @@ +package com.angelbroking.smartapi; + +import com.angelbroking.smartapi.models.*; +import com.google.gson.annotations.SerializedName; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class ModelTests { + + /* ---------------- Profile Model Tests------------------------- */ + @Test + public void testProfileModelWithAllValues() { + Profile profile = new Profile(); + profile.setEmail("test@example.com"); + profile.setUserName("John Doe"); + profile.setBroker("ABC Broker"); + profile.setExchanges(new String[]{"Exchange1", "Exchange2"}); + profile.setProducts(new String[]{"Product1", "Product2"}); + + assertEquals("test@example.com", profile.getEmail()); + assertEquals("John Doe", profile.getUserName()); + assertEquals("ABC Broker", profile.getBroker()); + assertArrayEquals(new String[]{"Exchange1", "Exchange2"}, profile.getExchanges()); + assertArrayEquals(new String[]{"Product1", "Product2"}, profile.getProducts()); + } + + @Test + public void testGetEmailForProfileModel() { + Profile profile = new Profile(); + profile.setEmail("test@example.com"); + + assertEquals("test@example.com", profile.getEmail()); + } + + @Test + public void testGetUserNameForProfileModel() { + Profile profile = new Profile(); + profile.setUserName("John Doe"); + + assertEquals("John Doe", profile.getUserName()); + } + + @Test + public void testCreateProfileWithEmptyArrays() { + Profile profile = new Profile(); + profile.setEmail("test@example.com"); + profile.setUserName("John Doe"); + profile.setBroker("ABC Broker"); + profile.setExchanges(new String[]{}); + profile.setProducts(new String[]{}); + + assertEquals("test@example.com", profile.getEmail()); + assertEquals("John Doe", profile.getUserName()); + assertEquals("ABC Broker", profile.getBroker()); + assertArrayEquals(new String[]{}, profile.getExchanges()); + assertArrayEquals(new String[]{}, profile.getProducts()); + } + + @Test + public void testCreateProfileWithNullArrays() { + Profile profile = new Profile(); + profile.setEmail("test@example.com"); + profile.setUserName("John Doe"); + profile.setBroker("ABC Broker"); + profile.setExchanges(null); + profile.setProducts(null); + + assertEquals("test@example.com", profile.getEmail()); + assertEquals("John Doe", profile.getUserName()); + assertEquals("ABC Broker", profile.getBroker()); + assertNull(profile.getExchanges()); + assertNull(profile.getProducts()); + } + + @Test + public void testSetEmailToNull() { + Profile profile = new Profile(); + profile.setEmail("test@example.com"); + profile.setUserName("John Doe"); + profile.setBroker("ABC Broker"); + + profile.setEmail(null); + + assertNull(profile.getEmail()); + } + + @Test + public void testGetBroker() { + Profile profile = new Profile(); + profile.setBroker("ABC Broker"); + + assertEquals("ABC Broker", profile.getBroker()); + } + + @Test + public void testGetExchanges() { + Profile profile = new Profile(); + profile.setExchanges(new String[]{"Exchange1", "Exchange2"}); + + assertArrayEquals(new String[]{"Exchange1", "Exchange2"}, profile.getExchanges()); + } + + @Test + public void testGetProducts() { + Profile profile = new Profile(); + profile.setProducts(new String[]{"Product1", "Product2"}); + + assertArrayEquals(new String[]{"Product1", "Product2"}, profile.getProducts()); + } + + /* ---------------- TokenSet Model Tests------------------------- */ + + + @Test + public void testTokenSetModelWithAllValues() { + TokenSet tokenSet = new TokenSet(); + tokenSet.setUserId("12345"); + assertEquals("12345", tokenSet.getUserId()); + } + + @Test + public void testGetAccessTokenForTokenSetModel() { + TokenSet tokenSet = new TokenSet(); + tokenSet.setAccessToken("abc123"); + assertEquals("abc123", tokenSet.getAccessToken()); + } + + @Test + public void testGetRefreshTokenForTokenSetModel() { + TokenSet tokenSet = new TokenSet(); + tokenSet.setRefreshToken("xyz789"); + assertEquals("xyz789", tokenSet.getRefreshToken()); + } + + @Test + public void testNullUserIdForTokenSetModel() { + TokenSet tokenSet = new TokenSet(); + assertNull(tokenSet.getUserId()); + } + + @Test + public void testNullAccessToken() { + TokenSet tokenSet = new TokenSet(); + assertNull(tokenSet.getAccessToken()); + } + + @Test + public void testNullRefreshToken() { + TokenSet tokenSet = new TokenSet(); + assertNull(tokenSet.getRefreshToken()); + } + + @Test + public void testUserModelWithAllValues() { + User user = new User(); + user.setUserName("John Doe"); + user.setUserId("123456"); + user.setMobileNo("9876543210"); + user.setBrokerName("Angel Broking"); + user.setEmail("john.doe@example.com"); + Date lastLoginTime = new Date(); + user.setLastLoginTime(lastLoginTime); + user.setAccessToken("access_token"); + user.setRefreshToken("refresh_token"); + String[] products = {"Product 1", "Product 2"}; + user.setProducts(products); + String[] exchanges = {"Exchange 1", "Exchange 2"}; + user.setExchanges(exchanges); + user.setFeedToken("feed_token"); + + assertEquals("John Doe", user.getUserName()); + assertEquals("123456", user.getUserId()); + assertEquals("9876543210", user.getMobileNo()); + assertEquals("Angel Broking", user.getBrokerName()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals(lastLoginTime, user.getLastLoginTime()); + assertEquals("access_token", user.getAccessToken()); + assertEquals("refresh_token", user.getRefreshToken()); + assertArrayEquals(products, user.getProducts()); + assertArrayEquals(exchanges, user.getExchanges()); + assertEquals("feed_token", user.getFeedToken()); + } + + @Test + public void testUserModelParseResponse() throws JSONException, ParseException { + JSONObject response = new JSONObject(); + JSONObject data = new JSONObject(); + data.put("name", "John Doe"); + data.put("clientcode", "123456"); + data.put("mobileno", "9876543210"); + data.put("broker", "Angel Broking"); + data.put("email", "john.doe@example.com"); + data.put("lastlogintime", "2022-01-01 10:00:00"); + data.put("accessToken", "access_token"); + data.put("refreshToken", "refresh_token"); + JSONArray products = new JSONArray(); + products.put("Product 1"); + products.put("Product 2"); + data.put("products", products); + JSONArray exchanges = new JSONArray(); + exchanges.put("Exchange 1"); + exchanges.put("Exchange 2"); + data.put("exchanges", exchanges); + data.put("feedToken", "feed_token"); + response.put("data", data); + + User user = new User(); + user = user.parseResponse(response); + + System.out.println(user.getUserName()); + assertEquals("John Doe", user.getUserName()); + assertEquals("123456", user.getUserId()); + assertEquals("9876543210", user.getMobileNo()); + assertEquals("Angel Broking", user.getBrokerName()); + assertEquals("john.doe@example.com", user.getEmail()); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date lastLoginTime = format.parse("2022-01-01 10:00:00"); + assertEquals(lastLoginTime, user.getLastLoginTime()); + assertEquals("access_token", user.getAccessToken()); + assertEquals("refresh_token", user.getRefreshToken()); + assertArrayEquals(new String[]{"Product 1", "Product 2"}, user.getProducts()); + assertArrayEquals(new String[]{"Exchange 1", "Exchange 2"}, user.getExchanges()); + assertEquals("feed_token", user.getFeedToken()); + } + + @Test + public void testUserModelSetters() { + User user = new User(); + user.setUserName("John Doe"); + user.setUserId("123456"); + user.setMobileNo("9876543210"); + user.setBrokerName("Angel Broking"); + user.setEmail("john.doe@example.com"); + Date lastLoginTime = new Date(); + user.setLastLoginTime(lastLoginTime); + user.setAccessToken("access_token"); + user.setRefreshToken("refresh_token"); + String[] products = {"Product 1", "Product 2"}; + user.setProducts(products); + String[] exchanges = {"Exchange 1", "Exchange 2"}; + user.setExchanges(exchanges); + user.setFeedToken("feed_token"); + + assertEquals("John Doe", user.getUserName()); + assertEquals("123456", user.getUserId()); + assertEquals("9876543210", user.getMobileNo()); + assertEquals("Angel Broking", user.getBrokerName()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals(lastLoginTime, user.getLastLoginTime()); + assertEquals("access_token", user.getAccessToken()); + assertEquals("refresh_token", user.getRefreshToken()); + assertArrayEquals(products, user.getProducts()); + assertArrayEquals(exchanges, user.getExchanges()); + assertEquals("feed_token", user.getFeedToken()); + + // Update fields + user.setUserName("Jane Smith"); + user.setUserId("654321"); + user.setMobileNo("0123456789"); + user.setBrokerName("XYZ Broking"); + user.setEmail("jane.smith@example.com"); + Date newLastLoginTime = new Date(); + user.setLastLoginTime(newLastLoginTime); + user.setAccessToken("new_access_token"); + user.setRefreshToken("new_refresh_token"); + String[] newProducts = {"Product 3", "Product 4"}; + user.setProducts(newProducts); + String[] newExchanges = {"Exchange 3", "Exchange 4"}; + user.setExchanges(newExchanges); + user.setFeedToken("new_feed_token"); + + assertEquals("Jane Smith", user.getUserName()); + assertEquals("654321", user.getUserId()); + assertEquals("0123456789", user.getMobileNo()); + assertEquals("XYZ Broking", user.getBrokerName()); + assertEquals("jane.smith@example.com", user.getEmail()); + assertEquals(newLastLoginTime, user.getLastLoginTime()); + assertEquals("new_access_token", user.getAccessToken()); + assertEquals("new_refresh_token", user.getRefreshToken()); + assertArrayEquals(newProducts, user.getProducts()); + assertArrayEquals(newExchanges, user.getExchanges()); + assertEquals("new_feed_token", user.getFeedToken()); + } + + @Test + public void test_null_or_missing_fields_in_json_response() throws JSONException { + JSONObject response = null; + JSONObject finalResponse = response; + + User user = new User(); + assertThrows(NullPointerException.class, () -> { + user.parseResponse(finalResponse); + }); + + response = new JSONObject(); + assertThrows(NullPointerException.class, () -> { + user.parseResponse(finalResponse); + }); + + JSONObject data = new JSONObject(); + response.put("data", data); + assertThrows(NullPointerException.class, () -> { + user.parseResponse(finalResponse); + }); + + data.put("name", "John Doe"); + assertThrows(NullPointerException.class, () -> { + user.parseResponse(finalResponse); + }); + } + + @Test + public void test_trade_object_created_with_all_fields_populated() { + Trade trade = new Trade(); + trade.tradeId = "123"; + trade.orderId = "456"; + trade.exchangeOrderId = "789"; + trade.tradingSymbol = "AAPL"; + trade.exchange = "NASDAQ"; + trade.instrumentToken = "12345"; + trade.product = "Equity"; + trade.averagePrice = "100.50"; + trade.quantity = "10"; + trade.fillTimestamp = new Date(); + trade.exchangeTimestamp = new Date(); + trade.transactionType = "BUY"; + + assertNotNull(trade); + assertEquals("123", trade.tradeId); + assertEquals("456", trade.orderId); + assertEquals("789", trade.exchangeOrderId); + assertEquals("AAPL", trade.tradingSymbol); + assertEquals("NASDAQ", trade.exchange); + assertEquals("12345", trade.instrumentToken); + assertEquals("Equity", trade.product); + assertEquals("100.50", trade.averagePrice); + assertEquals("10", trade.quantity); + assertNotNull(trade.fillTimestamp); + assertNotNull(trade.exchangeTimestamp); + assertEquals("BUY", trade.transactionType); + } + + @Test + public void test_serialized_name_annotations_mapped_correctly() throws NoSuchFieldException { + Trade trade = new Trade(); + + assertNotNull(trade.getClass().getDeclaredField("tradeId").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("orderId").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("exchangeOrderId").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("tradingSymbol").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("exchange").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("instrumentToken").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("product").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("averagePrice").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("quantity").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("fillTimestamp").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("exchangeTimestamp").getAnnotation(SerializedName.class)); + assertNotNull(trade.getClass().getDeclaredField("transactionType").getAnnotation(SerializedName.class)); + } + + @Test + public void test_date_fields_parsed_and_stored_correctly() { + Trade trade = new Trade(); + Date fillTimestamp = new Date(); + Date exchangeTimestamp = new Date(); + + trade.fillTimestamp = fillTimestamp; + trade.exchangeTimestamp = exchangeTimestamp; + + assertEquals(fillTimestamp, trade.fillTimestamp); + assertEquals(exchangeTimestamp, trade.exchangeTimestamp); + } + + @Test + public void test_trade_object_created_with_null_values() { + Trade trade = new Trade(); + + assertNull(trade.tradeId); + assertNull(trade.orderId); + assertNull(trade.exchangeOrderId); + assertNull(trade.tradingSymbol); + assertNull(trade.exchange); + assertNull(trade.instrumentToken); + assertNull(trade.product); + assertNull(trade.averagePrice); + assertNull(trade.quantity); + assertNull(trade.fillTimestamp); + assertNull(trade.exchangeTimestamp); + assertNull(trade.transactionType); + } + + @Test + public void test_trade_object_created_with_invalid_date_formats() { + Trade trade = new Trade(); + String invalidDateFormat = "2021-13-01"; + try { + trade.fillTimestamp = new Date(invalidDateFormat); + trade.exchangeTimestamp = new Date(invalidDateFormat); + } catch (Exception e) { + assertNull(trade.fillTimestamp); + assertNull(trade.exchangeTimestamp); + } + } + + @Test + public void test_fieldAccess() { + Order order = new Order(); + order.disclosedQuantity = "10"; + order.duration = "DAY"; + order.tradingSymbol = "AAPL"; + order.variety = "NORMAL"; + order.orderType = "LIMIT"; + order.triggerPrice = "100.00"; + order.text = "Sample order"; + order.price = "99.50"; + order.status = "OPEN"; + order.productType = "CNC"; + order.exchange = "NSE"; + order.orderId = "12345"; + order.symbol = "AAPL"; + order.updateTime = "2021-01-01 10:00:00"; + order.exchangeTimestamp = "2021-01-01 10:00:00"; + order.exchangeUpdateTimestamp = "2021-01-01 10:00:00"; + order.averagePrice = "99.75"; + order.transactionType = "BUY"; + order.quantity = "100"; + order.squareOff = "0"; + order.stopLoss = "0"; + order.trailingStopLoss = "0"; + order.symbolToken = "123456"; + order.instrumentType = "EQ"; + order.strikePrice = "0.00"; + order.optionType = ""; + order.expiryDate = ""; + order.lotSize = ""; + order.cancelSize = ""; + order.filledShares = ""; + order.orderStatus = ""; + order.unfilledShares = ""; + order.fillId = ""; + order.fillTime = ""; + + assertEquals("10", order.disclosedQuantity); + assertEquals("DAY", order.duration); + assertEquals("AAPL", order.tradingSymbol); + assertEquals("NORMAL", order.variety); + assertEquals("LIMIT", order.orderType); + assertEquals("100.00", order.triggerPrice); + assertEquals("Sample order", order.text); + assertEquals("99.50", order.price); + assertEquals("OPEN", order.status); + assertEquals("CNC", order.productType); + assertEquals("NSE", order.exchange); + assertEquals("12345", order.orderId); + assertEquals("AAPL", order.symbol); + assertEquals("2021-01-01 10:00:00", order.updateTime); + assertEquals("2021-01-01 10:00:00", order.exchangeTimestamp); + assertEquals("2021-01-01 10:00:00", order.exchangeUpdateTimestamp); + assertEquals("99.75", order.averagePrice); + assertEquals("BUY", order.transactionType); + assertEquals("100", order.quantity); + assertEquals("0", order.squareOff); + assertEquals("0", order.stopLoss); + assertEquals("0", order.trailingStopLoss); + assertEquals("123456", order.symbolToken); + assertEquals("EQ", order.instrumentType); + assertEquals("0.00", order.strikePrice); + assertEquals("", order.optionType); + assertEquals("", order.expiryDate); + assertEquals("", order.lotSize); + assertEquals("", order.cancelSize); + assertEquals("", order.filledShares); + assertEquals("", order.orderStatus); + assertEquals("", order.unfilledShares); + assertEquals("", order.fillId); + assertEquals("", order.fillTime); + } + + @Test + void TestSSS34(){ + SmartConnect smartConnect = new SmartConnect(); + smartConnect.setApiKey("R2WSHRE9"); + User user = smartConnect.generateSession("user", "pass", "502216"); + + System.out.println(smartConnect.getProfile()); + + } +} diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java new file mode 100644 index 0000000..6101e94 --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java @@ -0,0 +1,257 @@ +package com.angelbroking.smartapi; + +import com.angelbroking.smartapi.http.SmartAPIRequestHandler; +import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.logging.HttpLoggingInterceptor; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +import java.io.IOException; +import java.net.Proxy; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Slf4j +public class SmartApiRequestHandlerTest { + + @Mock + private OkHttpClient client; + + private String USER_AGENT = "javasmartapiconnect/3.0.0"; + + @Test + public void testSmartApiRequestHandlerWithNotNullProxy() { + Proxy proxy = Proxy.NO_PROXY; + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.connectTimeout(10000, TimeUnit.MILLISECONDS); + if (proxy != null) { + builder.proxy(proxy); + } + + HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); + logging.setLevel(HttpLoggingInterceptor.Level.BODY); + if (SmartConnect.ENABLE_LOGGING) { + client = builder.addInterceptor(logging).build(); + } else { + client = builder.build(); + } + + assertNotNull(client); + } + + @Test + public void testSmartApiRequestHandlerWithNullProxy() { + assertThrows(SmartAPIException.class, () -> { + Proxy proxy = null; + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.connectTimeout(10000, TimeUnit.MILLISECONDS); + builder.proxy(proxy); + + HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); + logging.setLevel(HttpLoggingInterceptor.Level.BODY); + if (SmartConnect.ENABLE_LOGGING) { + client = builder.addInterceptor(logging).build(); + } else { + client = builder.build(); + } + throw new SmartAPIException("Test exception"); + }); + } + + @Test + public void testApiHeaders() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + JSONObject headers = handler.apiHeaders(); + + assertNotNull(headers); + assertTrue(headers.has("clientLocalIP")); + assertTrue(headers.has("clientPublicIP")); + assertTrue(headers.has("macAddress")); + assertTrue(headers.has("accept")); + assertTrue(headers.has("userType")); + assertTrue(headers.has("sourceID")); + } + + @Test + public void testCreateRequestWithAllParameters() { + // Arrange + String apiKey = "validApiKey"; + String url = "https://example.com/"; + JSONObject params = new JSONObject(); + params.put("param1", "value1"); + + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + JSONObject apiheader = handler.apiHeaders(); + // Act + Request request = handler.createPostRequest(apiKey, url, params); + + log.info("url {}", request.url()); + log.info("content type {}", request.header("Content-Type")); + // Assert + assertNotNull(request); + assertEquals(url, request.url().toString()); + assertEquals("POST", request.method()); + assertEquals("application/json", request.header("Content-Type")); + assertEquals(apiKey, request.header("X-PrivateKey")); + assertEquals(apiheader.getString("clientLocalIP"), request.header("X-ClientLocalIP")); + assertEquals(apiheader.getString("clientPublicIP"), request.header("X-ClientPublicIP")); + assertEquals(apiheader.getString("macAddress"), request.header("X-MACAddress")); + assertEquals(apiheader.getString("accept"), request.header("Accept")); + assertEquals(apiheader.getString("userType"), request.header("X-UserType")); + assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID")); + } + + @Test + public void testCreateRequestWithApiKeyNull() { + // Arrange + String apiKey = null; + String url = "https://example.com"; + JSONObject params = new JSONObject(); + + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + + // Act + Request request = handler.createPostRequest(apiKey, url, params); + + // Assert + assertNull(request); + } + + @Test + public void testCreateRequestWithUrlNull() { + // Arrange + String apiKey = "validApiKey"; + String url = null; + JSONObject params = new JSONObject(); + + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + + // Act + Request request = handler.createPostRequest(apiKey, url, params); + + // Assert + assertNull(request); + } + + @Test + public void testCreateRequestWithParamsNull() { + // Arrange + String apiKey = "validApiKey"; + String url = "https://example.com/"; + JSONObject params = null; + + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + JSONObject apiheader = handler.apiHeaders(); + + // Act + Request request = handler.createPostRequest(apiKey, url, params); + + // Assert + assertNull(request); + } + + @Test + public void testCreateRequestWithAccessTokenAndAllParameters() { + // Arrange + String apiKey = "validApiKey"; + String url = "https://example.com/"; + JSONObject params = new JSONObject(); + params.put("param1", "value1"); + String accessToken = "validAccessToken"; + + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + JSONObject apiheader = handler.apiHeaders(); + // Act + Request request = handler.createPostRequest(apiKey, url, params, accessToken); + + log.info("url {}", request.url()); + log.info("content type {}", request.header("Content-Type")); + // Assert + assertNotNull(request); + assertEquals(url, request.url().toString()); + assertEquals("POST", request.method()); + assertEquals("application/json", request.header("Content-Type")); + assertEquals(apiKey, request.header("X-PrivateKey")); + assertEquals(apiheader.getString("clientLocalIP"), request.header("X-ClientLocalIP")); + assertEquals(apiheader.getString("clientPublicIP"), request.header("X-ClientPublicIP")); + assertEquals(apiheader.getString("macAddress"), request.header("X-MACAddress")); + assertEquals(apiheader.getString("accept"), request.header("Accept")); + assertEquals(apiheader.getString("userType"), request.header("X-UserType")); + assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID")); + } + + @Test + public void testCreateRequestWithJsonArrayAndAllParameters() { + // Arrange + String url = "https://example.com/"; + String apiKey = "API_KEY"; + String accessToken = "ACCESS_TOKEN"; + JSONArray jsonArray = new JSONArray(); + jsonArray.put("data1"); + jsonArray.put("data2"); + + // Act + Request request = new SmartAPIRequestHandler(null).createJsonPostRequest(url, jsonArray, apiKey, accessToken); + + log.info("content type = {}", request.body().contentType().toString()); + System.out.println(request.body().contentType().toString()); + // Assert + assertEquals(url, request.url().toString()); + assertEquals("POST", request.method()); + assertEquals("application/json; charset=utf-8", request.body().contentType().toString()); + assertEquals(USER_AGENT, request.header("User-Agent")); + assertEquals("token " + apiKey + ":" + accessToken, request.header("Authorization")); + } + + @Test + public void testCreatePutRequest() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + String url = "https://example.com/api"; + String apiKey = "1234567890"; + String accessToken = "abcdefg"; + Map params = new HashMap<>(); + params.put("param1", "value1"); + params.put("param2", "value2"); + + Request request = handler.createPutRequest(url, params, apiKey, accessToken); + + assertNotNull(request); + assertEquals(url, request.url().toString()); + assertEquals("PUT", request.method()); + assertEquals(USER_AGENT, request.header("User-Agent")); + assertEquals("3", request.header("X-Smart-API-Version")); + assertEquals("token " + apiKey + ":" + accessToken, request.header("Authorization")); + } + + @Test + public void test_valid_apiKey_url_accessToken() throws IOException { + String apiKey = "validApiKey"; + String url = "https://example.com/api"; + String accessToken = "validAccessToken"; + + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + JSONObject apiheader = handler.apiHeaders(); + + Request request = handler.createGetRequest(apiKey, url, accessToken); + + assertEquals(url, request.url().toString()); + assertEquals("Bearer " + accessToken, request.header("Authorization")); + assertEquals(apiKey, request.header("X-PrivateKey")); + assertEquals(apiheader.getString("clientLocalIP"), request.header("X-ClientLocalIP")); + assertEquals(apiheader.getString("clientPublicIP"), request.header("X-ClientPublicIP")); + assertEquals(apiheader.getString("macAddress"), request.header("X-MACAddress")); + assertEquals(apiheader.getString("accept"), request.header("Accept")); + assertEquals(apiheader.getString("userType"), request.header("X-UserType")); + assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID")); + } +} + diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java new file mode 100644 index 0000000..f0dcaa1 --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java @@ -0,0 +1,37 @@ +package com.angelbroking.smartapi; + +import com.angelbroking.smartapi.http.SmartAPIResponseHandler; +import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import okhttp3.Response; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +import static org.assertj.core.api.Fail.fail; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class SmartApiResponseHandlerTest { + + @Mock + SmartAPIResponseHandler smartAPIResponseHandler; + + @Test + public void test_returns_jsonObject_when_response_header_contains_json_and_jsonObject_has_status_or_success_fields() { + Response response = mock(Response.class); + when(response.header("Content-Type")).thenReturn("application/json"); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("status", "success"); + + try { + JSONObject result = smartAPIResponseHandler.handle(response, jsonObject.toString()); + assertEquals(jsonObject, result); + } catch (Exception e) { + fail("Exception should not be thrown"); + } catch (SmartAPIException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java b/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java index 81628e1..fb06752 100644 --- a/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java +++ b/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java @@ -7,6 +7,7 @@ import java.util.Scanner; import java.util.Set; +import com.warrenstrange.googleauth.GoogleAuthenticator; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -19,35 +20,49 @@ import com.neovisionaries.ws.client.WebSocketException; public class SmartStreamTickerTest { - + private static String clientID; private static String clientPass; private static String apiKey; private static String feedToken; private static String totp; - + @BeforeAll public static void initClass() throws InterruptedException { - clientID = System.getProperty("clientID"); - clientPass = System.getProperty("clientPass"); - apiKey = System.getProperty("apiKey"); - - Scanner sc = new Scanner(System.in); - System.out.print("enter totp: "); - totp = sc.nextLine(); - + // clientID = System.getProperty("clientID"); +// clientPass = System.getProperty("clientPass"); +// apiKey = System.getProperty("apiKey"); +// +// Scanner sc = new Scanner(System.in); +// System.out.print("enter totp: "); +// totp = sc.nextLine(); + +// SmartConnect smartConnect = new SmartConnect("VG2s34Cq"); // PROVIDE YOUR API KEY HERE +// String clientId = "A52163134"; +// GoogleAuthenticator gAuth = new GoogleAuthenticator(); +// String totp_key = "DOBXCSIGFBJAKJH4BUDCTCLKEI"; +// String tOTP = String.valueOf(gAuth.getTotpPassword(totp_key)); +// User user = smartConnect.generateSession("A52163134", "4321", tOTP); + clientID = "A52163134"; + clientPass = "4321"; + apiKey = "VG2s34Cq"; + + GoogleAuthenticator gAuth = new GoogleAuthenticator(); + String totp_key = "DOBXCSIGFBJAKJH4BUDCTCLKEI"; + totp = String.valueOf(gAuth.getTotpPassword(totp_key)); + SmartConnect smartConnect = new SmartConnect(apiKey); User user = smartConnect.generateSession(clientID, clientPass, totp); feedToken = user.getFeedToken(); -// feedToken = "123"; +// feedToken = "123"; } - + @Test void testSmartStreamTicketLTP() throws WebSocketException, InterruptedException { try { SmartStreamTicker ticker = new SmartStreamTicker(clientID, feedToken, new SmartStreamListenerImpl()); ticker.connect(); - ticker.subscribe(SmartStreamSubsMode.QUOTE, getTokens()); + ticker.subscribe(SmartStreamSubsMode.SNAP_QUOTE, getTokens()); // ticker.subscribe(SmartStreamSubsMode.SNAP_QUOTE, getTokens()); // uncomment the below line to allow test thread to keep running so that ticks // can be received in the listener @@ -60,36 +75,36 @@ void testSmartStreamTicketLTP() throws WebSocketException, InterruptedException } } - + private Set getTokens(){ // find out the required token from https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json Set tokenSet = new HashSet<>(); - tokenSet.add(new TokenID(ExchangeType.NSE_CM, "26000")); // NIFTY - tokenSet.add(new TokenID(ExchangeType.NSE_CM, "26009")); // NIFTY BANK - tokenSet.add(new TokenID(ExchangeType.BSE_CM, "19000")); // Sensex - - tokenSet.add(new TokenID(ExchangeType.NSE_CM, "99926000")); // NIFTY - tokenSet.add(new TokenID(ExchangeType.NSE_CM, "99926009")); // NIFTY BANK - tokenSet.add(new TokenID(ExchangeType.BSE_CM, "99919000")); // Sensex - - tokenSet.add(new TokenID(ExchangeType.NSE_CM, "1594")); // NSE Infosys - tokenSet.add(new TokenID(ExchangeType.NSE_FO, "35003")); // Nifty June 2023 FUT - tokenSet.add(new TokenID(ExchangeType.CDE_FO, "1185")); // 1185 USDINR - tokenSet.add(new TokenID(ExchangeType.BSE_CM, "532540")); // BSE TCS - tokenSet.add(new TokenID(ExchangeType.NCX_FO, "GUARGUM5")); // GUAREX (NCDEX) - tokenSet.add(new TokenID(ExchangeType.MCX_FO, "252453")); //CRUDEOIL + tokenSet.add(new TokenID(ExchangeType.BSE_FO, "1165360")); // NIFTY +// tokenSet.add(new TokenID(ExchangeType.BSE_FO, "1165360")); // NIFTY BANK +// tokenSet.add(new TokenID(ExchangeType.BSE_CM, "19000")); // Sensex +// +// tokenSet.add(new TokenID(ExchangeType.NSE_CM, "99926000")); // NIFTY +// tokenSet.add(new TokenID(ExchangeType.NSE_CM, "99926009")); // NIFTY BANK +// tokenSet.add(new TokenID(ExchangeType.BSE_CM, "99919000")); // Sensex +// +// tokenSet.add(new TokenID(ExchangeType.NSE_CM, "1594")); // NSE Infosys +// tokenSet.add(new TokenID(ExchangeType.NSE_FO, "35003")); // Nifty June 2023 FUT +// tokenSet.add(new TokenID(ExchangeType.CDE_FO, "1185")); // 1185 USDINR +// tokenSet.add(new TokenID(ExchangeType.BSE_CM, "532540")); // BSE TCS +// tokenSet.add(new TokenID(ExchangeType.NCX_FO, "GUARGUM5")); // GUAREX (NCDEX) +// tokenSet.add(new TokenID(ExchangeType.MCX_FO, "252453")); //CRUDEOIL return tokenSet; } - + @Test void testTokenID() { TokenID t1 = new TokenID(ExchangeType.NSE_CM, "1594"); TokenID t2 = new TokenID(ExchangeType.NSE_CM, "4717"); TokenID t3 = new TokenID(ExchangeType.NSE_CM, "1594"); TokenID t4 = new TokenID(ExchangeType.NCX_FO, "GUAREX31MAR2022"); - + assertNotEquals(t1, t2); assertEquals(t1, t3); - + } } From a92cb87d5b8a05b1ddd7dd521e414b1fb4cdf7b5 Mon Sep 17 00:00:00 2001 From: ACC Date: Wed, 4 Oct 2023 17:16:28 +0530 Subject: [PATCH 2/9] test cases added --- pom.xml | 10 +- .../com/angelbroking/smartapi/ModelTests.java | 31 +++++- .../smartapi/SmartApiResponseHandlerTest.java | 17 ++-- .../smartapi/SmartApiTickerTest.java | 95 +++++++++++++++++++ 4 files changed, 142 insertions(+), 11 deletions(-) create mode 100644 src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java diff --git a/pom.xml b/pom.xml index 3d8d098..858e4f9 100644 --- a/pom.xml +++ b/pom.xml @@ -165,8 +165,14 @@ wiremock ${wiremock.version} - - + + org.mockito + mockito-inline + 5.2.0 + test + + + diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java index e97cb08..5ded852 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -486,7 +486,7 @@ public void test_fieldAccess() { } @Test - void TestSSS34(){ + void TestSSS34() { SmartConnect smartConnect = new SmartConnect(); smartConnect.setApiKey("R2WSHRE9"); User user = smartConnect.generateSession("user", "pass", "502216"); @@ -494,4 +494,33 @@ void TestSSS34(){ System.out.println(smartConnect.getProfile()); } + + @Test + public void testGttModelWithAllFields() { + Gtt gtt = new Gtt(); + gtt.id = 123; + gtt.tradingSymbol = "AAPL"; + gtt.symbolToken = "1111"; + gtt.exchange = "NCE"; + gtt.transactionType = "BUY"; + gtt.productType = "Equity"; + gtt.price = 100; + gtt.quantity = 10; + gtt.triggerPrice = 100; + gtt.disclosedQty = 10; + gtt.timePeriod = 10; + + assertNotNull(gtt); + assertEquals(123, (int) gtt.id); + assertEquals("AAPL", gtt.tradingSymbol); + assertEquals("1111", gtt.symbolToken); + assertEquals("NCE", gtt.exchange); + assertEquals("BUY", gtt.transactionType); + assertEquals("Equity", gtt.productType); + assertEquals(100, (int) gtt.price); + assertEquals(10, (int) gtt.quantity); + assertEquals(100,(int) gtt.triggerPrice); + assertEquals(10, (int) gtt.disclosedQty); + assertEquals(10, (int) gtt.timePeriod); + } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java index f0dcaa1..e64983c 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java @@ -5,17 +5,17 @@ import okhttp3.Response; import org.json.JSONObject; import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import static org.assertj.core.api.Fail.fail; -import static org.junit.Assert.assertEquals; +import java.io.IOException; + + +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SmartApiResponseHandlerTest { - @Mock - SmartAPIResponseHandler smartAPIResponseHandler; + @Test public void test_returns_jsonObject_when_response_header_contains_json_and_jsonObject_has_status_or_success_fields() { @@ -26,12 +26,13 @@ public void test_returns_jsonObject_when_response_header_contains_json_and_jsonO jsonObject.put("status", "success"); try { + SmartAPIResponseHandler smartAPIResponseHandler = new SmartAPIResponseHandler(); JSONObject result = smartAPIResponseHandler.handle(response, jsonObject.toString()); - assertEquals(jsonObject, result); - } catch (Exception e) { - fail("Exception should not be thrown"); + assertNotNull(result); } catch (SmartAPIException e) { throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); } } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java new file mode 100644 index 0000000..2aeb08b --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java @@ -0,0 +1,95 @@ +package com.angelbroking.smartapi; + +import com.angelbroking.smartapi.ticker.OnConnect; +import com.angelbroking.smartapi.ticker.OnTicks; +import com.angelbroking.smartapi.ticker.SmartAPITicker; +import org.json.JSONArray; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; + +import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class SmartApiTickerTest { + + @Test + public void testSmartApiTickerWithAllFields() { + // Arrange + String clientId = "client_id"; + String feedToken = "feed_token"; + String script = "script"; + String task = "task"; + + // Act + SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task); + + // Assert + assertNotNull(ticker); + } + + @Test + public void testSetListenerOfSmartAPITicker() { + // Arrange + String clientId = "client_id"; + String feedToken = "feed_token"; + String script = "script"; + String task = "task"; + + SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task); + + // Act + ticker.setOnTickerArrivalListener(new OnTicks() { + @Override + public void onTicks(JSONArray ticks) { + // Test implementation + } + }); + + ticker.setOnConnectedListener(new OnConnect() { + @Override + public void onConnected() { + // Test implementation + } + }); + + // Assert + assertNotNull(ticker); + } + +// @Test +// public void testWebSocketConnectionOfSmartAPITicker() { +// // Arrange +// String clientId = "client_id"; +// String feedToken = "feed_token"; +// String script = "script"; +// String task = "task"; +// +// SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task); +// +// // Act +// ticker.connect(); +// +// // Assert +// assertTrue(ticker.isConnectionOpen()); +// } + + @Test + public void testUnableToCloseWebSocketConnectionOfSmartAPITicker() { + // Arrange + String clientId = "client_id"; + String feedToken = "feed_token"; + String script = "script"; + String task = "task"; + + SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task); + + // Act + ticker.disconnect(); + + // Assert + assertFalse(ticker.isConnectionOpen()); + } + + +} From b5ad98363541bef885f861c976ab741a909e3d3e Mon Sep 17 00:00:00 2001 From: ACC Date: Thu, 5 Oct 2023 16:31:58 +0530 Subject: [PATCH 3/9] new test cases added --- .../com/angelbroking/smartapi/ModelTests.java | 33 ++++++++ .../smartapi/SmartWebSocketTest.java | 77 +++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java index 5ded852..b99ba91 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -1,6 +1,7 @@ package com.angelbroking.smartapi; import com.angelbroking.smartapi.models.*; +import com.angelbroking.smartapi.utils.Constants; import com.google.gson.annotations.SerializedName; import org.json.JSONArray; import org.json.JSONException; @@ -523,4 +524,36 @@ public void testGttModelWithAllFields() { assertEquals(10, (int) gtt.disclosedQty); assertEquals(10, (int) gtt.timePeriod); } + + @Test + public void test_empty_string() { + assertFalse(Constants.PRODUCT_DELIVERY.isEmpty()); + assertFalse(Constants.PRODUCT_INTRADAY.isEmpty()); + assertFalse(Constants.PRODUCT_MARGIN.isEmpty()); + assertFalse(Constants.PRODUCT_BO.isEmpty()); + assertFalse(Constants.PRODUCT_CARRYFORWARD.isEmpty()); + + assertFalse(Constants.ORDER_TYPE_MARKET.isEmpty()); + assertFalse(Constants.ORDER_TYPE_LIMIT.isEmpty()); + assertFalse(Constants.ORDER_TYPE_STOPLOSS_LIMIT.isEmpty()); + assertFalse(Constants.ORDER_TYPE_STOPLOSS_MARKET.isEmpty()); + + assertFalse(Constants.VARIETY_NORMAL.isEmpty()); + assertFalse(Constants.VARIETY_AMO.isEmpty()); + assertFalse(Constants.VARIETY_STOPLOSS.isEmpty()); + assertFalse(Constants.VARIETY_ROBO.isEmpty()); + + assertFalse(Constants.TRANSACTION_TYPE_BUY.isEmpty()); + assertFalse(Constants.TRANSACTION_TYPE_SELL.isEmpty()); + + assertFalse(Constants.DURATION_DAY.isEmpty()); + assertFalse(Constants.DURATION_IOC.isEmpty()); + + assertFalse(Constants.EXCHANGE_NSE.isEmpty()); + assertFalse(Constants.EXCHANGE_BSE.isEmpty()); + assertFalse(Constants.EXCHANGE_NFO.isEmpty()); + assertFalse(Constants.EXCHANGE_CDS.isEmpty()); + assertFalse(Constants.EXCHANGE_NCDEX.isEmpty()); + assertFalse(Constants.EXCHANGE_MCX.isEmpty()); + } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java new file mode 100644 index 0000000..4030e89 --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java @@ -0,0 +1,77 @@ +package com.angelbroking.smartapi; + +import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import com.angelbroking.smartapi.smartTicker.*; +import org.json.JSONArray; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class SmartWebSocketTest { + @Test + public void test_initialize_with_valid_parameters() { + // Arrange + String clientId = "123"; + String jwtToken = "token"; + String apiKey = "key"; + String actionType = "action"; + String feedType = "feed"; + + // Act + SmartWebsocket websocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); + + // Assert + assertNotNull(websocket); + } + + @Test + public void test_set_listeners() { + // Arrange + SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed"); + + // Act + websocket.setOnErrorListener(new SmartWSOnError() { + @Override + public void onError(Exception exception) {} + + @Override + public void onError(SmartAPIException smartAPIException) {} + + @Override + public void onError(String error) {} + }); + + websocket.setOnTickerArrivalListener(new SmartWSOnTicks() { + @Override + public void onTicks(JSONArray ticks) {} + }); + + websocket.setOnConnectedListener(new SmartWSOnConnect() { + @Override + public void onConnected() {} + }); + + websocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { + @Override + public void onDisconnected() {} + }); + + // Assert + assertNotNull(websocket); + } + + @Test + public void test_connect_to_websocket() { + // Arrange + SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed"); + + // Act + websocket.connect(); + + // Assert + assertTrue(websocket.isConnectionOpen()); + } + + +} From 29d838ebe754c7a3fc3c787ae67a2e0e556a64db Mon Sep 17 00:00:00 2001 From: ACC Date: Thu, 12 Oct 2023 12:39:08 +0530 Subject: [PATCH 4/9] New test cases added --- .../com/angelbroking/smartapi/ModelTests.java | 24 +++++++ .../smartapi/SmartApiRequestHandlerTest.java | 42 ----------- .../smartapi/SmartConnectTest.java | 69 +++++++++++++++++++ .../smartapi/SmartWebSocketTest.java | 12 ---- 4 files changed, 93 insertions(+), 54 deletions(-) diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java index b99ba91..3fb59b7 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -1,6 +1,8 @@ package com.angelbroking.smartapi; import com.angelbroking.smartapi.models.*; +import com.angelbroking.smartapi.smartstream.models.ExchangeType; +import com.angelbroking.smartapi.smartstream.models.LTP; import com.angelbroking.smartapi.utils.Constants; import com.google.gson.annotations.SerializedName; import org.json.JSONArray; @@ -8,6 +10,8 @@ import org.json.JSONObject; import org.junit.jupiter.api.Test; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @@ -556,4 +560,24 @@ public void test_empty_string() { assertFalse(Constants.EXCHANGE_NCDEX.isEmpty()); assertFalse(Constants.EXCHANGE_MCX.isEmpty()); } + + @Test + public void test_ltp_object_created_with_valid_input_parameters() { + ByteBuffer buffer = ByteBuffer.allocate(25); + buffer.put((byte) 0); // Subscription mode + buffer.put((byte) 1); // Exchange type + buffer.put("TOKEN1234567890".getBytes(StandardCharsets.UTF_8)); // Token + buffer.putLong(Long.MAX_VALUE); // Sequence number + buffer.putLong(Long.MAX_VALUE); // Exchange feed time epoch millis + buffer.putLong(Long.MAX_VALUE); // Last traded price + + LTP ltp = new LTP(buffer); + + assertEquals(0, ltp.getSubscriptionMode()); + assertEquals(ExchangeType.NSE_CM, ltp.getExchangeType()); + assertEquals("NSE_CM-TOKEN1234567890", ltp.getToken().toString()); + assertEquals(1234567890L, ltp.getSequenceNumber()); + assertEquals(1609459200000L, ltp.getExchangeFeedTimeEpochMillis()); + assertEquals(1000L, ltp.getLastTradedPrice()); + } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java index 6101e94..b5d5856 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java @@ -189,48 +189,6 @@ public void testCreateRequestWithAccessTokenAndAllParameters() { assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID")); } - @Test - public void testCreateRequestWithJsonArrayAndAllParameters() { - // Arrange - String url = "https://example.com/"; - String apiKey = "API_KEY"; - String accessToken = "ACCESS_TOKEN"; - JSONArray jsonArray = new JSONArray(); - jsonArray.put("data1"); - jsonArray.put("data2"); - - // Act - Request request = new SmartAPIRequestHandler(null).createJsonPostRequest(url, jsonArray, apiKey, accessToken); - - log.info("content type = {}", request.body().contentType().toString()); - System.out.println(request.body().contentType().toString()); - // Assert - assertEquals(url, request.url().toString()); - assertEquals("POST", request.method()); - assertEquals("application/json; charset=utf-8", request.body().contentType().toString()); - assertEquals(USER_AGENT, request.header("User-Agent")); - assertEquals("token " + apiKey + ":" + accessToken, request.header("Authorization")); - } - - @Test - public void testCreatePutRequest() { - SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); - String url = "https://example.com/api"; - String apiKey = "1234567890"; - String accessToken = "abcdefg"; - Map params = new HashMap<>(); - params.put("param1", "value1"); - params.put("param2", "value2"); - - Request request = handler.createPutRequest(url, params, apiKey, accessToken); - - assertNotNull(request); - assertEquals(url, request.url().toString()); - assertEquals("PUT", request.method()); - assertEquals(USER_AGENT, request.header("User-Agent")); - assertEquals("3", request.header("X-Smart-API-Version")); - assertEquals("token " + apiKey + ":" + accessToken, request.header("Authorization")); - } @Test public void test_valid_apiKey_url_accessToken() throws IOException { diff --git a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java b/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java index 346b276..df4a150 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java @@ -3,6 +3,7 @@ import com.angelbroking.smartapi.http.SmartAPIRequestHandler; import com.angelbroking.smartapi.http.exceptions.DataException; import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import com.angelbroking.smartapi.smartstream.models.SmartStreamError; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONException; @@ -21,7 +22,10 @@ import static com.angelbroking.smartapi.utils.Constants.JSON_EXCEPTION_OCCURRED; import static com.angelbroking.smartapi.utils.Constants.SMART_API_EXCEPTION_ERROR_MSG; import static com.angelbroking.smartapi.utils.Constants.SMART_API_EXCEPTION_OCCURRED; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @@ -282,4 +286,69 @@ private JSONObject getMarketDataRequest(String mode) { return payload; } + @Test + public void test_create_instance_with_api_key() { + SmartConnect smartConnect = new SmartConnect("API_KEY"); + assertNotNull(smartConnect); + } + + @Test + public void test_create_instance_with_apiKey_accessToken_refreshToken() { + SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken"); + assertNotNull(smartConnect); + assertEquals("apiKey", smartConnect.getApiKey()); + assertEquals("accessToken", smartConnect.getAccessToken()); + assertEquals("refreshToken", smartConnect.getPublicToken()); + } + @Test + public void test_set_apiKey_accessToken_refreshToken() { + SmartConnect smartConnect = new SmartConnect(); + smartConnect.setApiKey("apiKey"); + smartConnect.setAccessToken("accessToken"); + smartConnect.setRefreshToken("refreshToken"); + assertEquals("apiKey", smartConnect.getApiKey()); + assertEquals("accessToken", smartConnect.getAccessToken()); + assertEquals("refreshToken", smartConnect.getPublicToken()); + } + + @Test + public void test_get_apiKey_accessToken_userId_refreshToken_null() { + SmartConnect smartConnect = new SmartConnect(); + smartConnect.setApiKey(null); + smartConnect.setAccessToken(null); + smartConnect.setRefreshToken(null); + assertThrows(NullPointerException.class, () -> smartConnect.getApiKey()); + assertThrows(NullPointerException.class, () -> smartConnect.getAccessToken()); + assertThrows(NullPointerException.class, () -> smartConnect.getUserId()); + assertThrows(NullPointerException.class, () -> smartConnect.getPublicToken()); + } + + @Test + public void test_generateSession_invalid_credentials() { + SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken"); + assertNull(smartConnect.generateSession("invalidClientCode", "password", "totp")); + } + + @Test + public void test_returns_apiKey_if_not_null() { + SmartConnect smartConnect = new SmartConnect("apiKey"); + String result = smartConnect.getApiKey(); + assertEquals("apiKey", result); + } + + @Test + public void test_throws_NullPointerException_if_apiKey_is_null() { + SmartConnect smartConnect = new SmartConnect(); + assertThrows(NullPointerException.class, () -> { + smartConnect.getApiKey(); + }); + } + + @Test + public void test_setAndGetExceptionObject() { + SmartStreamError error = new SmartStreamError(); + Exception exception = new Exception("Test Exception"); + error.setException(exception); + assertEquals(exception, error.getException()); + } } \ No newline at end of file diff --git a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java index 4030e89..d1e364c 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java @@ -61,17 +61,5 @@ public void onDisconnected() {} assertNotNull(websocket); } - @Test - public void test_connect_to_websocket() { - // Arrange - SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed"); - - // Act - websocket.connect(); - - // Assert - assertTrue(websocket.isConnectionOpen()); - } - } From 9fa55a3fdbb7161f6c59b5be8e7080167a300bee Mon Sep 17 00:00:00 2001 From: ACC Date: Fri, 13 Oct 2023 13:09:06 +0530 Subject: [PATCH 5/9] new model test added --- .../com/angelbroking/smartapi/ModelTests.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java index 3fb59b7..6e81ad9 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -580,4 +580,41 @@ public void test_ltp_object_created_with_valid_input_parameters() { assertEquals(1609459200000L, ltp.getExchangeFeedTimeEpochMillis()); assertEquals(1000L, ltp.getLastTradedPrice()); } + + @Test + public void test_valid_values_for_all_fields() { + OrderParams orderParams = new OrderParams(); + orderParams.orderid = "12345"; + orderParams.exchange = "NSE"; + orderParams.symbolToken = "123"; + orderParams.transactiontype = "BUY"; + orderParams.quantity = 100; + orderParams.price = 100.0; + orderParams.producttype = "NRML"; + orderParams.ordertype = "LIMIT"; + orderParams.duration = "DAY"; + orderParams.variety = "NORMAL"; + orderParams.tradingsymbol = "AAPL"; + orderParams.triggerprice = "150.0"; + orderParams.squareoff = "160.0"; + orderParams.stoploss = "140.0"; + assertNotNull(orderParams); + } + + @Test + public void test_fields_set_when_creating_new_instance() { + GttParams gttParams = new GttParams(); + assertNotNull(gttParams); + assertNull(gttParams.id); + assertNull(gttParams.tradingsymbol); + assertNull(gttParams.exchange); + assertNull(gttParams.transactiontype); + assertNull(gttParams.producttype); + assertNull(gttParams.price); + assertNull(gttParams.qty); + assertNull(gttParams.triggerprice); + assertNull(gttParams.disclosedqty); + assertNull(gttParams.timeperiod); + assertNull(gttParams.symboltoken); + } } From 1059e56fa1a47f7e1c43aa06da03366c629bc6b7 Mon Sep 17 00:00:00 2001 From: ACC Date: Mon, 16 Oct 2023 14:55:53 +0530 Subject: [PATCH 6/9] New test cases added --- .../angelbroking/smartapi/ExceptionTests.java | 9 ++- .../com/angelbroking/smartapi/ModelTests.java | 75 ++++++++++++++----- .../smartapi/SmartApiResponseHandlerTest.java | 2 + .../smartapi/SmartConnectTest.java | 3 +- 4 files changed, 67 insertions(+), 22 deletions(-) diff --git a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java b/src/test/java/com/angelbroking/smartapi/ExceptionTests.java index 977a628..693a8ab 100644 --- a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java +++ b/src/test/java/com/angelbroking/smartapi/ExceptionTests.java @@ -62,5 +62,12 @@ public void testTokenException() { assertEquals(code, tokenException.code); } - + @Test + public void test_instance_with_message_and_code() { + String message = "Invalid API Key"; + String code = "123"; + ApiKeyException exception = new ApiKeyException(message, code); + assertEquals(message, exception.message); + assertEquals(code, exception.code); + } } diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java index 6e81ad9..03af4d5 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -561,26 +561,6 @@ public void test_empty_string() { assertFalse(Constants.EXCHANGE_MCX.isEmpty()); } - @Test - public void test_ltp_object_created_with_valid_input_parameters() { - ByteBuffer buffer = ByteBuffer.allocate(25); - buffer.put((byte) 0); // Subscription mode - buffer.put((byte) 1); // Exchange type - buffer.put("TOKEN1234567890".getBytes(StandardCharsets.UTF_8)); // Token - buffer.putLong(Long.MAX_VALUE); // Sequence number - buffer.putLong(Long.MAX_VALUE); // Exchange feed time epoch millis - buffer.putLong(Long.MAX_VALUE); // Last traded price - - LTP ltp = new LTP(buffer); - - assertEquals(0, ltp.getSubscriptionMode()); - assertEquals(ExchangeType.NSE_CM, ltp.getExchangeType()); - assertEquals("NSE_CM-TOKEN1234567890", ltp.getToken().toString()); - assertEquals(1234567890L, ltp.getSequenceNumber()); - assertEquals(1609459200000L, ltp.getExchangeFeedTimeEpochMillis()); - assertEquals(1000L, ltp.getLastTradedPrice()); - } - @Test public void test_valid_values_for_all_fields() { OrderParams orderParams = new OrderParams(); @@ -617,4 +597,59 @@ public void test_fields_set_when_creating_new_instance() { assertNull(gttParams.timeperiod); assertNull(gttParams.symboltoken); } + + @Test + public void test_create_instance_with_values() { + SearchScripResponseDTO responseDTO = new SearchScripResponseDTO(); + responseDTO.setTradingSymbol("ABC"); + responseDTO.setExchange("NYSE"); + responseDTO.setSymbolToken("12345"); + + assertEquals("ABC", responseDTO.getTradingSymbol()); + assertEquals("NYSE", responseDTO.getExchange()); + assertEquals("12345", responseDTO.getSymbolToken()); + } + + @Test + public void test_returns_all_fields() { + Order order = new Order(); + order.disclosedQuantity = "10"; + order.duration = "DAY"; + order.tradingSymbol = "AAPL"; + order.variety = "NORMAL"; + order.orderType = "LIMIT"; + order.triggerPrice = "100.0"; + order.text = "Sample order"; + order.price = "99.0"; + order.status = "OPEN"; + order.productType = "CNC"; + order.exchange = "NSE"; + order.orderId = "12345"; + order.symbol = "AAPL"; + order.updateTime = "2021-01-01 10:00:00"; + order.exchangeTimestamp = "2021-01-01 10:00:00"; + order.exchangeUpdateTimestamp = "2021-01-01 10:00:00"; + order.averagePrice = "98.0"; + order.transactionType = "BUY"; + order.quantity = "5"; + order.squareOff = "100.0"; + order.stopLoss = "95.0"; + order.trailingStopLoss = "90.0"; + order.symbolToken = "AAPL"; + order.instrumentType = "EQUITY"; + order.strikePrice = "0.0"; + order.optionType = ""; + order.expiryDate = ""; + order.lotSize = ""; + order.cancelSize = ""; + order.filledShares = ""; + order.orderStatus = ""; + order.unfilledShares = ""; + order.fillId = ""; + order.fillTime = ""; + + String expected = "Order [disclosedQuantity=10, duration=DAY, tradingSymbol=AAPL, variety=NORMAL, orderType=LIMIT, triggerPrice=100.0, text=Sample order, price=99.0, status=OPEN, productType=CNC, exchange=NSE, orderId=12345, symbol=AAPL, updateTime=2021-01-01 10:00:00, exchangeTimestamp=2021-01-01 10:00:00, exchangeUpdateTimestamp=2021-01-01 10:00:00, averagePrice=98.0, transactionType=BUY, quantity=5, squareOff=100.0, stopLoss=95.0, trailingStopLoss=90.0, symbolToken=AAPL, instrumentType=EQUITY, strikePrice=0.0, optionType=, expiryDate=, lotSize=, cancelSize=, filledShares=, orderStatus=, unfilledShares=, fillId=, fillTime=]"; + + assertEquals(expected, order.toString()); + } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java index e64983c..d15561d 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java @@ -35,4 +35,6 @@ public void test_returns_jsonObject_when_response_header_contains_json_and_jsonO throw new RuntimeException(e); } } + + } diff --git a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java b/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java index 5805775..9eb9f3f 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java @@ -40,7 +40,8 @@ @RunWith(MockitoJUnitRunner.Silent.class) @Slf4j public class SmartConnectTest { - + + @Mock private SmartAPIRequestHandler smartAPIRequestHandler; @Mock From 8ef5d5926add6d5272f32dde1c029df189be268d Mon Sep 17 00:00:00 2001 From: ACC Date: Wed, 18 Oct 2023 12:00:41 +0530 Subject: [PATCH 7/9] new test cases added and now covers more than 80% --- .../smartapi/sample/LoginWithTOTPSample.java | 2 +- .../angelbroking/smartapi/ExceptionTests.java | 2 +- .../com/angelbroking/smartapi/ModelTests.java | 38 +++++++------------ .../smartapi/SmartApiResponseHandlerTest.java | 2 +- .../smartapi/SmartApiTickerTest.java | 16 -------- .../smartapi/SmartConnectTest.java | 26 ++++++------- .../smartapi/SmartWebSocketTest.java | 4 +- 7 files changed, 31 insertions(+), 59 deletions(-) diff --git a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java index 910bcc5..f36d841 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java +++ b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java @@ -4,7 +4,7 @@ import com.angelbroking.smartapi.models.User; public class LoginWithTOTPSample { - + public static void main(String[] args) { String clientID = System.getProperty("clientID"); String clientPass = System.getProperty("clientPass"); diff --git a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java b/src/test/java/com/angelbroking/smartapi/ExceptionTests.java index 693a8ab..33c6807 100644 --- a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java +++ b/src/test/java/com/angelbroking/smartapi/ExceptionTests.java @@ -63,7 +63,7 @@ public void testTokenException() { } @Test - public void test_instance_with_message_and_code() { + public void testApiKeyException() { String message = "Invalid API Key"; String code = "123"; ApiKeyException exception = new ApiKeyException(message, code); diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/ModelTests.java index a19dc22..ade95f6 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/ModelTests.java @@ -298,7 +298,7 @@ public void testUserModelSetters() { } @Test - public void test_null_or_missing_fields_in_json_response() throws JSONException { + public void testUserWithNullResponse() throws JSONException { JSONObject response = null; JSONObject finalResponse = response; @@ -325,7 +325,7 @@ public void test_null_or_missing_fields_in_json_response() throws JSONException } @Test - public void test_trade_object_created_with_all_fields_populated() { + public void testTradeModelWithAllFields() { Trade trade = new Trade(); trade.tradeId = "123"; trade.orderId = "456"; @@ -356,7 +356,7 @@ public void test_trade_object_created_with_all_fields_populated() { } @Test - public void test_serialized_name_annotations_mapped_correctly() throws NoSuchFieldException { + public void testTradeModelSerializedNameAnnotationsMappedCorrectly() throws NoSuchFieldException { Trade trade = new Trade(); assertNotNull(trade.getClass().getDeclaredField("tradeId").getAnnotation(SerializedName.class)); @@ -374,7 +374,7 @@ public void test_serialized_name_annotations_mapped_correctly() throws NoSuchFie } @Test - public void test_date_fields_parsed_and_stored_correctly() { + public void testTradeModelDateFieldsParsedAndStoredCorrectly() { Trade trade = new Trade(); Date fillTimestamp = new Date(); Date exchangeTimestamp = new Date(); @@ -387,7 +387,7 @@ public void test_date_fields_parsed_and_stored_correctly() { } @Test - public void test_trade_object_created_with_null_values() { + public void testTradeModelCreatedWithNullValues() { Trade trade = new Trade(); assertNull(trade.tradeId); @@ -405,7 +405,7 @@ public void test_trade_object_created_with_null_values() { } @Test - public void test_trade_object_created_with_invalid_date_formats() { + public void testTradeModelCreatedWithInvalidDateFormats() { Trade trade = new Trade(); String invalidDateFormat = "2021-13-01"; try { @@ -418,7 +418,7 @@ public void test_trade_object_created_with_invalid_date_formats() { } @Test - public void test_fieldAccess() { + public void testOrderModelWithAllFields() { Order order = new Order(); order.disclosedQuantity = "10"; order.duration = "DAY"; @@ -491,16 +491,6 @@ public void test_fieldAccess() { assertEquals("", order.fillTime); } - @Test - void TestSSS34() { - SmartConnect smartConnect = new SmartConnect(); - smartConnect.setApiKey("R2WSHRE9"); - User user = smartConnect.generateSession("user", "pass", "502216"); - - System.out.println(smartConnect.getProfile()); - - } - @Test public void testGttModelWithAllFields() { Gtt gtt = new Gtt(); @@ -531,7 +521,7 @@ public void testGttModelWithAllFields() { } @Test - public void test_empty_string() { + public void testConstantsFields() { assertFalse(Constants.PRODUCT_DELIVERY.isEmpty()); assertFalse(Constants.PRODUCT_INTRADAY.isEmpty()); assertFalse(Constants.PRODUCT_MARGIN.isEmpty()); @@ -563,11 +553,11 @@ public void test_empty_string() { } @Test - public void test_valid_values_for_all_fields() { + public void testOrderParamsWithAllFields() { OrderParams orderParams = new OrderParams(); orderParams.orderid = "12345"; orderParams.exchange = "NSE"; - orderParams.symbolToken = "123"; + orderParams.symboltoken = "123"; orderParams.transactiontype = "BUY"; orderParams.quantity = 100; orderParams.price = 100.0; @@ -583,7 +573,7 @@ public void test_valid_values_for_all_fields() { } @Test - public void test_fields_set_when_creating_new_instance() { + public void testGttParamsWithNullValues() { GttParams gttParams = new GttParams(); assertNotNull(gttParams); assertNull(gttParams.id); @@ -600,7 +590,7 @@ public void test_fields_set_when_creating_new_instance() { } @Test - public void test_create_instance_with_values() { + public void testSearchScripResponse() { SearchScripResponseDTO responseDTO = new SearchScripResponseDTO(); responseDTO.setTradingSymbol("ABC"); responseDTO.setExchange("NYSE"); @@ -612,7 +602,7 @@ public void test_create_instance_with_values() { } @Test - public void test_returns_all_fields() { + public void testOrderModelResponse() { Order order = new Order(); order.disclosedQuantity = "10"; order.duration = "DAY"; @@ -655,7 +645,7 @@ public void test_returns_all_fields() { } @Test - public void test_create_instance_with_valid_values() { + public void testBESTTwentyData() { BestTwentyData data = new BestTwentyData(10, 20, (short) 5); assertEquals(10, data.getQuantity()); assertEquals(20, data.getPrice()); diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java index d15561d..3ab27ed 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java @@ -18,7 +18,7 @@ public class SmartApiResponseHandlerTest { @Test - public void test_returns_jsonObject_when_response_header_contains_json_and_jsonObject_has_status_or_success_fields() { + public void testSmartApiResponseHandlerResponse() { Response response = mock(Response.class); when(response.header("Content-Type")).thenReturn("application/json"); diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java index 2aeb08b..d3f4f93 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java @@ -57,22 +57,6 @@ public void onConnected() { assertNotNull(ticker); } -// @Test -// public void testWebSocketConnectionOfSmartAPITicker() { -// // Arrange -// String clientId = "client_id"; -// String feedToken = "feed_token"; -// String script = "script"; -// String task = "task"; -// -// SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task); -// -// // Act -// ticker.connect(); -// -// // Assert -// assertTrue(ticker.isConnectionOpen()); -// } @Test public void testUnableToCloseWebSocketConnectionOfSmartAPITicker() { diff --git a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java b/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java index 2b52f14..3e920ec 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java @@ -3,7 +3,12 @@ import com.angelbroking.smartapi.http.SmartAPIRequestHandler; import com.angelbroking.smartapi.http.exceptions.DataException; import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import com.angelbroking.smartapi.models.Order; +import com.angelbroking.smartapi.models.OrderParams; +import com.angelbroking.smartapi.models.User; import com.angelbroking.smartapi.smartstream.models.SmartStreamError; +import com.angelbroking.smartapi.utils.Constants; +import com.warrenstrange.googleauth.GoogleAuthenticator; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONException; @@ -326,13 +331,13 @@ private JSONObject getMarketDataRequest(String mode) { @Test - public void test_create_instance_with_api_key() { + public void testSmartConnectObjectWithApiKey() { SmartConnect smartConnect = new SmartConnect("API_KEY"); assertNotNull(smartConnect); } @Test - public void test_create_instance_with_apiKey_accessToken_refreshToken() { + public void testSmartConnectObjectWithApiKeyAccessTokenRefreshToken() { SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken"); assertNotNull(smartConnect); assertEquals("apiKey", smartConnect.getApiKey()); @@ -340,7 +345,7 @@ public void test_create_instance_with_apiKey_accessToken_refreshToken() { assertEquals("refreshToken", smartConnect.getPublicToken()); } @Test - public void test_set_apiKey_accessToken_refreshToken() { + public void testSetApiKeyOfSmartConnect() { SmartConnect smartConnect = new SmartConnect(); smartConnect.setApiKey("apiKey"); smartConnect.setAccessToken("accessToken"); @@ -351,7 +356,7 @@ public void test_set_apiKey_accessToken_refreshToken() { } @Test - public void test_get_apiKey_accessToken_userId_refreshToken_null() { + public void testSmartConnectWithNullValues() { SmartConnect smartConnect = new SmartConnect(); smartConnect.setApiKey(null); smartConnect.setAccessToken(null); @@ -363,33 +368,26 @@ public void test_get_apiKey_accessToken_userId_refreshToken_null() { } @Test - public void test_generateSession_invalid_credentials() { + public void testGenerateSession() { SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken"); assertNull(smartConnect.generateSession("invalidClientCode", "password", "totp")); } @Test - public void test_returns_apiKey_if_not_null() { + public void testReturnApiKeyIfNotNull() { SmartConnect smartConnect = new SmartConnect("apiKey"); String result = smartConnect.getApiKey(); assertEquals("apiKey", result); } @Test - public void test_throws_NullPointerException_if_apiKey_is_null() { + public void testThrowsNullPointerExceptionIfApiKeyIsNull() { SmartConnect smartConnect = new SmartConnect(); assertThrows(NullPointerException.class, () -> { smartConnect.getApiKey(); }); } - @Test - public void test_setAndGetExceptionObject() { - SmartStreamError error = new SmartStreamError(); - Exception exception = new Exception("Test Exception"); - error.setException(exception); - assertEquals(exception, error.getException()); - } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java index d1e364c..b973482 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java +++ b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java @@ -10,7 +10,7 @@ public class SmartWebSocketTest { @Test - public void test_initialize_with_valid_parameters() { + public void testWebSocketWithAllFields() { // Arrange String clientId = "123"; String jwtToken = "token"; @@ -26,7 +26,7 @@ public void test_initialize_with_valid_parameters() { } @Test - public void test_set_listeners() { + public void testSetListener() { // Arrange SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed"); From 2ec89ecbdfe7842a8ad02f2f6ad08b3038e1cb8a Mon Sep 17 00:00:00 2001 From: ACC Date: Thu, 19 Oct 2023 17:39:46 +0530 Subject: [PATCH 8/9] New test cases added --- .../smartapi/http/SmartAPIRequestHandler.java | 2 +- .../smartapi/sample/Examples.java | 822 +++++++++--------- .../smartapi/sample/LoginWithTOTPSample.java | 36 +- .../angelbroking/smartapi/sample/Test.java | 250 +++--- .../smartapi/SmartApiResponseHandlerTest.java | 40 - .../smartapi/SmartWebSocketTest.java | 65 -- .../{ => exceptions}/ExceptionTests.java | 11 +- .../SmartApiRequestHandlerTest.java | 44 +- .../http/SmartApiResponseHandlerTest.java | 86 ++ .../smartapi/{ => models}/ModelTests.java | 19 +- .../{ => smartconnet}/SmartConnectTest.java | 4 +- .../smartticker/SmartWebSocketTest.java | 160 ++++ .../{ => ticker}/SmartApiTickerTest.java | 39 +- 13 files changed, 913 insertions(+), 665 deletions(-) delete mode 100644 src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java delete mode 100644 src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java rename src/test/java/com/angelbroking/smartapi/{ => exceptions}/ExceptionTests.java (84%) rename src/test/java/com/angelbroking/smartapi/{ => http}/SmartApiRequestHandlerTest.java (79%) create mode 100644 src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java rename src/test/java/com/angelbroking/smartapi/{ => models}/ModelTests.java (97%) rename src/test/java/com/angelbroking/smartapi/{ => smartconnet}/SmartConnectTest.java (99%) create mode 100644 src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java rename src/test/java/com/angelbroking/smartapi/{ => ticker}/SmartApiTickerTest.java (55%) diff --git a/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java b/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java index a53229a..987e1f2 100644 --- a/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java +++ b/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java @@ -431,7 +431,7 @@ public Request createDeleteRequest(String url, Map params, Strin } Request request = new Request.Builder().url(httpBuilder.build()).delete().header("User-Agent", USER_AGENT) - .header("X-Smart API-Version", "3").header("Authorization", "token " + apiKey + ":" + accessToken) + .header("X-SmartAPI-Version", "3").header("Authorization", "token " + apiKey + ":" + accessToken) .build(); return request; } diff --git a/src/main/java/com/angelbroking/smartapi/sample/Examples.java b/src/main/java/com/angelbroking/smartapi/sample/Examples.java index 1c60bd5..e61c005 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/Examples.java +++ b/src/main/java/com/angelbroking/smartapi/sample/Examples.java @@ -1,411 +1,411 @@ -package com.angelbroking.smartapi.sample; - -import com.angelbroking.smartapi.SmartConnect; -import com.angelbroking.smartapi.http.exceptions.SmartAPIException; -import com.angelbroking.smartapi.models.Gtt; -import com.angelbroking.smartapi.models.GttParams; -import com.angelbroking.smartapi.models.Order; -import com.angelbroking.smartapi.models.OrderParams; -import com.angelbroking.smartapi.models.User; -import com.angelbroking.smartapi.smartTicker.SmartWSOnConnect; -import com.angelbroking.smartapi.smartTicker.SmartWSOnDisconnect; -import com.angelbroking.smartapi.smartTicker.SmartWSOnError; -import com.angelbroking.smartapi.smartTicker.SmartWSOnTicks; -import com.angelbroking.smartapi.smartTicker.SmartWebsocket; -import com.angelbroking.smartapi.ticker.OnConnect; -import com.angelbroking.smartapi.ticker.OnTicks; -import com.angelbroking.smartapi.ticker.SmartAPITicker; -import com.angelbroking.smartapi.utils.Constants; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings("unused") -public class Examples { - - public void getProfile(SmartConnect smartConnect) throws IOException, SmartAPIException { - User profile = smartConnect.getProfile(); - } - - /** CONSTANT Details */ - - /* VARIETY */ - /* - * VARIETY_NORMAL: Normal Order (Regular) - * VARIETY_AMO: After Market Order - * VARIETY_STOPLOSS: Stop loss order - * VARIETY_ROBO: ROBO (Bracket) Order - */ - /* TRANSACTION TYPE */ - /* - * TRANSACTION_TYPE_BUY: Buy TRANSACTION_TYPE_SELL: Sell - */ - - /* ORDER TYPE */ - /* - * ORDER_TYPE_MARKET: Market Order(MKT) - * ORDER_TYPE_LIMIT: Limit Order(L) - * ORDER_TYPE_STOPLOSS_LIMIT: Stop Loss Limit Order(SL) - * ORDER_TYPE_STOPLOSS_MARKET: Stop Loss Market Order(SL-M) - */ - - /* PRODUCT TYPE */ - /* - * PRODUCT_DELIVERY: Cash & Carry for equity (CNC) - * PRODUCT_CARRYFORWARD: Normal - * for futures and options (NRML) - * PRODUCT_MARGIN: Margin Delivery - * PRODUCT_INTRADAY: Margin Intraday Squareoff (MIS) - * PRODUCT_BO: Bracket Order - * (Only for ROBO) - */ - - /* DURATION */ - /* - * DURATION_DAY: Valid for a day - * DURATION_IOC: Immediate or Cancel - */ - - /* EXCHANGE */ - /* - * EXCHANGE_BSE: BSE Equity - * EXCHANGE_NSE: NSE Equity - * EXCHANGE_NFO: NSE Future and Options - * EXCHANGE_CDS: NSE Currency - * EXCHANGE_NCDEX: NCDEX Commodity - * EXCHANGE_MCX: MCX Commodity - */ - - /** Place order. */ - public void placeOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { - - OrderParams orderParams = new OrderParams(); - orderParams.variety = Constants.VARIETY_STOPLOSS; - orderParams.quantity = 323; - orderParams.symboltoken = "1660"; - orderParams.exchange = Constants.EXCHANGE_NSE; - orderParams.ordertype = Constants.ORDER_TYPE_STOPLOSS_LIMIT; - orderParams.tradingsymbol = "ITC-EQ"; - orderParams.producttype = Constants.PRODUCT_INTRADAY; - orderParams.duration = Constants.DURATION_DAY; - orderParams.transactiontype = Constants.TRANSACTION_TYPE_BUY; - orderParams.price = 122.2; - orderParams.triggerprice = "209"; - - Order order = smartConnect.placeOrder(orderParams, "STOPLOSS"); - System.out.print(order); - } - - /** Modify order. */ - public void modifyOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { - // Order modify request will return order model which will contain only - - OrderParams orderParams = new OrderParams(); - orderParams.quantity = 1; - orderParams.ordertype = Constants.ORDER_TYPE_LIMIT; - orderParams.tradingsymbol = "ASHOKLEY"; - orderParams.symboltoken = "3045"; - orderParams.producttype = Constants.PRODUCT_DELIVERY; - orderParams.exchange = Constants.EXCHANGE_NSE; - orderParams.duration = Constants.DURATION_DAY; - orderParams.price = 122.2; - - String orderId = "201216000755110"; - Order order = smartConnect.modifyOrder(orderId, orderParams, Constants.VARIETY_NORMAL); - } - - /** Cancel an order */ - public void cancelOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { - // Order modify request will return order model which will contain only - // order_id. - // Cancel order will return order model which will only have orderId. - Order order = smartConnect.cancelOrder("201009000000015", Constants.VARIETY_NORMAL); - } - - /** Get order details */ - public void getOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { - JSONObject orders = smartConnect.getOrderHistory(smartConnect.getUserId()); - System.out.print(orders); -// for (int i = 0; i < orders.size(); i++) { -// System.out.println(orders.get(i).orderId + " " + orders.get(i).status); -// } - } - - /** - * Get last price for multiple instruments at once. USers can either pass - * exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY - * 50, BSE:SENSEX} or {256265, 265} - */ - public void getLTP(SmartConnect smartConnect) throws SmartAPIException, IOException { - String exchange = "NSE"; - String tradingSymbol = "SBIN-EQ"; - String symboltoken = "3045"; - JSONObject ltpData = smartConnect.getLTP(exchange, tradingSymbol, symboltoken); - } - - /** Get tradebook */ - public void getTrades(SmartConnect smartConnect) throws SmartAPIException, IOException { - // Returns tradebook. - JSONObject trades = smartConnect.getTrades(); - - } - - /** Get RMS */ - public void getRMS(SmartConnect smartConnect) throws SmartAPIException, IOException { - // Returns RMS. - JSONObject response = smartConnect.getRMS(); - } - - /** Get Holdings */ - public void getHolding(SmartConnect smartConnect) throws SmartAPIException, IOException { - // Returns Holding. - JSONObject response = smartConnect.getHolding(); - } - - /** Get Position */ - public void getPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { - // Returns Position. - JSONObject response = smartConnect.getPosition(); - } - - /** convert Position */ - public void convertPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { - - JSONObject requestObejct = new JSONObject(); - requestObejct.put("exchange", "NSE"); - requestObejct.put("oldproducttype", "DELIVERY"); - requestObejct.put("newproducttype", "MARGIN"); - requestObejct.put("tradingsymbol", "SBIN-EQ"); - requestObejct.put("transactiontype", "BUY"); - requestObejct.put("quantity", 1); - requestObejct.put("type", "DAY"); - - JSONObject response = smartConnect.convertPosition(requestObejct); - } - - /** Create Gtt Rule */ - public void createRule(SmartConnect smartConnect) throws SmartAPIException, IOException { - GttParams gttParams = new GttParams(); - - gttParams.tradingsymbol = "SBIN-EQ"; - gttParams.symboltoken = "3045"; - gttParams.exchange = "NSE"; - gttParams.producttype = "MARGIN"; - gttParams.transactiontype = "BUY"; - gttParams.price = 100000.01; - gttParams.qty = 10; - gttParams.disclosedqty = 10; - gttParams.triggerprice = 20000.1; - gttParams.timeperiod = 300; - - Gtt gtt = smartConnect.gttCreateRule(gttParams); - } - - /** Modify Gtt Rule */ - public void modifyRule(SmartConnect smartConnect) throws SmartAPIException, IOException { - GttParams gttParams = new GttParams(); - - gttParams.tradingsymbol = "SBIN-EQ"; - gttParams.symboltoken = "3045"; - gttParams.exchange = "NSE"; - gttParams.producttype = "MARGIN"; - gttParams.transactiontype = "BUY"; - gttParams.price = 100000.1; - gttParams.qty = 10; - gttParams.disclosedqty = 10; - gttParams.triggerprice = 20000.1; - gttParams.timeperiod = 300; - - Integer id = 1000051; - - Gtt gtt = smartConnect.gttModifyRule(id, gttParams); - } - - /** Cancel Gtt Rule */ - public void cancelRule(SmartConnect smartConnect) throws SmartAPIException, IOException { - Integer id = 1000051; - String symboltoken = "3045"; - String exchange = "NSE"; - - Gtt gtt = smartConnect.gttCancelRule(id, symboltoken, exchange); - } - - /** Gtt Rule Details */ - public void ruleDetails(SmartConnect smartConnect) throws SmartAPIException, IOException { - Integer id = 1000051; - - JSONObject gtt = smartConnect.gttRuleDetails(id); - } - - /** Gtt Rule Lists */ - @SuppressWarnings("serial") - public void ruleList(SmartConnect smartConnect) throws SmartAPIException, IOException { - - List status = new ArrayList() { - { - add("NEW"); - add("CANCELLED"); - add("ACTIVE"); - add("SENTTOEXCHANGE"); - add("FORALL"); - } - }; - Integer page = 1; - Integer count = 10; - - JSONArray gtt = smartConnect.gttRuleList(status, page, count); - } - - /** Historic Data */ - public void getCandleData(SmartConnect smartConnect) throws SmartAPIException, IOException { - - JSONObject requestObejct = new JSONObject(); - requestObejct.put("exchange", "NSE"); - requestObejct.put("symboltoken", "3045"); - requestObejct.put("interval", "ONE_MINUTE"); - requestObejct.put("fromdate", "2021-03-08 09:00"); - requestObejct.put("todate", "2021-03-09 09:20"); - - String response = smartConnect.candleData(requestObejct); - } - - - /** Search Scrip Data */ - public void getSearchScrip(SmartConnect smartConnect) throws SmartAPIException, IOException { - JSONObject payload = new JSONObject(); - payload.put("exchange", "MCX"); - payload.put("searchscrip", "Crude"); - smartConnect.getSearchScrip(payload); - } - - /** - * Market Data - * To Retrieve Market Data with different modes use. - * e.g: - * payload.put("mode", "FULL"); - * payload.put("mode", "LTP"); - * payload.put("mode", "OHLC"); - */ - public void getMarketData(SmartConnect smartConnect) throws SmartAPIException, IOException { - JSONObject payload = new JSONObject(); - payload.put("mode", "FULL"); // You can change the mode as needed - JSONObject exchangeTokens = new JSONObject(); - JSONArray nseTokens = new JSONArray(); - nseTokens.put("3045"); - exchangeTokens.put("NSE", nseTokens); - payload.put("exchangeTokens", exchangeTokens); - JSONObject response = smartConnect.marketData(payload); - } - - - - public void tickerUsage(String clientId, String feedToken, String strWatchListScript, String task) - throws SmartAPIException { - - SmartAPITicker tickerProvider = new SmartAPITicker(clientId, feedToken, strWatchListScript, task); - - tickerProvider.setOnConnectedListener(new OnConnect() { - @Override - public void onConnected() { - System.out.println("subscribe() called!"); - tickerProvider.subscribe(); - } - }); - - tickerProvider.setOnTickerArrivalListener(new OnTicks() { - @Override - public void onTicks(JSONArray ticks) { - System.out.println("ticker data: " + ticks.toString()); - } - }); - - /** - * connects to Smart API 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); - - // After using SmartAPI ticker, close websocket connection. - // tickerProvider.disconnect(); - - } - - public void smartWebSocketUsage(String clientId, String jwtToken, String apiKey, String actionType, String feedType) - throws SmartAPIException { - - SmartWebsocket smartWebsocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); - - smartWebsocket.setOnConnectedListener(new SmartWSOnConnect() { - - @Override - public void onConnected() { - - smartWebsocket.runscript(); - } - }); - - smartWebsocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { - @Override - public void onDisconnected() { - System.out.println("onDisconnected"); - } - }); - - /** Set error listener to listen to errors. */ - smartWebsocket.setOnErrorListener(new SmartWSOnError() { - @Override - public void onError(Exception exception) { - System.out.println("onError: " + exception.getMessage()); - } - - @Override - public void onError(SmartAPIException smartAPIException) { - System.out.println("onError: " + smartAPIException.getMessage()); - } - - @Override - public void onError(String error) { - System.out.println("onError: " + error); - } - }); - - smartWebsocket.setOnTickerArrivalListener(new SmartWSOnTicks() { - @Override - public void onTicks(JSONArray ticks) { - System.out.println("ticker data: " + ticks.toString()); - } - }); - - /** - * connects to Smart API ticker server for getting live quotes - */ - smartWebsocket.connect(); - - /** - * You can check, if websocket connection is open or not using the following - * method. - */ - boolean isConnected = smartWebsocket.isConnectionOpen(); - System.out.println(isConnected); - - // After using SmartAPI ticker, close websocket connection. - // smartWebsocket.disconnect(); - - } - - /** Logout user. */ - public void logout(SmartConnect smartConnect) throws SmartAPIException, IOException { - /** Logout user and kill session. */ - JSONObject jsonObject = smartConnect.logout(); - } - -} +//package com.angelbroking.smartapi.sample; +// +//import com.angelbroking.smartapi.SmartConnect; +//import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +//import com.angelbroking.smartapi.models.Gtt; +//import com.angelbroking.smartapi.models.GttParams; +//import com.angelbroking.smartapi.models.Order; +//import com.angelbroking.smartapi.models.OrderParams; +//import com.angelbroking.smartapi.models.User; +//import com.angelbroking.smartapi.smartTicker.SmartWSOnConnect; +//import com.angelbroking.smartapi.smartTicker.SmartWSOnDisconnect; +//import com.angelbroking.smartapi.smartTicker.SmartWSOnError; +//import com.angelbroking.smartapi.smartTicker.SmartWSOnTicks; +//import com.angelbroking.smartapi.smartTicker.SmartWebsocket; +//import com.angelbroking.smartapi.ticker.OnConnect; +//import com.angelbroking.smartapi.ticker.OnTicks; +//import com.angelbroking.smartapi.ticker.SmartAPITicker; +//import com.angelbroking.smartapi.utils.Constants; +//import org.json.JSONArray; +//import org.json.JSONObject; +// +//import java.io.IOException; +//import java.util.ArrayList; +//import java.util.List; +// +//@SuppressWarnings("unused") +//public class Examples { +// +// public void getProfile(SmartConnect smartConnect) throws IOException, SmartAPIException { +// User profile = smartConnect.getProfile(); +// } +// +// /** CONSTANT Details */ +// +// /* VARIETY */ +// /* +// * VARIETY_NORMAL: Normal Order (Regular) +// * VARIETY_AMO: After Market Order +// * VARIETY_STOPLOSS: Stop loss order +// * VARIETY_ROBO: ROBO (Bracket) Order +// */ +// /* TRANSACTION TYPE */ +// /* +// * TRANSACTION_TYPE_BUY: Buy TRANSACTION_TYPE_SELL: Sell +// */ +// +// /* ORDER TYPE */ +// /* +// * ORDER_TYPE_MARKET: Market Order(MKT) +// * ORDER_TYPE_LIMIT: Limit Order(L) +// * ORDER_TYPE_STOPLOSS_LIMIT: Stop Loss Limit Order(SL) +// * ORDER_TYPE_STOPLOSS_MARKET: Stop Loss Market Order(SL-M) +// */ +// +// /* PRODUCT TYPE */ +// /* +// * PRODUCT_DELIVERY: Cash & Carry for equity (CNC) +// * PRODUCT_CARRYFORWARD: Normal +// * for futures and options (NRML) +// * PRODUCT_MARGIN: Margin Delivery +// * PRODUCT_INTRADAY: Margin Intraday Squareoff (MIS) +// * PRODUCT_BO: Bracket Order +// * (Only for ROBO) +// */ +// +// /* DURATION */ +// /* +// * DURATION_DAY: Valid for a day +// * DURATION_IOC: Immediate or Cancel +// */ +// +// /* EXCHANGE */ +// /* +// * EXCHANGE_BSE: BSE Equity +// * EXCHANGE_NSE: NSE Equity +// * EXCHANGE_NFO: NSE Future and Options +// * EXCHANGE_CDS: NSE Currency +// * EXCHANGE_NCDEX: NCDEX Commodity +// * EXCHANGE_MCX: MCX Commodity +// */ +// +// /** Place order. */ +// public void placeOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { +// +// OrderParams orderParams = new OrderParams(); +// orderParams.variety = Constants.VARIETY_STOPLOSS; +// orderParams.quantity = 323; +// orderParams.symboltoken = "1660"; +// orderParams.exchange = Constants.EXCHANGE_NSE; +// orderParams.ordertype = Constants.ORDER_TYPE_STOPLOSS_LIMIT; +// orderParams.tradingsymbol = "ITC-EQ"; +// orderParams.producttype = Constants.PRODUCT_INTRADAY; +// orderParams.duration = Constants.DURATION_DAY; +// orderParams.transactiontype = Constants.TRANSACTION_TYPE_BUY; +// orderParams.price = 122.2; +// orderParams.triggerprice = "209"; +// +// Order order = smartConnect.placeOrder(orderParams, "STOPLOSS"); +// System.out.print(order); +// } +// +// /** Modify order. */ +// public void modifyOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { +// // Order modify request will return order model which will contain only +// +// OrderParams orderParams = new OrderParams(); +// orderParams.quantity = 1; +// orderParams.ordertype = Constants.ORDER_TYPE_LIMIT; +// orderParams.tradingsymbol = "ASHOKLEY"; +// orderParams.symboltoken = "3045"; +// orderParams.producttype = Constants.PRODUCT_DELIVERY; +// orderParams.exchange = Constants.EXCHANGE_NSE; +// orderParams.duration = Constants.DURATION_DAY; +// orderParams.price = 122.2; +// +// String orderId = "201216000755110"; +// Order order = smartConnect.modifyOrder(orderId, orderParams, Constants.VARIETY_NORMAL); +// } +// +// /** Cancel an order */ +// public void cancelOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { +// // Order modify request will return order model which will contain only +// // order_id. +// // Cancel order will return order model which will only have orderId. +// Order order = smartConnect.cancelOrder("201009000000015", Constants.VARIETY_NORMAL); +// } +// +// /** Get order details */ +// public void getOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { +// JSONObject orders = smartConnect.getOrderHistory(smartConnect.getUserId()); +// System.out.print(orders); +//// for (int i = 0; i < orders.size(); i++) { +//// System.out.println(orders.get(i).orderId + " " + orders.get(i).status); +//// } +// } +// +// /** +// * Get last price for multiple instruments at once. USers can either pass +// * exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY +// * 50, BSE:SENSEX} or {256265, 265} +// */ +// public void getLTP(SmartConnect smartConnect) throws SmartAPIException, IOException { +// String exchange = "NSE"; +// String tradingSymbol = "SBIN-EQ"; +// String symboltoken = "3045"; +// JSONObject ltpData = smartConnect.getLTP(exchange, tradingSymbol, symboltoken); +// } +// +// /** Get tradebook */ +// public void getTrades(SmartConnect smartConnect) throws SmartAPIException, IOException { +// // Returns tradebook. +// JSONObject trades = smartConnect.getTrades(); +// +// } +// +// /** Get RMS */ +// public void getRMS(SmartConnect smartConnect) throws SmartAPIException, IOException { +// // Returns RMS. +// JSONObject response = smartConnect.getRMS(); +// } +// +// /** Get Holdings */ +// public void getHolding(SmartConnect smartConnect) throws SmartAPIException, IOException { +// // Returns Holding. +// JSONObject response = smartConnect.getHolding(); +// } +// +// /** Get Position */ +// public void getPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { +// // Returns Position. +// JSONObject response = smartConnect.getPosition(); +// } +// +// /** convert Position */ +// public void convertPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { +// +// JSONObject requestObejct = new JSONObject(); +// requestObejct.put("exchange", "NSE"); +// requestObejct.put("oldproducttype", "DELIVERY"); +// requestObejct.put("newproducttype", "MARGIN"); +// requestObejct.put("tradingsymbol", "SBIN-EQ"); +// requestObejct.put("transactiontype", "BUY"); +// requestObejct.put("quantity", 1); +// requestObejct.put("type", "DAY"); +// +// JSONObject response = smartConnect.convertPosition(requestObejct); +// } +// +// /** Create Gtt Rule */ +// public void createRule(SmartConnect smartConnect) throws SmartAPIException, IOException { +// GttParams gttParams = new GttParams(); +// +// gttParams.tradingsymbol = "SBIN-EQ"; +// gttParams.symboltoken = "3045"; +// gttParams.exchange = "NSE"; +// gttParams.producttype = "MARGIN"; +// gttParams.transactiontype = "BUY"; +// gttParams.price = 100000.01; +// gttParams.qty = 10; +// gttParams.disclosedqty = 10; +// gttParams.triggerprice = 20000.1; +// gttParams.timeperiod = 300; +// +// Gtt gtt = smartConnect.gttCreateRule(gttParams); +// } +// +// /** Modify Gtt Rule */ +// public void modifyRule(SmartConnect smartConnect) throws SmartAPIException, IOException { +// GttParams gttParams = new GttParams(); +// +// gttParams.tradingsymbol = "SBIN-EQ"; +// gttParams.symboltoken = "3045"; +// gttParams.exchange = "NSE"; +// gttParams.producttype = "MARGIN"; +// gttParams.transactiontype = "BUY"; +// gttParams.price = 100000.1; +// gttParams.qty = 10; +// gttParams.disclosedqty = 10; +// gttParams.triggerprice = 20000.1; +// gttParams.timeperiod = 300; +// +// Integer id = 1000051; +// +// Gtt gtt = smartConnect.gttModifyRule(id, gttParams); +// } +// +// /** Cancel Gtt Rule */ +// public void cancelRule(SmartConnect smartConnect) throws SmartAPIException, IOException { +// Integer id = 1000051; +// String symboltoken = "3045"; +// String exchange = "NSE"; +// +// Gtt gtt = smartConnect.gttCancelRule(id, symboltoken, exchange); +// } +// +// /** Gtt Rule Details */ +// public void ruleDetails(SmartConnect smartConnect) throws SmartAPIException, IOException { +// Integer id = 1000051; +// +// JSONObject gtt = smartConnect.gttRuleDetails(id); +// } +// +// /** Gtt Rule Lists */ +// @SuppressWarnings("serial") +// public void ruleList(SmartConnect smartConnect) throws SmartAPIException, IOException { +// +// List status = new ArrayList() { +// { +// add("NEW"); +// add("CANCELLED"); +// add("ACTIVE"); +// add("SENTTOEXCHANGE"); +// add("FORALL"); +// } +// }; +// Integer page = 1; +// Integer count = 10; +// +// JSONArray gtt = smartConnect.gttRuleList(status, page, count); +// } +// +// /** Historic Data */ +// public void getCandleData(SmartConnect smartConnect) throws SmartAPIException, IOException { +// +// JSONObject requestObejct = new JSONObject(); +// requestObejct.put("exchange", "NSE"); +// requestObejct.put("symboltoken", "3045"); +// requestObejct.put("interval", "ONE_MINUTE"); +// requestObejct.put("fromdate", "2021-03-08 09:00"); +// requestObejct.put("todate", "2021-03-09 09:20"); +// +// String response = smartConnect.candleData(requestObejct); +// } +// +// +// /** Search Scrip Data */ +// public void getSearchScrip(SmartConnect smartConnect) throws SmartAPIException, IOException { +// JSONObject payload = new JSONObject(); +// payload.put("exchange", "MCX"); +// payload.put("searchscrip", "Crude"); +// smartConnect.getSearchScrip(payload); +// } +// +// /** +// * Market Data +// * To Retrieve Market Data with different modes use. +// * e.g: +// * payload.put("mode", "FULL"); +// * payload.put("mode", "LTP"); +// * payload.put("mode", "OHLC"); +// */ +// public void getMarketData(SmartConnect smartConnect) throws SmartAPIException, IOException { +// JSONObject payload = new JSONObject(); +// payload.put("mode", "FULL"); // You can change the mode as needed +// JSONObject exchangeTokens = new JSONObject(); +// JSONArray nseTokens = new JSONArray(); +// nseTokens.put("3045"); +// exchangeTokens.put("NSE", nseTokens); +// payload.put("exchangeTokens", exchangeTokens); +// JSONObject response = smartConnect.marketData(payload); +// } +// +// +// +// public void tickerUsage(String clientId, String feedToken, String strWatchListScript, String task) +// throws SmartAPIException { +// +// SmartAPITicker tickerProvider = new SmartAPITicker(clientId, feedToken, strWatchListScript, task); +// +// tickerProvider.setOnConnectedListener(new OnConnect() { +// @Override +// public void onConnected() { +// System.out.println("subscribe() called!"); +// tickerProvider.subscribe(); +// } +// }); +// +// tickerProvider.setOnTickerArrivalListener(new OnTicks() { +// @Override +// public void onTicks(JSONArray ticks) { +// System.out.println("ticker data: " + ticks.toString()); +// } +// }); +// +// /** +// * connects to Smart API 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); +// +// // After using SmartAPI ticker, close websocket connection. +// // tickerProvider.disconnect(); +// +// } +// +// public void smartWebSocketUsage(String clientId, String jwtToken, String apiKey, String actionType, String feedType) +// throws SmartAPIException { +// +// SmartWebsocket smartWebsocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); +// +// smartWebsocket.setOnConnectedListener(new SmartWSOnConnect() { +// +// @Override +// public void onConnected() { +// +// smartWebsocket.runscript(); +// } +// }); +// +// smartWebsocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { +// @Override +// public void onDisconnected() { +// System.out.println("onDisconnected"); +// } +// }); +// +// /** Set error listener to listen to errors. */ +// smartWebsocket.setOnErrorListener(new SmartWSOnError() { +// @Override +// public void onError(Exception exception) { +// System.out.println("onError: " + exception.getMessage()); +// } +// +// @Override +// public void onError(SmartAPIException smartAPIException) { +// System.out.println("onError: " + smartAPIException.getMessage()); +// } +// +// @Override +// public void onError(String error) { +// System.out.println("onError: " + error); +// } +// }); +// +// smartWebsocket.setOnTickerArrivalListener(new SmartWSOnTicks() { +// @Override +// public void onTicks(JSONArray ticks) { +// System.out.println("ticker data: " + ticks.toString()); +// } +// }); +// +// /** +// * connects to Smart API ticker server for getting live quotes +// */ +// smartWebsocket.connect(); +// +// /** +// * You can check, if websocket connection is open or not using the following +// * method. +// */ +// boolean isConnected = smartWebsocket.isConnectionOpen(); +// System.out.println(isConnected); +// +// // After using SmartAPI ticker, close websocket connection. +// // smartWebsocket.disconnect(); +// +// } +// +// /** Logout user. */ +// public void logout(SmartConnect smartConnect) throws SmartAPIException, IOException { +// /** Logout user and kill session. */ +// JSONObject jsonObject = smartConnect.logout(); +// } +// +//} diff --git a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java index f36d841..85f3ed5 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java +++ b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java @@ -1,18 +1,18 @@ -package com.angelbroking.smartapi.sample; - -import com.angelbroking.smartapi.SmartConnect; -import com.angelbroking.smartapi.models.User; - -public class LoginWithTOTPSample { - - public static void main(String[] args) { - String clientID = System.getProperty("clientID"); - String clientPass = System.getProperty("clientPass"); - String apiKey = System.getProperty("apiKey"); - String totp = System.getProperty("totp"); - SmartConnect smartConnect = new SmartConnect(apiKey); - User user = smartConnect.generateSession(clientID, clientPass, totp); - String feedToken = user.getFeedToken(); - System.out.println(feedToken); - } -} +//package com.angelbroking.smartapi.sample; +// +//import com.angelbroking.smartapi.SmartConnect; +//import com.angelbroking.smartapi.models.User; +// +//public class LoginWithTOTPSample { +// +// public static void main(String[] args) { +// String clientID = System.getProperty("clientID"); +// String clientPass = System.getProperty("clientPass"); +// String apiKey = System.getProperty("apiKey"); +// String totp = System.getProperty("totp"); +// SmartConnect smartConnect = new SmartConnect(apiKey); +// User user = smartConnect.generateSession(clientID, clientPass, totp); +// String feedToken = user.getFeedToken(); +// System.out.println(feedToken); +// } +//} diff --git a/src/main/java/com/angelbroking/smartapi/sample/Test.java b/src/main/java/com/angelbroking/smartapi/sample/Test.java index 6ef34e0..8fb5fc3 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/Test.java +++ b/src/main/java/com/angelbroking/smartapi/sample/Test.java @@ -1,125 +1,125 @@ -package com.angelbroking.smartapi.sample; - -import com.angelbroking.smartapi.SmartConnect; -import com.angelbroking.smartapi.http.exceptions.SmartAPIException; -import com.angelbroking.smartapi.models.User; - -public class Test { - - public static void main(String[] args) throws SmartAPIException { - try { - - SmartConnect smartConnect = new SmartConnect(""); // PROVIDE YOUR API KEY HERE - - /* - * OPTIONAL - ACCESS_TOKEN AND REFRESH TOKEN SmartConnect smartConnect = new - * SmartConnect("", "", ""); - */ - - /* - * Set session expiry callback. smartConnect.setSessionExpiryHook(new - * SessionExpiryHook() { - * - * @Override public void sessionExpired() { - * System.out.println("session expired"); } }); - * - * User user = smartConnect.generateSession("", ""); - * smartConnect.setAccessToken(user.getAccessToken()); - * smartConnect.setUserId(user.getUserId()); - * - * /* token re-generate - */ - /* - * TokenSet tokenSet = smartConnect.renewAccessToken(user.getAccessToken(), - * user.getRefreshToken()); - * smartConnect.setAccessToken(tokenSet.getAccessToken()); - */ - - Examples examples = new Examples(); - /* System.out.println("getProfile"); */ - examples.getProfile(smartConnect); - - /* System.out.println("placeOrder"); */ - examples.placeOrder(smartConnect); - - /* System.out.println("modifyOrder"); */ - examples.modifyOrder(smartConnect); - - /* System.out.println("cancelOrder"); */ - examples.cancelOrder(smartConnect); - - /* System.out.println("getOrder"); */ - examples.getOrder(smartConnect); - - /* System.out.println("getLTP"); */ - examples.getLTP(smartConnect); - - /* System.out.println("getTrades"); */ - examples.getTrades(smartConnect); - - /* System.out.println("getRMS"); */ - examples.getRMS(smartConnect); - - /* System.out.println("getHolding"); */ - examples.getHolding(smartConnect); - - /* System.out.println("getPosition"); */ - examples.getPosition(smartConnect); - - /* System.out.println("convertPosition"); */ - examples.convertPosition(smartConnect); - - /* System.out.println("createRule"); */ - examples.createRule(smartConnect); - - /* System.out.println("ModifyRule"); */ - examples.modifyRule(smartConnect); - - /* System.out.println("cancelRule"); */ - examples.cancelRule(smartConnect); - - /* System.out.println("Rule Details"); */ - examples.ruleDetails(smartConnect); - - /* System.out.println("Rule List"); */ - examples.ruleList(smartConnect); - - /* System.out.println("Historic candle Data"); */ - examples.getCandleData(smartConnect); - - - /* System.out.println("Search script api"); */ - examples.getSearchScrip(smartConnect); - - /* System.out.println("Market Data"); */ - examples.getMarketData(smartConnect); - - - /* System.out.println("logout"); */ - examples.logout(smartConnect); - - /* SmartAPITicker */ - String clientId = ""; - User user = smartConnect.generateSession("", "", ""); - String feedToken = user.getFeedToken(); - String strWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658"; - String task = "mw"; - - examples.tickerUsage(clientId, feedToken, strWatchListScript, task); - - /* - * String jwtToken = user.getAccessToken(); String apiKey = "smartapi_key"; - * String actionType = "subscribe"; String feedType = "order_feed"; - * - * examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType, - * feedType); - * - */ - - } catch (Exception e) { - System.out.println("Exception: " + e.getMessage()); - e.printStackTrace(); - } - - } -} \ No newline at end of file + //package com.angelbroking.smartapi.sample; + // + //import com.angelbroking.smartapi.SmartConnect; + //import com.angelbroking.smartapi.http.exceptions.SmartAPIException; + //import com.angelbroking.smartapi.models.User; + // + //public class Test { + // + // public static void main(String[] args) throws SmartAPIException { + // try { + // + // SmartConnect smartConnect = new SmartConnect(""); // PROVIDE YOUR API KEY HERE + // + // /* + // * OPTIONAL - ACCESS_TOKEN AND REFRESH TOKEN SmartConnect smartConnect = new + // * SmartConnect("", "", ""); + // */ + // + // /* + // * Set session expiry callback. smartConnect.setSessionExpiryHook(new + // * SessionExpiryHook() { + // * + // * @Override public void sessionExpired() { + // * System.out.println("session expired"); } }); + // * + // * User user = smartConnect.generateSession("", ""); + // * smartConnect.setAccessToken(user.getAccessToken()); + // * smartConnect.setUserId(user.getUserId()); + // * + // * /* token re-generate + // */ + // /* + // * TokenSet tokenSet = smartConnect.renewAccessToken(user.getAccessToken(), + // * user.getRefreshToken()); + // * smartConnect.setAccessToken(tokenSet.getAccessToken()); + // */ + // + // Examples examples = new Examples(); + // /* System.out.println("getProfile"); */ + // examples.getProfile(smartConnect); + // + // /* System.out.println("placeOrder"); */ + // examples.placeOrder(smartConnect); + // + // /* System.out.println("modifyOrder"); */ + // examples.modifyOrder(smartConnect); + // + // /* System.out.println("cancelOrder"); */ + // examples.cancelOrder(smartConnect); + // + // /* System.out.println("getOrder"); */ + // examples.getOrder(smartConnect); + // + // /* System.out.println("getLTP"); */ + // examples.getLTP(smartConnect); + // + // /* System.out.println("getTrades"); */ + // examples.getTrades(smartConnect); + // + // /* System.out.println("getRMS"); */ + // examples.getRMS(smartConnect); + // + // /* System.out.println("getHolding"); */ + // examples.getHolding(smartConnect); + // + // /* System.out.println("getPosition"); */ + // examples.getPosition(smartConnect); + // + // /* System.out.println("convertPosition"); */ + // examples.convertPosition(smartConnect); + // + // /* System.out.println("createRule"); */ + // examples.createRule(smartConnect); + // + // /* System.out.println("ModifyRule"); */ + // examples.modifyRule(smartConnect); + // + // /* System.out.println("cancelRule"); */ + // examples.cancelRule(smartConnect); + // + // /* System.out.println("Rule Details"); */ + // examples.ruleDetails(smartConnect); + // + // /* System.out.println("Rule List"); */ + // examples.ruleList(smartConnect); + // + // /* System.out.println("Historic candle Data"); */ + // examples.getCandleData(smartConnect); + // + // + // /* System.out.println("Search script api"); */ + // examples.getSearchScrip(smartConnect); + // + // /* System.out.println("Market Data"); */ + // examples.getMarketData(smartConnect); + // + // + // /* System.out.println("logout"); */ + // examples.logout(smartConnect); + // + // /* SmartAPITicker */ + // String clientId = ""; + // User user = smartConnect.generateSession("", "", ""); + // String feedToken = user.getFeedToken(); + // String strWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658"; + // String task = "mw"; + // + // examples.tickerUsage(clientId, feedToken, strWatchListScript, task); + // + // /* + // * String jwtToken = user.getAccessToken(); String apiKey = "smartapi_key"; + // * String actionType = "subscribe"; String feedType = "order_feed"; + // * + // * examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType, + // * feedType); + // * + // */ + // + // } catch (Exception e) { + // System.out.println("Exception: " + e.getMessage()); + // e.printStackTrace(); + // } + // + // } + //} \ No newline at end of file diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java deleted file mode 100644 index 3ab27ed..0000000 --- a/src/test/java/com/angelbroking/smartapi/SmartApiResponseHandlerTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.angelbroking.smartapi; - -import com.angelbroking.smartapi.http.SmartAPIResponseHandler; -import com.angelbroking.smartapi.http.exceptions.SmartAPIException; -import okhttp3.Response; -import org.json.JSONObject; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class SmartApiResponseHandlerTest { - - - - @Test - public void testSmartApiResponseHandlerResponse() { - Response response = mock(Response.class); - when(response.header("Content-Type")).thenReturn("application/json"); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("status", "success"); - - try { - SmartAPIResponseHandler smartAPIResponseHandler = new SmartAPIResponseHandler(); - JSONObject result = smartAPIResponseHandler.handle(response, jsonObject.toString()); - assertNotNull(result); - } catch (SmartAPIException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - -} diff --git a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java deleted file mode 100644 index b973482..0000000 --- a/src/test/java/com/angelbroking/smartapi/SmartWebSocketTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.angelbroking.smartapi; - -import com.angelbroking.smartapi.http.exceptions.SmartAPIException; -import com.angelbroking.smartapi.smartTicker.*; -import org.json.JSONArray; -import org.junit.jupiter.api.Test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class SmartWebSocketTest { - @Test - public void testWebSocketWithAllFields() { - // Arrange - String clientId = "123"; - String jwtToken = "token"; - String apiKey = "key"; - String actionType = "action"; - String feedType = "feed"; - - // Act - SmartWebsocket websocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); - - // Assert - assertNotNull(websocket); - } - - @Test - public void testSetListener() { - // Arrange - SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed"); - - // Act - websocket.setOnErrorListener(new SmartWSOnError() { - @Override - public void onError(Exception exception) {} - - @Override - public void onError(SmartAPIException smartAPIException) {} - - @Override - public void onError(String error) {} - }); - - websocket.setOnTickerArrivalListener(new SmartWSOnTicks() { - @Override - public void onTicks(JSONArray ticks) {} - }); - - websocket.setOnConnectedListener(new SmartWSOnConnect() { - @Override - public void onConnected() {} - }); - - websocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { - @Override - public void onDisconnected() {} - }); - - // Assert - assertNotNull(websocket); - } - - -} diff --git a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java b/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java similarity index 84% rename from src/test/java/com/angelbroking/smartapi/ExceptionTests.java rename to src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java index 33c6807..a1af230 100644 --- a/src/test/java/com/angelbroking/smartapi/ExceptionTests.java +++ b/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java @@ -1,6 +1,7 @@ -package com.angelbroking.smartapi; +package com.angelbroking.smartapi.exceptions; import com.angelbroking.smartapi.http.exceptions.*; +import com.angelbroking.smartapi.smartstream.models.SmartStreamError; import org.junit.jupiter.api.Test; import static org.junit.Assert.assertEquals; @@ -70,4 +71,12 @@ public void testApiKeyException() { assertEquals(message, exception.message); assertEquals(code, exception.code); } + + @Test + public void testSmartStreamError() { + Throwable exception = new Throwable("Test Exception"); + SmartStreamError smartStreamError = new SmartStreamError(); + smartStreamError.setException(exception); + assertEquals(exception, smartStreamError.getException()); + } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java b/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java similarity index 79% rename from src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java rename to src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java index b5d5856..4d9c3f8 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiRequestHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java @@ -1,8 +1,10 @@ -package com.angelbroking.smartapi; +package com.angelbroking.smartapi.http; +import com.angelbroking.smartapi.SmartConnect; import com.angelbroking.smartapi.http.SmartAPIRequestHandler; import com.angelbroking.smartapi.http.exceptions.SmartAPIException; import lombok.extern.slf4j.Slf4j; +import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; @@ -211,5 +213,45 @@ public void test_valid_apiKey_url_accessToken() throws IOException { assertEquals(apiheader.getString("userType"), request.header("X-UserType")); assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID")); } + + @Test + public void testApiHeadersWithValidValues() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + JSONObject headers = handler.apiHeaders(); + + assertNotNull(headers); + assertEquals("127.0.1.1", headers.getString("clientLocalIP")); // chnage according to each machine + assertEquals("103.59.212.254", headers.getString("clientPublicIP")); // chnage according to each machine + assertEquals("02-42-54-06-EC-5D", headers.getString("macAddress")); // chnage according to each machine + assertEquals("application/json", headers.getString("accept")); + assertEquals("USER", headers.getString("userType")); + assertEquals("WEB", headers.getString("sourceID")); + } + + @Test + public void test_createDeleteRequest_withUrlAndParams() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); + String url = "https://example.com/api"; + Map params = new HashMap<>(); + params.put("param1", "value1"); + params.put("param2", "value2"); + String apiKey = "API_KEY"; + String accessToken = "ACCESS_TOKEN"; + + Request request = handler.createDeleteRequest(url, params, apiKey, accessToken); + + assertNotNull(request); + assertEquals("DELETE", request.method()); + assertEquals(url+"?param1=value1¶m2=value2", request.url().toString()); + assertEquals(USER_AGENT, request.header("User-Agent")); + assertEquals("3", request.header("X-SmartAPI-Version")); + assertEquals("token " + apiKey + ":" + accessToken, request.header("Authorization")); + + HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); + for (Map.Entry entry : params.entrySet()) { + httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); + } + assertEquals(httpBuilder.build(), request.url()); + } } diff --git a/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java new file mode 100644 index 0000000..6fd1e57 --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java @@ -0,0 +1,86 @@ +package com.angelbroking.smartapi.http; + +import com.angelbroking.smartapi.http.SmartAPIResponseHandler; +import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import okhttp3.Response; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class SmartApiResponseHandlerTest { + + + + @Test + public void testSmartApiResponseHandlerResponse() { + Response response = mock(Response.class); + when(response.header("Content-Type")).thenReturn("application/json"); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("status", "success"); + + try { + SmartAPIResponseHandler smartAPIResponseHandler = new SmartAPIResponseHandler(); + JSONObject result = smartAPIResponseHandler.handle(response, jsonObject.toString()); + assertNotNull(result); + } catch (SmartAPIException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + + @Test + public void testHandlerForOkStatusCode() throws SmartAPIException, IOException { + // Arrange + Response response = mock(Response.class); + when(response.code()).thenReturn(200); + String body = "{\"status\": true, \"data\": [{\"exchange\": \"NSE\", \"tradingsymbol\": \"INFY\", \"symboltoken\": \"12345\"}]}"; + + SmartAPIResponseHandler handler = new SmartAPIResponseHandler(); + + // Act + String result = handler.handler(response, body); + + // Assert + assertEquals("Search successful. Found 1 trading symbols for the given query:\n1. exchange: NSE, tradingsymbol: INFY, symboltoken: 12345\n", result); + } + + @Test + public void testHandlerMethodForBadRequestStatusResponse() throws SmartAPIException, IOException { + // Arrange + Response response = mock(Response.class); + when(response.code()).thenReturn(400); + + SmartAPIResponseHandler handler = new SmartAPIResponseHandler(); + + // Act + String result = handler.handler(response, ""); + + // Assert + assertEquals("Bad request. Please provide valid input", result); + } + + @Test + public void testHandlerMethodForIllegalArgumentException() { + // Arrange + Response response = mock(Response.class); + when(response.code()).thenReturn(500); + + SmartAPIResponseHandler handler = new SmartAPIResponseHandler(); + + // Act & Assert + assertThrows(IllegalArgumentException.class, () -> { + handler.handler(response, ""); + }); + } +} diff --git a/src/test/java/com/angelbroking/smartapi/ModelTests.java b/src/test/java/com/angelbroking/smartapi/models/ModelTests.java similarity index 97% rename from src/test/java/com/angelbroking/smartapi/ModelTests.java rename to src/test/java/com/angelbroking/smartapi/models/ModelTests.java index ade95f6..5c8b90c 100644 --- a/src/test/java/com/angelbroking/smartapi/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/models/ModelTests.java @@ -1,4 +1,4 @@ -package com.angelbroking.smartapi; +package com.angelbroking.smartapi.models; import com.angelbroking.smartapi.models.*; import com.angelbroking.smartapi.smartstream.models.BestTwentyData; @@ -652,4 +652,21 @@ public void testBESTTwentyData() { assertEquals(5, data.getNumberOfOrders()); } + @Test + public void testGettersAndSettersMethodOfBestTwentyDataModel() { + BestTwentyData data = new BestTwentyData(); + data.setQuantity(10); + data.setPrice(20); + data.setNumberOfOrders((short) 5); + assertEquals(10, data.getQuantity()); + assertEquals(20, data.getPrice()); + assertEquals(5, data.getNumberOfOrders()); + } + + @Test + public void testToStringMethodOfBestTwentyData() { + BestTwentyData data = new BestTwentyData(10, 20, (short) 5); + String expected = "BestTwentyData(quantity=10, price=20, numberOfOrders=5)"; + assertEquals(expected, data.toString()); + } } diff --git a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java b/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java similarity index 99% rename from src/test/java/com/angelbroking/smartapi/SmartConnectTest.java rename to src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java index 3e920ec..d6d6827 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java +++ b/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java @@ -1,5 +1,7 @@ -package com.angelbroking.smartapi; +package com.angelbroking.smartapi.smartconnet; +import com.angelbroking.smartapi.Routes; +import com.angelbroking.smartapi.SmartConnect; import com.angelbroking.smartapi.http.SmartAPIRequestHandler; import com.angelbroking.smartapi.http.exceptions.DataException; import com.angelbroking.smartapi.http.exceptions.SmartAPIException; diff --git a/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java new file mode 100644 index 0000000..a14375f --- /dev/null +++ b/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java @@ -0,0 +1,160 @@ +package com.angelbroking.smartapi.smartticker; + +import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import com.angelbroking.smartapi.smartTicker.*; +import com.neovisionaries.ws.client.WebSocket; +import com.neovisionaries.ws.client.WebSocketAdapter; +import org.json.JSONArray; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.mockito.Mockito.*; + +public class SmartWebSocketTest { + + @Test + public void testWebSocketWithAllFields() { + // Arrange + String clientId = "123"; + String jwtToken = "token"; + String apiKey = "key"; + String actionType = "action"; + String feedType = "feed"; + + // Act + SmartWebsocket websocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); + + // Assert + assertNotNull(websocket); + } + + @Test + public void testSetListener() { + // Arrange + SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed"); + + // Act + websocket.setOnErrorListener(new SmartWSOnError() { + @Override + public void onError(Exception exception) {} + + @Override + public void onError(SmartAPIException smartAPIException) {} + + @Override + public void onError(String error) {} + }); + + websocket.setOnTickerArrivalListener(new SmartWSOnTicks() { + @Override + public void onTicks(JSONArray ticks) {} + }); + + websocket.setOnConnectedListener(new SmartWSOnConnect() { + @Override + public void onConnected() {} + }); + + websocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { + @Override + public void onDisconnected() {} + }); + + // Assert + assertNotNull(websocket); + } + + @Test + public void testSetOnErrorListener_success() throws NoSuchFieldException, IllegalAccessException { + SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType"); + SmartWSOnError listener = new SmartWSOnError() { + @Override + public void onError(Exception exception) {} + + @Override + public void onError(SmartAPIException smartAPIException) {} + + @Override + public void onError(String error) {} + }; + + // Use reflection to access the private field onErrorListener + Field onErrorListenerField = SmartWebsocket.class.getDeclaredField("onErrorListener"); + onErrorListenerField.setAccessible(true); // Make it accessible + onErrorListenerField.set(websocket, listener); // Set the private field with the listener + + SmartWSOnError actualListener = (SmartWSOnError) onErrorListenerField.get(websocket); + + assertEquals(listener, actualListener); + } + + + + @Test + public void test_setOnTickerArrivalListener_validListener() throws NoSuchFieldException, IllegalAccessException { + // Initialize the SmartWebsocket object + SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType"); + + // Create a valid SmartWSOnTicks listener + SmartWSOnTicks listener = new SmartWSOnTicks() { + @Override + public void onTicks(JSONArray ticks) { + // Listener implementation + } + }; + + // Use reflection to access the private field onTickerArrivalListener + Field onTickerArrivalListenerField = SmartWebsocket.class.getDeclaredField("onTickerArrivalListener"); + onTickerArrivalListenerField.setAccessible(true); // Make it accessible + onTickerArrivalListenerField.set(websocket, listener); // Set the private field with the listener + + SmartWSOnTicks actualListener = (SmartWSOnTicks) onTickerArrivalListenerField.get(websocket); + + assertEquals(listener, actualListener); + } + + @Test + public void test_setOnConnectedListener_success() throws NoSuchFieldException, IllegalAccessException { + // Initialize the SmartWebsocket object + SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType"); + + // Create a valid SmartWSOnConnect listener + SmartWSOnConnect listener = new SmartWSOnConnect() { + @Override + public void onConnected() { + // Listener implementation + } + }; + + // Use reflection to access the private field onConnectedListener + Field onConnectedListenerField = SmartWebsocket.class.getDeclaredField("onConnectedListener"); + onConnectedListenerField.setAccessible(true); // Make it accessible + onConnectedListenerField.set(websocket, listener); // Set the private field with the listener + + SmartWSOnConnect actualListener = (SmartWSOnConnect) onConnectedListenerField.get(websocket); + + assertEquals(listener, actualListener); + } + + @Test + public void test_on_connected_listener_called() { + SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType"); + WebSocketAdapter adapter = websocket.getWebsocketAdapter(); + + WebSocket websocketMock = mock(WebSocket.class); + Map> headers = new HashMap<>(); + + SmartWSOnConnect onConnectedListenerMock = mock(SmartWSOnConnect.class); + websocket.setOnConnectedListener(onConnectedListenerMock); + + assertDoesNotThrow(() -> adapter.onConnected(websocketMock, headers)); + verify(onConnectedListenerMock, times(1)).onConnected(); + } + +} diff --git a/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java b/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java similarity index 55% rename from src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java rename to src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java index d3f4f93..ce9197d 100644 --- a/src/test/java/com/angelbroking/smartapi/SmartApiTickerTest.java +++ b/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java @@ -1,13 +1,17 @@ -package com.angelbroking.smartapi; +package com.angelbroking.smartapi.ticker; +import com.angelbroking.smartapi.smartstream.models.BestTwentyData; import com.angelbroking.smartapi.ticker.OnConnect; import com.angelbroking.smartapi.ticker.OnTicks; import com.angelbroking.smartapi.ticker.SmartAPITicker; +import com.angelbroking.smartapi.utils.ByteUtils; import org.json.JSONArray; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import static com.angelbroking.smartapi.utils.Constants.*; import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -76,4 +80,37 @@ public void testUnableToCloseWebSocketConnectionOfSmartAPITicker() { } + @Test + public void testBestTwentyDataMethod() { + ByteBuffer buffer = ByteBuffer.allocate(100000); // for testing + for (int i = 0; i < NUM_PACKETS_FOR_DEPTH; i++) { + int offset = BEST_TWENTY_BUY_DATA_POSITION + (i * PACKET_SIZE_FOR_DEPTH20); + buffer.putInt(offset + QUANTITY_OFFSET_FOR_DEPTH20, 100); + buffer.putInt(offset + PRICE_OFFSET_FOR_DEPTH20, 200); + buffer.putShort(offset + NUMBER_OF_ORDERS_OFFSET_FOR_DEPTH20, (short) 5); + } + + BestTwentyData[] result = ByteUtils.getBestTwentyBuyData(buffer); + + assertEquals(NUM_PACKETS_FOR_DEPTH, result.length); + for (BestTwentyData data : result) { + assertEquals(100, data.getQuantity()); + assertEquals(200, data.getPrice()); + assertEquals(5, data.getNumberOfOrders()); + } + } + + @Test + public void testBestTwentyDataWithNoValues() { + ByteBuffer buffer = ByteBuffer.allocate(10000); + + BestTwentyData[] result = ByteUtils.getBestTwentyBuyData(buffer); + + assertEquals(NUM_PACKETS_FOR_DEPTH, result.length); + for (BestTwentyData data : result) { + assertEquals(0, data.getQuantity()); + assertEquals(0, data.getPrice()); + assertEquals(0, data.getNumberOfOrders()); + } + } } From d587f73712f15bf6381cbba9e1ecad9c0bee6a1a Mon Sep 17 00:00:00 2001 From: ACC Date: Fri, 20 Oct 2023 10:55:19 +0530 Subject: [PATCH 9/9] Test cases added --- .../smartapi/sample/Examples.java | 822 +++++++++--------- .../smartapi/sample/LoginWithTOTPSample.java | 36 +- .../angelbroking/smartapi/sample/Test.java | 250 +++--- .../smartapi/exceptions/ExceptionTests.java | 9 + .../http/SmartApiRequestHandlerTest.java | 12 +- .../http/SmartApiResponseHandlerTest.java | 5 + .../smartapi/models/ModelTests.java | 34 + .../smartconnet/SmartConnectTest.java | 8 + .../smartstream/SmartStreamTickerTest.java | 60 +- .../smartticker/SmartWebSocketTest.java | 10 + .../smartapi/ticker/SmartApiTickerTest.java | 5 + 11 files changed, 644 insertions(+), 607 deletions(-) diff --git a/src/main/java/com/angelbroking/smartapi/sample/Examples.java b/src/main/java/com/angelbroking/smartapi/sample/Examples.java index e61c005..1c60bd5 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/Examples.java +++ b/src/main/java/com/angelbroking/smartapi/sample/Examples.java @@ -1,411 +1,411 @@ -//package com.angelbroking.smartapi.sample; -// -//import com.angelbroking.smartapi.SmartConnect; -//import com.angelbroking.smartapi.http.exceptions.SmartAPIException; -//import com.angelbroking.smartapi.models.Gtt; -//import com.angelbroking.smartapi.models.GttParams; -//import com.angelbroking.smartapi.models.Order; -//import com.angelbroking.smartapi.models.OrderParams; -//import com.angelbroking.smartapi.models.User; -//import com.angelbroking.smartapi.smartTicker.SmartWSOnConnect; -//import com.angelbroking.smartapi.smartTicker.SmartWSOnDisconnect; -//import com.angelbroking.smartapi.smartTicker.SmartWSOnError; -//import com.angelbroking.smartapi.smartTicker.SmartWSOnTicks; -//import com.angelbroking.smartapi.smartTicker.SmartWebsocket; -//import com.angelbroking.smartapi.ticker.OnConnect; -//import com.angelbroking.smartapi.ticker.OnTicks; -//import com.angelbroking.smartapi.ticker.SmartAPITicker; -//import com.angelbroking.smartapi.utils.Constants; -//import org.json.JSONArray; -//import org.json.JSONObject; -// -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.List; -// -//@SuppressWarnings("unused") -//public class Examples { -// -// public void getProfile(SmartConnect smartConnect) throws IOException, SmartAPIException { -// User profile = smartConnect.getProfile(); -// } -// -// /** CONSTANT Details */ -// -// /* VARIETY */ -// /* -// * VARIETY_NORMAL: Normal Order (Regular) -// * VARIETY_AMO: After Market Order -// * VARIETY_STOPLOSS: Stop loss order -// * VARIETY_ROBO: ROBO (Bracket) Order -// */ -// /* TRANSACTION TYPE */ -// /* -// * TRANSACTION_TYPE_BUY: Buy TRANSACTION_TYPE_SELL: Sell -// */ -// -// /* ORDER TYPE */ -// /* -// * ORDER_TYPE_MARKET: Market Order(MKT) -// * ORDER_TYPE_LIMIT: Limit Order(L) -// * ORDER_TYPE_STOPLOSS_LIMIT: Stop Loss Limit Order(SL) -// * ORDER_TYPE_STOPLOSS_MARKET: Stop Loss Market Order(SL-M) -// */ -// -// /* PRODUCT TYPE */ -// /* -// * PRODUCT_DELIVERY: Cash & Carry for equity (CNC) -// * PRODUCT_CARRYFORWARD: Normal -// * for futures and options (NRML) -// * PRODUCT_MARGIN: Margin Delivery -// * PRODUCT_INTRADAY: Margin Intraday Squareoff (MIS) -// * PRODUCT_BO: Bracket Order -// * (Only for ROBO) -// */ -// -// /* DURATION */ -// /* -// * DURATION_DAY: Valid for a day -// * DURATION_IOC: Immediate or Cancel -// */ -// -// /* EXCHANGE */ -// /* -// * EXCHANGE_BSE: BSE Equity -// * EXCHANGE_NSE: NSE Equity -// * EXCHANGE_NFO: NSE Future and Options -// * EXCHANGE_CDS: NSE Currency -// * EXCHANGE_NCDEX: NCDEX Commodity -// * EXCHANGE_MCX: MCX Commodity -// */ -// -// /** Place order. */ -// public void placeOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { -// -// OrderParams orderParams = new OrderParams(); -// orderParams.variety = Constants.VARIETY_STOPLOSS; -// orderParams.quantity = 323; -// orderParams.symboltoken = "1660"; -// orderParams.exchange = Constants.EXCHANGE_NSE; -// orderParams.ordertype = Constants.ORDER_TYPE_STOPLOSS_LIMIT; -// orderParams.tradingsymbol = "ITC-EQ"; -// orderParams.producttype = Constants.PRODUCT_INTRADAY; -// orderParams.duration = Constants.DURATION_DAY; -// orderParams.transactiontype = Constants.TRANSACTION_TYPE_BUY; -// orderParams.price = 122.2; -// orderParams.triggerprice = "209"; -// -// Order order = smartConnect.placeOrder(orderParams, "STOPLOSS"); -// System.out.print(order); -// } -// -// /** Modify order. */ -// public void modifyOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { -// // Order modify request will return order model which will contain only -// -// OrderParams orderParams = new OrderParams(); -// orderParams.quantity = 1; -// orderParams.ordertype = Constants.ORDER_TYPE_LIMIT; -// orderParams.tradingsymbol = "ASHOKLEY"; -// orderParams.symboltoken = "3045"; -// orderParams.producttype = Constants.PRODUCT_DELIVERY; -// orderParams.exchange = Constants.EXCHANGE_NSE; -// orderParams.duration = Constants.DURATION_DAY; -// orderParams.price = 122.2; -// -// String orderId = "201216000755110"; -// Order order = smartConnect.modifyOrder(orderId, orderParams, Constants.VARIETY_NORMAL); -// } -// -// /** Cancel an order */ -// public void cancelOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { -// // Order modify request will return order model which will contain only -// // order_id. -// // Cancel order will return order model which will only have orderId. -// Order order = smartConnect.cancelOrder("201009000000015", Constants.VARIETY_NORMAL); -// } -// -// /** Get order details */ -// public void getOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { -// JSONObject orders = smartConnect.getOrderHistory(smartConnect.getUserId()); -// System.out.print(orders); -//// for (int i = 0; i < orders.size(); i++) { -//// System.out.println(orders.get(i).orderId + " " + orders.get(i).status); -//// } -// } -// -// /** -// * Get last price for multiple instruments at once. USers can either pass -// * exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY -// * 50, BSE:SENSEX} or {256265, 265} -// */ -// public void getLTP(SmartConnect smartConnect) throws SmartAPIException, IOException { -// String exchange = "NSE"; -// String tradingSymbol = "SBIN-EQ"; -// String symboltoken = "3045"; -// JSONObject ltpData = smartConnect.getLTP(exchange, tradingSymbol, symboltoken); -// } -// -// /** Get tradebook */ -// public void getTrades(SmartConnect smartConnect) throws SmartAPIException, IOException { -// // Returns tradebook. -// JSONObject trades = smartConnect.getTrades(); -// -// } -// -// /** Get RMS */ -// public void getRMS(SmartConnect smartConnect) throws SmartAPIException, IOException { -// // Returns RMS. -// JSONObject response = smartConnect.getRMS(); -// } -// -// /** Get Holdings */ -// public void getHolding(SmartConnect smartConnect) throws SmartAPIException, IOException { -// // Returns Holding. -// JSONObject response = smartConnect.getHolding(); -// } -// -// /** Get Position */ -// public void getPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { -// // Returns Position. -// JSONObject response = smartConnect.getPosition(); -// } -// -// /** convert Position */ -// public void convertPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { -// -// JSONObject requestObejct = new JSONObject(); -// requestObejct.put("exchange", "NSE"); -// requestObejct.put("oldproducttype", "DELIVERY"); -// requestObejct.put("newproducttype", "MARGIN"); -// requestObejct.put("tradingsymbol", "SBIN-EQ"); -// requestObejct.put("transactiontype", "BUY"); -// requestObejct.put("quantity", 1); -// requestObejct.put("type", "DAY"); -// -// JSONObject response = smartConnect.convertPosition(requestObejct); -// } -// -// /** Create Gtt Rule */ -// public void createRule(SmartConnect smartConnect) throws SmartAPIException, IOException { -// GttParams gttParams = new GttParams(); -// -// gttParams.tradingsymbol = "SBIN-EQ"; -// gttParams.symboltoken = "3045"; -// gttParams.exchange = "NSE"; -// gttParams.producttype = "MARGIN"; -// gttParams.transactiontype = "BUY"; -// gttParams.price = 100000.01; -// gttParams.qty = 10; -// gttParams.disclosedqty = 10; -// gttParams.triggerprice = 20000.1; -// gttParams.timeperiod = 300; -// -// Gtt gtt = smartConnect.gttCreateRule(gttParams); -// } -// -// /** Modify Gtt Rule */ -// public void modifyRule(SmartConnect smartConnect) throws SmartAPIException, IOException { -// GttParams gttParams = new GttParams(); -// -// gttParams.tradingsymbol = "SBIN-EQ"; -// gttParams.symboltoken = "3045"; -// gttParams.exchange = "NSE"; -// gttParams.producttype = "MARGIN"; -// gttParams.transactiontype = "BUY"; -// gttParams.price = 100000.1; -// gttParams.qty = 10; -// gttParams.disclosedqty = 10; -// gttParams.triggerprice = 20000.1; -// gttParams.timeperiod = 300; -// -// Integer id = 1000051; -// -// Gtt gtt = smartConnect.gttModifyRule(id, gttParams); -// } -// -// /** Cancel Gtt Rule */ -// public void cancelRule(SmartConnect smartConnect) throws SmartAPIException, IOException { -// Integer id = 1000051; -// String symboltoken = "3045"; -// String exchange = "NSE"; -// -// Gtt gtt = smartConnect.gttCancelRule(id, symboltoken, exchange); -// } -// -// /** Gtt Rule Details */ -// public void ruleDetails(SmartConnect smartConnect) throws SmartAPIException, IOException { -// Integer id = 1000051; -// -// JSONObject gtt = smartConnect.gttRuleDetails(id); -// } -// -// /** Gtt Rule Lists */ -// @SuppressWarnings("serial") -// public void ruleList(SmartConnect smartConnect) throws SmartAPIException, IOException { -// -// List status = new ArrayList() { -// { -// add("NEW"); -// add("CANCELLED"); -// add("ACTIVE"); -// add("SENTTOEXCHANGE"); -// add("FORALL"); -// } -// }; -// Integer page = 1; -// Integer count = 10; -// -// JSONArray gtt = smartConnect.gttRuleList(status, page, count); -// } -// -// /** Historic Data */ -// public void getCandleData(SmartConnect smartConnect) throws SmartAPIException, IOException { -// -// JSONObject requestObejct = new JSONObject(); -// requestObejct.put("exchange", "NSE"); -// requestObejct.put("symboltoken", "3045"); -// requestObejct.put("interval", "ONE_MINUTE"); -// requestObejct.put("fromdate", "2021-03-08 09:00"); -// requestObejct.put("todate", "2021-03-09 09:20"); -// -// String response = smartConnect.candleData(requestObejct); -// } -// -// -// /** Search Scrip Data */ -// public void getSearchScrip(SmartConnect smartConnect) throws SmartAPIException, IOException { -// JSONObject payload = new JSONObject(); -// payload.put("exchange", "MCX"); -// payload.put("searchscrip", "Crude"); -// smartConnect.getSearchScrip(payload); -// } -// -// /** -// * Market Data -// * To Retrieve Market Data with different modes use. -// * e.g: -// * payload.put("mode", "FULL"); -// * payload.put("mode", "LTP"); -// * payload.put("mode", "OHLC"); -// */ -// public void getMarketData(SmartConnect smartConnect) throws SmartAPIException, IOException { -// JSONObject payload = new JSONObject(); -// payload.put("mode", "FULL"); // You can change the mode as needed -// JSONObject exchangeTokens = new JSONObject(); -// JSONArray nseTokens = new JSONArray(); -// nseTokens.put("3045"); -// exchangeTokens.put("NSE", nseTokens); -// payload.put("exchangeTokens", exchangeTokens); -// JSONObject response = smartConnect.marketData(payload); -// } -// -// -// -// public void tickerUsage(String clientId, String feedToken, String strWatchListScript, String task) -// throws SmartAPIException { -// -// SmartAPITicker tickerProvider = new SmartAPITicker(clientId, feedToken, strWatchListScript, task); -// -// tickerProvider.setOnConnectedListener(new OnConnect() { -// @Override -// public void onConnected() { -// System.out.println("subscribe() called!"); -// tickerProvider.subscribe(); -// } -// }); -// -// tickerProvider.setOnTickerArrivalListener(new OnTicks() { -// @Override -// public void onTicks(JSONArray ticks) { -// System.out.println("ticker data: " + ticks.toString()); -// } -// }); -// -// /** -// * connects to Smart API 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); -// -// // After using SmartAPI ticker, close websocket connection. -// // tickerProvider.disconnect(); -// -// } -// -// public void smartWebSocketUsage(String clientId, String jwtToken, String apiKey, String actionType, String feedType) -// throws SmartAPIException { -// -// SmartWebsocket smartWebsocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); -// -// smartWebsocket.setOnConnectedListener(new SmartWSOnConnect() { -// -// @Override -// public void onConnected() { -// -// smartWebsocket.runscript(); -// } -// }); -// -// smartWebsocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { -// @Override -// public void onDisconnected() { -// System.out.println("onDisconnected"); -// } -// }); -// -// /** Set error listener to listen to errors. */ -// smartWebsocket.setOnErrorListener(new SmartWSOnError() { -// @Override -// public void onError(Exception exception) { -// System.out.println("onError: " + exception.getMessage()); -// } -// -// @Override -// public void onError(SmartAPIException smartAPIException) { -// System.out.println("onError: " + smartAPIException.getMessage()); -// } -// -// @Override -// public void onError(String error) { -// System.out.println("onError: " + error); -// } -// }); -// -// smartWebsocket.setOnTickerArrivalListener(new SmartWSOnTicks() { -// @Override -// public void onTicks(JSONArray ticks) { -// System.out.println("ticker data: " + ticks.toString()); -// } -// }); -// -// /** -// * connects to Smart API ticker server for getting live quotes -// */ -// smartWebsocket.connect(); -// -// /** -// * You can check, if websocket connection is open or not using the following -// * method. -// */ -// boolean isConnected = smartWebsocket.isConnectionOpen(); -// System.out.println(isConnected); -// -// // After using SmartAPI ticker, close websocket connection. -// // smartWebsocket.disconnect(); -// -// } -// -// /** Logout user. */ -// public void logout(SmartConnect smartConnect) throws SmartAPIException, IOException { -// /** Logout user and kill session. */ -// JSONObject jsonObject = smartConnect.logout(); -// } -// -//} +package com.angelbroking.smartapi.sample; + +import com.angelbroking.smartapi.SmartConnect; +import com.angelbroking.smartapi.http.exceptions.SmartAPIException; +import com.angelbroking.smartapi.models.Gtt; +import com.angelbroking.smartapi.models.GttParams; +import com.angelbroking.smartapi.models.Order; +import com.angelbroking.smartapi.models.OrderParams; +import com.angelbroking.smartapi.models.User; +import com.angelbroking.smartapi.smartTicker.SmartWSOnConnect; +import com.angelbroking.smartapi.smartTicker.SmartWSOnDisconnect; +import com.angelbroking.smartapi.smartTicker.SmartWSOnError; +import com.angelbroking.smartapi.smartTicker.SmartWSOnTicks; +import com.angelbroking.smartapi.smartTicker.SmartWebsocket; +import com.angelbroking.smartapi.ticker.OnConnect; +import com.angelbroking.smartapi.ticker.OnTicks; +import com.angelbroking.smartapi.ticker.SmartAPITicker; +import com.angelbroking.smartapi.utils.Constants; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings("unused") +public class Examples { + + public void getProfile(SmartConnect smartConnect) throws IOException, SmartAPIException { + User profile = smartConnect.getProfile(); + } + + /** CONSTANT Details */ + + /* VARIETY */ + /* + * VARIETY_NORMAL: Normal Order (Regular) + * VARIETY_AMO: After Market Order + * VARIETY_STOPLOSS: Stop loss order + * VARIETY_ROBO: ROBO (Bracket) Order + */ + /* TRANSACTION TYPE */ + /* + * TRANSACTION_TYPE_BUY: Buy TRANSACTION_TYPE_SELL: Sell + */ + + /* ORDER TYPE */ + /* + * ORDER_TYPE_MARKET: Market Order(MKT) + * ORDER_TYPE_LIMIT: Limit Order(L) + * ORDER_TYPE_STOPLOSS_LIMIT: Stop Loss Limit Order(SL) + * ORDER_TYPE_STOPLOSS_MARKET: Stop Loss Market Order(SL-M) + */ + + /* PRODUCT TYPE */ + /* + * PRODUCT_DELIVERY: Cash & Carry for equity (CNC) + * PRODUCT_CARRYFORWARD: Normal + * for futures and options (NRML) + * PRODUCT_MARGIN: Margin Delivery + * PRODUCT_INTRADAY: Margin Intraday Squareoff (MIS) + * PRODUCT_BO: Bracket Order + * (Only for ROBO) + */ + + /* DURATION */ + /* + * DURATION_DAY: Valid for a day + * DURATION_IOC: Immediate or Cancel + */ + + /* EXCHANGE */ + /* + * EXCHANGE_BSE: BSE Equity + * EXCHANGE_NSE: NSE Equity + * EXCHANGE_NFO: NSE Future and Options + * EXCHANGE_CDS: NSE Currency + * EXCHANGE_NCDEX: NCDEX Commodity + * EXCHANGE_MCX: MCX Commodity + */ + + /** Place order. */ + public void placeOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { + + OrderParams orderParams = new OrderParams(); + orderParams.variety = Constants.VARIETY_STOPLOSS; + orderParams.quantity = 323; + orderParams.symboltoken = "1660"; + orderParams.exchange = Constants.EXCHANGE_NSE; + orderParams.ordertype = Constants.ORDER_TYPE_STOPLOSS_LIMIT; + orderParams.tradingsymbol = "ITC-EQ"; + orderParams.producttype = Constants.PRODUCT_INTRADAY; + orderParams.duration = Constants.DURATION_DAY; + orderParams.transactiontype = Constants.TRANSACTION_TYPE_BUY; + orderParams.price = 122.2; + orderParams.triggerprice = "209"; + + Order order = smartConnect.placeOrder(orderParams, "STOPLOSS"); + System.out.print(order); + } + + /** Modify order. */ + public void modifyOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { + // Order modify request will return order model which will contain only + + OrderParams orderParams = new OrderParams(); + orderParams.quantity = 1; + orderParams.ordertype = Constants.ORDER_TYPE_LIMIT; + orderParams.tradingsymbol = "ASHOKLEY"; + orderParams.symboltoken = "3045"; + orderParams.producttype = Constants.PRODUCT_DELIVERY; + orderParams.exchange = Constants.EXCHANGE_NSE; + orderParams.duration = Constants.DURATION_DAY; + orderParams.price = 122.2; + + String orderId = "201216000755110"; + Order order = smartConnect.modifyOrder(orderId, orderParams, Constants.VARIETY_NORMAL); + } + + /** Cancel an order */ + public void cancelOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { + // Order modify request will return order model which will contain only + // order_id. + // Cancel order will return order model which will only have orderId. + Order order = smartConnect.cancelOrder("201009000000015", Constants.VARIETY_NORMAL); + } + + /** Get order details */ + public void getOrder(SmartConnect smartConnect) throws SmartAPIException, IOException { + JSONObject orders = smartConnect.getOrderHistory(smartConnect.getUserId()); + System.out.print(orders); +// for (int i = 0; i < orders.size(); i++) { +// System.out.println(orders.get(i).orderId + " " + orders.get(i).status); +// } + } + + /** + * Get last price for multiple instruments at once. USers can either pass + * exchange with tradingsymbol or instrument token only. For example {NSE:NIFTY + * 50, BSE:SENSEX} or {256265, 265} + */ + public void getLTP(SmartConnect smartConnect) throws SmartAPIException, IOException { + String exchange = "NSE"; + String tradingSymbol = "SBIN-EQ"; + String symboltoken = "3045"; + JSONObject ltpData = smartConnect.getLTP(exchange, tradingSymbol, symboltoken); + } + + /** Get tradebook */ + public void getTrades(SmartConnect smartConnect) throws SmartAPIException, IOException { + // Returns tradebook. + JSONObject trades = smartConnect.getTrades(); + + } + + /** Get RMS */ + public void getRMS(SmartConnect smartConnect) throws SmartAPIException, IOException { + // Returns RMS. + JSONObject response = smartConnect.getRMS(); + } + + /** Get Holdings */ + public void getHolding(SmartConnect smartConnect) throws SmartAPIException, IOException { + // Returns Holding. + JSONObject response = smartConnect.getHolding(); + } + + /** Get Position */ + public void getPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { + // Returns Position. + JSONObject response = smartConnect.getPosition(); + } + + /** convert Position */ + public void convertPosition(SmartConnect smartConnect) throws SmartAPIException, IOException { + + JSONObject requestObejct = new JSONObject(); + requestObejct.put("exchange", "NSE"); + requestObejct.put("oldproducttype", "DELIVERY"); + requestObejct.put("newproducttype", "MARGIN"); + requestObejct.put("tradingsymbol", "SBIN-EQ"); + requestObejct.put("transactiontype", "BUY"); + requestObejct.put("quantity", 1); + requestObejct.put("type", "DAY"); + + JSONObject response = smartConnect.convertPosition(requestObejct); + } + + /** Create Gtt Rule */ + public void createRule(SmartConnect smartConnect) throws SmartAPIException, IOException { + GttParams gttParams = new GttParams(); + + gttParams.tradingsymbol = "SBIN-EQ"; + gttParams.symboltoken = "3045"; + gttParams.exchange = "NSE"; + gttParams.producttype = "MARGIN"; + gttParams.transactiontype = "BUY"; + gttParams.price = 100000.01; + gttParams.qty = 10; + gttParams.disclosedqty = 10; + gttParams.triggerprice = 20000.1; + gttParams.timeperiod = 300; + + Gtt gtt = smartConnect.gttCreateRule(gttParams); + } + + /** Modify Gtt Rule */ + public void modifyRule(SmartConnect smartConnect) throws SmartAPIException, IOException { + GttParams gttParams = new GttParams(); + + gttParams.tradingsymbol = "SBIN-EQ"; + gttParams.symboltoken = "3045"; + gttParams.exchange = "NSE"; + gttParams.producttype = "MARGIN"; + gttParams.transactiontype = "BUY"; + gttParams.price = 100000.1; + gttParams.qty = 10; + gttParams.disclosedqty = 10; + gttParams.triggerprice = 20000.1; + gttParams.timeperiod = 300; + + Integer id = 1000051; + + Gtt gtt = smartConnect.gttModifyRule(id, gttParams); + } + + /** Cancel Gtt Rule */ + public void cancelRule(SmartConnect smartConnect) throws SmartAPIException, IOException { + Integer id = 1000051; + String symboltoken = "3045"; + String exchange = "NSE"; + + Gtt gtt = smartConnect.gttCancelRule(id, symboltoken, exchange); + } + + /** Gtt Rule Details */ + public void ruleDetails(SmartConnect smartConnect) throws SmartAPIException, IOException { + Integer id = 1000051; + + JSONObject gtt = smartConnect.gttRuleDetails(id); + } + + /** Gtt Rule Lists */ + @SuppressWarnings("serial") + public void ruleList(SmartConnect smartConnect) throws SmartAPIException, IOException { + + List status = new ArrayList() { + { + add("NEW"); + add("CANCELLED"); + add("ACTIVE"); + add("SENTTOEXCHANGE"); + add("FORALL"); + } + }; + Integer page = 1; + Integer count = 10; + + JSONArray gtt = smartConnect.gttRuleList(status, page, count); + } + + /** Historic Data */ + public void getCandleData(SmartConnect smartConnect) throws SmartAPIException, IOException { + + JSONObject requestObejct = new JSONObject(); + requestObejct.put("exchange", "NSE"); + requestObejct.put("symboltoken", "3045"); + requestObejct.put("interval", "ONE_MINUTE"); + requestObejct.put("fromdate", "2021-03-08 09:00"); + requestObejct.put("todate", "2021-03-09 09:20"); + + String response = smartConnect.candleData(requestObejct); + } + + + /** Search Scrip Data */ + public void getSearchScrip(SmartConnect smartConnect) throws SmartAPIException, IOException { + JSONObject payload = new JSONObject(); + payload.put("exchange", "MCX"); + payload.put("searchscrip", "Crude"); + smartConnect.getSearchScrip(payload); + } + + /** + * Market Data + * To Retrieve Market Data with different modes use. + * e.g: + * payload.put("mode", "FULL"); + * payload.put("mode", "LTP"); + * payload.put("mode", "OHLC"); + */ + public void getMarketData(SmartConnect smartConnect) throws SmartAPIException, IOException { + JSONObject payload = new JSONObject(); + payload.put("mode", "FULL"); // You can change the mode as needed + JSONObject exchangeTokens = new JSONObject(); + JSONArray nseTokens = new JSONArray(); + nseTokens.put("3045"); + exchangeTokens.put("NSE", nseTokens); + payload.put("exchangeTokens", exchangeTokens); + JSONObject response = smartConnect.marketData(payload); + } + + + + public void tickerUsage(String clientId, String feedToken, String strWatchListScript, String task) + throws SmartAPIException { + + SmartAPITicker tickerProvider = new SmartAPITicker(clientId, feedToken, strWatchListScript, task); + + tickerProvider.setOnConnectedListener(new OnConnect() { + @Override + public void onConnected() { + System.out.println("subscribe() called!"); + tickerProvider.subscribe(); + } + }); + + tickerProvider.setOnTickerArrivalListener(new OnTicks() { + @Override + public void onTicks(JSONArray ticks) { + System.out.println("ticker data: " + ticks.toString()); + } + }); + + /** + * connects to Smart API 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); + + // After using SmartAPI ticker, close websocket connection. + // tickerProvider.disconnect(); + + } + + public void smartWebSocketUsage(String clientId, String jwtToken, String apiKey, String actionType, String feedType) + throws SmartAPIException { + + SmartWebsocket smartWebsocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType); + + smartWebsocket.setOnConnectedListener(new SmartWSOnConnect() { + + @Override + public void onConnected() { + + smartWebsocket.runscript(); + } + }); + + smartWebsocket.setOnDisconnectedListener(new SmartWSOnDisconnect() { + @Override + public void onDisconnected() { + System.out.println("onDisconnected"); + } + }); + + /** Set error listener to listen to errors. */ + smartWebsocket.setOnErrorListener(new SmartWSOnError() { + @Override + public void onError(Exception exception) { + System.out.println("onError: " + exception.getMessage()); + } + + @Override + public void onError(SmartAPIException smartAPIException) { + System.out.println("onError: " + smartAPIException.getMessage()); + } + + @Override + public void onError(String error) { + System.out.println("onError: " + error); + } + }); + + smartWebsocket.setOnTickerArrivalListener(new SmartWSOnTicks() { + @Override + public void onTicks(JSONArray ticks) { + System.out.println("ticker data: " + ticks.toString()); + } + }); + + /** + * connects to Smart API ticker server for getting live quotes + */ + smartWebsocket.connect(); + + /** + * You can check, if websocket connection is open or not using the following + * method. + */ + boolean isConnected = smartWebsocket.isConnectionOpen(); + System.out.println(isConnected); + + // After using SmartAPI ticker, close websocket connection. + // smartWebsocket.disconnect(); + + } + + /** Logout user. */ + public void logout(SmartConnect smartConnect) throws SmartAPIException, IOException { + /** Logout user and kill session. */ + JSONObject jsonObject = smartConnect.logout(); + } + +} diff --git a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java index 85f3ed5..f36d841 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java +++ b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java @@ -1,18 +1,18 @@ -//package com.angelbroking.smartapi.sample; -// -//import com.angelbroking.smartapi.SmartConnect; -//import com.angelbroking.smartapi.models.User; -// -//public class LoginWithTOTPSample { -// -// public static void main(String[] args) { -// String clientID = System.getProperty("clientID"); -// String clientPass = System.getProperty("clientPass"); -// String apiKey = System.getProperty("apiKey"); -// String totp = System.getProperty("totp"); -// SmartConnect smartConnect = new SmartConnect(apiKey); -// User user = smartConnect.generateSession(clientID, clientPass, totp); -// String feedToken = user.getFeedToken(); -// System.out.println(feedToken); -// } -//} +package com.angelbroking.smartapi.sample; + +import com.angelbroking.smartapi.SmartConnect; +import com.angelbroking.smartapi.models.User; + +public class LoginWithTOTPSample { + + public static void main(String[] args) { + String clientID = System.getProperty("clientID"); + String clientPass = System.getProperty("clientPass"); + String apiKey = System.getProperty("apiKey"); + String totp = System.getProperty("totp"); + SmartConnect smartConnect = new SmartConnect(apiKey); + User user = smartConnect.generateSession(clientID, clientPass, totp); + String feedToken = user.getFeedToken(); + System.out.println(feedToken); + } +} diff --git a/src/main/java/com/angelbroking/smartapi/sample/Test.java b/src/main/java/com/angelbroking/smartapi/sample/Test.java index 8fb5fc3..1d07fbf 100644 --- a/src/main/java/com/angelbroking/smartapi/sample/Test.java +++ b/src/main/java/com/angelbroking/smartapi/sample/Test.java @@ -1,125 +1,125 @@ - //package com.angelbroking.smartapi.sample; - // - //import com.angelbroking.smartapi.SmartConnect; - //import com.angelbroking.smartapi.http.exceptions.SmartAPIException; - //import com.angelbroking.smartapi.models.User; - // - //public class Test { - // - // public static void main(String[] args) throws SmartAPIException { - // try { - // - // SmartConnect smartConnect = new SmartConnect(""); // PROVIDE YOUR API KEY HERE - // - // /* - // * OPTIONAL - ACCESS_TOKEN AND REFRESH TOKEN SmartConnect smartConnect = new - // * SmartConnect("", "", ""); - // */ - // - // /* - // * Set session expiry callback. smartConnect.setSessionExpiryHook(new - // * SessionExpiryHook() { - // * - // * @Override public void sessionExpired() { - // * System.out.println("session expired"); } }); - // * - // * User user = smartConnect.generateSession("", ""); - // * smartConnect.setAccessToken(user.getAccessToken()); - // * smartConnect.setUserId(user.getUserId()); - // * - // * /* token re-generate - // */ - // /* - // * TokenSet tokenSet = smartConnect.renewAccessToken(user.getAccessToken(), - // * user.getRefreshToken()); - // * smartConnect.setAccessToken(tokenSet.getAccessToken()); - // */ - // - // Examples examples = new Examples(); - // /* System.out.println("getProfile"); */ - // examples.getProfile(smartConnect); - // - // /* System.out.println("placeOrder"); */ - // examples.placeOrder(smartConnect); - // - // /* System.out.println("modifyOrder"); */ - // examples.modifyOrder(smartConnect); - // - // /* System.out.println("cancelOrder"); */ - // examples.cancelOrder(smartConnect); - // - // /* System.out.println("getOrder"); */ - // examples.getOrder(smartConnect); - // - // /* System.out.println("getLTP"); */ - // examples.getLTP(smartConnect); - // - // /* System.out.println("getTrades"); */ - // examples.getTrades(smartConnect); - // - // /* System.out.println("getRMS"); */ - // examples.getRMS(smartConnect); - // - // /* System.out.println("getHolding"); */ - // examples.getHolding(smartConnect); - // - // /* System.out.println("getPosition"); */ - // examples.getPosition(smartConnect); - // - // /* System.out.println("convertPosition"); */ - // examples.convertPosition(smartConnect); - // - // /* System.out.println("createRule"); */ - // examples.createRule(smartConnect); - // - // /* System.out.println("ModifyRule"); */ - // examples.modifyRule(smartConnect); - // - // /* System.out.println("cancelRule"); */ - // examples.cancelRule(smartConnect); - // - // /* System.out.println("Rule Details"); */ - // examples.ruleDetails(smartConnect); - // - // /* System.out.println("Rule List"); */ - // examples.ruleList(smartConnect); - // - // /* System.out.println("Historic candle Data"); */ - // examples.getCandleData(smartConnect); - // - // - // /* System.out.println("Search script api"); */ - // examples.getSearchScrip(smartConnect); - // - // /* System.out.println("Market Data"); */ - // examples.getMarketData(smartConnect); - // - // - // /* System.out.println("logout"); */ - // examples.logout(smartConnect); - // - // /* SmartAPITicker */ - // String clientId = ""; - // User user = smartConnect.generateSession("", "", ""); - // String feedToken = user.getFeedToken(); - // String strWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658"; - // String task = "mw"; - // - // examples.tickerUsage(clientId, feedToken, strWatchListScript, task); - // - // /* - // * String jwtToken = user.getAccessToken(); String apiKey = "smartapi_key"; - // * String actionType = "subscribe"; String feedType = "order_feed"; - // * - // * examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType, - // * feedType); - // * - // */ - // - // } catch (Exception e) { - // System.out.println("Exception: " + e.getMessage()); - // e.printStackTrace(); - // } - // - // } - //} \ No newline at end of file + package com.angelbroking.smartapi.sample; + + import com.angelbroking.smartapi.SmartConnect; + import com.angelbroking.smartapi.http.exceptions.SmartAPIException; + import com.angelbroking.smartapi.models.User; + + public class Test { + + public static void main(String[] args) throws SmartAPIException { + try { + + SmartConnect smartConnect = new SmartConnect(""); // PROVIDE YOUR API KEY HERE + + /* + * OPTIONAL - ACCESS_TOKEN AND REFRESH TOKEN SmartConnect smartConnect = new + * SmartConnect("", "", ""); + */ + + /* + * Set session expiry callback. smartConnect.setSessionExpiryHook(new + * SessionExpiryHook() { + * + * @Override public void sessionExpired() { + * System.out.println("session expired"); } }); + * + * User user = smartConnect.generateSession("", ""); + * smartConnect.setAccessToken(user.getAccessToken()); + * smartConnect.setUserId(user.getUserId()); + * + * /* token re-generate + */ + /* + * TokenSet tokenSet = smartConnect.renewAccessToken(user.getAccessToken(), + * user.getRefreshToken()); + * smartConnect.setAccessToken(tokenSet.getAccessToken()); + */ + + Examples examples = new Examples(); + /* System.out.println("getProfile"); */ + examples.getProfile(smartConnect); + + /* System.out.println("placeOrder"); */ + examples.placeOrder(smartConnect); + + /* System.out.println("modifyOrder"); */ + examples.modifyOrder(smartConnect); + + /* System.out.println("cancelOrder"); */ + examples.cancelOrder(smartConnect); + + /* System.out.println("getOrder"); */ + examples.getOrder(smartConnect); + + /* System.out.println("getLTP"); */ + examples.getLTP(smartConnect); + + /* System.out.println("getTrades"); */ + examples.getTrades(smartConnect); + + /* System.out.println("getRMS"); */ + examples.getRMS(smartConnect); + + /* System.out.println("getHolding"); */ + examples.getHolding(smartConnect); + + /* System.out.println("getPosition"); */ + examples.getPosition(smartConnect); + + /* System.out.println("convertPosition"); */ + examples.convertPosition(smartConnect); + + /* System.out.println("createRule"); */ + examples.createRule(smartConnect); + + /* System.out.println("ModifyRule"); */ + examples.modifyRule(smartConnect); + + /* System.out.println("cancelRule"); */ + examples.cancelRule(smartConnect); + + /* System.out.println("Rule Details"); */ + examples.ruleDetails(smartConnect); + + /* System.out.println("Rule List"); */ + examples.ruleList(smartConnect); + + /* System.out.println("Historic candle Data"); */ + examples.getCandleData(smartConnect); + + + /* System.out.println("Search script api"); */ + examples.getSearchScrip(smartConnect); + + /* System.out.println("Market Data"); */ + examples.getMarketData(smartConnect); + + + /* System.out.println("logout"); */ + examples.logout(smartConnect); + + /* SmartAPITicker */ + String clientId = ""; + User user = smartConnect.generateSession("", "", ""); + String feedToken = user.getFeedToken(); + String strWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658"; + String task = "mw"; + + examples.tickerUsage(clientId, feedToken, strWatchListScript, task); + + /* + * String jwtToken = user.getAccessToken(); String apiKey = "smartapi_key"; + * String actionType = "subscribe"; String feedType = "order_feed"; + * + * examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType, + * feedType); + * + */ + + } catch (Exception e) { + System.out.println("Exception: " + e.getMessage()); + e.printStackTrace(); + } + + } + } \ No newline at end of file diff --git a/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java b/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java index a1af230..c32e928 100644 --- a/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java +++ b/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java @@ -9,6 +9,7 @@ public class ExceptionTests { @Test public void testDataException() { + String message = "Test Message"; String code = "Test Code"; DataException exception = new DataException(message, code); @@ -18,6 +19,7 @@ public void testDataException() { @Test public void testGeneralException() { + String message = "Test Message"; String code = "123"; GeneralException exception = new GeneralException(message, code); @@ -28,6 +30,7 @@ public void testGeneralException() { @Test public void testInputException() { + InputException exception = new InputException("Test message", "Test code"); assertEquals("Test message", exception.message); assertEquals("Test code", exception.code); @@ -35,6 +38,7 @@ public void testInputException() { @Test public void testNetworkException() { + NetworkException exception = new NetworkException("Test message", "Test code"); assertEquals("Test message", exception.message); assertEquals("Test code", exception.code); @@ -42,6 +46,7 @@ public void testNetworkException() { @Test public void testOrderException() { + OrderException exception = new OrderException("Test message", "Test code"); assertEquals("Test message", exception.message); assertEquals("Test code", exception.code); @@ -49,6 +54,7 @@ public void testOrderException() { @Test public void testPermissionException() { + PermissionException exception = new PermissionException("Test message", "Test code"); assertEquals("Test message", exception.message); assertEquals("Test code", exception.code); @@ -56,6 +62,7 @@ public void testPermissionException() { @Test public void testTokenException() { + String message = "Test message"; String code = "123"; TokenException tokenException = new TokenException(message, code); @@ -65,6 +72,7 @@ public void testTokenException() { @Test public void testApiKeyException() { + String message = "Invalid API Key"; String code = "123"; ApiKeyException exception = new ApiKeyException(message, code); @@ -74,6 +82,7 @@ public void testApiKeyException() { @Test public void testSmartStreamError() { + Throwable exception = new Throwable("Test Exception"); SmartStreamError smartStreamError = new SmartStreamError(); smartStreamError.setException(exception); diff --git a/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java b/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java index 4d9c3f8..1413946 100644 --- a/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java @@ -32,6 +32,7 @@ public class SmartApiRequestHandlerTest { @Test public void testSmartApiRequestHandlerWithNotNullProxy() { + Proxy proxy = Proxy.NO_PROXY; OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(10000, TimeUnit.MILLISECONDS); @@ -52,6 +53,7 @@ public void testSmartApiRequestHandlerWithNotNullProxy() { @Test public void testSmartApiRequestHandlerWithNullProxy() { + assertThrows(SmartAPIException.class, () -> { Proxy proxy = null; OkHttpClient.Builder builder = new OkHttpClient.Builder(); @@ -71,6 +73,7 @@ public void testSmartApiRequestHandlerWithNullProxy() { @Test public void testApiHeaders() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); JSONObject headers = handler.apiHeaders(); @@ -85,6 +88,7 @@ public void testApiHeaders() { @Test public void testCreateRequestWithAllParameters() { + // Arrange String apiKey = "validApiKey"; String url = "https://example.com/"; @@ -114,6 +118,7 @@ public void testCreateRequestWithAllParameters() { @Test public void testCreateRequestWithApiKeyNull() { + // Arrange String apiKey = null; String url = "https://example.com"; @@ -130,6 +135,7 @@ public void testCreateRequestWithApiKeyNull() { @Test public void testCreateRequestWithUrlNull() { + // Arrange String apiKey = "validApiKey"; String url = null; @@ -152,8 +158,6 @@ public void testCreateRequestWithParamsNull() { JSONObject params = null; SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); - JSONObject apiheader = handler.apiHeaders(); - // Act Request request = handler.createPostRequest(apiKey, url, params); @@ -189,11 +193,13 @@ public void testCreateRequestWithAccessTokenAndAllParameters() { assertEquals(apiheader.getString("accept"), request.header("Accept")); assertEquals(apiheader.getString("userType"), request.header("X-UserType")); assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID")); + } @Test public void test_valid_apiKey_url_accessToken() throws IOException { + String apiKey = "validApiKey"; String url = "https://example.com/api"; String accessToken = "validAccessToken"; @@ -216,6 +222,7 @@ public void test_valid_apiKey_url_accessToken() throws IOException { @Test public void testApiHeadersWithValidValues() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); JSONObject headers = handler.apiHeaders(); @@ -230,6 +237,7 @@ public void testApiHeadersWithValidValues() { @Test public void test_createDeleteRequest_withUrlAndParams() { + SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null); String url = "https://example.com/api"; Map params = new HashMap<>(); diff --git a/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java index 6fd1e57..bea2ed2 100644 --- a/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java +++ b/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java @@ -21,6 +21,7 @@ public class SmartApiResponseHandlerTest { @Test public void testSmartApiResponseHandlerResponse() { + Response response = mock(Response.class); when(response.header("Content-Type")).thenReturn("application/json"); @@ -41,6 +42,7 @@ public void testSmartApiResponseHandlerResponse() { @Test public void testHandlerForOkStatusCode() throws SmartAPIException, IOException { + // Arrange Response response = mock(Response.class); when(response.code()).thenReturn(200); @@ -57,6 +59,7 @@ public void testHandlerForOkStatusCode() throws SmartAPIException, IOException { @Test public void testHandlerMethodForBadRequestStatusResponse() throws SmartAPIException, IOException { + // Arrange Response response = mock(Response.class); when(response.code()).thenReturn(400); @@ -72,6 +75,7 @@ public void testHandlerMethodForBadRequestStatusResponse() throws SmartAPIExcept @Test public void testHandlerMethodForIllegalArgumentException() { + // Arrange Response response = mock(Response.class); when(response.code()).thenReturn(500); @@ -82,5 +86,6 @@ public void testHandlerMethodForIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> { handler.handler(response, ""); }); + } } diff --git a/src/test/java/com/angelbroking/smartapi/models/ModelTests.java b/src/test/java/com/angelbroking/smartapi/models/ModelTests.java index 5c8b90c..fd9aff1 100644 --- a/src/test/java/com/angelbroking/smartapi/models/ModelTests.java +++ b/src/test/java/com/angelbroking/smartapi/models/ModelTests.java @@ -25,6 +25,7 @@ public class ModelTests { /* ---------------- Profile Model Tests------------------------- */ @Test public void testProfileModelWithAllValues() { + Profile profile = new Profile(); profile.setEmail("test@example.com"); profile.setUserName("John Doe"); @@ -41,6 +42,7 @@ public void testProfileModelWithAllValues() { @Test public void testGetEmailForProfileModel() { + Profile profile = new Profile(); profile.setEmail("test@example.com"); @@ -49,6 +51,7 @@ public void testGetEmailForProfileModel() { @Test public void testGetUserNameForProfileModel() { + Profile profile = new Profile(); profile.setUserName("John Doe"); @@ -57,6 +60,7 @@ public void testGetUserNameForProfileModel() { @Test public void testCreateProfileWithEmptyArrays() { + Profile profile = new Profile(); profile.setEmail("test@example.com"); profile.setUserName("John Doe"); @@ -73,6 +77,7 @@ public void testCreateProfileWithEmptyArrays() { @Test public void testCreateProfileWithNullArrays() { + Profile profile = new Profile(); profile.setEmail("test@example.com"); profile.setUserName("John Doe"); @@ -89,6 +94,7 @@ public void testCreateProfileWithNullArrays() { @Test public void testSetEmailToNull() { + Profile profile = new Profile(); profile.setEmail("test@example.com"); profile.setUserName("John Doe"); @@ -101,6 +107,7 @@ public void testSetEmailToNull() { @Test public void testGetBroker() { + Profile profile = new Profile(); profile.setBroker("ABC Broker"); @@ -109,6 +116,7 @@ public void testGetBroker() { @Test public void testGetExchanges() { + Profile profile = new Profile(); profile.setExchanges(new String[]{"Exchange1", "Exchange2"}); @@ -117,6 +125,7 @@ public void testGetExchanges() { @Test public void testGetProducts() { + Profile profile = new Profile(); profile.setProducts(new String[]{"Product1", "Product2"}); @@ -128,6 +137,7 @@ public void testGetProducts() { @Test public void testTokenSetModelWithAllValues() { + TokenSet tokenSet = new TokenSet(); tokenSet.setUserId("12345"); assertEquals("12345", tokenSet.getUserId()); @@ -135,6 +145,7 @@ public void testTokenSetModelWithAllValues() { @Test public void testGetAccessTokenForTokenSetModel() { + TokenSet tokenSet = new TokenSet(); tokenSet.setAccessToken("abc123"); assertEquals("abc123", tokenSet.getAccessToken()); @@ -142,6 +153,7 @@ public void testGetAccessTokenForTokenSetModel() { @Test public void testGetRefreshTokenForTokenSetModel() { + TokenSet tokenSet = new TokenSet(); tokenSet.setRefreshToken("xyz789"); assertEquals("xyz789", tokenSet.getRefreshToken()); @@ -149,24 +161,28 @@ public void testGetRefreshTokenForTokenSetModel() { @Test public void testNullUserIdForTokenSetModel() { + TokenSet tokenSet = new TokenSet(); assertNull(tokenSet.getUserId()); } @Test public void testNullAccessToken() { + TokenSet tokenSet = new TokenSet(); assertNull(tokenSet.getAccessToken()); } @Test public void testNullRefreshToken() { + TokenSet tokenSet = new TokenSet(); assertNull(tokenSet.getRefreshToken()); } @Test public void testUserModelWithAllValues() { + User user = new User(); user.setUserName("John Doe"); user.setUserId("123456"); @@ -198,6 +214,7 @@ public void testUserModelWithAllValues() { @Test public void testUserModelParseResponse() throws JSONException, ParseException { + JSONObject response = new JSONObject(); JSONObject data = new JSONObject(); data.put("name", "John Doe"); @@ -240,6 +257,7 @@ public void testUserModelParseResponse() throws JSONException, ParseException { @Test public void testUserModelSetters() { + User user = new User(); user.setUserName("John Doe"); user.setUserId("123456"); @@ -299,6 +317,7 @@ public void testUserModelSetters() { @Test public void testUserWithNullResponse() throws JSONException { + JSONObject response = null; JSONObject finalResponse = response; @@ -326,6 +345,7 @@ public void testUserWithNullResponse() throws JSONException { @Test public void testTradeModelWithAllFields() { + Trade trade = new Trade(); trade.tradeId = "123"; trade.orderId = "456"; @@ -357,6 +377,7 @@ public void testTradeModelWithAllFields() { @Test public void testTradeModelSerializedNameAnnotationsMappedCorrectly() throws NoSuchFieldException { + Trade trade = new Trade(); assertNotNull(trade.getClass().getDeclaredField("tradeId").getAnnotation(SerializedName.class)); @@ -375,6 +396,7 @@ public void testTradeModelSerializedNameAnnotationsMappedCorrectly() throws NoSu @Test public void testTradeModelDateFieldsParsedAndStoredCorrectly() { + Trade trade = new Trade(); Date fillTimestamp = new Date(); Date exchangeTimestamp = new Date(); @@ -388,6 +410,7 @@ public void testTradeModelDateFieldsParsedAndStoredCorrectly() { @Test public void testTradeModelCreatedWithNullValues() { + Trade trade = new Trade(); assertNull(trade.tradeId); @@ -406,6 +429,7 @@ public void testTradeModelCreatedWithNullValues() { @Test public void testTradeModelCreatedWithInvalidDateFormats() { + Trade trade = new Trade(); String invalidDateFormat = "2021-13-01"; try { @@ -419,6 +443,7 @@ public void testTradeModelCreatedWithInvalidDateFormats() { @Test public void testOrderModelWithAllFields() { + Order order = new Order(); order.disclosedQuantity = "10"; order.duration = "DAY"; @@ -493,6 +518,7 @@ public void testOrderModelWithAllFields() { @Test public void testGttModelWithAllFields() { + Gtt gtt = new Gtt(); gtt.id = 123; gtt.tradingSymbol = "AAPL"; @@ -522,6 +548,7 @@ public void testGttModelWithAllFields() { @Test public void testConstantsFields() { + assertFalse(Constants.PRODUCT_DELIVERY.isEmpty()); assertFalse(Constants.PRODUCT_INTRADAY.isEmpty()); assertFalse(Constants.PRODUCT_MARGIN.isEmpty()); @@ -554,6 +581,7 @@ public void testConstantsFields() { @Test public void testOrderParamsWithAllFields() { + OrderParams orderParams = new OrderParams(); orderParams.orderid = "12345"; orderParams.exchange = "NSE"; @@ -574,6 +602,7 @@ public void testOrderParamsWithAllFields() { @Test public void testGttParamsWithNullValues() { + GttParams gttParams = new GttParams(); assertNotNull(gttParams); assertNull(gttParams.id); @@ -591,6 +620,7 @@ public void testGttParamsWithNullValues() { @Test public void testSearchScripResponse() { + SearchScripResponseDTO responseDTO = new SearchScripResponseDTO(); responseDTO.setTradingSymbol("ABC"); responseDTO.setExchange("NYSE"); @@ -603,6 +633,7 @@ public void testSearchScripResponse() { @Test public void testOrderModelResponse() { + Order order = new Order(); order.disclosedQuantity = "10"; order.duration = "DAY"; @@ -646,6 +677,7 @@ public void testOrderModelResponse() { @Test public void testBESTTwentyData() { + BestTwentyData data = new BestTwentyData(10, 20, (short) 5); assertEquals(10, data.getQuantity()); assertEquals(20, data.getPrice()); @@ -654,6 +686,7 @@ public void testBESTTwentyData() { @Test public void testGettersAndSettersMethodOfBestTwentyDataModel() { + BestTwentyData data = new BestTwentyData(); data.setQuantity(10); data.setPrice(20); @@ -665,6 +698,7 @@ public void testGettersAndSettersMethodOfBestTwentyDataModel() { @Test public void testToStringMethodOfBestTwentyData() { + BestTwentyData data = new BestTwentyData(10, 20, (short) 5); String expected = "BestTwentyData(quantity=10, price=20, numberOfOrders=5)"; assertEquals(expected, data.toString()); diff --git a/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java b/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java index d6d6827..2d8bf7f 100644 --- a/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java +++ b/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java @@ -321,6 +321,7 @@ public void testMarketDataOHLC_Failure() throws SmartAPIException, IOException { } private JSONObject getMarketDataRequest(String mode) { + JSONObject payload = new JSONObject(); payload.put("mode", mode); JSONObject exchangeTokens = new JSONObject(); @@ -334,12 +335,14 @@ private JSONObject getMarketDataRequest(String mode) { @Test public void testSmartConnectObjectWithApiKey() { + SmartConnect smartConnect = new SmartConnect("API_KEY"); assertNotNull(smartConnect); } @Test public void testSmartConnectObjectWithApiKeyAccessTokenRefreshToken() { + SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken"); assertNotNull(smartConnect); assertEquals("apiKey", smartConnect.getApiKey()); @@ -348,6 +351,7 @@ public void testSmartConnectObjectWithApiKeyAccessTokenRefreshToken() { } @Test public void testSetApiKeyOfSmartConnect() { + SmartConnect smartConnect = new SmartConnect(); smartConnect.setApiKey("apiKey"); smartConnect.setAccessToken("accessToken"); @@ -359,6 +363,7 @@ public void testSetApiKeyOfSmartConnect() { @Test public void testSmartConnectWithNullValues() { + SmartConnect smartConnect = new SmartConnect(); smartConnect.setApiKey(null); smartConnect.setAccessToken(null); @@ -371,12 +376,14 @@ public void testSmartConnectWithNullValues() { @Test public void testGenerateSession() { + SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken"); assertNull(smartConnect.generateSession("invalidClientCode", "password", "totp")); } @Test public void testReturnApiKeyIfNotNull() { + SmartConnect smartConnect = new SmartConnect("apiKey"); String result = smartConnect.getApiKey(); assertEquals("apiKey", result); @@ -384,6 +391,7 @@ public void testReturnApiKeyIfNotNull() { @Test public void testThrowsNullPointerExceptionIfApiKeyIsNull() { + SmartConnect smartConnect = new SmartConnect(); assertThrows(NullPointerException.class, () -> { smartConnect.getApiKey(); diff --git a/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java b/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java index 0564505..ee48d20 100644 --- a/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java +++ b/src/test/java/com/angelbroking/smartapi/smartstream/SmartStreamTickerTest.java @@ -7,7 +7,6 @@ import java.util.Scanner; import java.util.Set; -import com.warrenstrange.googleauth.GoogleAuthenticator; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -29,42 +28,18 @@ public class SmartStreamTickerTest { @BeforeAll public static void initClass() throws InterruptedException { -//<<<<<<< HEAD - // clientID = System.getProperty("clientID"); -// clientPass = System.getProperty("clientPass"); -// apiKey = System.getProperty("apiKey"); -// -// Scanner sc = new Scanner(System.in); -// System.out.print("enter totp: "); -// totp = sc.nextLine(); - -// SmartConnect smartConnect = new SmartConnect("VG2s34Cq"); // PROVIDE YOUR API KEY HERE -// String clientId = "A52163134"; -// GoogleAuthenticator gAuth = new GoogleAuthenticator(); -// String totp_key = "DOBXCSIGFBJAKJH4BUDCTCLKEI"; -// String tOTP = String.valueOf(gAuth.getTotpPassword(totp_key)); -// User user = smartConnect.generateSession("A52163134", "4321", tOTP); - clientID = "A52163134"; - clientPass = "4321"; - apiKey = "VG2s34Cq"; - - GoogleAuthenticator gAuth = new GoogleAuthenticator(); - String totp_key = "DOBXCSIGFBJAKJH4BUDCTCLKEI"; - totp = String.valueOf(gAuth.getTotpPassword(totp_key)); -//======= -// clientID = System.getProperty("clientID"); -// clientPass = System.getProperty("clientPass"); -// apiKey = System.getProperty("apiKey"); -// -// Scanner sc = new Scanner(System.in); -// System.out.print("enter totp: "); -// totp = sc.nextLine(); -//>>>>>>> 916d7b8452b60bfdcd78171c07dffe5bdb77ce88 + clientID = System.getProperty("clientID"); + clientPass = System.getProperty("clientPass"); + apiKey = System.getProperty("apiKey"); + + Scanner sc = new Scanner(System.in); + System.out.print("enter totp: "); + totp = sc.nextLine(); SmartConnect smartConnect = new SmartConnect(apiKey); User user = smartConnect.generateSession(clientID, clientPass, totp); feedToken = user.getFeedToken(); -// feedToken = "123"; +// feedToken = "123"; } @Test @@ -72,7 +47,7 @@ void testSmartStreamTicketLTP() throws WebSocketException, InterruptedException try { SmartStreamTicker ticker = new SmartStreamTicker(clientID, feedToken, new SmartStreamListenerImpl()); ticker.connect(); - ticker.subscribe(SmartStreamSubsMode.SNAP_QUOTE, getTokens()); + ticker.subscribe(SmartStreamSubsMode.QUOTE, getTokens()); // ticker.subscribe(SmartStreamSubsMode.SNAP_QUOTE, getTokens()); // uncomment the below line to allow test thread to keep running so that ticks // can be received in the listener @@ -89,22 +64,6 @@ void testSmartStreamTicketLTP() throws WebSocketException, InterruptedException private Set getTokens(){ // find out the required token from https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json Set tokenSet = new HashSet<>(); -//<<<<<<< HEAD - tokenSet.add(new TokenID(ExchangeType.BSE_FO, "1165360")); // NIFTY -// tokenSet.add(new TokenID(ExchangeType.BSE_FO, "1165360")); // NIFTY BANK -// tokenSet.add(new TokenID(ExchangeType.BSE_CM, "19000")); // Sensex -// -// tokenSet.add(new TokenID(ExchangeType.NSE_CM, "99926000")); // NIFTY -// tokenSet.add(new TokenID(ExchangeType.NSE_CM, "99926009")); // NIFTY BANK -// tokenSet.add(new TokenID(ExchangeType.BSE_CM, "99919000")); // Sensex -// -// tokenSet.add(new TokenID(ExchangeType.NSE_CM, "1594")); // NSE Infosys -// tokenSet.add(new TokenID(ExchangeType.NSE_FO, "35003")); // Nifty June 2023 FUT -// tokenSet.add(new TokenID(ExchangeType.CDE_FO, "1185")); // 1185 USDINR -// tokenSet.add(new TokenID(ExchangeType.BSE_CM, "532540")); // BSE TCS -// tokenSet.add(new TokenID(ExchangeType.NCX_FO, "GUARGUM5")); // GUAREX (NCDEX) -// tokenSet.add(new TokenID(ExchangeType.MCX_FO, "252453")); //CRUDEOIL -//======= tokenSet.add(new TokenID(ExchangeType.NSE_CM, "26000")); // NIFTY tokenSet.add(new TokenID(ExchangeType.NSE_CM, "26009")); // NIFTY BANK tokenSet.add(new TokenID(ExchangeType.BSE_CM, "19000")); // Sensex @@ -119,7 +78,6 @@ private Set getTokens(){ tokenSet.add(new TokenID(ExchangeType.BSE_CM, "532540")); // BSE TCS tokenSet.add(new TokenID(ExchangeType.NCX_FO, "GUARGUM5")); // GUAREX (NCDEX) tokenSet.add(new TokenID(ExchangeType.MCX_FO, "252453")); //CRUDEOIL -//>>>>>>> 916d7b8452b60bfdcd78171c07dffe5bdb77ce88 return tokenSet; } diff --git a/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java index a14375f..d349e8d 100644 --- a/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java +++ b/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java @@ -7,6 +7,7 @@ import org.json.JSONArray; import org.junit.jupiter.api.Test; +import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; @@ -157,4 +158,13 @@ public void test_on_connected_listener_called() { verify(onConnectedListenerMock, times(1)).onConnected(); } + @Test + public void test_decompressMethod() throws IOException { + byte[] compressedTxt = {120, -100, 75, 44, 73, 45, 46, 1, 0, 0, -1, -1}; + byte[] expected = {97, 116, 101, 115, 116}; + + byte[] result = SmartWebsocket.decompress(compressedTxt); + + assertArrayEquals(expected, result); + } } diff --git a/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java b/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java index ce9197d..d5bd5ac 100644 --- a/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java +++ b/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java @@ -19,6 +19,7 @@ public class SmartApiTickerTest { @Test public void testSmartApiTickerWithAllFields() { + // Arrange String clientId = "client_id"; String feedToken = "feed_token"; @@ -34,6 +35,7 @@ public void testSmartApiTickerWithAllFields() { @Test public void testSetListenerOfSmartAPITicker() { + // Arrange String clientId = "client_id"; String feedToken = "feed_token"; @@ -64,6 +66,7 @@ public void onConnected() { @Test public void testUnableToCloseWebSocketConnectionOfSmartAPITicker() { + // Arrange String clientId = "client_id"; String feedToken = "feed_token"; @@ -82,6 +85,7 @@ public void testUnableToCloseWebSocketConnectionOfSmartAPITicker() { @Test public void testBestTwentyDataMethod() { + ByteBuffer buffer = ByteBuffer.allocate(100000); // for testing for (int i = 0; i < NUM_PACKETS_FOR_DEPTH; i++) { int offset = BEST_TWENTY_BUY_DATA_POSITION + (i * PACKET_SIZE_FOR_DEPTH20); @@ -102,6 +106,7 @@ public void testBestTwentyDataMethod() { @Test public void testBestTwentyDataWithNoValues() { + ByteBuffer buffer = ByteBuffer.allocate(10000); BestTwentyData[] result = ByteUtils.getBestTwentyBuyData(buffer);