Example #1
0
 def update_balance(self):
     try:
         binance_client = self._initialize_binance_client()
         eur_available = float(
             binance_client.get_asset_balance(asset='EUR')['free'])
         eth_available = round(
             float(binance_client.get_asset_balance(asset='ETH')['free']),
             8)
         latest_trade = get_current_eth_eur_value(connector='binance')
         current_etheur_value = float(latest_trade.price)
         print("current_etheur_value", current_etheur_value)
         self.account_balance = AccountBalance(
             timestamp_utc=datetime.utcnow(),
             pair="ETH-EUR",
             exchange="Binance",
             eth_available=eth_available,
             eur_available=eur_available,
             balance_total=current_etheur_value * eth_available +
             eur_available)
         # print("eth_available", eth_available )
         # print("eur_available", eur_available )
         self._write_account_balance(self.account_balance,
                                     connector="binance")
     except Exception as e:
         print("Oops!  Something went wrong with updating the account")
         print(e)
         pass
Example #2
0
    def update_balance(self):
        latest_trade = get_current_eth_eur_value(connector="binance")
        try:
            current_etheur_value = float(latest_trade.price)
        except Exception as e:
            print(
                "Oops!  Something went wrong with fetching the latest live_trades"
            )
            raise e
        influx_connector = InfluxConnector()
        client = influx_connector.get_client()
        query_str = f"SELECT time, exchange, pair, eth_available,eur_available,balance_total FROM simulator_account_balance  order by time desc limit 1"
        result_set = client.query(query_str)
        if len(result_set) > 0:
            result_points = list(
                result_set.get_points("simulator_account_balance"))
            self.account_balance = AccountBalance(
                timestamp_utc=datetime.utcnow(),
                exchange=result_points[0]['exchange'],
                pair=result_points[0]['pair'],
                eth_available=result_points[0]['eth_available'],
                eur_available=result_points[0]['eur_available'],
                balance_total=current_etheur_value *
                result_points[0]['eth_available'] +
                result_points[0]['eur_available'])

            self._write_account_balance(self.account_balance,
                                        connector="simulator")
Example #3
0
    def update_balance(self):
        client_id, api_key, api_secret = BitstampConnector._get_api_keys()
        nonce, timestamp, content_type = BitstampConnector._get_nonce_timestamp_content_type(
        )
        payload_string = BitstampConnector._get_payload_string('balance',
                                                               order_id=None,
                                                               amount=None,
                                                               price=None)

        message = 'BITSTAMP ' + api_key + \
            'POST' + \
            'www.bitstamp.net' + \
            '/api/v2/balance/etheur/' + \
            '' + \
            content_type + \
            nonce + \
            timestamp + \
            'v2' + \
            payload_string
        message = message.encode('utf-8')
        signature = BitstampConnector._generate_signature(message, api_secret)
        headers = BitstampConnector._generate_headers(message, signature,
                                                      nonce, timestamp,
                                                      content_type, api_key)

        r = requests.post('https://www.bitstamp.net/api/v2/balance/etheur/',
                          headers=headers,
                          data=payload_string)
        if not r.status_code == 200:
            raise Exception('Status code not 200')

        signature_check = BitstampConnector._get_signature_check(
            nonce, timestamp, r.headers, r.content, api_secret)
        if not r.headers.get('X-Server-Auth-Signature') == signature_check:
            raise Exception('Signatures do not match')

        content_dict = BitstampConnector._prepare_response(r.content)
        if bool(content_dict):
            latest_trade = get_current_eth_eur_value()
            try:
                current_etheur_value = latest_trade.price
            except Exception as e:
                print(
                    "Oops!  Something went wrong with fetching the latest live_trades"
                )
                raise e

            self.account_balance = AccountBalance(
                timestamp_utc=datetime.utcnow(),
                pair="ETH-EUR",
                exchange="Bitstamp",
                eth_available=float(content_dict['eth_available']),
                eur_available=float(content_dict["eur_available"]),
                balance_total=float(current_etheur_value) *
                float(content_dict['eth_available']) +
                float(content_dict["eur_available"]))
            self._write_account_balance(self.account_balance,
                                        connector="bitstamp")
Example #4
0
    def apply(self, connector: AccountConnector, live_trades_connector_name):
        lower_bound = float(-inf)
        data = self._collect_data()
        data_validation_successful = self._data_validation_successful(data)
        print("data_validation_successful", data_validation_successful)
        last_relevant_record = data[-2:-1]
        last_relevant_close_value = last_relevant_record['close'].values[0]
        print("last close-value", last_relevant_close_value)
        current_eth_eur_value = getattr(
            api.get_current_eth_eur_value(
                connector=live_trades_connector_name), 'price')
        print("current eth-eur-value:", current_eth_eur_value)
        last_transaction = connector.get_last_transaction()
        status = self._get_current_status(last_transaction)
        print("last relevant close-value", last_relevant_close_value)
        print(data.index[-3], "ema_3:", data[-3:-2]['ema_3'].values[0],
              "ema_6:", data[-3:-2]['ema_6'].values[0], "ema_9:",
              data[-3:-2]['ema_9'].values[0])
        print(data.index[-2], "ema_3:", data[-2:-1]['ema_3'].values[0],
              "ema_6:", data[-2:-1]['ema_6'].values[0], "ema_9:",
              data[-2:-1]['ema_9'].values[0])
        print(data.index[-2], "sma_21:", data[-2:-1]['sma_21'].values[0],
              "sma_50:", data[-2:-1]['sma_50'].values[0], "sma_100:",
              data[-2:-1]['sma_100'].values[0])
        is_down_trend_long = self._is_down_trend_long(data)
        is_down_trend_short = self._is_down_trend_short(data)
        print("is_down_trend_long", is_down_trend_long)
        print("is_down_trend_short", is_down_trend_short)
        if status == 'in':
            print("in-trade")
            upper_bound = last_transaction.price * 1.004
            print("buying price", last_transaction.price)
            print("upper_bound", upper_bound)
            # if current_eth_eur_value > last_transaction.price/1.0025 and current_eth_eur_value > lower_bound:
            #     lower_bound = current_eth_eur_value
            if self._take_profit(data, upper_bound, current_eth_eur_value):
                print("take-profit")
                print("last buying price:", last_transaction.price,
                      ",current eth-eur-value:", current_eth_eur_value)
                tradeable_eth = connector.tradeable_eth()
                connector.sell_eth(tradeable_eth, current_eth_eur_value)
            elif self._stop_loss(data):
                # This case will never happen, since we don't use any stop-loss in this strategy
                pass
            else:
                pass
        if status == 'out':
            print("out-trade")
            if self._entry_signal(
                    data, current_eth_eur_value, is_down_trend_long,
                    is_down_trend_short) and data_validation_successful:
                print("enter trade")
                eth_to_buy = calculate_eth(connector.tradeable_eur(),
                                           current_eth_eur_value)
                connector.buy_eth(eth_to_buy, current_eth_eur_value)

        return data
Example #5
0
    def buy_eth(self, amount, price):
        if not self._valid_transaction_volume(amount, price, 'buy'):
            print("not enough money on account")
            return
        if amount <= 0 or amount is None or price is None:
            return
        latest_trade = get_current_eth_eur_value(connector="binance")
        try:
            current_etheur_value = latest_trade.price
        except Exception as e:
            print(
                "Oops!  Something went wrong with fetching the latest live_trades"
            )
            raise e
        # The price might jumped up again on current_etheur_value, therefore, we want to take the value, which satisfied the rules
        base_price = min(current_etheur_value, price)

        print("base_price", base_price)

        # current_etheur_value= 1000
        for idx in range(3):
            try:
                bidding_value = round(float(base_price) + idx * 1, 2)
                print("bidding_value", bidding_value)
                order = self._buy_limit_order(amount, bidding_value)
                print(order)
                if not self._is_valid_limit_response(order):
                    break

                order_id = order['orderId']
                print("order", order)
                print("order_id", order_id)
                time.sleep(10)
                status_content = self._check_order_status(order_id)
                print("status_content", status_content['status'])
                if status_content['status'] == 'FILLED':
                    transaction = Transaction(
                        timestamp_utc=datetime.fromtimestamp(
                            status_content['time'] / 1000.0).astimezone(
                                pytz.utc),
                        exchange="Binance",
                        pair="ETH-EUR",
                        amount=float(status_content['executedQty']),
                        price=float(status_content['price']),
                        id=str(status_content['orderId']),
                        type="buy")
                    self._write_transaction(transaction, connector="binance")
                    return status_content

            except ValueError:
                print("Oops!  Something went wrong with buying ETH")
        return None
Example #6
0
    def apply(self, connector: AccountConnector, live_trades_connector_name):
        lower_bound = float(-inf)
        data = SimpleStrategy._collect_data()
        last_relevant_record = data[-2:-1]
        last_relevant_close_value = last_relevant_record['close'].values[0]
        current_eth_eur_value = getattr(
            api.get_current_eth_eur_value(live_trades_connector_name), 'price')
        print("current eth-eur-value:", current_eth_eur_value)
        last_transaction = connector.get_last_transaction()
        status = SimpleStrategy._get_current_status(last_transaction)
        print("last relevant close-value", last_relevant_close_value)
        print("last bullish engulfing pattern",
              data.loc[data['engulfing'] > 0])
        if status == 'in':
            print("in-trade")
            lower_bound = last_transaction.price / 1.0025
            print("lower_bound", lower_bound)
            # if current_eth_eur_value > last_transaction.price/1.0025 and current_eth_eur_value > lower_bound:
            #     lower_bound = current_eth_eur_value
            # print("lower_bound", lower_bound)
            if SimpleStrategy._take_profit(data):
                print("take-profit")
                print("last buying price:", last_transaction.price,
                      ",current eth-eur-value:", current_eth_eur_value)
                tradeable_eth = connector.tradeable_eth()
                connector.sell_eth(tradeable_eth, current_eth_eur_value)
            elif SimpleStrategy._stop_loss(data, lower_bound):
                print("stop-loss")
                print("last buying price:", last_transaction.price,
                      ",current eth-eur-value:", current_eth_eur_value)
                tradeable_eth = connector.tradeable_eth()
                connector.sell_eth(tradeable_eth, current_eth_eur_value)
            else:
                pass
        if status == 'out':
            print("out-trade")
            if SimpleStrategy._entry_signal(data):
                print("enter trade")
                print("ema_10:", data[-3:-2]['ema_10'].values[0], "ema_20:",
                      data[-3:-2]['ema_20'].values[0])
                eth_to_buy = calculate_eth(connector.tradeable_eur(),
                                           current_eth_eur_value)
                connector.buy_eth(eth_to_buy, current_eth_eur_value)

        return data
Example #7
0
    def sell_eth(self, amount, price):
        if not self._valid_transaction_volume(amount, price, 'sell'):
            print("not enough eth on account")
            return
        if amount <= 0 or amount is None or price is None:
            return
        latest_trade = get_current_eth_eur_value()
        try:
            current_etheur_value = latest_trade.price
        except Exception as e:
            print(
                "Oops!  Something went wrong with fetching the latest live_trades"
            )
            raise e
        # The price might jumped up again on current_etheur_value, therefore, we want to take the value, which satisfied the rules
        base_price = max(current_etheur_value, price)
        # print("base_price", base_price)
        # current_etheur_value= 3000
        for idx in range(3):
            try:
                bidding_value = round(float(base_price) - idx * 0.5, 2)
                print("bidding_value", bidding_value)
                limit_content = BitstampConnector._sell_limit_order(
                    amount, bidding_value)
                print(limit_content)
                if not BitstampConnector._is_valid_limit_response(
                        limit_content):
                    break

                order_id = limit_content['id']
                print("limit_content", limit_content)
                print("order_id", order_id)
                time.sleep(10)
                status_content = BitstampConnector._check_order_status(
                    str(order_id))
                print("status_content", status_content['status'])
                if status_content['status'] == 'Open':
                    if float(status_content['amount_remaining']) < amount:
                        # a subset of the original order is fulfilled
                        cancel_content = BitstampConnector._cancel_order(
                            str(order_id))
                        print("open, limit_content", limit_content)
                        transaction = Transaction(
                            timestamp_utc=datetime.strptime(
                                limit_content['datetime'],
                                "%Y-%m-%d %H:%M:%S.%f").replace(
                                    tzinfo=pytz.utc),
                            exchange="Bitstamp",
                            pair="ETH-EUR",
                            amount=float(limit_content['amount']),
                            price=float(limit_content['price']),
                            id=str(limit_content['id']),
                            type="sell")
                        self._write_transaction(transaction,
                                                connector="bitstamp")
                        return limit_content
                    else:
                        cancel_content = BitstampConnector._cancel_order(
                            str(order_id))
                        print("cancel_content", cancel_content)
                elif status_content['status'] == 'Finished':
                    print("finished, limit_content", limit_content)
                    if bool(limit_content['id']):
                        print(limit_content)
                        transaction = Transaction(
                            timestamp_utc=datetime.strptime(
                                limit_content['datetime'],
                                "%Y-%m-%d %H:%M:%S.%f").replace(
                                    tzinfo=pytz.utc),
                            exchange="Bitstamp",
                            pair="ETH-EUR",
                            amount=float(limit_content['amount']),
                            price=float(limit_content['price']),
                            id=str(limit_content['id']),
                            type="sell")
                        self._write_transaction(transaction,
                                                connector="bitstamp")
                    return limit_content
                else:
                    cancel_content = BitstampConnector._cancel_order(
                        str(order_id))

            except ValueError:
                print("Oops!  Something went wrong with selling ETH")
        return None