Merge branch '1.0-dev'

This commit is contained in:
Erik C. Thauvin 2022-09-09 11:56:57 -07:00
commit af30050ed7
18 changed files with 173 additions and 106 deletions

View file

@ -29,11 +29,11 @@ defaults_gradle: &defaults_gradle
- store_test_results:
path: build/reports/
jobs:
build_gradle_jdk17:
build_gradle_jdk18:
<<: *defaults
docker:
- image: cimg/openjdk:17.0
- image: cimg/openjdk:18.0
<<: *defaults_gradle
@ -50,4 +50,4 @@ workflows:
gradle:
jobs:
- build_gradle_jdk11
- build_gradle_jdk17
- build_gradle_jdk18

View file

@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
java-version: [ 11, 17 ]
java-version: [ 11, 18 ]
steps:
- uses: actions/checkout@v2

View file

@ -21,5 +21,15 @@
<option name="name" value="maven" />
<option name="url" value="https://oss.sonatype.org/content/repositories/snapshots" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenLocal" />
<option name="name" value="MavenLocal" />
<option name="url" value="file:$MAVEN_REPOSITORY$/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenLocal" />
<option name="name" value="MavenLocal" />
<option name="url" value="file:$PROJECT_DIR$/../../maven/repository/" />
</remote-repository>
</component>
</project>

6
.idea/kotlinc.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.7.10" />
</component>
</project>

5
.idea/misc.xml generated
View file

@ -1,5 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="17" project-jdk-type="JavaSDK" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="18" project-jdk-type="JavaSDK" />
</project>

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
</set>
</option>
</component>
</project>

View file

@ -2,21 +2,24 @@
[![Known Vulnerabilities](https://snyk.io/test/github/ethauvin/cryptoprice/badge.svg?targetFile=pom.xml)](https://snyk.io/test/github/ethauvin/cryptoprice?targetFile=pom.xml) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ethauvin_cryptoprice&metric=alert_status)](https://sonarcloud.io/dashboard?id=ethauvin_cryptoprice) [![GitHub CI](https://github.com/ethauvin/cryptoprice/actions/workflows/gradle.yml/badge.svg)](https://github.com/ethauvin/cryptoprice/actions/workflows/gradle.yml) [![CircleCI](https://circleci.com/gh/ethauvin/cryptoprice/tree/master.svg?style=shield)](https://circleci.com/gh/ethauvin/cryptoprice/tree/master)
# Retrieve cryptocurrencies current prices
# Retrieve cryptocurrencies current (buy, sell or spot) prices
A simple Kotlin/Java/Android implementation of the spot price [Coinbase Public API](https://developers.coinbase.com/api/v2#get-spot-price).
A simple Kotlin/Java/Android implementation of the prices [Coinbase Public API](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices).
## Examples (TL;DR)
```kotlin
import net.thauvin.erik.crypto.CryptoPrice.Companion.buyPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.sellPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.spotPrice
// ...
val btc = spotPrice("BTC") // Bitcoin
println(btc.amount)
val eth = spotPrice("ETH", "EUR") // Ethereum in Euros
val eth = sellPrice("ETH", "EUR") // Ethereum in Euro
println(eth.amount)
val eth = buyPrice("LTC", "GBP") // Litecoin in Pound sterling
println(eth.amount)
```
@ -28,21 +31,31 @@ To use with [Gradle](https://gradle.org/), include the following dependency in y
```gradle
dependencies {
implementation("net.thauvin.erik:cryptoprice:0.9.0")
implementation("net.thauvin.erik:cryptoprice:1.0.0")
}
```
Instructions for using with Maven, Ivy, etc. can be found on [Maven Central](https://search.maven.org/artifact/net.thauvin.erik/cryptoprice/0.9.0/jar).
Instructions for using with Maven, Ivy, etc. can be found on [Maven Central](https://search.maven.org/search?q=g:%22net.thauvin.erik%22%20AND%20a:%22cryptoprice%22).
### Spot Price
### Prices
The `spotPrice` function defines the following parameters:
The `spotPrice`, `buyPrice` and `sellPrice` functions define the following parameters:
```kotlin
spotPrice(
base: String, // Required
currency: String = "USD",
date: LocalDate? = null,
date: LocalDate? = null
)
buyPrice(
base: String, // Required
currency: String = "USD"
)
sellPrice(
base: String, // Required
currency: String = "USD"
)
```
@ -57,7 +70,7 @@ A `CryptoPrice` object is returned defined as follows:
```kotlin
CryptoPrice(val base: String, val currency: String, val amount: BigDecimal)
```
The parameter names match the [Coinbase API](https://developers.coinbase.com/api/v2#get-spot-price).
The parameter names match the [Coinbase API](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices).
#### Format
@ -86,7 +99,7 @@ println(price.toJson())
{"data":{"base":"BTC","currency":"USD","amount":"34567.89"}}
```
The `data` object matches the [Coinbase API](https://developers.coinbase.com/api/v2#get-spot-price). To specify a different (or no) key, use:
The `data` object matches the [Coinbase API](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices). To specify a different (or no) key, use:
```kotlin
println(price.toJson("bitcoin"))
@ -109,15 +122,15 @@ val eth = """{"ether":{"base":"ETH","currency":"USD","amount":"2345.67"}}""".toP
### Extending
A generic `apiCall()` function is available to access other [API data endpoints](https://developers.coinbase.com/api/v2#data-endpoints). For example to retrieve the current [buy price](https://developers.coinbase.com/api/v2#get-buy-price) of a cryptocurrency:
A generic `apiCall()` function is available to access other [data API endpoints](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-currencies). For example to retrieve the [exchange rates](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-exchange-rates#get-exchange-rates):
```kotlin
apiCall(paths = listOf("prices", "BTC-USD", "buy"), params = emptyMap())
apiCall(listOf("exchange-rates"), mapOf("currency" to "usd"))
```
will return something like:
```json
{"data":{"base":"BTC","currency":"USD","amount":"34554.32"}}
{"data":{"currency":"BTC","rates":{"AED":"36.73","AFN":"589.50",…}}}
```
See the [examples](https://github.com/ethauvin/cryptoprice/blob/master/examples/) for more details.

View file

@ -1,4 +1,4 @@
image: openjdk:17
image: openjdk:18
pipelines:
default:

View file

@ -8,21 +8,21 @@ import org.gradle.api.tasks.testing.logging.TestLogEvent
plugins {
id("application")
id("com.github.ben-manes.versions") version "0.42.0"
id("io.gitlab.arturbosch.detekt") version "1.20.0"
id("io.gitlab.arturbosch.detekt") version "1.21.0"
id("java")
id("maven-publish")
id("org.jetbrains.dokka") version "1.6.21"
id("org.jetbrains.kotlinx.kover") version "0.5.0"
id("org.sonarqube") version "3.3"
id("org.jetbrains.dokka") version "1.7.10"
id("org.jetbrains.kotlinx.kover") version "0.6.0"
id("org.sonarqube") version "3.4.0.2513"
id("signing")
kotlin("jvm") version "1.6.21"
kotlin("jvm") version "1.7.10"
}
defaultTasks(ApplicationPlugin.TASK_RUN_NAME)
description = "Retrieve cryptocurrencies current prices."
description = "Retrieve cryptocurrencies prices."
group = "net.thauvin.erik"
version = "0.9.0"
version = "1.0.0"
val deployDir = "deploy"
val gitHub = "ethauvin/$name"
@ -43,9 +43,9 @@ repositories {
dependencies {
implementation(platform(kotlin("bom")))
implementation(kotlin("stdlib-jdk8"))
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("com.squareup.okhttp3:okhttp:4.9.3")
implementation("com.squareup.okhttp3:okhttp:4.10.0")
implementation("org.json:json:20220320")
testImplementation(kotlin("test"))
@ -71,7 +71,7 @@ sonarqube {
property("sonar.organization", "ethauvin-github")
property("sonar.host.url", "https://sonarcloud.io")
property("sonar.sourceEncoding", "UTF-8")
property("sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/kover/report.xml")
property("sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/kover/xml/report.xml")
}
}
@ -132,7 +132,7 @@ tasks {
register("deploy") {
description = "Copies all needed files to the $deployDir directory."
group = PublishingPlugin.PUBLISH_TASK_GROUP
dependsOn(build, jar)
dependsOn(clean, build, jar)
outputs.dir(deployDir)
inputs.files(copyToDeploy)
mustRunAfter(clean)

View file

@ -2,6 +2,6 @@
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>ThrowsCount:CryptoPrice.kt$CryptoPrice.Companion$ @JvmStatic @JvmOverloads @Throws(CryptoException::class, IOException::class) fun apiCall(paths: List&lt;String>, params: Map&lt;String, String> = emptyMap()): String</ID>
<ID>ThrowsCount:CryptoPrice.kt$CryptoPrice.Companion$@JvmStatic @JvmOverloads @Throws(CryptoException::class, IOException::class) fun apiCall(paths: List&lt;String>, params: Map&lt;String, String> = emptyMap()): String</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -3,7 +3,7 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("application")
id("com.github.ben-manes.versions") version "0.42.0"
kotlin("jvm") version "1.6.21"
kotlin("jvm") version "1.7.10"
}
// ./gradlew run
@ -20,7 +20,8 @@ repositories {
}
dependencies {
implementation("net.thauvin.erik:cryptoprice:0.9.0")
implementation("net.thauvin.erik:cryptoprice:1.0.0")
implementation("org.json:json:20220320")
}
java {

View file

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View file

@ -2,50 +2,55 @@ package com.example;
import net.thauvin.erik.crypto.CryptoException;
import net.thauvin.erik.crypto.CryptoPrice;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Collections;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
public class CryptoPriceSample {
public static void main(String[] args) {
public static void main(final String[] args) {
try {
if (args.length > 0) {
final CryptoPrice price;
final String currency;
if (args.length == 2) {
price = CryptoPrice.spotPrice(args[0], args[1]);
currency = args[1];
} else {
price = CryptoPrice.spotPrice(args[0]);
currency = Currency.getInstance(Locale.getDefault()).getCurrencyCode();
}
System.out.println("The current " + price.getBase() + " price is " + price.getAmount() + " in "
+ price.getCurrency());
final var price = CryptoPrice.spotPrice(args[0], currency);
System.out.println("The current " + price.getBase() + " price is " + price.toCurrency());
} else {
// Get current Bitcoin spot price.
final CryptoPrice price = CryptoPrice.spotPrice("BTC");
final var price = CryptoPrice.spotPrice("BTC");
System.out.println("The current Bitcoin price is " + price.toCurrency());
System.out.println();
// Get current Ethereum spot price in Pound sterling.
final CryptoPrice gbpPrice = CryptoPrice.spotPrice("ETH", "GBP");
System.out.println("The current Ethereum price is " + gbpPrice.toCurrency());
// Get current Ethereum buy price in Pound sterling.
final var gbpPrice = CryptoPrice.buyPrice("ETH", "GBP");
System.out.println("The current Ethereum buy price is " + gbpPrice.toCurrency());
// Get current Litecoin spot price in Euros.
final CryptoPrice euroPrice = CryptoPrice.spotPrice("LTC", "EUR");
System.out.println("The current Litecoin price is " + euroPrice.toCurrency());
// Get current Litecoin sell price in Euros.
final var euroPrice = CryptoPrice.sellPrice("LTC", "EUR");
System.out.println("The current Litecoin sell price is " + euroPrice.toCurrency());
System.out.println();
// Get current Bitcoin buy price using API.
// See: https://developers.coinbase.com/api/v2#get-buy-price
final CryptoPrice buyPrice = CryptoPrice
.toPrice(CryptoPrice.apiCall(List.of("prices", "BTC-USD", "buy"), Collections.emptyMap()));
System.out.println("The current " + buyPrice.getBase() + " buy price is " + buyPrice.getAmount()
+ " in " + buyPrice.getCurrency());
// Get exchange rate using API.
// See: https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-exchange-rates
final var response = CryptoPrice.apiCall(List.of("exchange-rates"),
Collections.singletonMap("currency", "USD"));
final var rates = new JSONObject(response).getJSONObject("data").getJSONObject("rates");
System.out.println("The USD-EUR exchange rate is: " + rates.getString("EUR"));
}
} catch (CryptoException e) {
System.err.println("HTTP Status Code: " + e.getStatusCode());
System.err.println(e.getMessage());
} catch (IllegalArgumentException e) {
System.err.println("Could not display the specified currency: " + args[1]);
} catch (IOException e) {
System.err.println(e.getMessage());
}

View file

@ -2,16 +2,19 @@ package com.example
import net.thauvin.erik.crypto.CryptoException
import net.thauvin.erik.crypto.CryptoPrice.Companion.apiCall
import net.thauvin.erik.crypto.CryptoPrice.Companion.buyPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.sellPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.spotPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.toPrice
import org.json.JSONObject
import java.io.IOException
import java.util.*
fun main(args: Array<String>) {
try {
if (args.isNotEmpty()) {
val price = if (args.size == 2) spotPrice(args[0], args[1]) else spotPrice(args[0])
println("The current ${price.base} price is ${price.amount} in ${price.currency}")
val currency = if (args.size == 2) args[1] else Currency.getInstance(Locale.getDefault()).currencyCode
val price = spotPrice(args[0], currency)
println("The current ${price.base} price is ${price.toCurrency()}")
} else {
// Get current Bitcoin spot price.
val price = spotPrice("BTC")
@ -19,24 +22,27 @@ fun main(args: Array<String>) {
println()
// Get current Ethereum spot price in Pound sterling.
val gbpPrice = spotPrice("ETH", "GBP")
println("The current Ethereum price is ${gbpPrice.toCurrency()}")
// Get current Ethereum sell price in Pound sterling.
val gbpPrice = sellPrice("ETH", "GBP")
println("The current Ethereum sell price is ${gbpPrice.toCurrency()}")
// Get current Litecoin spot price in Euro.
val euroPrice = spotPrice("LTC", "EUR")
println("The current Litecoin price is ${euroPrice.toCurrency()}")
// Get current Litecoin buy price in Euro.
val euroPrice = buyPrice("LTC", "EUR")
println("The current Litecoin buy price is ${euroPrice.toCurrency()}")
println()
// Get current Bitcoin buy price using API.
// See: https://developers.coinbase.com/api/v2#get-buy-price
val buyPrice = apiCall(listOf("prices", "BTC-USD", "buy"), emptyMap()).toPrice()
println("The current ${buyPrice.base} buy price is ${buyPrice.amount} in ${buyPrice.currency}")
// Get exchange rate using API.
// See: https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-exchange-rates
val response = apiCall(listOf("exchange-rates"), mapOf("currency" to "usd"))
val rates = JSONObject(response).getJSONObject("data").getJSONObject("rates")
println("The USD-EUR exchange rate is: ${rates.getString("EUR")}")
}
} catch (e: CryptoException) {
System.err.println("HTTP Status Code: ${e.statusCode}")
System.err.println(e.message)
} catch (e: IllegalArgumentException) {
System.err.println("Could not display the specified currency: ${args[1]}")
} catch (e: IOException) {
System.err.println(e.message)
}

View file

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

12
pom.xml
View file

@ -8,9 +8,9 @@
<modelVersion>4.0.0</modelVersion>
<groupId>net.thauvin.erik</groupId>
<artifactId>cryptoprice</artifactId>
<version>0.9.0</version>
<version>1.0.0</version>
<name>cryptoprice</name>
<description>Retrieve cryptocurrencies current prices.</description>
<description>Retrieve cryptocurrencies prices.</description>
<url>https://github.com/ethauvin/cryptoprice</url>
<licenses>
<license>
@ -40,7 +40,7 @@
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-bom</artifactId>
<version>1.6.10</version>
<version>1.7.10</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -50,19 +50,19 @@
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>1.6.10</version>
<version>1.7.10</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
<version>4.10.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
<version>20220320</version>
<scope>runtime</scope>
</dependency>
</dependencies>

View file

@ -42,11 +42,10 @@ import java.io.IOException
import java.math.BigDecimal
import java.text.NumberFormat
import java.time.LocalDate
import java.util.Currency
import java.util.Locale
import java.util.*
/**
* Retrieves and holds a cryptocurrency current spot price.
* Retrieves and holds a cryptocurrency price.
*
* @constructor Constructs a new [CryptoPrice] object.
*
@ -116,6 +115,19 @@ open class CryptoPrice(val base: String, val currency: String, val amount: BigDe
}
}
/**
* Retrieves the buy price.
*
* @param base The cryptocurrency ticker symbol, such as `BTC`, `ETH`, `LTC`, etc.
* @param currency The fiat currency ISO 4217 code, such as `USD`, `GPB`, `EUR`, etc.
*/
@JvmStatic
@JvmOverloads
@Throws(CryptoException::class, IOException::class)
fun buyPrice(base: String, currency: String = "USD"): CryptoPrice {
return apiCall(listOf("prices", "$base-$currency", "buy"), emptyMap()).toPrice()
}
/**
* Prints the current prices for the specified cryptocurrencies.
*/
@ -129,7 +141,20 @@ open class CryptoPrice(val base: String, val currency: String, val amount: BigDe
}
/**
* Retrieves the current spot price.
* Retrieves the sell price.
*
* @param base The cryptocurrency ticker symbol, such as `BTC`, `ETH`, `LTC`, etc.
* @param currency The fiat currency ISO 4217 code, such as `USD`, `GPB`, `EUR`, etc.
*/
@JvmStatic
@JvmOverloads
@Throws(CryptoException::class, IOException::class)
fun sellPrice(base: String, currency: String = "USD"): CryptoPrice {
return apiCall(listOf("prices", "$base-$currency", "sell"), emptyMap()).toPrice()
}
/**
* Retrieves the spot price.
*
* @param base The cryptocurrency ticker symbol, such as `BTC`, `ETH`, `LTC`, etc.
* @param currency The fiat currency ISO 4217 code, such as `USD`, `GPB`, `EUR`, etc.

View file

@ -33,11 +33,13 @@
package net.thauvin.erik.crypto
import net.thauvin.erik.crypto.CryptoPrice.Companion.apiCall
import net.thauvin.erik.crypto.CryptoPrice.Companion.buyPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.sellPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.spotPrice
import net.thauvin.erik.crypto.CryptoPrice.Companion.toPrice
import org.json.JSONObject
import java.time.LocalDate
import java.util.Locale
import java.util.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@ -54,29 +56,35 @@ class CryptoPriceTest {
@Test
@Throws(CryptoException::class)
fun testBitcoinPrice() {
val price = spotPrice("BTC")
val prices = listOf(spotPrice("BTC"), buyPrice("BTC"), sellPrice("BTC"))
for (price in prices) {
assertEquals("BTC", price.base, "BTC")
assertEquals("USD", price.currency, "is USD")
assertTrue(price.amount.signum() > 0, "BTC > 0")
}
}
@Test
@Throws(CryptoException::class)
fun testEtherPrice() {
val price = spotPrice("ETH", "EUR")
val prices = listOf(spotPrice("ETH", "EUR"), buyPrice("ETH", "EUR"), sellPrice("ETH", "EUR"))
for (price in prices) {
assertEquals("ETH", price.base, "ETH")
assertEquals("EUR", price.currency, "is EUR")
assertTrue(price.amount.signum() > 0, "ETH > 0")
}
}
@Test
@Throws(CryptoException::class)
fun testLitecoinPrice() {
val price = spotPrice("LTC", "GBP")
val prices = listOf(spotPrice("LTC", "GBP"), buyPrice("LTC", "GBP"), sellPrice("LTC", "GBP"))
for (price in prices) {
assertEquals("LTC", price.base, "LTC")
assertEquals("GBP", price.currency, "is GBP")
assertTrue(price.amount.signum() > 0, "LTC > 0")
}
}
@Test
@Throws(CryptoException::class)
@ -102,7 +110,7 @@ class CryptoPriceTest {
@Test
@Throws(CryptoException::class)
fun testSpotPrice() {
fun testPrices() {
assertFailsWith(
message = "FOO did not fail",
exceptionClass = CryptoException::class,
@ -112,11 +120,11 @@ class CryptoPriceTest {
assertFailsWith(
message = "BAR did not fail",
exceptionClass = CryptoException::class,
block = { spotPrice("BTC", "BAR") }
block = { buyPrice("BTC", "BAR") }
)
try {
spotPrice("FOOBAR")
sellPrice("FOOBAR")
} catch (e: CryptoException) {
assertNotEquals(400, e.statusCode, "FOOBAR status code is not 400")
}