Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

code cleanup along with ws 2.0 #7

Open
wants to merge 61 commits into
base: main
Choose a base branch
from

Conversation

SameerShaikhAcc
Copy link

@SameerShaikhAcc SameerShaikhAcc commented Apr 13, 2023

The code improvements and changes are based on the JIRA ticket https://angelbrokingpl.atlassian.net/browse/SSS-13 and the feedback from the pull request kadam-mithun#1.

The following changes are implemented:

  • Replaced the use of + notation with StringBuilder for better performance.
  • Renamed attributes to follow camelCase convention and added SerializedName separately for improved readability.
  • Removed commented code.
  • Eliminated redundant usage of SerializedName annotation.
  • Implemented Lombok for getter and setter methods.
  • Moved constants to a separate class for better organization.
  • Used the HTTP library for status code messages.
  • Removed redundant return statements to simplify the code.
  • handled test cases
  • updated readme.md

README.md Outdated
public void getOrder(SmartConnect smartConnect) throws SmartAPIException, IOException {
List<Order> orders = smartConnect.getOrderHistory(smartConnect.getUserId());
for (Order order : orders) {
logger.info(order.orderId + " " + order.status);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should use logger.info("{} {}", order.orderId, order.status)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have replaced String concatenation with place holder
log.info("{} {}", order.orderId, order.status);

README.md Outdated
// Returns tradebook.
List<Trade> trades = smartConnect.getTrades();
for (Trade trade : trades) {
logger.info(trade.tradingSymbol + " " + trades.size());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here.

Copy link
Author

@SameerShaikhAcc SameerShaikhAcc Apr 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have replaced String concatenation with place holder
log.info("{} {}", trade.tradingSymbol, trades.size());

import java.util.Map;

/**
* Generates end-points for all smart api calls.
*
* <p>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this?

Copy link
Author

@SameerShaikhAcc SameerShaikhAcc Apr 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have removed the "< p >" from comments


@Data

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this? Ideally the request body for smartConnect and the methods should be segregated into 2 files.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have segregated SmartConnect into 2 files SmartConnect and SmartConnectParams
POJO methods have been moved to SmartConnectParams

}
}

private static final Logger logger = LoggerFactory.getLogger(SmartConnect.class);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use logger from lombok @slf4j

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have used @slf4j instead of private static final Logger logger = LoggerFactory.getLogger(SmartConnect.class);


// initialize 2fa exception and call constructor of Base Exception
public DataException(String message, String code){
public DataSmartAPIException(String message, String code){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the above comment is required.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment is been removed

public Integer timePeriod;

private Integer timePeriod;

@Override
public String toString() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In almost all the model classes we see this toString, Are we using this toString somewhere?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unnecessary toString is been removed

public void getHolding(SmartConnect smartConnect) throws SmartAPIException {
// Returns Holding.
JSONObject response = smartConnect.getHolding();
logger.debug("getHolding {}", response);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned last time, please remove these debug statements. Please review the dentire code for these debug statements.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have removed some debug statements and replaced some with log.info or log.error if necessary.


public class LoginWithTOTPSample {

private static final Logger logger = LoggerFactory.getLogger(LoginWithTOTPSample.class);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use logger from @slf4j

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have used @slf4j

(quote.getLowPrice() / 100.0),
(quote.getClosePrice() / 100.0),
getExchangeTime(quote.getExchangeFeedTimeEpochMillis()),
Instant.now().toEpochMilli() - quote.getExchangeFeedTimeEpochMillis());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are not making any asserts in these tests. What are we really testing?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SmartStreamListenerImpl is not a test class it is used in SmartStreamTicker.
SmartStreamTicker is used for connecting with the webSocket

Copy link

@NakshArora NakshArora left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please review the comments..

README.md Outdated

JSONObject requestObejct = new JSONObject();
JSONObject requestObejct = new JSONObject();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use Model class instead of JSONObject

@@ -100,7 +100,7 @@ <h2 title="Class Routes" class="title">Class Routes</h2>
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.angelbroking.smartapi.Routes</li>
<li>com.angelbroking.smartapi.routes.Routes</li>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you change this?

} catch (IOException ex) {
log.error("{} {}", IO_EXCEPTION_OCCURRED, ex.getMessage());
throw new IOException(String.format("%s: %s", IO_EXCEPTION_ERROR_MSG, ex.getMessage()));
} catch (JSONException ex) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we should catch JSONException, not able see any json inside method

orderParams.setSymbolToken("3045");
orderParams.setProductType("INTRADAY");
orderParams.setOrderType("LIMIT");
HttpResponse order = smartConnect.placeOrder(orderParams, "NORMAL");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Map to model instead of HttpResponse

public static final String LOGIN_URL = "https://apiconnect.angelbroking.com/rest/auth/angelbroking/user/v1/loginByPassword";
public static final String WSURI = "wss://wsfeeds.angelbroking.com/NestHtml5Mobile/socket/stream";
// public static final String SMARTSTREAM_WSURI = "ws://smartapisocket.angelone.in/smart-stream";
public static final String SMARTSTREAM_WSURI = "ws://mds-uat.angelone.in/smart-stream";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is UAT URL. Please switch to prod URL

Copy link
Author

@SameerShaikhAcc SameerShaikhAcc May 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have changed SMARTSTREAM_WSURI from ws://mds-uat.angelone.in/smart-stream to ws://smartapisocket.angelone.in/smart-stream

doc/com/angelbroking/smartapi/Routes.html Show resolved Hide resolved
return ResponseParser.parseResponse(smartAPIRequestHandler.getRequest(smartConnectParams.getApiKey(), url, smartConnectParams.getAccessToken()));

} catch (IOException ex) {
log.error("{} {}", IO_EXCEPTION_OCCURRED, ex.getMessage());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log messages should clearly denote that the error occurred while doing which operation?
In case an issue arises in the future, how can we find out that the error occurred while doing which operation?
Log should look something like "Error occurred while getting user profile" with ex.getMessage()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be addressed at all places.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have done changes in SmartConnect class for all log messages as well as for exception

try {
HttpResponse httpResponse = smartAPIRequestHandler.postRequest(smartConnectParams.getApiKey(), routes.getLoginUrl(), Utils.createLoginParams(clientCode, password, totp));
responseDTO = new ObjectMapper().readValue(httpResponse.getBody(), UserResponseDTO.class);
String url = routes.get(SMART_CONNECT_API_USER_PROFILE);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please split this into 2 try catch blocks. One for postRequest and the other one for parsing the object. This is creating unnecessary confusion.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed, will be using a single-try catch block.

public HttpResponse placeOrder(OrderParams orderParams, String variety) throws SmartAPIException, IOException {
try {
Validators validator = new Validators();
orderParams.setVariety(variety);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put the line which is required to be in the try-catch block. L141-L144 need not be inside the try catch block.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be done at all places.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have removed unnecessary code from try-catch block

Routes routes = new Routes();
try {
StringBuilder sb = new StringBuilder();
sb.append(routes.getSWsuri()).append("?jwttoken=").append(this.jwtToken).append("&&clientcode=").append(this.clientId).append("&&apikey=").append(this.apiKey);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please move constants to separate file.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have moved to constants

switch (mode) {
case LTP: {
ByteBuffer packet = ByteBuffer.wrap(binary).order(ByteOrder.LITTLE_ENDIAN);
LTP ltp = ByteUtils.mapByteBufferToLTP(packet);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can simply write it as mapByteBufferToLTP(packet) instead of ByteUtils.mapByteBufferToLTP(packet);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done for LTP,Quote,Snap_quote

// Added a private constructor to hide the implicit public one.


private ResponseParser() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you want me to remove the constructor or comment or both?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as discussed have removed the comments

if (macAddressBytes != null) {
StringBuilder macAddressStr = new StringBuilder();
for (int i = 0; i < macAddressBytes.length; i++) {
macAddressStr.append(String.format("%02X%s", macAddressBytes[i], (i < macAddressBytes.length - 1) ? "-" : ""));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please move constants.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

log.error("Error loading configuration file: {}", e.getMessage());
throw new IOException("Failed to load configuration file");
}
URL urlName = new URL(properties.getProperty("url"));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Constants.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@NakshArora
Copy link

  1. Please add meaningful log messages for easy debugging in case of issues.
  2. Please review the statements to be kept in the try-catch blocks.
  3. Review Exceptions.
  4. Move constants to separate file.
  5. Remove Html files.
  6. Remove default constructors.
  7. Meaningful variable names.

@moizm89 moizm89 changed the title Websocket 2 implementation code cleanup along with ws 2.0 Jun 21, 2023
anurag-amx pushed a commit that referenced this pull request Nov 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants