Package com.quantcomponents.core.exceptions

Examples of com.quantcomponents.core.exceptions.RequestFailedException


  @Override
  public List<IContract> searchContracts(IContract criteria, ITaskMonitor taskMonitor) throws ConnectException, RequestFailedException {
    String symbol = criteria.getSymbol();
    if (symbol == null || symbol.trim().length() == 0) {
      throw new RequestFailedException("Symbol must be speficied for Yahoo! Finance ticker query");
    }
    String quotedSymbol;
    try {
      quotedSymbol = URLEncoder.encode(symbol, URL_ENCODING_ENCODING);
    } catch (UnsupportedEncodingException e) {
      throw new RequestFailedException("Exception encoding symbol: " + symbol, e);
    }
    String queryUrl = String.format(YAHOO_TICKER_QUERY_URL, quotedSymbol);
    logger.log(Level.INFO, "Query Yahoo!Finance for tickers: " + queryUrl);
    JSON response = null;
    try {
      String responseString = httpQuery(queryUrl);
      String jsonResponse = responseString.replace("YAHOO.Finance.SymbolSuggest.ssCallback(", "").replace(")","");
      Reader responseReader = new StringReader(jsonResponse);
      logger.log(Level.FINE, "Response from Yahoo!Finance: " + jsonResponse);
      response = JSON.parse(responseReader);
    } catch (IOException e) {
      throw new ConnectException("Exception while connecting to: " + queryUrl + " [" + e.getMessage() + "]");
    } catch (JSONException e) {
      throw new RequestFailedException("Exception parsing response data from: " + queryUrl, e);
    }
    @SuppressWarnings("unchecked")
    List<JSON> securityList = (List<JSON>) response.get("ResultSet").get("Result").getValue();
    List<IContract> contractList = new LinkedList<IContract>();
    for (JSON security : securityList) {
View Full Code Here


    String quotedSymbol;
    try {
      quotedSymbol = URLEncoder.encode(contract.getSymbol(), URL_ENCODING_ENCODING);
    }
    catch (UnsupportedEncodingException e) {
      throw new RequestFailedException("Exception encoding symbol: " + contract.getSymbol(), e);
    }   
    String queryUrl = String.format(YAHOO_STOCK_PRICES_QUERY_URL, quotedSymbol, startMonth, startDay, startYear,
        endMonth, endDay, endYear, encodeBarSize(barSize));
    logger.log(Level.INFO, "Query Yahoo!Finance for historical prices: " + queryUrl);
    String responseString;
    try {
      responseString = httpQuery(queryUrl);
    } catch (IOException e) {
      throw new ConnectException("Exception while connecting to: " + queryUrl + " [" + e.getMessage() + "]");
    }
    String[] lines = responseString.split("\\n");
    logger.log(Level.INFO, "Received " + (lines.length - 1) + " lines");
    if (!lines[0].equals(YAHOO_STOCK_PRICES_HEADER)) {
      throw new RequestFailedException("Response format not recognized: " + responseString.substring(0, 200) + "...");
    }
    List<IOHLCPoint> points = new LinkedList<IOHLCPoint>();
    DateFormat dateFormat = new SimpleDateFormat(YAHOO_STOCK_PRICES_DATE_FORMAT);
    for (int lineNo = lines.length - 1; lineNo > 0; lineNo--) { // Yahoo! returns prices in reverse chronological order
      try {
        logger.log(Level.INFO, "Processing line " + lineNo + ": " + lines[lineNo]);
        IOHLCPoint point = parsePriceLine(lines[lineNo], barSize, dateFormat);
        logger.log(Level.INFO, "Adding point" + point);
        points.add(point);
      } catch (ParseException e) {
        throw new RequestFailedException("Error while parsing line: " + lineNo, e);
      }
    }   
    return points;
  }
View Full Code Here

      break;
    case ONE_MONTH:
      code = "m";
      break;
    default:
      throw new RequestFailedException("Price from Yahoo!Finance are only in daily, weekly, monthly periods");
    }
    return code;
  }
View Full Code Here

  private StockInfo getStockInfo(String symbol) throws RequestFailedException, HttpException, IOException {
    String quotedSymbol;
    try {
      quotedSymbol = URLEncoder.encode(symbol, URL_ENCODING_ENCODING);
    } catch (UnsupportedEncodingException e) {
      throw new RequestFailedException("Exception encoding symbol: " + symbol, e);
    }
    String queryUrl = String.format(YAHOO_STOCK_QUERY_URL, quotedSymbol);
    String responseString = httpQuery(queryUrl);
    Matcher m = STOCK_CURRENCY_PATTERN.matcher(responseString);
    if (!m.matches()) {
View Full Code Here

    case 2:
      return 3; // 750 - 999
    case 3:
      return 4; // more than 999
    default:
      throw new RequestFailedException("Illegal number of market data lines");
    }
  }
View Full Code Here

   
    // check number of years
    long numberOfYears = remainingPeriod / 360L / 24L / 60L / 60L / 1000L;
    int maxYears = maxYearsOfHistoricalData();
    if (numberOfYears > maxYears) {
      throw new RequestFailedException("Current number of market data lines only allows for " + maxYears + " of historical data");
    }
    // break request in smaller batches to comply with IB limitations
    long maxPeriodForOneRequest = remainingPeriod;
    long barsPerInterval = maxPeriodForOneRequest / barSize.getDurationInMs();
    if (barsPerInterval > maxBarPerRequest) {
      maxPeriodForOneRequest = barSize.getDurationInMs() * maxBarPerRequest;
    }
    maxPeriodForOneRequest = Math.min(maxPeriodForOneRequest, maxRequestPeriodPerBarSize(barSize));
   
    Date nextEndDateTime = endDateTime;
   
    // comply with IB timing restrictions
    long lastBatchTime = 0L;
    int requestNo = 0;
   
    int approxCallNo = (int) (remainingPeriod / maxPeriodForOneRequest);
    if (taskMonitor != null) {
      taskMonitor.beginTask(approxCallNo * 10); // retrieving then adding partial results: IB calls count 7 - saving results count 3
    }

    logger.log(Level.INFO, "Start downloading: " + new Date()); // TODO: remove
    boolean forceSleep = false;
    while (remainingPeriod > 0) {
     
      if (taskMonitor != null && taskMonitor.isCancelled()) {
        throw new RequestFailedException("Request cancelled by user");
      }
     
      if (requestNo % numOfReqsInHistDataReqBatches == 0 || forceSleep) {
        long elapsedSinceLastBatch = System.currentTimeMillis() - lastBatchTime;
        logger.log(Level.INFO, "Now: " + timestampDateFormat.format(new Date()) + "; Elapsed: " + elapsedSinceLastBatch); // TODO: remove
        if (elapsedSinceLastBatch < minElapsedBetweenHistDataReqBatches) {
          try {
            logger.log(Level.INFO, "Sleeping: " + (minElapsedBetweenHistDataReqBatches - elapsedSinceLastBatch) + "ms"); // TODO: remove
            for (long partElapsed = 0L; partElapsed < minElapsedBetweenHistDataReqBatches - elapsedSinceLastBatch; partElapsed += HIST_DATA_REQUEST_SLEEP_QUANTUM) {
              Thread.sleep(HIST_DATA_REQUEST_SLEEP_QUANTUM);
              if (taskMonitor != null && taskMonitor.isCancelled()) {
                throw new RequestFailedException("Request cancelled by user");
              }
            }
          } catch (InterruptedException e) {
            throw new RequestFailedException("Exception while sleeping through request batches", e);
          }
        }
        lastBatchTime = System.currentTimeMillis();
        forceSleep = false;
      }
      long currentRequestPeriod;
      if (remainingPeriod > maxPeriodForOneRequest) {
        currentRequestPeriod = maxPeriodForOneRequest;
      } else if (remainingPeriod < minHistDataPeriodMs) {
        currentRequestPeriod = minHistDataPeriodMs;
      } else {
        currentRequestPeriod = remainingPeriod;
      }
      TimePeriod requestPeriod = TimePeriod.findApproxPeriod(currentRequestPeriod);
      List<IOHLCPoint> partialResult = null;

      logger.log(Level.INFO, "Request #" + requestNo + ". Data until: " + nextEndDateTime); // TODO: remove
      try {
       
        partialResult = doGetHistoricalData(contract, nextEndDateTime, requestPeriod, barSize, dataType, includeAfterHours);
       
      } catch (PacingViolationException e) {
        logger.log(Level.WARNING, "Pacing violation exception while retrieving historical data from IB. Force sleep", e);
        forceSleep = true;
        continue;
      } catch (NoDataReturnedException e) {
        logger.log(Level.INFO, "Historical data request from IB returned no data. Continue with next request", e);
        partialResult = null;
      }
      if (partialResult == null || nextEndDateTime.equals(partialResult.get(0).getIndex())) { // empty or duplicate result
        logger.log(Level.INFO, "Empty or duplicate result: " + nextEndDateTime); // TODO: remove
        nextEndDateTime = TimePeriod.subtractPeriodFromDate(nextEndDateTime, requestPeriod);
      } else {
        tmpResults.addFirst(partialResult);
        nextEndDateTime = partialResult.get(0).getIndex();
      }
      remainingPeriod = nextEndDateTime.getTime() - startDateTime.getTime();
      requestNo++;
     
      if (taskMonitor != null) {
        taskMonitor.worked(7);
      }
    }

    logger.log(Level.INFO, "All data downloaded. Create time series: " + new Date()); // TODO: remove
    List<IOHLCPoint> result = new ArrayList<IOHLCPoint>();

    IOHLCPoint lastBarAdded = null;
    Date dateOfLastBarAdded = new Date(0L);
    for (List<IOHLCPoint> partialResult : tmpResults) {

      if (taskMonitor != null && taskMonitor.isCancelled()) {
        throw new RequestFailedException("Request cancelled by user");
      }
     
      for (IOHLCPoint bar : partialResult) {
        Date endOfLastBarAdded = new Date(dateOfLastBarAdded.getTime() + barSize.getDurationInMs());
        if (!bar.getIndex().before(startDateTime)) {
View Full Code Here

        if (requestClient.getErrorMessage().contains("pacing violation")) {
          throw new PacingViolationException(requestClient.getErrorMessage(), requestClient.getException());
        } else if (requestClient.getErrorMessage().contains("query returned no data")) {
          throw new NoDataReturnedException(requestClient.getErrorMessage(), requestClient.getException());
        }
        throw new RequestFailedException(requestClient.getErrorMessage(), requestClient.getException());
      }
      throw new RequestFailedException();
    }
  }
View Full Code Here

TOP

Related Classes of com.quantcomponents.core.exceptions.RequestFailedException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.