måndag 10 mars 2014

Instant trade all your NMC to BTC on CEX.io
Console application [VB + Newtonsoft Json library]

This little application checks your NMC (NameCoin) balance,  gets the last price from ticker and places order* on all your NMC to sell for BTC.

*) It places the order, but doesn't check if and when it is completed. Ususally it goes thru instantly when using the last price.

If you want to get other price from ticker to use, you can use following parameters for that:

last - last BTC price
high - last 24 hours price high
low - last 24 hours price low
bid - highest buy order
ask - lowest sell order
Change green coloured the text in code.

You'll need Newtonsoft JSON library for parsing the json response from server.
http://json.codeplex.com/

1. Make new Console application in VB and copy/paste this code below.
2. Reference the Newtonsoft.dll to application
3. Fill in (see the corresponding colours in the code) your username, API key and API secret from CEX.io -> Profile -> API
When creating the API key you must check at least the Account balance and Place order checkboxes.
API secret is shown before you activate the key, be sure to copy that, it will not be shown after the activation!

Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Net
Imports System.Text
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Module Module1

    Sub Main()

        Dim balance As String = getdata("https://cex.io/api/balance/")
        Dim price As String = getdata("https://cex.io/api/ticker/NMC/BTC")

        Dim pricevalues As Newtonsoft.Json.Linq.JObject
        pricevalues = JObject.Parse(price)

        Dim balancevalues As Newtonsoft.Json.Linq.JObject
        balancevalues = JObject.Parse(balance)

        Dim bal, last As String
        Try
            bal = balancevalues.GetValue("NMC")("available")
            last = pricevalues.GetValue("last")
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
        End Try

        drawline()
        Console.WriteLine(Now.ToLongTimeString)
        Console.WriteLine("Account balance NMC: " & bal & " NMC")
        Console.WriteLine("Last price 1 NMC = " & last & " BTC")
        drawline()

        If CDbl(bal) > 0 Then
            Console.WriteLine("ORDER PLACED - Server response:")
            Console.WriteLine(getdata("https://cex.io/api/place_order/NMC/BTC", bal, last))
        Else
            Console.WriteLine("Balance NMC = 0, no order placed")
        End If

        Console.ReadKey()

    End Sub

    Sub drawline()
        Dim strC As String
        strC = New String("-"c, 80)
        Console.WriteLine(strC)
    End Sub

    Function getdata(ByVal URL As String, Optional ByVal bal As String = "", Optional ByVal last As String = "")

        Dim G_USERNAME As String = "username"
        Dim G_APIKEY As String = "API key"
        Dim G_APIKEY_SECRET As String = "API secret"
        Dim nonce = Get_Nonce()
        Dim message As String
        Dim signature = hash_sha256(nonce & G_USERNAME & G_APIKEY, G_APIKEY_SECRET)

        If bal = "" Or last = "" Then
            message = "key=" & G_APIKEY & "&" & "nonce=" & nonce & "&" & "signature=" & signature
        Else
            message = "key=" & G_APIKEY & "&" & "nonce=" & nonce & "&" & "signature=" & signature & "&type=sell&price=" & last & "&amount=" & bal
        End If

        getdata = sourcestring(URL, message)

    End Function

    Function hash_sha256(ByVal StringToHash, ByVal KeyForHash) As Object

        Dim sha256, ObjUTF8, hmac
        ObjUTF8 = CreateObject("System.Text.UTF8Encoding")
        sha256 = CreateObject("system.security.cryptography.HMACSHA256")
        sha256.Key = ObjUTF8.GetBytes(KeyForHash)
        hmac = sha256.ComputeHash(ObjUTF8.GetBytes(StringToHash))
        sha256.Clear()

        Dim a
        Dim b = hmac.length
        For Each c As Byte In hmac
            a += Strings.Right("0" & Conversion.Hex(c), 2)
        Next
        Return UCase(a)
    End Function

    Function Get_Nonce() As Long
        Dim centuryBegin As Date = #1/1/2014#
        Dim currentDate As Date = Date.Now
        Dim elapsedTicks As Long = currentDate.Ticks - centuryBegin.Ticks
        Return elapsedTicks
    End Function

    Function sourcestring(ByVal url, ByVal message) As String

        Dim request As WebRequest = WebRequest.Create(url)
        request.Method = "POST"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(message)
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()

        Try
            Dim response As WebResponse = request.GetResponse()

            ' BEGIN DEBUG --------------------Uncomment below to get debuginfo------------------------

            'drawline()
            'Console.WriteLine("==== Debug info ====")
            'Console.WriteLine(url.ToString)
            'Console.WriteLine(Replace(message, "&", System.Environment.NewLine))
            'Console.WriteLine("HTTP STATUS: " & CType(response, HttpWebResponse).StatusDescription)

            '-----------------------------------------------------------------------------------------
            dataStream = response.GetResponseStream()
            Dim reader As New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()
            Return responseFromServer

            reader.Close()
            dataStream.Close()
            response.Close()
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
            Return Nothing
        End Try

    End Function

End Module

NOTE: Server response is not parsed, but it is fully readable.

Inga kommentarer:

Skicka en kommentar