hidechae hidechae - 2 months ago 33
Scala Question

How to call poloniex trading api in scala

My code is following.

import org.apache.commons.codec.binary.Hex
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.util.ByteString
import javax.crypto.spec.SecretKeySpec
import javax.crypto.Mac

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class Poloniex {
def post(postData: String): Future[HttpResponse] = {
val command = "returnBalances"
val nonce = (System.currentTimeMillis / 1000).toString
val postData = s"nonce=$nonce&command=$command"
val headers: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(
RawHeader("Key", API_KEY),
RawHeader("Sign", hmacSha512(postData))
)

val entity = HttpEntity(postData)

for {
r <- Http().singleRequest(HttpRequest(HttpMethods.POST, TRADING_URL, headers, entity))
} yield r
}

private def hmacSha512(postData: String): String = {
val secret = new SecretKeySpec(API_SECRET.getBytes, HMAC_SHA512)
val mac = Mac.getInstance(HMAC_SHA512)
mac.init(secret)
val result: Array[Byte] = mac.doFinal(postData.getBytes)
new String(Hex.encodeHex(result))
}
}


I get

{"error":"Invalid command."}


But I couldn't find why I get error.
Can you find the reason why it get error?

The api documentation is here.
https://poloniex.com/support/api/

Thanks.

Answer Source

The content type of the request must be application/x-www-form-urlencoded. To set this, use FormData:

val entity =
  FormData(Map("nonce" -> nonce, "command" -> command)).toEntity(HttpCharsets.`UTF-8`)