API Language Examples


sa_ddam213
Gender: Unknown
Country: Unknown
Threads: 18, Posts: 99
#0

 

Below you can find examples of connecting and using the Cryptopia API in various lanuages 

 

Lanuages Examples:

  1. C# .NET
  2. Ruby
  3. Python
  4. Curl
  5. Java
  6. Php
  7. NodeJs

 



Posted: 9/7/2015 9:30:53 PM Edited: 5/10/2016 10:19:45 PM
sa_ddam213
Gender: Unknown
Country: Unknown
Threads: 18, Posts: 99
#1

Quick C# Public api example (GetCurrencies)

string requestUri = "https://www.cryptopia.co.nz/Api/GetCurrencies";
using (var client = new HttpClient())
{
   var jsonData = await client.GetStringAsync(requestUri);
}

 

Quick C# Private api example (GetBalance)

string apiKey = "my key";
string apiSecret = "my secret";
string requestUri = "https://www.cryptopia.co.nz/Api/GetBalance";
var postData = new
{
    Currency = "DOT"
};

// Create Request var request = new HttpRequestMessage(); request.Method = HttpMethod.Post; request.RequestUri = new Uri(requestUri); request.Content = new ObjectContent(typeof(object), postData, new JsonMediaTypeFormatter()); // Authentication string requestContentBase64String = string.Empty; if (request.Content != null) { // Hash content to ensure message integrity using (var md5 = MD5.Create())
{ requestContentBase64String = Convert.ToBase64String(md5.ComputeHash(await request.Content.ReadAsByteArrayAsync()));
} } //create random nonce for each request var nonce = Guid.NewGuid().ToString("N"); //Creating the raw signature string var signature = Encoding.UTF8.GetBytes(string.Concat(apiKey, HttpMethod.Post, HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower()), nonce, requestContentBase64String)); using (var hmac = new HMACSHA256(Convert.FromBase64String(apiSecret))) { request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}", apiKey, Convert.ToBase64String(hmac.ComputeHash(signature)), nonce)); } // Send Request using (var client = new HttpClient()) { var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync());
//{"Success":true,"Error":null,"Data":[{"CurrencyId":2,"Symbol":"DOT","Total":9646.07411016,"Available":9646.07411016,"Unconfirmed":0.0,"HeldForTrades":0.0,"PendingWithdraw":0.0,"Address":"1HEfio1kreDBgj5uCw4VHbEDSgc6YJXfTN","Status":"OK","StatusMessage":null}]} } }

 



Posted: 9/7/2015 10:05:28 PM Edited: 9/11/2015 6:57:55 AM
zen
Gender: Male
Country: Afghanistan
Threads: 0, Posts: 1
#2

https://github.com/sigwo/node-cryptopia

Does all the public calls in node.js. Private calls coming soon. ;)

I'll push a npm module for easier pulling after I'm finished with private calls. 



Posted: 9/9/2015 7:11:20 AM
dropoutupshot
Gender: Unknown
Country: Unknown
Threads: 1, Posts: 12
#3

 

http://pastebin.com/f13k4bYh

Python public & private api calls !!!

#!/usr/bin/python

import time
import hmac
import urllib
import requests
import hashlib
import base64
import sys
import json

API_KEY = 'YOUR API KEY'
API_SECRET = 'YOUR API SECRET'


def api_query( method, req = None ):
if not req:
req = {}
#print "def api_query( method = " + method + ", req = " + str( req ) + " ):"
time.sleep( 1 )
public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ])
if method in public_set:
url = "https://www.cryptopia.co.nz/api/" + method
if req:
for param in req:
url += '/' + str( param )
r = requests.get( url )
elif method in private_set:
url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )
response = r.text
print "( Response ): " + response
return response.replace("false","False").replace("true","True").replace('":null','":None' )


# Public:
# +
# print api_query("GetCurrencies")

# +
print api_query("GetMarket", [ 100, 6 ] )
# {"Success":True,"Message":None,"Data":{"TradePairId":100,"Label":"DOT/BTC","AskPrice":0.00000020,"BidPrice":0.00000019,"Low":0.00000019,"High":0.00000021,"Volume":1263556.65136394,"LastPrice":0.00000019,"LastVolume":774.83684404,"BuyVolume":50896673.08961847,"SellVolume":33046510.52562918,"Change":0.0},"Error":None}

# Private:
print api_query("GetBalance")

# +
# print api_query("GetBalance", {'CurrencyId':2} )

 



Posted: 9/10/2015 7:04:17 AM Edited: 9/11/2015 3:31:59 PM
dropoutupshot
Gender: Unknown
Country: Unknown
Threads: 1, Posts: 12
#4

http://pastebin.com/YwX2p49i

 

PHP public & private api calls. 

 

 

<?php

function api_query($method, array $req = array()) {
$API_KEY = 'YOUR API KEY';
$API_SECRET = 'YOUR API SECRET';
$public_set = array( "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" );
$private_set = array( "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" );
static $ch = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; Cryptopia.co.nz API PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
if ( in_array( $method ,$public_set ) ) {
$url = "https://www.cryptopia.co.nz/api/" . $method;
if ($req) { foreach ($req as $r ) { $url = $url . '/' . $r; } }
curl_setopt($ch, CURLOPT_URL, $url );
} elseif ( in_array( $method, $private_set ) ) {
$url = "https://www.cryptopia.co.nz/Api/" . $method;
$nonce = explode(' ', microtime())[1];
$post_data = json_encode( $req );
$m = md5( $post_data, true );
$requestContentBase64String = base64_encode( $m );
$signature = $API_KEY . "POST" . strtolower( urlencode( $url ) ) . $nonce . $requestContentBase64String;
$hmacsignature = base64_encode( hash_hmac("sha256", $signature, base64_decode( $API_SECRET ), true ) );
$header_value = "amx " . $API_KEY . ":" . $hmacsignature . ":" . $nonce;
$headers = array("Content-Type: application/json; charset=utf-8", "Authorization: $header_value");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $req ) );
}
// run the query
$res = curl_exec($ch);
if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
return $res;
}


// Public:
// +
// echo api_query( "GetCurrencies" );
// +
// echo api_query( "GetTradePairs" );
// +
// echo api_query( "GetMarkets" );
// +
// echo api_query( "GetMarkets", array( 6 ) );
// +
// echo api_query("GetMarket", array( 100, 6 ) );
// +
// echo api_query("GetMarketHistory", array( 100 ) );
// +
// echo api_query("GetMarketOrders", array( 100 ) );

// Private:
// +
// echo api_query("GetBalance", array( 'CurrencyId'=> 2 ) ) . PHP_EOL;

// +
echo api_query("GetOpenOrders", array( 'Market'=> "DOT/DOGE" ) );


?>


Posted: 9/10/2015 7:26:35 AM Edited: 9/11/2015 8:10:14 PM
dropoutupshot
Gender: Unknown
Country: Unknown
Threads: 1, Posts: 12
#5

http://pastebin.com/TBsSZQtK

 

Ruby public & private api calls!

  

#!/usr/bin/ruby

require "uri"
require "set"
require "cgi"
require "json"
require "base64"
require "openssl"
require "net/http"
require "net/https"

def api_query( method, req = {} )
_API_KEY = "YOUR_API_KEY"
_API_SECRET = "YOUR_API_SECRET"
public_set = Set[ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ]
private_set = Set[ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ]
if public_set.include?( method )
url = 'https://www.cryptopia.co.nz/api/' + method
if req
for param in req
uri += '/' + param.to_s
end
end
uri = URI( url )
r = Net::HTTP::Get.new( uri.path, initheader = {'Content-Type' =>'application/json'})
elsif private_set.include?( method )
url = "https://www.cryptopia.co.nz/Api/" + method
uri = URI( url )
nonce = Time.now.to_i.to_s
post_data = req.to_json.to_s
  md5 = Digest::MD5.new.digest( post_data )
requestContentBase64String = Base64.encode64( md5 )
signature = ( _API_KEY + "POST" + CGI::escape( url ).downcase + nonce + requestContentBase64String ).strip
hmac_raw = OpenSSL::HMAC.digest('sha256', Base64.decode64( _API_SECRET ), signature )
hmacsignature = Base64.encode64( OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), Base64.decode64( _API_SECRET ), signature) ).strip
header_value = "amx " + _API_KEY + ":" + hmacsignature + ":" + nonce
r = Net::HTTP::Post.new(uri.path)
r.body = req.to_json
r["Authorization"] = header_value
r["Content-Type"] = "application/json; charset=utf-8"
end
sleep(1)
https = Net::HTTP.new( uri.host, uri.port )
https.use_ssl = true
r["User-Agent"] = "Mozilla/4.0 (compatible; Cryptopia.co.nz API Ruby client)"
res = https.request( r )
return res.body
end


# Public
# print api_query('GetCurrencies')
# +
# print api_query( "GetTradePairs" );
# +
# print api_query( "GetMarkets" );
# +
# print api_query( "GetMarkets", [ 6 ] );
# +
# print api_query("GetMarket", [ 100, 6 ] );
# +
# print api_query("GetMarketHistory", [ 100 ] );
# +
# print api_query("GetMarketOrders", [ 100 ] );

# Private
# print api_query("GetBalance")

print api_query("GetBalance", {'CurrencyId' => 2} )



Posted: 9/10/2015 7:39:33 AM Edited: 9/11/2015 10:44:45 PM
dropoutupshot
Gender: Unknown
Country: Unknown
Threads: 1, Posts: 12
#6

http://pastebin.com/JUnDUj3H

Curl public & private api calls.

 

# Public:
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetCurrencies
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetTradePairs
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarkets
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarkets/6
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarket/100
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarket/100/6
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarketHistory/100
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarketOrders/100
# curl -H "Content-Type: application/json" -X GET https://www.cryptopia.co.nz/api/GetMarketOrders/100

##############################

# Private:
API_KEY='YOUR_API_KEY'
API_SECRET='YOUR_API_SECRET'

api_query(){
method="$1"
post_data="$2"
[ -z "$post_data" ] && post_data="{}"
url="https://www.cryptopia.co.nz/Api/$method"
nonce="$(date +%s)"
requestContentBase64String="$( printf "$post_data" | openssl dgst -md5 -binary | base64 )"
url_encoded=$( printf $url | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- "" | cut -c 3- | awk '{print tolower($0)}')
signature="${API_KEY}POST${url_encoded}${nonce}${requestContentBase64String}"
hmacsignature=$(echo -n $signature | openssl sha256 -binary -hmac "$(echo -n $API_SECRET | base64 -d)" | base64 )
header_value="amx ${API_KEY}:${hmacsignature}:${nonce}"

curl \
--header "Authorization: $header_value" \
--header "Content-Type: application/json; charset=utf-8" \
--request 'POST' \
--data "${post_data}" \
"${url}"
}

# +
# api_query GetBalance '{"CurrencyId": 2}'

# +
api_query GetBalance

 

 

 



Posted: 9/10/2015 7:56:29 AM Edited: 9/13/2015 10:55:12 AM
elbandi
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 2
#7

Hi,

Is there a sandbox api url?

 

If i develop some app, i dont want to use live coins. (it would be very bad, if i miss a comma, and i buy 1 coin for 100 btc...)

 

Elbandi



Posted: 10/24/2015 2:00:20 PM
dropoutupshot
Gender: Unknown
Country: Unknown
Threads: 1, Posts: 12
#8

 

Private & Public Api Calls via Node.JS

 

http://pastebin.com/K4nYb7MX 

 

var https = require('https');
var async = require('async');
var crypto = require('crypto');

API_KEY='YOUR_API_KEY'
API_SECRET='YOUR_API_SECRET'

function apiQuery( callback2, method, params ) { if ( ! params ) params = {}; var public_set = [ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ]; var private_set = [ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ]; var host_name = 'www.cryptopia.co.nz'; var uri = '/Api/' + method; if ( public_set.indexOf( method ) > -1 ) { if ( params ) uri += "/" + params.join('/'); var options = { host: host_name, path: uri, }; callback = function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { return callback2(null, str); }); } https.request(options, callback).end(); } else if ( private_set.indexOf( method ) > -1 ) { var nonce = Math.floor(new Date().getTime() / 1000); var md5 = crypto.createHash('md5').update( JSON.stringify( params ) ).digest(); var requestContentBase64String = md5.toString('base64'); var signature = API_KEY + "POST" + encodeURIComponent( 'https://' + host_name + uri ).toLowerCase() + nonce + requestContentBase64String; var hmacsignature = crypto.createHmac('sha256', new Buffer( API_SECRET, "base64" ) ).update( signature ).digest().toString('base64'); var header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce; var headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }; var options = { host: host_name, path: uri, method: 'POST', headers: headers }; callback = function(response) { var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { return callback2(null, str); }); } var req = https.request(options, callback); req.write( JSON.stringify( params ) ); req.end(); } }

async.series([ function(callback) { // Public: // apiQuery( callback, "GetCurrencies" ); // + // apiQuery( callback, "GetMarket", [ 100, 6 ] ); // + // Private: // apiQuery( callback, "GetBalance" ); // + // apiQuery( callback, "SubmitTrade", { 'Market': "020/DOGE", 'Type': "Sell", 'Rate': 0.001, 'Amount': 1000 } ) // [ '{"Success":true,"Error":null,"Data":{"OrderId":496433,"FilledOrders":[]}}' ] apiQuery( callback, 'CancelTrade', { 'CancelType': 'Trade', 'OrderId': 496433 } ); // + // [ '{"Success":true,"Error":null,"Data":[496433]}' ] }, ], function(error, results) { console.log(results); });



Posted: 10/30/2015 3:01:53 PM
sa_ddam213
Gender: Unknown
Country: Unknown
Threads: 18, Posts: 99
#9

Java Private API example (thanks sampey)

 

import JSON.JsonObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;

/**
 *
 * @author Sampey
 */

public class HttpCryptopia {
   
    public String privateUrl = "https://www.cryptopia.co.nz/Api/";
    public String publicKey = "YOUR_PUBLIC_KEY";
    public String privateKey = "YOUR_PRIVATE_KEY";
   
    public HttpCryptopia(String method,String jSonPostParam) throws Exception {
        String urlMethod = privateUrl + method;
        String nonce     = String.valueOf(System.currentTimeMillis());
        
        String reqSignature =
                publicKey
                + "POST"
                + URLEncoder.encode(urlMethod,StandardCharsets.UTF_8.toString()).toLowerCase()
                + nonce
                + getMD5_B64(jSonPostParam);
       
        String AUTH = "amx "
                + publicKey
                +":"
                + this.sha256_B64(reqSignature)
                +":"
                + nonce;

        String response = this.continueForHttp(urlMethod, jSonPostParam,AUTH);
       
        System.out.println("API RESPONSE : " + response);
    }
   
    private String continueForHttp(String urlMethod, String postParam,String AUTH) throws Exception {
        URLConnection con = new URL(urlMethod).openConnection(); // CREATE POST CONNECTION
        con.setDoOutput(true);
       
        HttpsURLConnection httpsConn = (HttpsURLConnection) con;
        httpsConn.setRequestMethod("POST");
        httpsConn.setInstanceFollowRedirects(true);

        con.setRequestProperty("Authorization", AUTH);
        con.setRequestProperty("Content-Type", "application/json");
       
        // WRITE POST PARAMS
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParam);
        wr.flush();
        wr.close();

        // READ THE RESPONSE
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
   
    private String getMD5_B64(String postParameter) throws Exception {
        return Base64.getEncoder().encodeToString(MessageDigest.getInstance("MD5").digest(postParameter.getBytes("UTF-8")));
    }
       
    private String sha256_B64(String msg) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(Base64.getDecoder().decode(privateKey), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(msg.getBytes("UTF-8")));
    }
   
/*-------------------- // MAIN IS TO AUTO-EXECUTE THIS CLASS -----------------------------------*/   
   
    public static void main(String[] args) {
        try {
            // YOU CAN FORMAT THE JSON STRING USING THE LIBRARY YOU PREFER (OR MANUALLY)
            JsonObject jo = new JsonObject();
            jo.add("Currency", "DOT"); // EXAMPLE {"Currency":"DOT"}

            new HttpCryptopia("GetBalance", jo.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}


Posted: 5/10/2016 10:15:09 PM
191WESotw6vPEDEe
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#10

 

 

the old node js script does no longer work.. i can not access private funtions like GetBalance.. the server replies:

{"Success":false,"Error":"Bad Request","Data":null}

 

any updates on the api? or a node specific problem ( https and so on.. )

i also opened ticket 6019..

 

edit: the above java code is working.. but it's pretty the same.. so who can see a difference?

 

 

var https = require('https');
var async = require('async');
var crypto = require('crypto');

API_KEY='YOUR_API_KEY'
API_SECRET='YOUR_API_SECRET'

function apiQuery( callback2, method, params ) { if ( ! params ) params = {}; var public_set = [ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ]; var private_set = [ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ]; var host_name = 'www.cryptopia.co.nz'; var uri = '/Api/' + method; if ( public_set.indexOf( method ) > -1 ) { if ( params ) uri += "/" + params.join('/'); var options = { host: host_name, path: uri, }; callback = function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { return callback2(null, str); }); } https.request(options, callback).end(); } else if ( private_set.indexOf( method ) > -1 ) { var nonce = Math.floor(new Date().getTime() / 1000); var md5 = crypto.createHash('md5').update( JSON.stringify( params ) ).digest(); var requestContentBase64String = md5.toString('base64'); var signature = API_KEY + "POST" + encodeURIComponent( 'https://' + host_name + uri ).toLowerCase() + nonce + requestContentBase64String; var hmacsignature = crypto.createHmac('sha256', new Buffer( API_SECRET, "base64" ) ).update( signature ).digest().toString('base64'); var header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce; var headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }; var options = { host: host_name, path: uri, method: 'POST', headers: headers }; callback = function(response) { var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { return callback2(null, str); }); } var req = https.request(options, callback); req.write( JSON.stringify( params ) ); req.end(); } }

async.series([ function(callback) { // Public: // apiQuery( callback, "GetCurrencies" ); // + // apiQuery( callback, "GetMarket", [ 100, 6 ] ); // + // Private: // apiQuery( callback, "GetBalance" ); // + // apiQuery( callback, "SubmitTrade", { 'Market': "020/DOGE", 'Type': "Sell", 'Rate': 0.001, 'Amount': 1000 } ) // [ '{"Success":true,"Error":null,"Data":{"OrderId":496433,"FilledOrders":[]}}' ] apiQuery( callback, 'CancelTrade', { 'CancelType': 'Trade', 'OrderId': 496433 } ); // + // [ '{"Success":true,"Error":null,"Data":[496433]}' ] }, ], function(error, results) { console.log(results); });

dropoutupshot: 10/30/2015 3:01:53 PM

 

 



Posted: 5/14/2016 3:47:27 PM Edited: 7/12/2016 10:46:39 AM
volovdmbot
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 5
#11

 

http://pastebin.com/f13k4bYh

Python public & private api calls !!!

...

url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )

...

 

in Python 3 it looks like:

 

url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data.encode('utf-8'))
requestContentBase64String = base64.b64encode(m.digest()).decode('utf-8')
signature = API_KEY + "POST" + urllib.parse.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature.encode('utf-8'), hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature.decode('utf-8') + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )



 

dropoutupshot: 9/10/2015 7:04:17 AM

 



Posted: 5/17/2016 8:50:42 PM Edited: 5/17/2016 8:55:14 PM
sa_ddam213
Gender: Unknown
Country: Unknown
Threads: 18, Posts: 99
#12

the old node js script does no longer work.. i can not access private funtions like GetBalance.. the server replies: {"Success":false,"Error":"Bad Request","Data":null} any updates on the api? or a node specific problem ( https and so on.. ) i also opened ticket 6019.. edit: the above java code is working.. but it's pretty the same.. so who can see a difference?
191WESotw6vPEDEe: 5/14/2016 3:47:27 PM

 

It could be that nodejs https module is adding some padding to the content witch is cauing the api serializer to discard the message

Try adding a 'Content-Length' parameter to the header


var headers = {
 'Authorization': header_value,
 'Content-Type':'application/json; charset=utf-8',
 'Content-Length' : Buffer.byteLength(JSON.stringify(params)),
};


Posted: 7/12/2016 10:48:55 AM
shawmjustin
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#13

I am currently building a node.js client that makes this a lot easier to use. As of now I only have it working for 2 methods. (GetBalance, GetCurrencies) Here's the github directory for this client https://github.com/shawmjustin/cryptopia-client. There are directions in the README.md. 

 

If you need anything specific, please let me know and I can prioritize which methods I work on in which order..  I'm sort of just putting this together in my free time.

 

Twitter: https://twitter.com/_justin_shaw

Instagram: https://www.instagram.com/stupid50s/

Snapchat username: shawmjustin

 

Feel free to connect with me!



Posted: 6/1/2017 7:12:23 PM Edited: 6/1/2017 7:13:10 PM
rossc
Gender: Unknown
Country: Unknown
Threads: 1, Posts: 2
#14

Hi, im having trouble with submit trade api in php. can you please give example? ive tried everything and keep getting a bad request error, thanks.



Posted: 6/15/2017 3:02:22 PM Edited: 6/15/2017 3:03:04 PM
hakan7punkt
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 19
#15

Hi, im having trouble with submit trade api in php. can you please give example? ive tried everything and keep getting a bad request error, thanks.

rossc: 6/15/2017 3:02:22 PM

 There is a working example in this thread for PHP. You can check your code with it.



Posted: 6/16/2017 3:36:48 PM
bitterresentful
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#16

When using the Private API + PHP you MUST include the Currency parameter in the $req array when using GetBalance.

If you want to get all of your balances you must set $req = array('Currency'=>'');

Using the PHP API wrapper this would look like:

api_query('GetBalance', array('Currency'=>''));

The API documentation for GetBalance lists Currency as an optional parameter. I kept getting a Bad Request error which took a while to solve. Till I ran across this thread: https://www.cryptopia.co.nz/Forum/Thread/1324?postId=7773




Posted: 7/14/2017 12:14:35 AM
mrcappuccino
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#17

Hello, using this as a test and inputted my API keys.

print api_query("GetBalance")


print api_query("GetBalance", {'CurrencyId':2} )

 

print api_query("GetBalance", {'CurrencyID':'BTC'})

 

All of these give an empty response. Anyone know what is wrong?

 

 

http://pastebin.com/f13k4bYh

Python public & private api calls !!!

#!/usr/bin/python

import time
import hmac
import urllib
import requests
import hashlib
import base64
import sys
import json

API_KEY = 'YOUR API KEY'
API_SECRET = 'YOUR API SECRET'


def api_query( method, req = None ):
if not req:
req = {}
#print "def api_query( method = " + method + ", req = " + str( req ) + " ):"
time.sleep( 1 )
public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ])
if method in public_set:
url = "https://www.cryptopia.co.nz/api/" + method
if req:
for param in req:
url += '/' + str( param )
r = requests.get( url )
elif method in private_set:
url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )
response = r.text
print "( Response ): " + response
return response.replace("false","False").replace("true","True").replace('":null','":None' )


# Public:
# +
# print api_query("GetCurrencies")

# +
print api_query("GetMarket", [ 100, 6 ] )
# {"Success":True,"Message":None,"Data":{"TradePairId":100,"Label":"DOT/BTC","AskPrice":0.00000020,"BidPrice":0.00000019,"Low":0.00000019,"High":0.00000021,"Volume":1263556.65136394,"LastPrice":0.00000019,"LastVolume":774.83684404,"BuyVolume":50896673.08961847,"SellVolume":33046510.52562918,"Change":0.0},"Error":None}

# Private:
print api_query("GetBalance")

# +
# print api_query("GetBalance", {'CurrencyId':2} )

 

dropoutupshot: 9/10/2015 7:04:17 AM

 



Posted: 7/18/2017 8:32:38 AM
amazzuca
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#18

 

http://pastebin.com/f13k4bYh

Python public & private api calls !!!

#!/usr/bin/python

import time
import hmac
import urllib
import requests
import hashlib
import base64
import sys
import json

API_KEY = 'YOUR API KEY'
API_SECRET = 'YOUR API SECRET'


def api_query( method, req = None ):
if not req:
req = {}
#print "def api_query( method = " + method + ", req = " + str( req ) + " ):"
time.sleep( 1 )
public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ])
if method in public_set:
url = "https://www.cryptopia.co.nz/api/" + method
if req:
for param in req:
url += '/' + str( param )
r = requests.get( url )
elif method in private_set:
url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )
response = r.text
print "( Response ): " + response
return response.replace("false","False").replace("true","True").replace('":null','":None' )


# Public:
# +
# print api_query("GetCurrencies")

# +
print api_query("GetMarket", [ 100, 6 ] )
# {"Success":True,"Message":None,"Data":{"TradePairId":100,"Label":"DOT/BTC","AskPrice":0.00000020,"BidPrice":0.00000019,"Low":0.00000019,"High":0.00000021,"Volume":1263556.65136394,"LastPrice":0.00000019,"LastVolume":774.83684404,"BuyVolume":50896673.08961847,"SellVolume":33046510.52562918,"Change":0.0},"Error":None}

# Private:
print api_query("GetBalance")

# +
# print api_query("GetBalance", {'CurrencyId':2} )

 

dropoutupshot: 9/10/2015 7:04:17 AM

 

Hi, I'm receiving the following error:

TypeError: Incorrect padding. 

 

It has to do wit the 

hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())

line.

 

somebody help please!

 

Thanks.



Posted: 7/18/2017 7:00:14 PM
orenmagic
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#19

On NodeJS example:

Excuse me but this is strange

 if ( ! params ) params = {};

...

if ( params ) uri += "/" + params.join('/');

On empty params it tries to perform join on Object => error

Edited my script to

 if ( ! params ) params = [];


Posted: 8/8/2017 8:11:21 PM Edited: 8/8/2017 8:15:33 PM
Al_z
Gender: Unknown
Country: Unknown
Threads: 2, Posts: 22
#20

Python 3.6 Public API Frontend
===================

https://github.com/doubleelforbes/CTPAPI

Python 3.6 Private API Frontend
====================

https://github.com/doubleelforbes/CTPrivAPI



Posted: 8/10/2017 2:37:54 PM
adrival0799
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#21

 

http://pastebin.com/f13k4bYh

Python public & private api calls !!!

#!/usr/bin/python

import time
import hmac
import urllib
import requests
import hashlib
import base64
import sys
import json

API_KEY = 'YOUR API KEY'
API_SECRET = 'YOUR API SECRET'


def api_query( method, req = None ):
if not req:
req = {}
#print "def api_query( method = " + method + ", req = " + str( req ) + " ):"
time.sleep( 1 )
public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ])
if method in public_set:
url = "https://www.cryptopia.co.nz/api/" + method
if req:
for param in req:
url += '/' + str( param )
r = requests.get( url )
elif method in private_set:
url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )
response = r.text
print "( Response ): " + response
return response.replace("false","False").replace("true","True").replace('":null','":None' )


# Public:
# +
# print api_query("GetCurrencies")

# +
print api_query("GetMarket", [ 100, 6 ] )
# {"Success":True,"Message":None,"Data":{"TradePairId":100,"Label":"DOT/BTC","AskPrice":0.00000020,"BidPrice":0.00000019,"Low":0.00000019,"High":0.00000021,"Volume":1263556.65136394,"LastPrice":0.00000019,"LastVolume":774.83684404,"BuyVolume":50896673.08961847,"SellVolume":33046510.52562918,"Change":0.0},"Error":None}

# Private:
print api_query("GetBalance")

# +
# print api_query("GetBalance", {'CurrencyId':2} )

 

dropoutupshot: 9/10/2015 7:04:17 AM

 

Hi, I'm receiving the following error:

TypeError: Incorrect padding. 

 

It has to do wit the 

hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())

line.

 

somebody help please!

 

Thanks.

amazzuca: 7/18/2017 7:00:14 PM

Had the same issue. Its an error when the base.64decode function tries to decode the Api Secret and this one is missing one character.

 

I'm not sure if it was because i missed a "=" when copying the Api secret from my panel, but I just generated a new key and solved it.



Posted: 8/12/2017 5:39:30 PM
coinmyne
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 2
#22

Here is my object oriented python wrapper. I haven't tested the withdrawal, tipping or transfering functions yet, because I don't use these features of the API. Enjoy.

import urllib
import urllib2
import json
import time
import hmac,hashlib
import random
import base64

	
class cryptopia:
	def __init__(self, key='', secret='', url='https://www.cryptopia.co.nz/api/'):
		self.apikey = key
		self.apisecret = secret
		self.apisite = url
		self.api_params = {}
		return
		
	def public_api(self, meth):
		return json.loads(urllib2.urlopen(urllib2.Request(self.apisite + meth)).read())
		
	#this method prepares the post data and perfomes the hashes and signatures for private API calls.
	#  NOTE: much of the code for the private_api method has been taken or adapted from https://pastebin.com/f13k4bYh
	def private_api(self, meth):
		time.sleep(1)
		params = self.api_params
		url = self.apisite + meth
		nonce = str(int(time.time()))
		post_data = json.dumps(params)
		hash = hashlib.md5()
		hash.update(post_data)
		base64hash = base64.b64encode(hash.digest())
		sig = self.apikey + "POST" + urllib.quote_plus(url).lower() + nonce + base64hash
		hmacsig = base64.b64encode(hmac.new(base64.b64decode(self.apisecret), sig, hashlib.sha256).digest())
		hdr = "amx " + self.apikey + ":" + hmacsig + ":" + nonce
		headers = { 'Authorization': hdr, 'Content-Type':'application/json; charset=utf-8' }
		request = urllib2.Request(url, data=post_data, headers=headers)
		return urllib2.urlopen(request).read()
	
# Public API methods

	#gets a list of (and information about) all currencies
	def getCurrencies(self):
		return self.public_api('GetCurrencies')
	
	#gets a list of (and information about) valid trading pairs
	def getTradePairs(self):
		return self.public_api('GetTradePairs')
	
	#gets data for markets for all base currencies or for a specified one.
	def getMarkets(self, BaseMarket='', Hours=24):
		p = 'GetMarkets'
		if (BaseMarket != ''):
			p += '/'
			p += BaseMarket
		p += '/'
		p += str(Hours)
		return self.public_api(p)
		
	#gets market data for a specific trading pair. Market can be a name (e.g, LTC_BTC), or
	#  a trade pair ID (e.g., 100)
	def getMarket(self, Market, Hours=24):
		return self.public_api('GetMarket/' + Market + '/' + str(Hours))
		
	#gets the market history for a specific trade pair
	def getMarketHistory(self, Market, Hours=24):
		return self.public_api('GetMarketHistory/' + Market + '/' + str(Hours))
		
	#gets the currently open buy and sell orders for a specific trade pair
	def getMarketOrders(self, Market, OrderCount=100):
		return self.public_api('GetMarketOrders/' + Market + '/' + str(OrderCount))

	#gets the currently open buy and sell orders for a list of trade pairs
	def getMarketOrderGroups(self, Market, OrderCount=100):
		return self.public_api('GetMarketOrderGroups/' + Market + '/' + str(OrderCount))

# Private API methods
		
	#gets all balances
	def getBalances(self):
		return self.private_api('GetBalance')
		
	#gets balance of a certain coin by symbol (e.g., BTC or LTC)
	def getBalanceByName(self, Currency):
		self.api_params.clear()
		self.api_params['Currency'] = Currency
		return self.private_api('GetBalance')
		
	#gets balance of a particular coin by the currency ID
	def getBalanceByID(self, CurrencyID):
		self.api_params.clear()
		self.api_params['CurrencyId'] = CurrencyID
		return self.private_api('GetBalance')
		
	#gets (or generates, if necessary) a deposit address for a coin by symbol
	def getDepositAddressByName(self, Currency):
		self.api_params.clear()
		self.api_params['Currency'] = Currency
		return self.private_api('GetDepositAddress')

	#gets (or generates, if necessary) a deposit address for a coin by currency ID
	def getDepositAddressByID(self, CurrencyID):
		self.api_params.clear()
		self.api_params['CurrencyId'] = CurrencyID
		return self.private_api('GetDepositAddress')
		
	#gets a list of all open orders, up to number of orders specified in OrderCount
	def getAllOpenOrders(self, OrderCount=100):
		self.api_params.clear()
		self.api_params['Count'] = OrderCount
		return self.private_api('GetOpenOrders')
		
	#gets a list of open orders for a certain trade pair by Market name (e.g., DOGE_BTC or DOT_LTC)
	def getOpenOrdersByMarket(self, Market, OrderCount=100):
		self.api_params.clear()
		self.api_params['Market'] = Market
		self.api_params['Count'] = OrderCount
		return self.private_api('GetOpenOrders')
		
	#gets a list of open orders for a certain trade pair based on the trade pair ID
	def getOpenOrdersByTradePairID(self, TradePairID, OrderCount=100):
		self.api_params.clear()
		self.api_params['TradePairId'] = TradePairID
		self.api_params['Count'] = OrderCount
		return self.private_api('GetOpenOrders')
		
	#gets a list of the most recent trades, up to the number of trades specified by TradeCount
	def getAllTradeHistory(self, TradeCount=100):
		self.api_params.clear()
		self.api_params['Count'] = TradeCount
		return self.private_api('GetTradeHistory')

	#gets a list of the most recent trades for a certain tade pair, based on the market name (e.g., DOGE_BTC)
	def getTradeHistoryByMarket(self, Market, TradeCount=100):
		self.api_params.clear()
		self.api_params['Market'] = Market
		self.api_params['Count'] = TradeCount
		return self.private_api('GetTradeHistory')

	#gets a list of the most recent trades for a certain trade pair, based on the trade pair ID
	def getTradeHistoryByTradePaidID(self, TradePairID, TradeCount=100):
		self.api_params.clear()
		self.api_params['TradePairId'] = TradePairID
		self.api_params['Count'] = TradeCount
		return self.private_api('GetTradeHistory')
		
	#gets a list of the most recent deposits, up to the number specified in DepositCount
	def getDeposits(self, DepositCount=100):
		self.api_params.clear()
		self.api_params['Type'] = 'Deposit'
		self.api_params['Count'] = DepositCount
		return self.private_api('GetTransactions')

	#gets a list of the most recent withdrawals, up to the number specified in WithdrawalCount
	def getWithdrawals(self, WithdrawalCount=100):
		self.api_params.clear()
		self.api_params['Type'] = 'Withdraw'
		self.api_params['Count'] = WithdrawalCount
		return self.private_api('GetTransactions')
		
	#submits a request (by market name - e.g., DOGE_BTC) to buy or sell the amount of coins specified 
	#  by Amount for the price specified by Rate. Valid trade types are "Buy" and "Sell"
	def submitTradeByMarket(self, Market, TradeType, Rate, Amount):
		self.api_params.clear()
		self.api_params['Market'] = Market
		self.api_params['Type'] = TradeType
		self.api_params['Rate'] = Rate
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitTrade')

	#submits a request (by trade pair ID) to buy or sell the amount of coins specified 
	#  by Amount for the price specified by Rate. Valid trade types are "Buy" and "Sell"
	def submitTradeByTradePairID(self, TradePairID, TradeType, Rate, Amount):
		self.api_params.clear()
		self.api_params['TradePairId'] = TradePairID
		self.api_params['Type'] = TradeType
		self.api_params['Rate'] = Rate
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitTrade')

	#cancels all open orders for all trade pairs
	def cancelAllTrades(self):
		self.api_params.clear()
		self.api_params['Type'] = 'All'
		return self.private_api('CancelTrade')
		
	#cancels all open orders for the trade pair specified by TradePairID
	def cancelAllTradePairTrades(self, TradePairID):
		self.api_params.clear()
		self.api_params['Type'] = 'TradePair'
		self.api_params['TradePairId'] = TradePairID
		return self.private_api('CancelTrade')
		
	#cancels a single order, specified by OrderID
	def cancelTrade(self, OrderID):
		self.api_params.clear()
		self.api_params['Type'] = 'Trade'
		self.api_params['OrderId'] = OrderID
		return self.private_api('CancelTrade')
		
	#submits a tip to the troll box by currency symbol
	def submitTipByName(self, Currency, ActiveUsers, Amount):
		self.api_params.clear()
		self.api_params['Currency'] = Currency
		self.api_params['ActiveUsers'] = ActiveUsers
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitTip')
		
	#submits a tip to the troll box by currency ID
	def submitTipByID(self, CurrencyID, ActiveUsers, Amount):
		self.api_params.clear()
		self.api_params['CurrencyId'] = CurrencyID
		self.api_params['ActiveUsers'] = ActiveUsers
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitTip')
		
	#submits a withdrawal request by currency symbol
	def submitWithdrawalByName(self, Currency, Address, PaymentID, Amount):
		self.api_params.clear()
		self.api_params['Currency'] = Currency
		self.api_params['Address'] = Address
		self.api_params['PaymentId'] = PaymentID
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitWithdraw')

	#submits a withdrawal request by currency ID
	def submitWithdrawalByName(self, CurrencyID, Address, PaymentID, Amount):
		self.api_params.clear()
		self.api_params['CurrencyId'] = Currency
		self.api_params['Address'] = Address
		self.api_params['PaymentId'] = PaymentID
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitWithdraw')
		
	#submits a transfer request by currency symbol 
	def submitTransferByName(self, Currency, Username, Amount):
		self.api_params.clear()
		self.api_params['Currency'] = Currency
		self.api_params['Username'] = Username
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitTransfer')

	#submits a transfer request by currency ID 
	def submitTransferByName(self, CurrencyID, Username, Amount):
		self.api_params.clear()
		self.api_params['CurrencyId'] = CurrencyID
		self.api_params['Username'] = Username
		self.api_params['Amount'] = Amount
		return self.private_api('SubmitTransfer')

		
API_KEY = 'your key'
API_SECRET = 'your secret'

my_api = cryptopia(API_KEY, API_SECRET)

# test public api call
print (my_api.getMarketOrders('LTC_BTC', 10))

# test private api call
print (my_api.getBalanceByName('BTC'))


Posted: 9/3/2017 11:23:00 PM Edited: 9/4/2017 12:04:48 AM
mmrj9
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 1
#23

This version of the node.js script seems to be working.

 

 

var https = require('https');
var async = require('async');
var crypto = require('crypto');

API_KEY = 'KEY'
API_SECRET = 'SECRET'

function apiQuery(callback2, method, params) {
if (!params)
params = {};
var public_set = [
"GetCurrencies",
"GetTradePairs",
"GetMarkets",
"GetMarket",
"GetMarketHistory",
"GetMarketOrders"
];
var private_set = [
"GetBalance",
"GetDepositAddress",
"GetOpenOrders",
"GetTradeHistory",
"GetTransactions",
"SubmitTrade",
"CancelTrade",
"SubmitTip"
];
var host_name = 'www.cryptopia.co.nz';
var uri = '/Api/' + method;
if (public_set.indexOf(method) > -1) {
if (params)
uri += "/" + Object.values(params).join('/');
var options = {
host: host_name,
path: uri
};
callback = function(response) {
var str = '';
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
return callback2(null, str);
});
}
https.request(options, callback).end();
} else if (private_set.indexOf(method) > -1) {
var nonce = Math.floor(new Date().getTime() / 1000);
var md5 = crypto.createHash('md5').update(JSON.stringify(params)).digest();
var requestContentBase64String = md5.toString('base64');
var signature = API_KEY + "POST" + encodeURIComponent('https://' + host_name + uri).toLowerCase() + nonce + requestContentBase64String;
var hmacsignature = crypto.createHmac('sha256', new Buffer(API_SECRET, "base64")).update(signature).digest().toString('base64');
var header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce;
var headers = {
'Authorization': header_value,
'Content-Type': 'application/json; charset=utf-8',
'Content-Length' : Buffer.byteLength(JSON.stringify(params)),
};
var options = {
host: host_name,
path: uri,
method: 'POST',
headers: headers
};
callback = function(response) {
var str = ''
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
return callback2(null, str);
});
}
var req = https.request(options, callback);
req.write(JSON.stringify(params));
req.end();
}
}

export default apiQuery;

// async.series([ function(callback) { // Public: // apiQuery( callback, "GetCurrencies" ); // + // apiQuery(
// callback, "GetMarket", [ 100, 6 ] ); // + // Private: // apiQuery( callback, "GetBalance" ); // + //
// apiQuery( callback, "SubmitTrade", { 'Market': "020/DOGE", 'Type': "Sell", 'Rate': 0.001, 'Amount': 1000 } ) // [
// '{"Success":true,"Error":null,"Data":{"OrderId":496433,"FilledOrders":[]}}' ] apiQuery( callback, 'CancelTrade', {
// 'CancelType': 'Trade', 'OrderId': 496433 } ); // + // [ '{"Success":true,"Error":null,"Data":[496433]}' ] },
// ], function(error, results) { console.log(results); });



Posted: 9/14/2017 1:14:56 AM Edited: 9/14/2017 1:16:30 AM
rveloso
Gender: Unknown
Country: Unknown
Threads: 0, Posts: 2
#24

Hello,

 

Trying to do a powershell version of the API.

Haven't got it to authenticate yet.

Managed to get the same signature as PHP reports, but something must be wrong in the call or missing as I always get a "Signature does not match request parameters".

Anyone care the comment?

$cryptopiaApiKey = "key";
$cryptopiaSecret = "secret";

$cryptopiaEndpoint = "https://www.cryptopia.co.nz/Api/"
$cryptopiaMarketPath = $cryptopiaEndpoint + "GetMarket"
$cryptopiaBalancePath = $cryptopiaEndpoint + "GetBalance"

Function md5($string){
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$md5.ComputeHash($utf8.GetBytes($string))
#[System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($string)))
}

Function cryptopiaDecode($secret){
$sigMod4 = $secret.length % 4
if($sigMod4 -eq 2){
$secretBase64 = $secret + "=="
}elseif($sigMod4 -eq 3){
$secretBase64 = $secret + "="
}else{
$secretBase64 = $secret
}
[System.Convert]::FromBase64String($secretBase64)
}

Function getHmacSha256($message, $secret){
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = $secret
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message))
$signature
}

$unixtime=[int][double]::Parse($(Get-Date -date (Get-Date).ToUniversalTime()-uformat %s))
$req = @{Currency = 'HUSH'}
$postData = ConvertTo-Json $req -Compress

$nonce = $unixtime
$nonce
#$nonce = "1506151943"

$m = md5 $postData
$requestContentBase64String = [Convert]::ToBase64String($m)
$encodedUrl = [System.Web.HttpUtility]::UrlEncode($cryptopiaBalancePath).ToLower()
$signature = $cryptopiaApiKey + "POST" + $encodedUrl + $nonce + $requestContentBase64String
$cryptopiaSecretDecoded = cryptopiaDecode $cryptopiaSecret
$hmacsignature = getHmacSha256 $signature $cryptopiaSecretDecoded
$hmacSignatureBase64 = [Convert]::ToBase64String($hmacsignature)

$header_value = "amx " + $cryptopiaApiKey + ":" + $hmacSignatureBase64 + ":" + $nonce
$header_value
$headers = @{"Content-Type"="application/json; charset=utf-8";"Authorization"=$header_value}
$headers

$response = Invoke-WebRequest -UseBasicParsing $cryptopiaBalancePath -Headers $headers -Method POST -Body $postData
$response

 



Posted: 9/23/2017 4:17:00 PM