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.

onsdag 5 mars 2014

Slush mining proxy as service in Windows

This is simple tutorial about how to start Slush mining proxy as service on Windows PC.
For reference I've used this on Windows 2003 server, but it should be same on other versions as well. Basic knowledge of Windows and it's components is required.

Things we'll need:
After we have installed the Resource Kit, the 2 files (srvany.exe & instsrv.exe) can be found at: C:\Program Files\Windows Resource Kits\Tools\ 
I suggest you copy these 2 files to C:\Windows\system32\ for easier typing on the command shell later on.

1. Start command shell (cmd.exe) and browse to C:\Windows\system32\
2. Install the "custom" service by typing following command:
    instsrv ANYNAME C:\Windows\system32\srvany.exe    
Note that you must specify full path to the srvany.exe, even that we are in same folder. You can  (and should) of course replace ANYNAME with your own. At this point we only create the custom service and only specifying its name. I used Proxyservice as name in this example. 
    Screenshot above shows whole procedure.
    Note that the first try without full path gives error, so we try again with full path and get the right response.



3. Open Registry Editor by typing regedit on the "Run..." box under the Start-menu.
- I'll call the registry keys as "folder" in the following, even they are not really folders, but the icon shows them as ones.
4. Browse to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Proxyservice (The last "folder" is our desided name for the service.)
Now we need to create few things in the "folder" before we can finally start our new service:
- a key called Parameters and
- two string values called Application and AppParameters
5. Right-click the "folder" Proxyservice and choose New -> Key. A new "folder" appears. Rename this New key #1 to Parameters
6. Right-click the "folder" Proxyservice again and choose this time New -> String Value.
Repeat that once more. Now there should be New Value #1 and New Value #2 inside the Parameters key. Rename these to Application and AppParameters
7. The Application value points to the application we want to start as service, in our case it is the mining_proxy.exe. Edit the value to C:\miningproxy\mining_proxy.exe
8. The AppParameters are the same command line parameters that you can use when starting mining proxy from batch-file (.bat). If you're mining at Slush's pool, you can leave this empty, as the mining_proxy connects to Slush as default.
In this example I used ghash.io pool, so we edit the value to -o uk1.ghash.io -q
Now that everything has been set, the key and its strings should look like following:








9. Go to Control Panel -> Administrative Tools -> Services and you should find the service there with name Proxyservice. If everything is correct, try start the service and it should run finally! 
You can see it running on Task Manager with name mining_proxy.exe
(Just remember check the box "show processes from all users" to see it.)
P.S. For those who can't bother to edit Registry by own, here is .reg file for that:
Copy it to emtpy textfile and name it whatever.reg 
Note that there must be an empty line at the bottom of the file and yet again, replace Proxyservice with the name you desided earlier, if you changed it.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Proxyservice\Parameters]
"Application"="C:\\miningproxy\\mining_proxy.exe"
"AppParameters"="-o uk1.ghash.io -q"