Example #1
0
 def test_getHistory(self):
     connection = btceapi.BTCEConnection()
     info = btceapi.APIInfo(connection)
     for pair in info.pair_names:
         btceapi.getTradeHistory(pair, connection, info)
         btceapi.getTradeHistory(pair, connection)
         btceapi.getTradeHistory(pair, info=info)
         btceapi.getTradeHistory(pair)
Example #2
0
    def __init__(self, symbol):
        self.symbol = symbol
        self.base = symbol.split("_")[0].upper()
        self.alt = symbol.split("_")[1].upper()

        self.ticks = btceapi.getTradeHistory(self.symbol)
        self.last_tid = max([t.tid for t in self.ticks])

        self.fig = plt.figure()
        self.axes = self.fig.add_subplot(111)
        self.bid_line, = self.axes.plot(*zip(*self.bid),
                                        linestyle='None',
                                        marker='o',
                                        color='red')
        self.ask_line, = self.axes.plot(*zip(*self.ask),
                                        linestyle='None',
                                        marker='o',
                                        color='green')

        self.fig.canvas.draw()

        self.timer_id = wx.NewId()
        self.actor = self.fig.canvas.manager.frame
        self.timer = wx.Timer(self.actor, id=self.timer_id)
        self.timer.Start(10000)  # update every 10 seconds
        wx.EVT_TIMER(self.actor, self.timer_id, self.update)

        pylab.show()
Example #3
0
    def showLastTrades(self, pair):
        ''' Show last ask and bid trades of current window '''
        connection = btceapi.BTCEConnection()
        window = self.interval*self.listlength
        timediff = datetime.timedelta(seconds=window)
        sellvalue = 0
        buyvalue = 0
        sellamount = 0
        buyamount = 0
        countask = 0
        countbid = 0
            
        history = btceapi.getTradeHistory(pair, connection)
        # print "History length:", len(history) unnecessary
        
        for h in history:
            
            if h.trade_type == u'ask' and h.date >= (datetime.datetime.now() - timediff):
        #give total amount of ask trades of last window
                countask += 1
                sellamount += h.amount
                sellvalue += (h.amount*h.price)
            elif h.trade_type == u'bid' and h.date >= (datetime.datetime.now() - timediff):
        #give total amount of bid trades of last window
                countbid += 1
                buyamount += h.amount
                buyvalue += (h.amount*h.price)

        print "Number of sell trades:", countask, "Total amount: %s BTC" % sellamount, "With value: %s EUR" % sellvalue
        print "Number of buy trades: ", countbid, "Total amount: %s BTC" % buyamount, "With value: %s EUR" % buyvalue
        
        connection.close()
Example #4
0
def get_history(pair):
	def format_trade(t):
		return {'date': str(t.date), 'price': t.price, 'type': t.trade_type}
	history = btceapi.getTradeHistory(pair)
	ask, bid = None, None
	for h in history:
		if not ask and h.trade_type == "ask":
			ask = h
		if not bid and h.trade_type == "bid":
			bid = h
		if bid and ask:
			break
	return map(format_trade, [ask, bid])
Example #5
0
    def call_trade_history(self, pair):
        history = btceapi.getTradeHistory(pair)

        print len(history)

        pylab.plot([t.date for t in history if t.trade_type == u'ask'],
                   [t.price for t in history if t.trade_type == u'ask'], 'ro')

        pylab.plot([t.date for t in history if t.trade_type == u'bid'],
                   [t.price for t in history if t.trade_type == u'bid'], 'go')

        pylab.grid()
        pylab.show()
 def call_trade_history(self, pair):
     history = btceapi.getTradeHistory(pair)
     
     print len(history)
     
     pylab.plot([t.date for t in history if t.trade_type == u'ask'],
                [t.price for t in history if t.trade_type == u'ask'], 'ro')
     
     pylab.plot([t.date for t in history if t.trade_type == u'bid'],
                [t.price for t in history if t.trade_type == u'bid'], 'go')
     
     pylab.grid()          
     pylab.show()
Example #7
0
    def graphHistory(self, pair):
        ''' Build graph of trade history of pair '''
        history = btceapi.getTradeHistory(pair)

        print "History length:", len(history)

        pylab.plot([t.date for t in history if t.trade_type == u'ask'],
           [t.price for t in history if t.trade_type == u'ask'], 'ro')

        pylab.plot([t.date for t in history if t.trade_type == u'bid'],
           [t.price for t in history if t.trade_type == u'bid'], 'go')

        pylab.grid()
        pylab.show()
        pylab.close()
Example #8
0
def getHistory(minutes=5, operation="b"):
    if operation != "b" and operation != "a":
        raise ValueError(
            "Operation should be either 'a' for asks, or 'b' for bids")

    since_time = datetime.datetime.now() - datetime.timedelta(minutes=minutes)
    trades = btceapi.getTradeHistory(pair=pair, count=minutes *
                                     10)  #Have no idea how many items we need
    trades.sort(key=lambda x: x.date, reverse=False)

    prices_bids = dict()
    prices_asks = dict()

    extra_items = 0

    for t in trades:
        if t.date < since_time:
            #print t.date
            extra_items += 1
            continue

        if t.trade_type == "bid":
            prices_bids[t.date] = t.price

        if t.trade_type == "ask":
            prices_asks[t.date] = t.price

    print "downloaded %d extra records" % extra_items

    print 'asks:'
    print len(prices_asks)
    print prices_asks

    print ''

    print 'bids:'
    print len(prices_bids)
    print prices_bids

    returnDict = prices_bids if operation == "b" else prices_asks

    return returnDict
Example #9
0
    def update(self, event):
        ticks = btceapi.getTradeHistory(self.symbol)
        self.ticks += [t for t in ticks if t.tid > self.last_tid]

        for t in ticks:
            if t.tid > self.last_tid:
                print("%s: %s %f at %s %f" % \
                        (t.trade_type, self.base, t.amount, self.alt, t.price))

        self.last_tid = max([t.tid for t in ticks])

        x, y = zip(*self.bid)
        self.bid_line.set_xdata(x)
        self.bid_line.set_ydata(y)

        x, y = zip(*self.ask)
        self.ask_line.set_xdata(x)
        self.ask_line.set_ydata(y)

        pylab.gca().relim()
        pylab.gca().autoscale_view()

        self.fig.canvas.draw()
Example #10
0
    def update(self, event):
        ticks = btceapi.getTradeHistory(self.symbol)
        self.ticks += [t for t in ticks if t.tid > self.last_tid]

        for t in ticks:
            if t.tid > self.last_tid:
                print "%s: %s %f at %s %f" % \
                        (t.trade_type, self.base, t.amount, self.alt, t.price)

        self.last_tid = max([t.tid for t in ticks])

        x, y = zip(*self.bid)
        self.bid_line.set_xdata(x)
        self.bid_line.set_ydata(y)

        x, y = zip(*self.ask)
        self.ask_line.set_xdata(x)
        self.ask_line.set_ydata(y)

        pylab.gca().relim()
        pylab.gca().autoscale_view()

        self.fig.canvas.draw()
Example #11
0
def _runHandler(trade_handler):
    last_tid = False
    while trade_handler.running:
        conn = btceapi.BTCEConnection()
        loop_start = time.time()
        interval = trade_handler.collectionInterval

        p = trade_handler.type
        try:
            trade_handler.asks, trade_handler.bids = btceapi.getDepth(p, conn)
        except:
            print "getDepth Error"
        # Collect the set of handlers for which we should get trade history.
        try:
            tradeHistory = btceapi.getTradeHistory(p, conn)
            if tradeHistory[0].tid != last_tid:
                trade_handler.tradeHistory = tradeHistory
                last_tid = trade_handler.arrangePriceHistory(tradeHistory)
        except:
            print "getTradeHistory Error"
        conn.close()

        while trade_handler.running and time.time() - loop_start < interval:
            time.sleep(0.5)
Example #12
0
    def __init__(self, symbol):
        self.symbol = symbol
        self.base = symbol.split("_")[0].upper()
        self.alt = symbol.split("_")[1].upper()

        self.ticks = btceapi.getTradeHistory(self.symbol)
        self.last_tid = max([t.tid for t in self.ticks])

        self.fig = plt.figure()
        self.axes = self.fig.add_subplot(111)
        self.bid_line, = self.axes.plot(*zip(*self.bid), \
                linestyle='None', marker='o', color='red')
        self.ask_line, = self.axes.plot(*zip(*self.ask), \
                linestyle='None', marker='o', color='green')
        
        self.fig.canvas.draw()

        self.timer_id = wx.NewId()
        self.actor = self.fig.canvas.manager.frame
        self.timer = wx.Timer(self.actor, id=self.timer_id)
        self.timer.Start(10000) # update every 10 seconds
        wx.EVT_TIMER(self.actor, self.timer_id, self.update)

        pylab.show()
Example #13
0
# the BTC/USD history will be displayed.

if len(sys.argv) >= 2:
    pair = sys.argv[1]
    print "Showing history for %s" % pair
else:
    print "No currency pair provided, defaulting to btc_usd"
    pair = "btc_usd"
    
if sys.argv[2]:
    count = int(sys.argv[2])
else:
    print "No count given. Defaulting to max of 2000."
    count = 2000

history = btceapi.getTradeHistory(pair, count = count)

print len(history)

# Moving Average
totalweight = 0
totalvolume = 0
for t in history:
            totalweight += t.price * t.amount
            totalvolume += t.amount
movingaverage = totalweight / totalvolume
print movingaverage

'''
pylab.plot([t.timestamp for t in history if t.type == u'ask'],
           [t.price for t in history if t.type == u'ask'], 'ro')
Example #14
0
#!/usr/bin/python
import sys
import pylab
import btceapi

# If an argument is provided to this script, it will be interpreted
# as a currency pair for which history should be displayed. Otherwise
# the BTC/USD history will be displayed.

if len(sys.argv) >= 2:
    pair = sys.argv[1]
    print("Showing history for %s" % pair)
else:
    print("No currency pair provided, defaulting to btc_usd")
    pair = "btc_usd"

history = btceapi.getTradeHistory(pair)

print(len(history))

pylab.plot([t.timestamp for t in history if t.type == u'ask'],
           [t.price for t in history if t.type == u'ask'], 'ro')

pylab.plot([t.timestamp for t in history if t.type == u'bid'],
           [t.price for t in history if t.type == u'bid'], 'go')

pylab.grid()
pylab.show()
Example #15
0
sample_rate = 30
DeltaList = [0] * sample_rate
buy_flag = False
delta = 0
adjust = 0.99999
conn.close()
while True:
    ask_list = []
    price_list = []
    if counter == sample_rate:
        counter = 0
        print "counter has zeroed"
        print "delta list is: %s" % DeltaList
    try:
        conn = btceapi.BTCEConnection()
        tradeHistory = btceapi.getTradeHistory(pair, conn)
        available = getattr(api.getInfo(conn), "balance_usd")
        asks, bids = btceapi.getDepth("btc_usd", conn)
        for ask in asks:
            ask_list.append(ask[0])
        for i in range(int(1.5 * sample_rate)):
            price_list.append(tradeHistory[i].price)
        last_mean = mean
        mean = numpy.mean(ask_list)
    except:
        print "error getDepth"
        pass
    conn.close()
    try:
        DeltaList[counter] = float(mean - last_mean)
        filtered_delta = filter(lambda x: x != 0, DeltaList)
Example #16
0
def _runBot(bot):
    while bot.running:
        loop_start = time.time()

        # Collect the set of pairs for which we should get depth.
        depth_pairs = set()
        for handler, pairs in bot.depthHandlers:
            depth_pairs.update(pairs)

        # Get current depth
        depths = {}
        conn = btceapi.BTCEConnection()
        for p in depth_pairs:
            try:
                asks, bids = btceapi.getDepth(p, conn)
                depths[p] = (datetime.datetime.now(), asks, bids)
            except:
                bot.onDepthRetrievalError(p, traceback.format_exc())

        # Collect the set of pairs for which we should get trade history.
        trade_history_pairs = set()
        for handler, pairs in bot.tradeHistoryHandlers:
            trade_history_pairs.update(pairs)

        trade_histories = {}
        for p in trade_history_pairs:
            try:
                trades = btceapi.getTradeHistory(p, conn)
                trade_histories[p] = (datetime.datetime.now(), trades)
            except:
                bot.onTradeHistoryRetrievalError(p, traceback.format_exc())

        conn.close()

        for p, (t, asks, bids) in depths.items():
            for handler, pairs in bot.depthHandlers:
                if p in pairs:
                    try:
                        handler(t, p, asks, bids)
                    except:
                        bot.onDepthHandlingError(p, handler,
                                                 traceback.format_exc())

        for p, (t, trades) in trade_histories.items():
            # Merge new trades into the bot's history.
            bot.mergeTradeHistory(p, trades)

            # Provide full history to traders
            for handler, pairs in bot.tradeHistoryHandlers:
                if p in pairs:
                    try:
                        handler(t, p, bot.tradeHistoryItems[p])
                    except:
                        bot.onTradeHistoryHandlingError(
                            p, handler, traceback.format_exc())

        # Tell all bots that have requested it that we're at the end
        # of an update loop.
        for handler in bot.loopEndHandlers:
            try:
                handler(datetime.datetime.now())
            except:
                # TODO: refactor this somewhere
                t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                print("%s Error while calling loop end handler (%r): %s" %
                      (t, handler, traceback.format_exc()))

        while bot.running and time.time() - loop_start < bot.collectionInterval:
            time.sleep(0.5)

    # Give traders and opportunity to do thread-specific cleanup.
    for t in bot.traders:
        t.onExit()
Example #17
0
def calcAvgPrice(self, pair, buy_margin, sell_margin, alfa=0.994, beta=1, lastMinutes=60, count =150 ):
	
	if not(singleMode):
		print_trade_history(self, self.api, pair)
	
	buy_margin, sell_margin = (int(buy_margin), int(sell_margin))
	avg_price, licznik, mianownik, volume=(0,0,0,0)
	ile=count
	dlugosc=0
	nowStart= self._now()
	freshHistory = btceapi.getTradeHistory(pair, None, count)
	freshHistory = filter(lambda x: nowStart - x.__getstate__()["date"]<timedelta(minutes=lastMinutes), freshHistory)
	if freshHistory:
		lastFreshRecord = freshHistory[-1].__getstate__()
		self.history = filter(lambda x: nowStart - x.__getstate__()["date"]<timedelta(minutes=lastMinutes), self.history)
		self.history = filter(lambda x: lastFreshRecord["date"] - x.__getstate__()["date"] > timedelta(minutes=0), self.history)
	self.history = freshHistory+self.history
	
	if self.history:
		q=self.history[-1].__getstate__()
		ost_date=q["date"]
	else:
		print "no history available"
		self.live_trades=False
	
	range = truncate((nowStart - ost_date).total_seconds()/60,0) 
	if (range < lastMinutes/8) or not(self.history) or self.fatalError:
		self.live_trades=False
		iPrint( "No trades! range: " , range ,"<", lastMinutes, "div 8!", "error:",self.fatalError)
		iPrint("%"*30)
	else:
		self.live_trades=True
	
	now= self._now()
	for h in self.history:
		q=h.__getstate__()
		if (now-q["date"])>=timedelta(minutes=0):
			wspolczynnik = self.alfas[alfa,int((now - q["date"]).total_seconds())]
			volume+=q["amount"]
			licznik+=q["price"]*q["amount"]*wspolczynnik
			mianownik+=q["amount"]*wspolczynnik
	

	
	
	avg_price = truncate(licznik/mianownik, 8)
	volume=truncate(volume, 2)

	VM_plus, VM_minus, size = vortex(10, 90, self.history, nowStart, alfa2)
	iPrint(VM_plus, VM_minus, size)
	if (VM_plus is not None) and (VM_minus is not None) and (size>5):
		future_factor = VM_plus - VM_minus
	else:
		future_factor=0
	post_avg_prediction = predictAvg(avg_price, future_factor, 2)
	avg_price_backup = avg_price
	if abs(post_avg_prediction - avg_price)/avg_price < decimal.Decimal("0.02"):
		avg_price= post_avg_prediction
		
	else:
		print ("!"*50)
		print avg_price , post_avg_prediction, VM_plus, VM_minus, abs(post_avg_prediction - avg_price)/avg_price, decimal.Decimal("0.02")
		cancel_all_active_orders_of_pair(self.api, self.pair)
		self.fatalError=True
		self.live_trades=False
		print "fatalError"
		
		
	'''if abs(self.depthIndicator)<decimal.Decimal("0.004"):
		if self.depthIndicatorCount>0:
			bak=avg_price
			avg_price = avg_price*(1+ self.depthIndicator)
			print bak, "-->", avg_price
	else:
		print ("!"*50)
		cancel_all_active_orders_of_pair(self.api, self.pair)
		self.fatalError=True
		self.live_trades=False
		print "fatalError"'''
	
	iPrint( "alfa= ", alfa, len(self.history), "orders", range, "/", lastMinutes, "min. vol", volume, pair)
	iPrint( "AVG: ",avg_price_backup, "-->", avg_price )
	iPrint(VM_plus, VM_minus, "-->" , future_factor)
	
	
	
	###################### UWZGLEDNIA BETA CZYNNIK!!! ###########################################
	if (beta<1):
		ticker = btceapi.getTicker(pair, None)
		avg_price_ticker=truncate(getattr(ticker, 'avg'),8)
		avg_price= truncate(avg_price*beta + avg_price_ticker*(1-beta), 8)
		iPrint( "Beta" , beta)
		iPrint( "AVG:",avg_price)
	
	#avgVector+=[[avg_price, now]]
	
	
	buy_floor=truncate(avg_price*(100000-buy_margin)/100000, 6)
	sell_ceiling=truncate(avg_price*(100000+sell_margin)/100000, 6)
	iPrint( "low: ",buy_floor)
	iPrint( "AVG:",avg_price)
	iPrint( "high:", sell_ceiling)
	self.avg_price_calc_time = self._now()
	print "AVGbedzieRowne1", self.avg_price_calc_time
	self.depthIndicator, self.depthIndicatorCount = 0,0
	
	
	return (buy_floor, avg_price, sell_ceiling)
Example #18
0
# Analytics object
act = AveragesAnalytics(res_name, fee, 2)

# Prepare object data
act.current_sum = [float(act.startsum), 0.]
act.buy_allowed = False

# Activate timeout objects
buy_timeout = ActionTimeout("buy", res_value)
sell_timeout = ActionTimeout("sell", res_value)

# Loop
while True:
    try:
        # Get latest trades and update DB
        last_trades = btceapi.getTradeHistory(pair, count=100,
                                              connection=shared_data.conn)
    except Exception as ex:
        # Ignore all exceptions, just print them out and keep it on.
        #print(dt_date(now()),
        #      "getTradeHistory failed. Skipping actions and reopening connection.\n
        #      The error was:", ex)
        # Try to open new connection
        shared_data.conn = btceapi.common.BTCEConnection()
    else:
        for t in last_trades:
            time = dt_timestamp(t.date)
            working_dataset.update(time, t.price)

        # Calculate averages based on working dataset
        mas = MovingAverages(working_dataset, (fast, slow), realtime=True)
        # Calculate SAR for working dataset
Example #19
0
# VERY Simple task
# Grabs most recent batch of trades for all available pairs, inserts into DB

import btceapi
import MySQLdb as mdb
import sys

alltrades = btceapi.getTradeHistory(sys.argv[1])
data = list()

conn = mdb.connect('localhost', 'trading', 'ilikeponies', 'TDB')

try:

    cur = conn.cursor()
    for t in alltrades:
        cur.execute(
            "INSERT INTO BTCE_TRADES (Pair, price, amount, tid, trade_type, time) VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\');"
            % (str(t.pair), str(t.price), str(t.amount), str(
                t.tid), str(t.trade_type), str(t.date)))

except mdb.IntegrityError:
    print 'Primary key duplicate'

conn.commit()
Example #20
0
def _runBot(bot):
    while bot.running:
        sys.stdout.flush()
        loop_start = time.time()
        
        # Collect the set of pairs for which we should get depth.
        depthPairs = set()
        for handler, pairs in bot.depthHandlers:
            depthPairs.update(pairs)
            
        # Get current depth
        depths = {}
        conn = btceapi.BTCEConnection()
        for p in depthPairs:
            try:
                asks, bids = btceapi.getDepth(p, conn)
                depths[p] = (datetime.datetime.now(), asks, bids)
            except:
                bot.onDepthRetrievalError(p, traceback.format_exc())
                   
        # Collect the set of pairs for which we should get trade history.
        tradeHistoryPairs = set()
        for handler, pairs in bot.tradeHistoryHandlers:
            tradeHistoryPairs.update(pairs)
        
        tradeHistories = {}
        for p in tradeHistoryPairs:
            try:
                trades = btceapi.getTradeHistory(p, conn)
                tradeHistories[p] = (datetime.datetime.now(), trades)
            except:
                bot.onTradeHistoryRetrievalError(p, traceback.format_exc())
        conn.close()

        for p, (t, asks, bids) in depths.items():
            for handler, pairs in bot.depthHandlers:
                if p in pairs:
                    try:
                        handler(t, p, asks, bids)
                    except:
                        bot.onDepthHandlingError(p, handler, traceback.format_exc())
       
        for p, (t, trades) in tradeHistories.items():
            # Merge new trades into the bot's history.
            bot.mergeTradeHistory(p, trades)
            
            # Provide full history to traders
            for handler, pairs in bot.tradeHistoryHandlers:
                if p in pairs:
                    try:
                        handler(t, p, bot.tradeHistoryItems[p])
                    except:
                        bot.onTradeHistoryHandlingError(p, handler, traceback.format_exc())
                        
        # Tell all bots that have requested it that we're at the end
        # of an update loop.
        for handler in bot.loopEndHandlers:
            try:
                handler(datetime.datetime.now())
            except:
                # TODO: refactor this somewhere
                t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                logging.debug("%s Error while calling loop end handler (%r): %s" % (t, handler, traceback.format_exc()))
                
        while bot.running and time.time() - loop_start < bot.collectionInterval:
            time.sleep(0.5)

    # Give traders and opportunity to do thread-specific cleanup.
    for t in bot.traders:
        t.onExit()
Example #21
0
# VERY Simple task
# Grabs most recent batch of trades for all available pairs, inserts into DB

import btceapi
import MySQLdb as mdb
import sys

alltrades = btceapi.getTradeHistory(sys.argv[1])
data = list()

conn = mdb.connect('localhost', 'trading', 'ilikeponies', 'TDB')

try:

	cur = conn.cursor()
	for t in alltrades:
		cur.execute("INSERT INTO BTCE_TRADES (Pair, price, amount, tid, trade_type, time) VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\');" % (str(t.pair), str(t.price), str(t.amount), str(t.tid), str(t.trade_type), str(t.date)) )
	
except mdb.IntegrityError:
	print 'Primary key duplicate'	

conn.commit()
Example #22
0
#!/usr/bin/env python3
import sys
import pylab
import btceapi

# If an argument is provided to this script, it will be interpreted
# as a currency pair for which history should be displayed. Otherwise
# the BTC/USD history will be displayed.

if len(sys.argv) >= 2:
    pair = sys.argv[1]
    print("Showing history for %s" % pair)
else:
    print("No currency pair provided, defaulting to btc_usd")
    pair = "btc_usd"
    
history = btceapi.getTradeHistory(pair)

print(len(history))

pylab.plot([t.date for t in history if t.trade_type == 'ask'],
           [t.price for t in history if t.trade_type == 'ask'], 'ro')

pylab.plot([t.date for t in history if t.trade_type == 'bid'],
           [t.price for t in history if t.trade_type == 'bid'], 'go')

pylab.grid()          
pylab.show()
Example #23
0
def calcAvgPrice(self,
                 pair,
                 buy_margin,
                 sell_margin,
                 alfa=0.994,
                 beta=1,
                 lastMinutes=60,
                 count=150):

    if not (singleMode):
        print_trade_history(self, self.api, pair)

    buy_margin, sell_margin = (int(buy_margin), int(sell_margin))
    avg_price, licznik, mianownik, volume = (0, 0, 0, 0)
    ile = count
    dlugosc = 0
    nowStart = self._now()
    freshHistory = btceapi.getTradeHistory(pair, None, count)
    freshHistory = filter(
        lambda x: nowStart - x.__getstate__()["date"] < timedelta(
            minutes=lastMinutes), freshHistory)
    if freshHistory:
        lastFreshRecord = freshHistory[-1].__getstate__()
        self.history = filter(
            lambda x: nowStart - x.__getstate__()["date"] < timedelta(
                minutes=lastMinutes), self.history)
        self.history = filter(
            lambda x: lastFreshRecord["date"] - x.__getstate__()["date"] >
            timedelta(minutes=0), self.history)
    self.history = freshHistory + self.history

    if self.history:
        q = self.history[-1].__getstate__()
        ost_date = q["date"]
    else:
        print "no history available"
        self.live_trades = False

    range = truncate((nowStart - ost_date).total_seconds() / 60, 0)
    if (range < lastMinutes / 8) or not (self.history) or self.fatalError:
        self.live_trades = False
        iPrint("No trades! range: ", range, "<", lastMinutes, "div 8!",
               "error:", self.fatalError)
        iPrint("%" * 30)
    else:
        self.live_trades = True

    now = self._now()
    for h in self.history:
        q = h.__getstate__()
        if (now - q["date"]) >= timedelta(minutes=0):
            wspolczynnik = self.alfas[alfa,
                                      int((now - q["date"]).total_seconds())]
            volume += q["amount"]
            licznik += q["price"] * q["amount"] * wspolczynnik
            mianownik += q["amount"] * wspolczynnik

    avg_price = truncate(licznik / mianownik, 8)
    volume = truncate(volume, 2)

    VM_plus, VM_minus, size = vortex(10, 90, self.history, nowStart, alfa2)
    iPrint(VM_plus, VM_minus, size)
    if (VM_plus is not None) and (VM_minus is not None) and (size > 5):
        future_factor = VM_plus - VM_minus
    else:
        future_factor = 0
    post_avg_prediction = predictAvg(avg_price, future_factor, 2)
    avg_price_backup = avg_price
    if abs(post_avg_prediction -
           avg_price) / avg_price < decimal.Decimal("0.02"):
        avg_price = post_avg_prediction

    else:
        print("!" * 50)
        print avg_price, post_avg_prediction, VM_plus, VM_minus, abs(
            post_avg_prediction -
            avg_price) / avg_price, decimal.Decimal("0.02")
        cancel_all_active_orders_of_pair(self.api, self.pair)
        self.fatalError = True
        self.live_trades = False
        print "fatalError"
    '''if abs(self.depthIndicator)<decimal.Decimal("0.004"):
		if self.depthIndicatorCount>0:
			bak=avg_price
			avg_price = avg_price*(1+ self.depthIndicator)
			print bak, "-->", avg_price
	else:
		print ("!"*50)
		cancel_all_active_orders_of_pair(self.api, self.pair)
		self.fatalError=True
		self.live_trades=False
		print "fatalError"'''

    iPrint("alfa= ", alfa, len(self.history), "orders", range, "/",
           lastMinutes, "min. vol", volume, pair)
    iPrint("AVG: ", avg_price_backup, "-->", avg_price)
    iPrint(VM_plus, VM_minus, "-->", future_factor)

    ###################### UWZGLEDNIA BETA CZYNNIK!!! ###########################################
    if (beta < 1):
        ticker = btceapi.getTicker(pair, None)
        avg_price_ticker = truncate(getattr(ticker, 'avg'), 8)
        avg_price = truncate(avg_price * beta + avg_price_ticker * (1 - beta),
                             8)
        iPrint("Beta", beta)
        iPrint("AVG:", avg_price)

    #avgVector+=[[avg_price, now]]

    buy_floor = truncate(avg_price * (100000 - buy_margin) / 100000, 6)
    sell_ceiling = truncate(avg_price * (100000 + sell_margin) / 100000, 6)
    iPrint("low: ", buy_floor)
    iPrint("AVG:", avg_price)
    iPrint("high:", sell_ceiling)
    self.avg_price_calc_time = self._now()
    print "AVGbedzieRowne1", self.avg_price_calc_time
    self.depthIndicator, self.depthIndicatorCount = 0, 0

    return (buy_floor, avg_price, sell_ceiling)
Example #24
0
act = AveragesAnalytics(res_name, fee, 2)

# Prepare object data
act.current_sum = [float(act.startsum), 0.]
act.buy_allowed = False

# Activate timeout objects
buy_timeout = ActionTimeout("buy", res_value)
sell_timeout = ActionTimeout("sell", res_value)

# Loop
while True:
    try:
        # Get latest trades and update DB
        last_trades = btceapi.getTradeHistory(pair,
                                              count=100,
                                              connection=shared_data.conn)
    except Exception as ex:
        # Ignore all exceptions, just print them out and keep it on.
        #print(dt_date(now()),
        #      "getTradeHistory failed. Skipping actions and reopening connection.\n
        #      The error was:", ex)
        # Try to open new connection
        shared_data.conn = btceapi.common.BTCEConnection()
    else:
        for t in last_trades:
            time = dt_timestamp(t.date)
            working_dataset.update(time, t.price)

        # Calculate averages based on working dataset
        mas = MovingAverages(working_dataset, (fast, slow), realtime=True)