How to sell stock with Java SDK?

Hello everyone,

I’m trying to sell a stock using java sdk REST Api. I’m successfully able to buy a stock.
Buy API:
@PostMapping(“/place-order”)
public String placeOrderByOrderId(String orderId) {
ApiClient defaultClient = Configuration.getDefaultApiClient();

    OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2");
    OAUTH2.setAccessToken(upstoxConfigHolder.getAccessToken());

    OrderApi apiInstance = new OrderApi();
    PlaceOrderRequest body = new PlaceOrderRequest();
    body.setQuantity(1);
    body.setProduct(PlaceOrderRequest.ProductEnum.D);
    body.setValidity(PlaceOrderRequest.ValidityEnum.DAY);
    body.setPrice(0F);
    body.setTag("string");
    body.setInstrumentToken(orderId);
    body.orderType(PlaceOrderRequest.OrderTypeEnum.MARKET);
    body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.BUY);
    body.setDisclosedQuantity(0);
    body.setTriggerPrice(0F);
    body.setIsAmo(false);

    String apiVersion = upstoxConfigHolder.getApiVersion();
    try {
        PlaceOrderResponse result = apiInstance.placeOrder(body, apiVersion);
        OrderHistory o = new OrderHistory();
        o.setOrderId(result.getData().getOrderId());
        o.setOrderStatus(String.valueOf(result.getStatus()));
        orderHistoryRepository.save(o);
        return "success";
    } catch (ApiException e) {
        System.err.println("Exception when calling OrderApi#placeOrder ");
        e.printStackTrace();
        return e.getMessage();
    }
}

For selling this particular stock, I changed the TransactionTypeEnum to SELL:
body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.SELL);

but I’m getting the following error:

Exception when calling OrderApi#sellOrder
com.upstox.ApiException: Bad Request
at com.upstox.ApiClient.handleResponse(ApiClient.java:926)
at com.upstox.ApiClient.execute(ApiClient.java:842)
at io.swagger.client.api.OrderApi.placeOrderWithHttpInfo(OrderApi.java:956)
at io.swagger.client.api.OrderApi.placeOrder(OrderApi.java:941)
at com.algo.trading.controller.AlgoTradingController.sellOrderByOrderId(AlgoTradingController.java:166)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:255)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:188)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:925)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:830)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1089)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
at java.base/java.lang.Thread.run(Thread.java:840)

Kindly suggest a solution

Refer to the sample code provided here for guidance on placing an order using the Java SDK:

Don’t hesitate to get in touch with me if you encounter any issues while following the sample code.

Hi Pradeep.

Thank you for your reply but its the selling through an API which is causing the issue. Need more information on how to sell the using API

Rest assured that the code to sell order provided below is functional and is in sync with our Example Codes.

import com.upstox.ApiClient;
import com.upstox.ApiException;
import com.upstox.Configuration;
import com.upstox.api.PlaceOrderRequest;
import com.upstox.api.PlaceOrderResponse;
import com.upstox.auth.*;
import io.swagger.client.api.OrderApi;
public class Main {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        OAuth OAUTH2 = (OAuth) defaultClient.getAuthentication("OAUTH2");
        OAUTH2.setAccessToken("{your_access_token}");

        OrderApi apiInstance = new OrderApi();
        PlaceOrderRequest body = new PlaceOrderRequest();
        body.setQuantity(1);
        body.setProduct(PlaceOrderRequest.ProductEnum.D);
        body.setValidity(PlaceOrderRequest.ValidityEnum.DAY);
        body.setPrice(0F);
        body.setTag("string");
        body.setInstrumentToken("NSE_EQ|INE669E01016");
        body.orderType(PlaceOrderRequest.OrderTypeEnum.MARKET);
        body.setTransactionType(PlaceOrderRequest.TransactionTypeEnum.SELL);
        body.setDisclosedQuantity(0);
        body.setTriggerPrice(0F);
        body.setIsAmo(false);

        String apiVersion = "2.0"; // String | API Version Header
        try {
            PlaceOrderResponse result = apiInstance.placeOrder(body, apiVersion);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling OrderApi#placeOrder ");
            e.printStackTrace();
        }
    }
}

If you still get error please check for these two conditions

  1. During market hours, ensure that setIsAmo is set to false, and after market hours, set it to true.
  2. If you don’t have DDPI activation, perform a CDSL verification before placing your first sell order of the day. For additional details, refer to this comment on CDSL Verification or DDPI activation.

We are working on our end to ensure that users receive a detailed response for if they encounter errors while selling orders using the Java SDK

1 Like

Thank you Ketan. I was able to sell order successfully.

2 Likes