Author

Topic: REQ: mtgox Trading API Sample Code [PHP] (Read 7275 times)

hex
newbie
Activity: 45
Merit: 0
September 21, 2011, 10:44:48 AM
#18
Here is mine vb.net class. You just supply it credentials and it returns parsed json Smiley

Code:
' bitcointalk.org - hex, GPL
Public Class MtGoxAPI
Public Property ApiKey As String
Public Property ApiSecretKey As String
Public Property UserName As String
Public Property Password As String

Public Enum Urls
GetTicker
GetDepth
GetTrades
GetFunds
BuyBTC
SellBTC
GetOrders
Info
'...
End Enum

Private Function GetUrl(url As Urls) As String
Select Case url
Case Urls.GetTicker
Return "http://mtgox.com/api/0/data/ticker.php"
Case Urls.GetDepth
Return "http://mtgox.com/api/0/data/getDepth.php"
Case Urls.GetTrades
Return "http://mtgox.com/api/0/data/getTrades.php"
Case Urls.GetFunds
Return "https://mtgox.com/api/0/getFunds.php"
Case Urls.BuyBTC
Return "https://mtgox.com/api/0/buyBTC.php"
Case Urls.SellBTC
Return "https://mtgox.com/api/0/sellBTC.php"
Case Urls.GetOrders
Return "https://mtgox.com/api/0/getOrders.php"
Case Urls.Info
Return "https://mtgox.com/api/0/info.php"
Case Else
Throw New NotImplementedException()
End Select
End Function

Public Shared Function UrlEncode(url As String) As String
Dim r = url.Replace("!", "%21")
r = r.Replace("*", "%2A")
r = r.Replace("'", "%27")
r = r.Replace("(", "%28")
r = r.Replace(")", "%29")
r = r.Replace(";", "%3B")
r = r.Replace(":", "%3A")
r = r.Replace("@", "%40")
r = r.Replace("&", "%26")
r = r.Replace("=", "%3D")
r = r.Replace("+", "%2B")
r = r.Replace("$", "%24")
r = r.Replace(",", "%2C")
r = r.Replace("/", "%2F")
r = r.Replace("?", "%3F")
r = r.Replace("#", "%23")
r = r.Replace("[", "%5B")
r = r.Replace("]", "%5D")
Return r
End Function

Public Function Request(url As Urls, params As List(Of Tuple(Of String, String))) As Newtonsoft.Json.Linq.JObject

Dim strUrl = GetUrl(url)
If params Is Nothing Then params = New List(Of Tuple(Of String, String))

Dim req As Net.HttpWebRequest = System.Net.HttpWebRequest.Create(strUrl)
req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20110920 Firefox/8.0"

Dim authRequired = Not (url = Urls.GetTicker Or url = Urls.GetDepth Or url = Urls.GetTrades)

If authRequired Then
If String.IsNullOrEmpty(ApiKey) Or String.IsNullOrEmpty(ApiSecretKey) Or _
String.IsNullOrEmpty(UserName) Or String.IsNullOrEmpty(Password) Then Throw New ArgumentNullException("auth properties not set")

req.Headers.Add("Rest-Key", ApiKey)
params.Add(Tuple.Create("nonce", DateTime.Now.Ticks.ToString()))
params.Add(Tuple.Create("name", UserName))
params.Add(Tuple.Create("pass", Password))
End If

If params.Count Then
' we need to POST
req.AllowWriteStreamBuffering = True
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
Dim postSB As New System.Text.StringBuilder()
For Each param In params
If postSB.Length Then postSB.Append("&")
postSB.Append(UrlEncode(param.Item1))
postSB.Append("=")
postSB.Append(UrlEncode(param.Item2))
Next
Dim postBin = System.Text.Encoding.ASCII.GetBytes(postSB.ToString())

If authRequired Then
Dim hmac = System.Security.Cryptography.HMACSHA512.Create()
hmac.Key = Convert.FromBase64String(ApiSecretKey)
Dim hash = hmac.ComputeHash(postBin)
req.Headers.Add("Rest-Sign", Convert.ToBase64String(hash))
End If

req.GetRequestStream.Write(postBin, 0, postBin.Length)
End If



Dim response = req.GetResponse.GetResponseStream()
Dim reader As IO.StreamReader = New IO.StreamReader(response)
'Return reader.ReadToEnd()

Return Newtonsoft.Json.Linq.JObject.Parse(reader.ReadToEnd())

End Function



End Class
newbie
Activity: 29
Merit: 0
August 11, 2011, 06:45:13 AM
#17
The last responder didn't seem to pick up the fact that you're attempting to use the new api-key/secret path, not the old /code/ username-password strategy.

Anyway, I addressed this issue here:
https://bitcointalksearch.org/topic/m.396543
hero member
Activity: 566
Merit: 500
OH, i see in your code:

Code:
string postData = "group1=BTC&btca=" + btcAddr + "&amount="
                                    + btcAmount + "&nonce=" + nonce;

Add the username and password to the postData and that should work.

Here is how i do it in VB .Net :

Code:
    html = ""
    postString = "name=" & userName & "&pass=" & password & "&amount=" & amount & "&price=" & price
    postArray = System.Text.Encoding.GetEncoding(1252).GetBytes(postString)
    myURL = "https://mtgox.com/code/buyBTC.php"
    winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    winHttpReq.settimeouts(60000, 60000, 60000, 60000)
    winHttpReq.Open("POST", myURL, False)
    winHttpReq.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    winHttpReq.Send(postArray)
    html = winHttpReq.responseText
legendary
Activity: 1304
Merit: 1014
Anyways, here is my C# code which I don't think is working.  I get "{"error":"Must be logged in"}"

A little help anyone?

Code:
   Console.Out.WriteLine("Making withdraw request to Mt. Gox...");
            
            HttpWebRequest request =
                (HttpWebRequest)WebRequest.Create("https://mtgox.com/api/0/withdraw.php");
            request.Method = WebRequestMethods.Http.Post;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";

            String btcAddr = mainForm.getSendToBitcoinAddress();
            String btcAmount = .01;

            String nonce = DateTime.UtcNow.Millisecond.ToString();
            Console.Out.WriteLine("nonce: " + nonce);
        
            string postData = "group1=BTC&btca=" + btcAddr + "&amount="
                                    + btcAmount + "&nonce=" + nonce;

            String key = "xxxxxxxxxxxxxxxxxxx";
            String keySecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            byte[] keyByte = Convert.FromBase64String(keySecret);
            HMACSHA512 hmacsha512 = new HMACSHA512(keyByte);

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] messageBytes = encoding.GetBytes(postData);
            byte[] hashmessage = hmacsha512.ComputeHash(messageBytes);
            String base64SignedPostData = Convert.ToBase64String(hashmessage);

            request.Headers.Add("Rest-Key", key);
            request.Headers.Add("Rest-Sign", base64SignedPostData);

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();

            Console.WriteLine(responseFromServer);

            //Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

member
Activity: 98
Merit: 10
interesting

my goal with my bot was to allow people with small amounts of bitcoins compete against the dark pools. It allows for you to queue  trades locally and not put them in the order book until there are outstanding buy/sell orders that match the desired price. This allow the dark pools to empty the trade book and raise the price.
legendary
Activity: 1304
Merit: 1014
you need to get an "API_KEY" and "SECRET" from mtgox, here is a bot that I wrote http://bitklein.com/sniper.php.gz


Interesting bot.

I don't know why but I had to add 'user' and 'pass' to get mine to work in addition to supplying the api key and the secret key.  What I am doing still works though but I am afraid that I am doing it the wrong way.

member
Activity: 98
Merit: 10
you need to get an "API_KEY" and "SECRET" from mtgox, here is a bot that I wrote http://bitklein.com/sniper.php.gz
legendary
Activity: 1304
Merit: 1014
I am using a modification of this PHP code which I ported to C#.  In this example there was no 'user' or 'pass' variable.  Should these variables be in the documentation?

https://en.bitcoin.it/wiki/MtGox/API#Authentication
member
Activity: 98
Merit: 10
Ok, I got a little further.  I am not using CURL.  I am using C#.

This answer is not even in the documentation or wiki.  I found it in another post.  I added user=xxx&pass=xxx to the POST data and it worked.

by what means are you retrieving the api data?
legendary
Activity: 1304
Merit: 1014
Ok, I got a little further.  I am not using CURL.  I am using C#.

This answer is not even in the documentation or wiki.  I found it in another post.  I added user=xxx&pass=xxx to the POST data and it worked.
member
Activity: 98
Merit: 10
I am trying to convert the Mt. Gox code to C# and I am getting

OK
{"error":"Must be logged in"}

Not sure what to do next...any ideas?



what does your curl code look like?
legendary
Activity: 1304
Merit: 1014
I am trying to convert the Mt. Gox code to C# and I am getting

OK
{"error":"Must be logged in"}

Not sure what to do next...any ideas?

member
Activity: 98
Merit: 10
can someone tell me more about php-curl and post fields for making a trade, and the number format thing?
member
Activity: 108
Merit: 10
Thanks guys. Very helpful.
newbie
Activity: 36
Merit: 0
vip
Activity: 608
Merit: 501
-
newbie
Activity: 56
Merit: 0
I can offer you my automated trading script in PERL, fully operational for 5 BTC.

Time is money,
Train
member
Activity: 108
Merit: 10
Hey guys. I'm not stupid, I swear.

I've been coding some trading tools (for mtgox and several of the other trading sites), and I'm getting tripped up on mtgox's new API thing. I've been doing all this in about two or three hours a night after the family goes to sleep, so I really don't have time for super-deep-dives, and the scant documentation on the mtgox website is really tripping me up.

I guess what I'm looking for is some sample code on the trading section of the API (not the ticker or depth charts) in PHP, preferrably.

What's tripping me up in particular:
* I understand the concept of a nonce code and how to make one. What I don't understand is where or how it wants me to pass it in.
* How and where am I passing in the API keys?
* I'm pretty sure I've got a handle on the POST stuff, but I wouldn't hate it if the sample code included that, too.
Jump to: