/*
* Base for making api class for btc-e.com
* DmT
* 2012
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography;
namespace BtceTestApp
{
class BtceApi
{
string key;
HMACSHA512 hashMaker;
public BtceApi(string key, string secret)
{
this.key = key;
hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(secret));
}
public string GetInfo()
{
return Query(new Dictionary<string, string>()
{
{ "method", "getInfo" }
});
}
string Query(Dictionary<string, string> args)
{
args.Add("nonce", GetNonce().ToString());
var dataStr = BuildPostData(args);
var data = Encoding.ASCII.GetBytes(dataStr);
var request = WebRequest.Create(new Uri("
https://btc-e.com/tapi")) as HttpWebRequest;
if (request == null)
throw new Exception("Non HTTP WebRequest");
request.Method = "POST";
request.Timeout = 15000;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Headers.Add("Key", key);
var sign = ByteArrayToString(hashMaker.ComputeHash(data)).ToLower();
request.Headers.Add("Sign", sign);
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
var response = request.GetResponse();
var resStream = response.GetResponseStream();
var resStreamReader = new StreamReader(resStream);
var resString = resStreamReader.ReadToEnd();
return resString;
}
static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}
static string BuildPostData(Dictionary<string, string> d)
{
string s = "";
for (int i = 0; i < d.Count; i++)
{
var item = d.ElementAt(i);
var key = item.Key;
var val = item.Value;
s += String.Format("{0}={1}", key, val);
if (i != d.Count - 1)
s += "&";
}
return s;
}
static DateTime unixEpoch = new DateTime(1970, 1, 1);
int GetNonce()
{
var now = DateTime.UtcNow;
var dif = now - unixEpoch;
return (int)dif.TotalSeconds;
}
}
}