Skip to content

Commit

Permalink
implementation of Bitmarket
Browse files Browse the repository at this point in the history
Took 1 hour 28 minutes
  • Loading branch information
stanbar committed Feb 22, 2018
1 parent 55ae0c8 commit 7c30ae9
Show file tree
Hide file tree
Showing 12 changed files with 221 additions and 50 deletions.
8 changes: 8 additions & 0 deletions src/main/kotlin/com/stasbar/taxledger/Extensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,18 @@

package com.stasbar.taxledger

import com.stasbar.taxledger.models.Transactionable
import java.util.*

fun Date.toCalendar(): Calendar {
val cal = Calendar.getInstance()
cal.time = this
return cal
}

fun ExchangeApi<Transactionable, Transactionable>.silentTry(block: () -> Unit) {
try {
block()
} catch (e: Throwable) {
}
}
15 changes: 14 additions & 1 deletion src/main/kotlin/com/stasbar/taxledger/Logger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ package com.stasbar.taxledger
import com.stasbar.taxledger.translations.Text
import org.fusesource.jansi.Ansi.ansi
import org.fusesource.jansi.AnsiConsole
import java.text.SimpleDateFormat
import java.util.*

object Logger {
val dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

fun info(message: String?) {
AnsiConsole.out.println(ansi().a("\n").fgBrightCyan().a(0x2714.toChar()).a(getString(Text.Logger.INFO)).reset().a(message).a("\n"))
Expand All @@ -40,8 +43,18 @@ object Logger {
}

fun d(message: String?) {
val time = dateFormat.format(Date(System.currentTimeMillis()))
if (DEBUG)
AnsiConsole.out.println(ansi().a("\n").fgBrightGreen().a(0x2716.toChar()).a(getString(Text.Logger.DEBUG)).reset().a(message).a("\n"))
AnsiConsole.out.println(ansi()
.a("\n")
.fgBrightGreen()
.a(0x2716.toChar())
.a(getString(Text.Logger.DEBUG))
.reset()
.a(time)
.a(" ")
.a(message)
.a("\n"))
}

}
5 changes: 4 additions & 1 deletion src/main/kotlin/com/stasbar/taxledger/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ private val terminal = TerminalBuilder
/**
* In debug mode logs are printed onto console
*/
val DEBUG = false
var DEBUG = false


/**
Expand Down Expand Up @@ -280,6 +280,9 @@ fun performActions(action: String): Boolean {
Desktop.getDesktop().browse(URI(Misc.twitter))
}
}
"DEBUG" -> {
DEBUG = true
}


else -> return false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,16 +115,15 @@ class BitBayApi(credentials: LinkedHashSet<Credential>, private val gson: Gson)
}

override fun transactions(): List<BitBayTransaction> {
val limit = 1000
val limit = 400
val transactions = ArrayList<BitBayTransaction>()
var nextPageCursor = "start"
var previousPageCursor = "start"
var isFirstRequest = true
do {
if (isFirstRequest) {
isFirstRequest = false
Thread.sleep(1000)
}
Logger.d("transactions() sleeping 1sec")
Thread.sleep(1000)
Logger.d("transactions() woke up")

val queryMap = HashMap<String, Any?>()
queryMap["limit"] = limit.toString()
//queryMap["offset"] = offset.toString()
Expand Down Expand Up @@ -187,15 +186,15 @@ class BitBayApi(credentials: LinkedHashSet<Credential>, private val gson: Gson)
fun getHistory(types: List<BitBayHistoryType>): List<BitBayHistory> {
val transactions = ArrayList<BitBayHistory>()

var limit = 1000
var limit = 400
var offset: Int? = null
var hasNextPages = false
var isFirstRequest = true
do {
if (isFirstRequest) {
isFirstRequest = false
Thread.sleep(1000)
}
Logger.d("getHistory() sleeping 1sec")
Thread.sleep(1000)
Logger.d("getHistory() woke up")


val queryMap = HashMap<String, Any?>()
queryMap["limit"] = limit
queryMap["offset"] = offset
Expand All @@ -218,6 +217,7 @@ class BitBayApi(credentials: LinkedHashSet<Credential>, private val gson: Gson)
val newTransactions = transactionsResponse.items
//Sorry BitBay, but I don't trust you
.filter { it.type in types.map { it.name } }

transactions.addAll(newTransactions)

hasNextPages = transactionsResponse.hasNextPage
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import com.stasbar.taxledger.models.Transaction
import com.stasbar.taxledger.models.Transactionable

class BitfinexHistory(
val ID: Int, //Trade database id
val ID: Int, //BitmarketTransaction database id
val PAIR: String, //Pair (BTCUSD, …)
val MTS_CREATE: Int, //Execution timestamp
val ORDER_ID: Int, //Order id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,17 @@
package com.stasbar.taxledger.exchanges.bitmarket

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import com.stasbar.taxledger.ExchangeApi
import com.stasbar.taxledger.exchanges.bitmarket.models.BitMarketTransaction
import com.stasbar.taxledger.Logger
import com.stasbar.taxledger.exchanges.bitmarket.models.BitmarketTransaction
import com.stasbar.taxledger.exchanges.bitmarket.requests.BitmarketHistoryRequest
import com.stasbar.taxledger.exchanges.bitmarket.requests.TransactionsRequest
import com.stasbar.taxledger.exchanges.bitmarket.responses.BitmarketResponse
import com.stasbar.taxledger.models.Transactionable
import com.stasbar.taxledger.silentTry
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
Expand All @@ -44,8 +51,12 @@ interface BitmarketService {
fun info(): Call<String>

@FormUrlEncoded
@POST("api2")
fun transactions(@FieldMap(encoded = true) fields: Map<String, String>): Call<BitMarketTransaction>
@POST("api2/")
fun transactions(@FieldMap(encoded = true) fields: Map<String, String>): Call<JsonElement>

@FormUrlEncoded
@POST("api2/")
fun history(@FieldMap(encoded = true) fields: Map<String, String>): Call<JsonElement>
}

class BitmarketApi(private val publicKey: String, private val privateKey: String, val gson: Gson) : ExchangeApi<Transactionable, Transactionable> {
Expand All @@ -69,12 +80,68 @@ class BitmarketApi(private val publicKey: String, private val privateKey: String
}

override fun transactions(): List<Transactionable> {
val request = TransactionsRequest()
//TODO Fix it, it's just mockup
return service.value.transactions(request.toMap()).execute().body()?.results!! ?: emptyList()
//TODO pagination

val request = TransactionsRequest("LTCPLN")
val transactions = arrayListOf<BitmarketTransaction>()
val response = service.value.transactions(request.toMap()).execute()
if (response.isSuccessful) {
val responseBody = response.body()
try {
silentTry {
println(responseBody?.asJsonObject)
println(responseBody?.asJsonArray)
}

val transactionsResponse: BitmarketResponse? = gson.fromJson(responseBody, object : TypeToken<BitmarketResponse>() {}.type)
if (transactionsResponse != null) {
transactions.addAll(transactionsResponse.data.results)
}
} catch (e: JsonSyntaxException) {
Logger.err(e.message)
Logger.err(responseBody.toString())
return emptyList()
}
} else {
Logger.err("Unsuccessfully fetched transactions error code: ${response.code()} body: ${response.errorBody()?.charStream()?.readText()} ")
return emptyList()
}
return transactions

}

override fun depositsAndWithdraws(): List<Transactionable> {

val request = BitmarketHistoryRequest("PLN")
val transactions = arrayListOf<BitmarketTransaction>()
val response = service.value.transactions(request.toMap()).execute()
if (response.isSuccessful) {
val responseBody = response.body()
try {
silentTry {
println(responseBody?.asJsonObject)
println(responseBody?.asJsonArray)
}

val transactionsResponse: BitmarketResponse? = gson.fromJson(responseBody, object : TypeToken<BitmarketResponse>() {}.type)
if (transactionsResponse != null) {
transactions.addAll(transactionsResponse.data.results)
}
} catch (e: JsonSyntaxException) {
Logger.err(e.message)
Logger.err(responseBody.toString())
return emptyList()
}
} else {
Logger.err("Unsuccessfully fetched transactions error code: ${response.code()} body: ${response.errorBody()?.charStream()?.readText()} ")
return emptyList()
}
return transactions
}

}





Original file line number Diff line number Diff line change
Expand Up @@ -31,35 +31,34 @@ import com.stasbar.taxledger.models.Transactionable
import java.math.BigDecimal
import java.util.*

class BitMarketTransaction(val total : Int,
val start : Int,
val count : Int,
val results : List<Trade>) {

}
data class BitmarketTransaction(val id: String,
val type: String,
val amountCrypto: BigDecimal,
val currencyCrypto: String,
val amountFiat: BigDecimal,
val currencyFiat: String,
val rate: BigDecimal,
val commission: BigDecimal?,
val time: Long) : Transactionable {

override fun operationType() = when (type) {
"buy" -> OperationType.BUY
"sell" -> OperationType.SELL
"deposit" -> OperationType.DEPOSIT
"withdraw" -> OperationType.WITHDRAW
else -> OperationType.UNSUPPORTED

data class Trade(val id:String,
val type : String,
val amountCrypto : BigDecimal,
val currencyCrypto : String,
val amountFiat : BigDecimal,
val currencyFiat : String,
val rate : BigDecimal,
val time : Date) : Transactionable {

override fun operationType(): OperationType {
return if (type == "buy") OperationType.BUY else OperationType.SELL
}

override fun toTransaction(): Transaction {
return if(operationType() == OperationType.BUY) toBuyTransaction() else toSellTransaction()
return if (operationType() == OperationType.BUY) toBuyTransaction() else toSellTransaction()
}

private fun toBuyTransaction(): Transaction {
return Transaction(exchangeName = Abucoins.name
, id = id
, time = time
, time = Date(time)
, operationType = operationType()
, bought = amountCrypto
, boughtCurrency = currencyCrypto
Expand All @@ -73,7 +72,7 @@ data class Trade(val id:String,

return Transaction(exchangeName = Abucoins.name
, id = id
, time = time
, time = Date(time)
, operationType = operationType()
, bought = amountFiat
, boughtCurrency = currencyFiat
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017 Stanislaw stasbar Baranski
* Copyright (c) 2018 Stanislaw stasbar Baranski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -26,21 +26,23 @@ package com.stasbar.taxledger.exchanges.bitmarket.requests

import com.google.gson.annotations.SerializedName

abstract class BaseRequest{
abstract class BitmarketBaseRequest {
abstract val method : Method
val tonce : Long = System.currentTimeMillis() / 1000

open fun toMap(): MutableMap<String, String> {
val map: MutableMap<String, String> = HashMap()
map.put("method",method.methodName)
map.put("tonce",tonce.toString())
map.put("tonce", (System.currentTimeMillis() / 1000).toString())
return map
}

}
enum class Method(val methodName: String){
@SerializedName("trades")TRADES("trades"),
@SerializedName("info")INFO("info");
@SerializedName("info")
INFO("info"),
@SerializedName("history")
HISTORY("history");

override fun toString(): String {
return methodName
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2018 Stanislaw stasbar Baranski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* __ __
* _____/ /_____ ______/ /_ ____ ______
* / ___/ __/ __ `/ ___/ __ \/ __ `/ ___/
* (__ ) /_/ /_/ (__ ) /_/ / /_/ / /
* /____/\__/\__,_/____/_.___/\__,_/_/
* taxledger@stasbar.com
*/

package com.stasbar.taxledger.exchanges.bitmarket.requests

class BitmarketHistoryRequest(val currency: String, val count: Int? = null, val start: Int? = null) : BitmarketBaseRequest() {
override val method: Method = Method.HISTORY

override fun toMap(): MutableMap<String, String> {
val map = super.toMap()
map["currency"] = currency
count?.let { map.put("count", it.toString()) }
start?.let { map.put("start", it.toString()) }
return super.toMap()
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017 Stanislaw stasbar Baranski
* Copyright (c) 2018 Stanislaw stasbar Baranski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -24,4 +24,4 @@

package com.stasbar.taxledger.exchanges.bitmarket.requests

class InfoRequest(override val method: Method = Method.INFO) : BaseRequest()
class InfoRequest(override val method: Method = Method.INFO) : BitmarketBaseRequest()

0 comments on commit 7c30ae9

Please sign in to comment.