Bitcoin Forum
April 24, 2024, 11:58:36 PM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: REQ: mtgox Trading API Sample Code [PHP]  (Read 7275 times)
rizzn (OP)
Member
**
Offline Offline

Activity: 108
Merit: 10



View Profile
July 18, 2011, 08:56:47 AM
 #1

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.
It is a common myth that Bitcoin is ruled by a majority of miners. This is not true. Bitcoin miners "vote" on the ordering of transactions, but that's all they do. They can't vote to change the network rules.
Advertised sites are not endorsed by the Bitcoin Forum. They may be unsafe, untrustworthy, or illegal in your jurisdiction.
TrainDeluxe
Newbie
*
Offline Offline

Activity: 56
Merit: 0


View Profile
July 18, 2011, 06:17:12 PM
 #2

I can offer you my automated trading script in PERL, fully operational for 5 BTC.

Time is money,
Train
MagicalTux
VIP
Hero Member
*
Offline Offline

Activity: 608
Merit: 501


-


View Profile
July 18, 2011, 11:48:00 PM
 #3

You may want to read that:

https://en.bitcoin.it/wiki/MtGox/API#Authentication
r4in
Newbie
*
Offline Offline

Activity: 36
Merit: 0


View Profile
July 19, 2011, 01:00:58 AM
 #4

You might also want to look here:
http://forum.bitcoin.org/index.php?topic=27939.msg362816#msg362816
rizzn (OP)
Member
**
Offline Offline

Activity: 108
Merit: 10



View Profile
July 19, 2011, 04:57:29 AM
 #5

Thanks guys. Very helpful.
charliesheen
Member
**
Offline Offline

Activity: 98
Merit: 10


View Profile WWW
July 23, 2011, 08:03:48 AM
 #6

can someone tell me more about php-curl and post fields for making a trade, and the number format thing?

jimbobway
Legendary
*
Offline Offline

Activity: 1304
Merit: 1014



View Profile
July 25, 2011, 04:42:29 AM
 #7

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?

charliesheen
Member
**
Offline Offline

Activity: 98
Merit: 10


View Profile WWW
July 25, 2011, 05:09:25 AM
 #8

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?

jimbobway
Legendary
*
Offline Offline

Activity: 1304
Merit: 1014



View Profile
July 25, 2011, 05:15:23 AM
 #9

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.
charliesheen
Member
**
Offline Offline

Activity: 98
Merit: 10


View Profile WWW
July 25, 2011, 05:18:29 AM
 #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?

jimbobway
Legendary
*
Offline Offline

Activity: 1304
Merit: 1014



View Profile
July 25, 2011, 05:50:00 AM
 #11

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
charliesheen
Member
**
Offline Offline

Activity: 98
Merit: 10


View Profile WWW
July 25, 2011, 05:57:16 AM
 #12

you need to get an "API_KEY" and "SECRET" from mtgox, here is a bot that I wrote http://bitklein.com/sniper.php.gz

jimbobway
Legendary
*
Offline Offline

Activity: 1304
Merit: 1014



View Profile
July 25, 2011, 06:12:34 AM
 #13

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.

charliesheen
Member
**
Offline Offline

Activity: 98
Merit: 10


View Profile WWW
July 25, 2011, 06:17:39 AM
 #14

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.

jimbobway
Legendary
*
Offline Offline

Activity: 1304
Merit: 1014



View Profile
July 25, 2011, 06:32:43 AM
 #15

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

runlinux
Hero Member
*****
Offline Offline

Activity: 566
Merit: 500



View Profile WWW
July 25, 2011, 06:45:09 PM
 #16

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

mdbitcoin
Newbie
*
Offline Offline

Activity: 29
Merit: 0


View Profile
August 11, 2011, 10: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:
http://bitcointalk.org/index.php?topic=31525.msg396543#msg396543
hex
Newbie
*
Offline Offline

Activity: 45
Merit: 0



View Profile WWW
September 21, 2011, 02:44:48 PM
 #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
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!