
io.mstream.trader.datafeed.stocks.quandl.QuandlClient Maven / Gradle / Ivy
The newest version!
package io.mstream.trader.datafeed.stocks.quandl;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.mstream.trader.commons.utils.exception.NotFoundException;
import io.mstream.trader.commons.utils.exception.ParsingException;
import io.mstream.trader.datafeed.stocks.Stock;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Single;
import rx.functions.Func1;
import javax.inject.Inject;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.function.Supplier;
import static java.lang.String.format;
public class QuandlClient {
private static final Logger LOGGER =
LoggerFactory.getLogger(QuandlClient.class);
private final UriBuilder uriBuilder;
private final ObjectMapper mapper;
private final Supplier> httpClientSupplier;
@Inject
public QuandlClient(
UriBuilder uriBuilder,
ObjectMapper mapper,
@Quandl
Supplier> httpClientSupplier
) {
this.uriBuilder = uriBuilder;
this.mapper = mapper;
this.httpClientSupplier = httpClientSupplier;
}
public Single price(Stock stock, LocalDate date) {
URI uri = uriBuilder.stockPrice(stock, date);
LOGGER.debug("sending request: " + uri);
return httpClientSupplier
.get()
.createGet(uri.getPath() + "?" + uri.getQuery())
.flatMap(responseHandler())
.toSingle();
}
private Func1, Observable>
responseHandler() {
return resp -> {
int responseStatusCode =
resp
.getStatus()
.code();
LOGGER.debug("quandl responds with code " + responseStatusCode);
switch (responseStatusCode) {
case 200:
return resp
.getContent()
.map(bb -> {
try {
return
Double.toString(
mapper
.readTree(
bb.toString(
Charset.defaultCharset()
)
)
.at("/dataset/data/0/1")
.doubleValue());
} catch (IOException e) {
throw ParsingException.get();
}
}
);
case 404:
throw NotFoundException.get();
default:
throw new RuntimeException(
format(
"quandl reponded with status code %d",
responseStatusCode
)
);
}
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy