#please donate: 1DQNJWxVsbiVwTbxVwHXqnN5gfjs8VK2Kk
import threading
import websocket
import cjson,json
import time,binascii
import md5,base64,hmac,hashlib
CHANNELS = {
"USD":{
    "trade":"dbf1dee9-4f2e-4a08-8cb7-748919a71b21",
    "ticker":"d5f06780-30a8-4a48-a2f8-7ed181b4a13f",
    "depth":"24e67e0d-1cad-4cc0-9e7a-f8523ef460fe",
    }
}

def serialize(obj):
	return cjson.encode(obj)
def deserialize(msg):
	return cjson.decode(msg)

class MtGoxAPI(threading.Thread):

	def __init__(self, apikey, secret):
	    self.counter = 0
	    self.apikey = apikey
	    self.secret = secret
	    threading.Thread.__init__(self)

	def run(self):
	    self.open_socket("ws://websocket.mtgox.com/mtgox")

	def nonce(self):
	    self.counter += 1
	    return ( int( time.time() ) * 1000 ) + self.counter

	def encode_and_sign(self,data):
	    binary = binascii.unhexlify( self.apikey.replace("-","") )
	    signed = hmac.new( base64.b64decode(self.secret), data, hashlib.sha512 ).digest()
	    encoded = base64.b64encode( "%s%s%s" % (binary, sign, data) )
	    return encoded

	def subscribe(self,channel):
	    output = serialize({"op":"subscribe",
		                "channel":channel,
		                })

	def unsubscribe(self,channel):
	    output = serialize({"op":"unsubscribe",
		                "channel":channel,
		                })

	def request(self,apicall,cry="USD",params=list(),item="BTC"):
	    nonce = self.nonce()
	    id = md5.new( str(nonce) ).hexdigest()
	    query = {"id":id,
		    "call":apicall,
		    "nonce":nonce,
		    "currency":cry,
		    "parameters":params,
		    "item":item
		    }
	    output = serialize({"op":"call",
		                "id":id,
		                "call":self.encode_and_sign(serialize(query)),
		                "context":"mtgox.com"
		                })
	    self.ws.send(output)
	    return id

	def handle_result(self,data):
	    print(data)
	def handle_depth(self,data):
	    print(data)
	def handle_ticker(self,data):
	    print(data)

	def on_message(self,ws,message):
	    data = deserialize(message)
	    op = data.get("op")
	    if op == "private":
		if private == "depth": self.handle_depth(data)
		elif private == "trade": self.trades.append(data)
		elif private == "ticker": self.handle_ticker(data)
		elif private == "result": self.handle_result(data)

	def on_open(self,ws):
	    print "###    Connection opened    ###"

	def on_close(self,ws):
	    print "###    Connection closed    ###"

	def on_error(self,ws, error):
	    print error

	def open_socket(self,url):
	    websocket.enableTrace(False)
	    self.ws = websocket.WebSocketApp(url,
		                            on_message = self.on_message,
		                            on_error = self.on_error,
		                            on_close = self.on_close)
	    self.ws.on_open = self.on_open
	    self.ws.run_forever()

if __name__ == "__main__":
	apikey = u""
	secret = u""
	main = MtGoxAPI(apikey,secret).start()
