API Sprachen Beispiele


Lafu
Gender: Unknown
Country: Unknown
Threads: 130, Posts: 262
#0

Hier finden Sie einige Beispiele fürs verbinden und nutzen der Cryptopia API in verschiedenen Sprachen !

API  Sprachen Beispiele:


    C# .NET
    Ruby
    Python
    Curl
    Java
    Php
    NodeJs

Kurzes Beispiel in c# öffentliche API (GetCurrencies)

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

Kurzes Beispiel in c# Private API (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}]}
   }
}

Python öffentlichen & private API

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 schaut es so aus

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 )

Beispiel Private Java API  (Dank 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();
        }
    }
}

Private & Offentliche Api  Node.JS

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);
});

 Öffentliche & Private API  Curl

# 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

 Öffentliche & Private API  Ruby

#!/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} )

 Öffentliche & Private API   PHP

<?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: 10/8/2016 3:25:14 AM