def detail(request, coin_id): """ This is the view corresponding to the cryptocurrency trading page, and details of the analysis the platform provides. I.e, Price predictions, chart analysis results, and sentiment analysis :param request: Django request :type request: request :param coin_id: UID of coin in DB :type coin_id: int :return: redirect to dashboard detail page """ coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) coin_id_tag = coin.ticker.lower() if int(coin_id) >= 4: return shortcuts.redirect('/dashboard/auth-keys') item = get_trading_data(coin_id_tag) json_data_charts = json.loads( json.dumps(item, indent=4, cls=DecimalEncoder)) trend_data = _get_support_res_from_json(json_data_charts) price = CryptoApi.get_prices(coin.ticker, 'usd')['last'] if price > trend_data[0]: CoinPrices.objects.filter(pk=coin_id).update(trend="Bullish") if price < trend_data[1]: CoinPrices.objects.filter(pk=coin_id).update(trend="Bearish") all_coins = CoinPrices.objects.all() wallet = CryptoApi.get_balance_eq() buy = BuyForm(request.POST, prefix='buy') sell = SellForm(request.POST, prefix='sell') dynamodb = boto3.resource('dynamodb', region_name='us-east-2') dynamo_table = dynamodb.Table('wallet') _make_buy(buy, coin, dynamo_table) _make_sell(sell, coin, dynamo_table) pos_neg_next_day = coin.current_price - coin.predictions return shortcuts.render( request, 'dashboard/detail.html', { 'coin': coin, 'all_coins': all_coins, 'wallet': wallet, 'b_form': BuyForm(prefix='buy'), 's_form': SellForm(prefix='sell'), 'pos_neg_next_day': pos_neg_next_day, 'resi': trend_data[0], 'support': trend_data[1], 'resi2': trend_data[2], 'support2': trend_data[3] })
def get(self, request, format=None): """ Returns data from view to Ajax function for visual representation """ all_coins = CoinPrices.objects.all() wallet = CryptoApi.get_balance_eq() labels = list(wallet.keys()) value = list(wallet.values()) senti_labels = [] pred_labels = [] senti_values = [] predicted_change = [] for coin in all_coins: senti_labels.append(str(coin.ticker)) if coin.is_favorite and coin.ticker != 'EUR': pred_labels.append(str(coin.ticker)) senti_values.append(float(coin.sentiment_score)) a = coin.predictions c = coin.current_price if a == c: if coin.is_favorite and coin.ticker != 'EUR': predicted_change.append(0) price_check = (abs(float((a - c) / c))) * 100 if a > c: current_biggest_diff = price_check else: current_biggest_diff = -1 * price_check if coin.is_favorite and coin.ticker != 'EUR': predicted_change.append(current_biggest_diff) length = len(labels) i = 0 while i < length: if labels[i] == 'usd': i = i + 1 else: prices = CryptoApi.get_prices(labels[i], "usd") last_price = prices['last'] value[i] = float(value[i]) * float(last_price) i = i + 1 data = { "labels": labels, "senti_labels": senti_labels, "pred_labels": pred_labels, "default": value, "senti_default": senti_values, "predicted_change": predicted_change, } return Response(data)
def index(request): """ This is the view which represents the dashboard page. It indexes every other app on the platform :param request: Django request :return: redirect to dashboard """ table = boto3.resource('dynamodb', region_name='us-east-2').Table handle_auth(request, table) for coin_id in range(1, 6): coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) if is_crypto(coin_id): curr_price = CryptoApi.get_prices(str(coin.ticker), "usd")['last'] CoinPrices.objects.filter(pk=coin_id).update( current_price=curr_price) else: last_price = CurrencyRates().get_rates('USD')['GBP'] CoinPrices.objects.filter(pk=5).update(current_price=last_price) response, response_charts = get_response_data(coin, coin_id, table) json_data = json.loads((json.dumps(response['Item'], indent=4, cls=DecimalEncoder))) json_data_charts = json.loads((json.dumps(response_charts['Item'], indent=4, cls=DecimalEncoder))) update_current_trend(coin, coin_id, json_data, json_data_charts) all_coins = CoinPrices.objects.all() for c in all_coins: sentiment = sum(Scraper.analyze_tweets_numerical(c.ticker)[0:3]) CoinPrices.objects.filter(ticker=c.ticker).update( sentiment_score=round(sentiment, 2)) tables.RequestConfig(request).configure(CoinTable(all_coins)) return shortcuts.render( request, 'dashboard/index.html', { 'all_coins': all_coins, 'table': table, 'equity': round(CryptoApi.get_equity(), 2) })
def check_for_break(ticker): prices = CryptoApi.get_prices(str(ticker), "usd") coin_resi = "" coin_support = "" dynamodb = boto3.resource('dynamodb', region_name='us-east-2') dynamoTables = dynamodb.Table('crypto_predictions') try: response = dynamoTables.get_item(Key={'coin_id': ticker}) except ClientError as e: print(e.response['Error']['Message']) else: print(response) item = response['Item'] print("Get Item Succeeded") lol = (json.dumps(item, indent=4, cls=DecimalEncoder) ) ############################## change jsondata_charts = json.loads(lol) coin_resi = float(jsondata_charts['resi']) coin_support = float(jsondata_charts['support']) if float(prices['last']) > coin_resi: return 'Bull' else: if float(prices['last']) < coin_support: return 'Bear' return 'NA'
def update_current_trend(coin, coin_id, json_data, json_data_charts): """ Updates db with current trend state :param coin: Coin object :type coin: Coin :param coin_id: UID of coin in DB :type coin_id: int :param json_data: Data to be parsed :type json_data: Json :param json_data_charts: Chart data to be parsed :type: json_chart_data: Json """ if coin_id < 4: pred_price = float("{0:.2f}".format(json_data['pred'])) coin_resi = str(json_data_charts['resi']) coin_support = str(json_data_charts['support']) CoinPrices.objects.filter(pk=coin_id).update(predictions=pred_price) price = CryptoApi.get_prices(coin.ticker, 'usd')['last'] CoinPrices.objects.filter(pk=coin_id).update(trend="Tightening") if price > coin_resi: CoinPrices.objects.filter(pk=coin_id).update(trend="Bullish") if price < coin_support: CoinPrices.objects.filter(pk=coin_id).update(trend="Bearish")
def forex(request, coin_id): """ This is the view corresponding to the FX trading page, and details of the analysis the platform provides. I.e, Price predictions, chart analysis results, and sentiment analysis """ coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) all_coins = CoinPrices.objects.all() wallet = CryptoApi.get_balance_eq() text = 0.0 buy = BuyForm(request.POST, prefix='buy') sell = SellForm(request.POST, prefix='sell') if buy.is_valid(): text = buy.cleaned_data['post'] buy = BuyForm() ForexApi.buy_order(str(coin.ticker + "_USD"), text, coin.ticker) wallet = CryptoApi.get_balance_eq() time.sleep(5) if sell.is_valid(): text = sell.cleaned_data['post'] sell = SellForm() ForexApi.sell_order(str(coin.ticker + "_USD")) wallet = CryptoApi.get_balance_eq() time.sleep(5) positions = ForexApi.get_pos()['positions'] dict = {} for s in positions: dict = s instrument = " " units = " " if 'instrument' in dict: instrument = dict['instrument'] units = dict['long']['units'] return shortcuts.render( request, 'dashboard/forex.html', { 'coin': coin, 'all_coins': all_coins, 'wallet': wallet, 'b_form': BuyForm(prefix='buy'), 's_form': SellForm(prefix='sell'), 'trade_amount': text, 'instrument': instrument, 'units': units })
def forex(request, coin_id): """ This is the view corresponding to the FX trading page, and details of the analysis the platform provides. I.e, Price predictions, chart analysis results, and sentiment analysis :param request: request from Django :type request: request :param coin_id: uid of coin in DB :type coin_id: int :return redirect to forex trading page """ coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) all_coins = CoinPrices.objects.all() trade_amount = 0.0 buy = BuyForm(request.POST, prefix='buy') sell = SellForm(request.POST, prefix='sell') if buy.is_valid(): trade_amount = _make_buy_fx(buy, coin) if sell.is_valid(): trade_amount = _make_sell_fx(sell, coin) fx_positions = dict({s for s in ForexApi.get_pos()['positions']}) instrument = fx_positions['instrument'], units = fx_positions['long']['units'] \ if 'instrument' in fx_positions else None wallet = CryptoApi.get_balance_eq() time.sleep(5) return shortcuts.render( request, 'dashboard/forex.html', { 'coin': coin, 'all_coins': all_coins, 'wallet': wallet, 'b_form': BuyForm(prefix='buy'), 's_form': SellForm(prefix='sell'), 'trade_amount': trade_amount, 'instrument': instrument, 'units': units })
def index(request): """This is the view which represents the dashboard page. It indexes every other app on the platform""" # def say(message): # pythoncom.CoInitialize() # engine = pyttsx3.init() # engine.say(message) # engine.runAndWait() username = request.user.username dynamodb = boto3.resource('dynamodb', region_name='us-east-2') dynamoTable = dynamodb.Table('crypto_prediction') dynamoTables = dynamodb.Table('crypto_predictions') dynamoTableAuth = dynamodb.Table('auth') try: response_auth = dynamoTableAuth.get_item(Key={'username': username}) except ClientError as e: print(e.response['Error']['Message']) return shortcuts.redirect('/dashboard/auth-keys') else: pass for i in range(1, 6): coin_id = i coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) try: from json.decoder import JSONDecodeError as Js_error except ImportError: Js_error = ValueError if i < 5: prices = CryptoApi.get_prices(str(coin.ticker), "usd") last_price = prices['last'] CoinPrices.objects.filter(pk=coin_id).update( current_price=last_price) if 4 < i < 6: c = CurrencyRates() c_dict = c.get_rates('USD') last_price = c_dict['GBP'] CoinPrices.objects.filter(pk=5).update(current_price=last_price) coin_id_tag = coin.ticker.lower() now = datetime.datetime.now() try: response = dynamoTable.get_item(Key={ 'date': now.strftime("%Y-%m-%d"), 'coin_id': coin_id_tag }) if coin_id < 4: response_charts = dynamoTables.get_item( Key={'coin_id': coin_id_tag}) except ClientError as e: print(e.response['Error']['Message']) else: item = response['Item'] item2 = response_charts['Item'] chart = (json.dumps(item, indent=4, cls=DecimalEncoder)) chart2 = (json.dumps(item2, indent=4, cls=DecimalEncoder)) json_data = json.loads(chart) json_data_charts = json.loads(chart2) pred_price = float("{0:.2f}".format(json_data['pred'])) coin_resi = str(json_data_charts['resi']) coin_support = str(json_data_charts['support']) if i < 4: CoinPrices.objects.filter(pk=coin_id).update( predictions=pred_price) price = CryptoApi.get_prices(coin.ticker, 'usd')['last'] CoinPrices.objects.filter(pk=coin_id).update( trend="Tightening") if price > coin_resi: CoinPrices.objects.filter(pk=coin_id).update( trend="Bullish") if price < coin_support: CoinPrices.objects.filter(pk=coin_id).update( trend="Bearish") all_coins = CoinPrices.objects.all() all_coins = CoinPrices.objects.all() for c in all_coins: result = Scraper.analyze_tweets_numerical(c.ticker) senti_score = result[0] + result[1] + result[2] CoinPrices.objects.filter(ticker=c.ticker).update( sentiment_score=round(senti_score, 2)) table = CoinTable(all_coins) tables.RequestConfig(request).configure(table) equity = CryptoApi.get_equity() context = { 'all_coins': all_coins, 'table': table, 'equity': round(equity, 2) } # say("Welcome to Braikout Dashboard") # say("Current total Equity is. " + str(equity) + " dollars") return shortcuts.render(request, 'dashboard/index.html', context)
def detail(request, coin_id): """ This is the view corresponding to the cryptocurrency trading page, and details of the analysis the platform provides. I.e, Price predictions, chart analysis results, and sentiment analysis """ global coin_support2, coin_resistance_2, all_coins, coin_resistance coin_resistance = "" coin_support = "" coin_resistance_2 = "" coin_support2 = "" dynamodb = boto3.resource('dynamodb', region_name='us-east-2') dynamoTables = dynamodb.Table('crypto_predictions') coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) all_coins = CoinPrices.objects.all() coin_id_tag = coin.ticker.lower() if int(coin_id) < 4: try: response = dynamoTables.get_item(Key={'coin_id': coin_id_tag}) except ClientError as e: print(e.response['Error']['Message']) else: item = response['Item'] result = (json.dumps(item, indent=4, cls=DecimalEncoder)) json_data_charts = json.loads(result) coin_resistance = str(json_data_charts['resi']) coin_support = str(json_data_charts['support']) coin_resistance_2 = str(json_data_charts['resi2']) coin_support2 = str(json_data_charts['support2']) price = CryptoApi.get_prices(coin.ticker, 'usd')['last'] if price > coin_resistance: CoinPrices.objects.filter(pk=coin_id).update(trend="Bullish") if price < coin_support: CoinPrices.objects.filter(pk=coin_id).update(trend="Bearish") all_coins = CoinPrices.objects.all() wallet = CryptoApi.get_balance_eq() buy = BuyForm(request.POST, prefix='buy') sell = SellForm(request.POST, prefix='sell') if buy.is_valid(): text = buy.cleaned_data['post'] buy = BuyForm() CryptoApi.buy_crypto(text, coin.ticker) time.sleep(5) wallet = CryptoApi.get_balance_eq() for key, val in wallet.items(): dynamoTable.put_item(Item={'coin_id': key, 'amount': val}) if sell.is_valid(): text = sell.cleaned_data['post'] sell = SellForm() CryptoApi.sell_crypto(text, coin.ticker) time.sleep(5) wallet = CryptoApi.get_balance_eq() for key, val in wallet.items(): dynamoTable.put_item(Item={'coin_id': key, 'amount': val}) pos_neg_next_day = coin.current_price - coin.predictions return shortcuts.render( request, 'dashboard/detail.html', { 'coin': coin, 'all_coins': all_coins, 'wallet': wallet, 'b_form': BuyForm(prefix='buy'), 's_form': SellForm(prefix='sell'), 'pos_neg_next_day': pos_neg_next_day, 'resi': coin_resistance, 'support': coin_support, 'resi2': coin_resistance_2, 'support2': coin_support2 })
def _update_balance_table(dynamo_table): time.sleep(5) wallet = CryptoApi.get_balance_eq() for key, val in wallet.items(): dynamo_table.put_item(Item={'coin_id': key, 'amount': val})
def _make_sell(sell, coin, dynamo_table): if sell.is_valid(): text = sell.cleaned_data['post'] sell = SellForm() CryptoApi.sell_crypto(text, coin.ticker) _update_balance_table(dynamo_table)
def _make_buy(buy, coin, dynamo_table): if buy.is_valid(): text = buy.cleaned_data['post'] buy = BuyForm() CryptoApi.buy_crypto(text, coin.ticker) _update_balance_table(dynamo_table)