# Donations: 16RdQZ86NUWQbE6rM86JbxnnaCDcAKqa9

from urllib import urlencode
import urllib2
import time
from datetime import datetime
from hashlib import sha512
from hmac import HMAC
import base64
import json
from threading import Timer
class Connector:
    bitstampTicker={
    	    'url':'http://www.bitstamp.net/api/ticker/',
    	    'interval':10,
    	    'ticker_history':[]
    }
    	
    	
    def __init__(self):
        self.updateBitstampTicker()
        
    def updateBitstampTicker(self):
        ticker=self.perform_query(self.bitstampTicker['url'])
        temp={}
        temp['last']=float(ticker['last'])
        self.bitstampTicker['ticker_history'].append(temp)
        Timer(self.bitstampTicker['interval'], self.updateBitstampTicker, ()).start()

        
            
    def perform_query(self,url,data="",headers={}):
        try:
            #print(url)
            #print(str(data))
            #print(str(headers))
            req = urllib2.Request(url)
            res = urllib2.urlopen(req,data)
            #print(res)
            a=json.load(res)
            #print (a)
            return a
        except Exception,e:
            print "Eccezione nella richiesta:" + str(Exception) + '---' + str(e)


    def getPrice(self):
        return self.bitstampTicker['ticker_history'][-1]['last']
class Trader:
    trend=0
    oldTrend=0
    price=0
    oldPrice=0
    conn=Connector()
    #hisoricalData=[]
    #deph={}
    
    def __init__(self):
        self.action()
        
    def updatePrice(self):
        print(self.price)
        self.oldPrice=self.price
        self.price=self.conn.getPrice()
        
    def updateTrend(self):
        self.trend= self.price-self.oldPrice
    def checkMax(self):
        if self.oldTrend>0 and self.trend<0:
            return True
        return False
    def checkMin(self):
        if self.oldTrend<0 and self.trend>0:
            return True
        return False
    def buy(self,qty):
        print 'buy'
    def sell(self,qty):
        print 'sell'
    def update(self):
          self.updatePrice()
          self.updateTrend()
    def action(self):
        print ('action')
        self.update()
        if self.trend>0 and self.checkMin():
            self.buy(0.01)
        elif self.trend<0 and self.checkMax():
            sell.sell(0.01)
        Timer(10, self.action, ()).start()

  
if __name__ == "__main__":        
    Trader()