hidechae hidechae - 6 months ago 96
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)
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.


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`)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download