Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

This page contains some code snippets of Java interaction with API-NG. The example shows how to use Java to send requests to get a list of markets, then the list of runners for the chosen market and finally how to place a bet.

In the sample code we demonstrate both the json-rpc and REST protocols. All requests are handled in the json format. To post a request we prepare the json string using Java objects and then we serialize the object using the gson library.

The "operations" object is an instance of ApiNgOperations, that implements some wrapper methods for the APING operations. We send the filter data, app key and the session token. The method prepares the params for the request and then calls the method makeRequest that gets a json string, that is the actual request body, and posts the request to the API-NG endpoint.

private String makeRequest(String operation, Map<String, Object> params, String appKey, String ssoToken, boolean jsoRpc) {
String requestString;
          //Handling the JSON-RPC request
      JsonrpcRequest request = new JsonrpcRequest();
      request.setMethod(ApiNGDemo.getProp().getProperty("SPORTS_APING_V1_0") + operation);

      requestString =  JsonConverter.convertToJson(request);
} else {
      //Handling the REST request
      params.put("id", 1);

      requestString =  JsonConverter.convertToJson(params);

//We need to pass the "sendPostRequest" method a string in json format:  requestString
HttpUtil requester = new HttpUtil();
return requester.sendPostRequest(requestString, operation, appKey, ssoToken);

The following code snippet shows how we post the request to the API-NG.

String jsonRequest = param;
HttpPost post = new HttpPost(composeUrl(ApiNGDemo.isJsonRpcrequest(), operation));
	String responseString = null;
	try {
		post.setHeader(HTTP_HEADER_CONTENT_TYPE, ApiNGDemo.getProp().getProperty("APPLICATION_JSON"));
		post.setHeader(HTTP_HEADER_ACCEPT, ApiNGDemo.getProp().getProperty("APPLICATION_JSON"));
		post.setHeader(HTTP_HEADER_ACCEPT_CHARSET, ApiNGDemo.getProp().getProperty("ENCODING_UTF8"));
		post.setHeader(HTTP_HEADER_X_APPLICATION, appKey);
		post.setHeader(HTTP_HEADER_X_AUTHENTICATION, ssoToken);

		post.setEntity(new StringEntity(jsonRequest, ApiNGDemo.getProp().getProperty("ENCODING_UTF8")));
		HttpClient httpClient = new DefaultHttpClient();
		ResponseHandler<String> handler = new JsonResponseHandler();

		HttpParams httpParams = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, new Integer(ApiNGDemo.getProp().getProperty("TIMEOUT")).intValue());
		HttpConnectionParams.setSoTimeout(httpParams, new Integer(ApiNGDemo.getProp().getProperty("TIMEOUT")).intValue());

		responseString = httpClient.execute(post, handler);

Code Snippets

Find Horse Racing event id

To invoke listEventTypes we need to pass a marketFilter. In this case we set the "text query" to "Horse Racing".

MarketFilter marketFilter;
marketFilter = new MarketFilter();
marketFilter.setTextQuery("Horse Racing");
Set<String> eventTypeIds = new HashSet<String>();
List<EventTypeResult> r = operations.listEventTypes(marketFilter, applicationKey, sessionToken);
for (EventTypeResult eventTypeResult : r) {
    System.out.println("Found the market type: " + eventTypeResult.getEventType().toString());

Get next available horse races

To invoke listMarketCatalogue we need to pass:

  • marketFilter.where we set the event type = 7 (that is the "Horse Racing" market event type id), and the Market Start Time
  • marketProject to set the type and amount of data returned about the market
  • marketSort, to choose how the result will be ordered
  • maxResult, in this = 1
TimeRange time = new TimeRange();
time.setFrom(new Date());

marketFilter = new MarketFilter();

Set<MarketProjection> marketProjection = new HashSet<MarketProjection>();

String maxResult = "1";

List<MarketCatalogue> marketCatalogueresult = operations.listMarketCatalogue(marketFilter, marketProjection, MarketSort.FIRST_TO_START, maxResult, applicationKey, sessionToken);

Get list of runners in the market

To get the list of runners we call the method listMarketBook passing:

  • marketIds: the market id that we got in the previous call
  • priceProjection: the projection of price data you want to receive in the response
  • we don't need orderProjection, matchProjectionand currencyCode that are declared null
String marketIdChosen = marketCatalogueResult.get(0).getMarketId();

PriceProjection priceProjection = new PriceProjection();
Set<PriceData> priceData = new HashSet<PriceData>();

//In this case we don't need these objects so they are declared null
OrderProjection orderProjection = null;
MatchProjection matchProjection = null;
String currencyCode = null;

List<String> marketIds = new ArrayList<String>();
List<MarketBook> marketBookReturn = operations.listMarketBook(marketIds, priceProjection,
                        orderProjection, matchProjection, currencyCode, applicationKey, sessionToken);

Place a bet

With all the data needed we can try to place a bet. Based on previous request we provide:

  • marketId: the market id we have found in the previous request
  • instructions: the instructions to place a new order:
    • selectionId: the runner's selection id we have found in the previous request
    • side: BACK
    • orderType: LIMIT
    • size: specified in the properties file
    • price: specified in the properties file
  • customerRef: 1 - unique reference for a transaction specified by user, must be different for each request
Runner runner;
long selectionId = 0;
if (marketBookReturn.size() != 0) {
     runner = marketBookReturn.get(0).getRunners().get(0);
     selectionId = runner.getSelectionId();
     System.out.println("Found a runner with selection id: " + runner.getSelectionId());

     List<PlaceInstruction> instructions = new ArrayList<PlaceInstruction>();
     PlaceInstruction instruction = new PlaceInstruction();

     LimitOrder limitOrder = new LimitOrder();
     //API-NG will return an error with the default size=0. This is an expected behaviour.
     //Yuo can adjust the size and price value in the "" file


     String customerRef = "1";

     System.out.println("Trying to place a bet...");
     PlaceExecutionReport placeBetResult = operations.placeOrders(marketIdChosen, instructions, customerRef, applicationKey, sessionToken);

Next, for the placeOrders call, we need to verify the result. This is done using placeBetResult.getStatus() call.

if (placeBetResult.getStatus() == ExecutionReportStatus.SUCCESS) {
    System.out.println("Your bet has been placed!!");
} else if (placeBetResult.getStatus() == ExecutionReportStatus.FAILURE) {
    System.out.println("Your bet has NOT been placed :*( ");
    System.out.println("The error is: " + placeBetResult.getErrorCode() + ": " + placeBetResult.getErrorCode().getMessage());
    System.out.println("More luck next time");