为什么我的Poloniex贷款机器人无法返回平衡?

时间:2017-09-17 04:02:37

标签: java http bots poloniex

最近,作为一个个人好奇心项目,我一直在编写一个非常简单的机器人,用于Poloniex(一种加密货币交换)。我已经能够使公共API正常工作,但是当我开始测试交易API时,事情开始分崩离析。当我运行这个(以及30个其他变体以试图让事情发挥作用)时,我得到的就是 {"error":"Invalid command."}。我是新手基本上使用我正在使用的每一个库,因此我可以缩小范围,但我无法缩小范围。

Poloniex API文档位于:https://poloniex.com/support/api/

public String returnBalances() {
    try {
        long nonce = System.nanoTime();
        String params = "command=returnBalances&nonce=" + nonce;

        URL u = new URL(URL_PRIVATE + "?" + params);

        String sign = getSign(params);

        if(sign == null) return null;

        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
        huc.setRequestMethod("GET");
        huc.setRequestProperty("Key", API_Key);
        huc.setRequestProperty("Sign", sign);
        huc.setRequestProperty("nonce", String.valueOf(nonce));

        return getDataFromHUC(huc);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private String getSign(String c) {
    try {
        SecretKeySpec mac_key = new SecretKeySpec(API_secret.getBytes(), "HmacSHA512");
        Mac mac = Mac.getInstance("HmacSHA512");
        mac.init(mac_key);
        String sign = bytesToHex(mac.doFinal((c).getBytes()));
        return sign;
    }
    catch (Exception e) {
        return null;
    }
}
private String getDataFromHUC(HttpURLConnection huc) {
    try {
        huc.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line+"\n");
        }
        br.close();
        String data = sb.toString();

        return data;
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

此外,当我搜索搜索的内容时,我发现没有一个人使用java.net库(我是)。我完全错过了我应该做的事情吗?如果可能的话,我更愿意使用这些库,所以我可以尽可能多地了解幕后发生的事情。

对不起,如果这个网站或其他地方有明显的答案。我已经在这里工作了好几个小时而没有任何进展,所以我一定会犯错误。

P.S。我知道我的运行时错误处理可能质量很差,但我没有遇到任何问题,所以改进它是一个低优先级。

1 个答案:

答案 0 :(得分:0)

如提供的文档中所述,整个TradingAPI需要POST请求。

因此,您需要url(r'^polls/', include('polls.urls', namespace='test'))

而不是huc.setRequestMethod("GET");

您可能还需要在此之后启用输入和输出:

huc.setRequestMethod("POST");

不要忘记设置内容类型和内容长度:

huc.setDoInput(true);
huc.setDoOutput(true);

而不是将参数添加到URL的末尾,您需要将它们写入输出(在设置请求属性后立即):

huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty("Content-Length", params.length());

它也可以像你不需要将nonce作为请求属性一样发送。

我希望这有帮助!