def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time poo = poloniex(settings.API_KEY,settings.API_SECRET) now = get_utc_unixtime() r = poo.returnDepositHistory(0,now) deposits = r['deposits'] + r['withdrawals'] for d in deposits: print(d) currency = d['currency'] amount = float(d['amount']) * ( -1 if 'withdrawalNumber' in d.keys() else 1 ) timestamp = d['timestamp'] txid = d['withdrawalNumber'] if 'withdrawalNumber' in d.keys() else d['txid'] status = d['status'] created_on = datetime.datetime.fromtimestamp(timestamp) try: d = Deposit.objects.get(txid=txid) except: d = Deposit() d.symbol=currency d.amount = amount d.txid = txid d.type = 'deposit' if amount > 0 else 'withdrawal' d.status = status d.created_on = created_on d.modified_on = created_on d.created_on_str = datetime.datetime.strftime(created_on - datetime.timedelta(hours=int(7)),'%Y-%m-%d %H:%M') d.save()
def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time #hit API poo = poloniex(settings.API_KEY,settings.API_SECRET) balances = poo.returnBalances() #record balances deposited_amount_btc, deposited_amount_usd = get_deposit_balance() with transaction.atomic(): for ticker in balances: val = float(balances[ticker]['available']) + float(balances[ticker]['onOrders']) if val > 0.0001: exchange_rate_coin_to_btc = get_exchange_rate_to_btc(ticker) exchange_rate_btc_to_usd = get_exchange_rate_btc_to_usd() exchange_rate_coin_to_usd = exchange_rate_btc_to_usd * exchange_rate_coin_to_btc btc_val = exchange_rate_coin_to_btc * val usd_val = exchange_rate_btc_to_usd * btc_val b = Balance(symbol=ticker,coin_balance=val,btc_balance=btc_val,exchange_to_btc_rate=exchange_rate_coin_to_btc,usd_balance=usd_val,exchange_to_usd_rate=exchange_rate_coin_to_btc,deposited_amount_btc=deposited_amount_btc if ticker =='BTC' else 0.00, deposited_amount_usd=deposited_amount_usd if ticker =='BTC' else 0.00) b.save() for b in Balance.objects.filter(date_str='0'): # django timezone stuff , FML b.date_str = datetime.datetime.strftime(b.created_on - datetime.timedelta(hours=int(7)),'%Y-%m-%d %H:%M') b.save() #normalize trade recommendations too. merp for tr in Trade.objects.filter(created_on_str=''): # django timezone stuff , FML tr.created_on_str = datetime.datetime.strftime(tr.created_on - datetime.timedelta(hours=int(7)),'%Y-%m-%d %H:%M') tr.save()
def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time poo = poloniex(settings.API_KEY, settings.API_SECRET) if settings.MAKE_TRADES: time.sleep(40) for t in Trade.objects.filter(created_on__lt=datetime.datetime.now(), status='scheduled'): #bid right below the lowest ask, or right above the highest bid so that our orders get filled action = t.type price = Price.objects.filter( symbol=t.symbol).order_by('-created_on').first() if action == 'sell': rate = price.lowestask * 0.999 else: rate = price.highestbid * 1.001 t.price = rate if action == 'buy': try: response = {} if not settings.MAKE_TRADES else poo.buy( t.symbol, rate, t.amount) except Exception as e: print_and_log('(st)act_upon_recommendation:buy: ' + str(e)) elif action == 'sell': try: response = {} if not settings.MAKE_TRADES else poo.sell( t.symbol, rate, t.amount) except Exception as e: print_and_log('(st)act_upon_recommendation:sell: ' + str(e)) t.response = response, t.orderNumber = response.get('orderNumber', '') t.status = 'error' if response.get('error', False) else 'open' t.calculatefees() t.calculate_exchange_rates() t.save() ot = t.opposite_trade ot.opposite_price = rate ot.net_profit = ((rate * t.amount) - (ot.price * ot.amount) if action == 'sell' else (ot.price * ot.amount) - (rate * t.amount)) - ot.fee_amount - t.fee_amount ot.calculate_profitability_exchange_rates() ot.save()
def handle(self, *args, **options): # setup self.poo = poloniex(settings.API_KEY, settings.API_SECRET) self.setup() print_and_log("(t){} ---- ****** STARTING TRAINERS ******* ".format(str(datetime.datetime.now()))) self.get_traders() print_and_log("(t){} ---- ****** DONE TRAINING ALL TRAINERS ******* ".format(str(datetime.datetime.now()))) while True: # TLDR -- which NNs should run at this granularity? should_run = [] recommendations = dict.fromkeys(range(0, len(self.predictors))) for i in range(0, len(self.predictor_configs)): config = self.predictor_configs[i] if (int(get_utc_unixtime() / 60) % config['granularity'] == 0 and datetime.datetime.now().second < 1): should_run.append(i) # TLDR -- update open orders bfore placing new ones if len(should_run) > 0: self.handle_open_orders() # TLDR -- run the NNs specified at this granularity for i in should_run: config = self.predictor_configs[i] recommend = self.run_predictor(i) recommendations[i] = recommend time.sleep(1) # TLDR - act upon recommendations for i in range(0, len(recommendations)): recommendation = recommendations[i] config = self.predictor_configs[i] if recommendation is not None: print_and_log("(t)recommendation {} - {} : {}".format(i, str(config['name']), recommendation)) self.act_upon_recommendation(i, recommendation) # TLDR - cleanup and stats if len(should_run) > 0: pct_buy = round(100.0 * sum(recommendations[i] == 'BUY' for i in recommendations) / len(recommendations)) pct_sell = round(100.0 * sum(recommendations[i] == 'SELL' for i in recommendations) / len(recommendations)) print_and_log("(t)TLDR - {}% buy & {}% sell: {}".format(pct_buy, pct_sell, recommendations)) print_and_log("(t) ******************************************************************************* ") print_and_log("(t) portfolio is {}".format(self.get_portfolio_breakdown_pct())) print_and_log("(t) ******************************************************************************* ") print_and_log("(t) {} ..... waiting again ..... ".format(str(datetime.datetime.now()))) print_and_log("(t) ******************************************************************************* ") time.sleep(1)
def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time #hit API poo = poloniex(settings.API_KEY, settings.API_SECRET) balances = poo.returnBalances() #record balances deposited_amount_btc, deposited_amount_usd = get_deposit_balance() with transaction.atomic(): for ticker in balances: val = float(balances[ticker]['available']) + float( balances[ticker]['onOrders']) if val > 0.0001: exchange_rate_coin_to_btc = get_exchange_rate_to_btc( ticker) exchange_rate_btc_to_usd = get_exchange_rate_btc_to_usd() exchange_rate_coin_to_usd = exchange_rate_btc_to_usd * exchange_rate_coin_to_btc btc_val = exchange_rate_coin_to_btc * val usd_val = exchange_rate_btc_to_usd * btc_val b = Balance(symbol=ticker, coin_balance=val, btc_balance=btc_val, exchange_to_btc_rate=exchange_rate_coin_to_btc, usd_balance=usd_val, exchange_to_usd_rate=exchange_rate_coin_to_btc, deposited_amount_btc=deposited_amount_btc if ticker == 'BTC' else 0.00, deposited_amount_usd=deposited_amount_usd if ticker == 'BTC' else 0.00) b.save() for b in Balance.objects.filter(date_str='0'): # django timezone stuff , FML b.date_str = datetime.datetime.strftime( b.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M') b.save() #normalize trade recommendations too. merp for tr in Trade.objects.filter(created_on_str=''): # django timezone stuff , FML tr.created_on_str = datetime.datetime.strftime( tr.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M') tr.save()
def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time poo = poloniex(settings.API_KEY, settings.API_SECRET) if settings.MAKE_TRADES: time.sleep(40) for t in Trade.objects.filter(created_on__lt=datetime.datetime.now(), status='scheduled'): # bid right below the lowest ask, or right above the highest bid so that our orders get filled action = t.type price = Price.objects.filter(symbol=t.symbol).order_by('-created_on').first() if action == 'sell': rate = price.lowestask * 0.999 else: rate = price.highestbid * 1.001 t.price = rate if action == 'buy': try: response = {} if not settings.MAKE_TRADES else poo.buy(t.symbol, rate, t.amount) except Exception as e: print_and_log('(st)act_upon_recommendation:buy: ' + str(e)) elif action == 'sell': try: response = {} if not settings.MAKE_TRADES else poo.sell(t.symbol, rate, t.amount) except Exception as e: print_and_log('(st)act_upon_recommendation:sell: ' + str(e)) t.response = response t.orderNumber = response.get('orderNumber', '') t.status = 'error' if response.get('error', False) else 'open' t.calculatefees() t.calculate_exchange_rates() t.save() ot = t.opposite_trade ot.opposite_price = rate ot.net_profit = ((rate * t.amount) - (ot.price * ot.amount) if action == 'sell' else (ot.price * ot.amount) - (rate * t.amount)) - ot.fee_amount - t.fee_amount ot.calculate_profitability_exchange_rates() ot.save()
def handle(self, *args, **options): from history.poloniex import poloniex # hit API poo = poloniex(settings.API_KEY, settings.API_SECRET) balances = poo.returnBalances() balances = json.dumps(balances) balances = json.loads(balances) # record balances deposited_amount_btc, deposited_amount_usd = get_deposit_balance() with transaction.atomic(): try: for ticker2 in balances['info']: print(ticker2) val = float(ticker2['balance']) print(val) if val > 0.0001: ticker = ticker2 ['currency'] exchange_rate_coin_to_btc = get_exchange_rate_to_btc(ticker) exchange_rate_btc_to_usd = get_exchange_rate_btc_to_usd() btc_val = val / exchange_rate_coin_to_btc usd_val = btc_val / exchange_rate_btc_to_usd b = Balance(symbol=ticker, coin_balance=val, btc_balance=btc_val, exchange_to_btc_rate=exchange_rate_coin_to_btc, usd_balance=usd_val, exchange_to_usd_rate=exchange_rate_coin_to_btc, deposited_amount_btc=deposited_amount_btc if ticker == 'BTC' else 0.00, deposited_amount_usd=deposited_amount_usd if ticker == 'BTC' else 0.00) b.save() except Exception as e: print(e) for b in Balance.objects.filter(date_str='0'): # django timezone stuff , FML b.date_str = datetime.datetime.strftime(b.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M') b.save() # normalize trade recommendations too. merp for tr in Trade.objects.filter(created_on_str=''): # django timezone stuff , FML tr.created_on_str = datetime.datetime.strftime( tr.created_on - datetime.timedelta(hours=int(7)), '%Y-%m-%d %H:%M') tr.save()
def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time poo = poloniex(settings.API_KEY,settings.API_SECRET) price = poo.returnTicker() for ticker in price.keys(): this_price = price[ticker]['last'] this_volume = price[ticker]['quoteVolume'] the_str = ticker + ',' + str(time.time()) + ',' + this_price + ", " + this_volume print("(pp)"+the_str) p = Price() p.price = this_price p.volume = this_volume p.lowestask = price[ticker]['lowestAsk'] p.highestbid = price[ticker]['highestBid'] p.symbol = ticker p.created_on_str = str(p.created_on) p.save()
def handle(self, *args, **options): from history.poloniex import poloniex from history.models import Price import time poo = poloniex(settings.API_KEY, settings.API_SECRET) price = poo.returnTicker() for ticker in price.keys(): this_price = price[ticker]['last'] this_volume = price[ticker]['quoteVolume'] the_str = ticker + ',' + str( time.time()) + ',' + this_price + ", " + this_volume print("(pp)" + the_str) p = Price() p.price = this_price p.volume = this_volume p.lowestask = price[ticker]['lowestAsk'] p.highestbid = price[ticker]['highestBid'] p.symbol = ticker p.created_on_str = str(p.created_on) p.save()
def handle(self, *args, **options): # setup self.poo = poloniex(settings.API_KEY, settings.API_SECRET) self.setup() print_and_log("(t){} ---- ****** STARTING TRAINERS ******* ".format( str(datetime.datetime.now()))) self.get_traders() print_and_log( "(t){} ---- ****** DONE TRAINING ALL TRAINERS ******* ".format( str(datetime.datetime.now()))) while True: # TLDR -- which NNs should run at this granularity? should_run = [] recommendations = dict.fromkeys(range(0, len(self.predictors))) for i in range(0, len(self.predictor_configs)): config = self.predictor_configs[i] if (int(get_utc_unixtime() / 60) % config['granularity'] == 0 and datetime.datetime.now().second < 1): should_run.append(i) # TLDR -- update open orders bfore placing new ones if len(should_run) > 0: self.handle_open_orders() # TLDR -- run the NNs specified at this granularity for i in should_run: config = self.predictor_configs[i] recommend = self.run_predictor(i) recommendations[i] = recommend time.sleep(1) # TLDR - act upon recommendations for i in range(0, len(recommendations)): recommendation = recommendations[i] config = self.predictor_configs[i] if recommendation is not None: print_and_log("(t)recommendation {} - {} : {}".format( i, str(config['name']), recommendation)) self.act_upon_recommendation(i, recommendation) # TLDR - cleanup and stats if len(should_run) > 0: pct_buy = round(100.0 * sum(recommendations[i] == 'BUY' for i in recommendations) / len(recommendations)) pct_sell = round(100.0 * sum(recommendations[i] == 'SELL' for i in recommendations) / len(recommendations)) print_and_log("(t)TLDR - {}% buy & {}% sell: {}".format( pct_buy, pct_sell, recommendations)) print_and_log( "(t) ******************************************************************************* " ) print_and_log("(t) portfolio is {}".format( self.get_portfolio_breakdown_pct())) print_and_log( "(t) ******************************************************************************* " ) print_and_log("(t) {} ..... waiting again ..... ".format( str(datetime.datetime.now()))) print_and_log( "(t) ******************************************************************************* " ) time.sleep(1)