예제 #1
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        close = df['close'].values

        # ************** Calc EMA
        ema5 = talib.EMA(close[-5:], timeperiod=5)[-1]
        ema10 = talib.EMA(close[-10:], timeperiod=10)[-1]
        ema20 = talib.EMA(close[-20:], timeperiod=20)[-1]
        close_price = self.get_price(TradeState.none, df.tail(), self.pair)

        print(ema5)
        print(ema10)
        print('close_price:', str(close_price), 'ema:', str(ema20))
        if close_price < ema10 or close_price < ema20:
            new_action = TradeState.sell
        elif close_price > ema5 and close_price > ema10:
            new_action = TradeState.buy

        # ************** Calc EMA Death Cross
        ema_interval_short = 6
        ema_interval_long = 25
        ema_short = talib.EMA(close[-ema_interval_short:],
                              timeperiod=ema_interval_short)[-1]
        ema_long = talib.EMA(close[-ema_interval_long:],
                             timeperiod=ema_interval_long)[-1]
        if ema_short <= ema_long:  # If we are below death cross, sell
            new_action = TradeState.sell

        trade_price = self.get_price(new_action, df.tail(), self.pair)
        print("Trade price: {}".format(trade_price))

        # Get stop-loss
        if new_action == TradeState.buy and self.stop_loss.calculate(close):
            print('stop-loss detected,..selling')
            new_action = TradeState.sell

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #2
0
파일: macd.py 프로젝트: w1r2p1/mosquito
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        close = df['close'].values

        last_row = df.tail(1).copy()

        # ************** Calc SMA-50
        sma = df['close'].rolling(window=50).mean().values[-1]
        print('sma-50:', sma)

        # ************** Calc EMA-30
        ema_period = 30
        ema = df['close'].ewm(span=ema_period, adjust=False).mean().values[-1]
        print('ema-30:', ema)

        ema_above_sma = ema > sma
        print('ema_above_sma: ', ema_above_sma)

        if ema_above_sma:
            # self.buy_triggers += 1
            # if self.buy_triggers >= 5:
            new_action = TradeState.buy
        else:
            new_action = TradeState.sell
            self.buy_triggers = 0

        trade_price = self.get_price(new_action, df.tail(), self.pair)
        """
        # Get stop-loss
        if new_action == TradeState.buy and self.stop_loss.calculate(close):
            print('stop-loss detected,..selling')
            new_action = TradeState.sell
        """

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)

        return self.actions
예제 #3
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back, self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt, ',..waiting for more data..')
            return self.actions

        self.actions.clear()

        df = look_back.tail(self.min_history_ticks)
        df_blueprint = Model.calculate_features(df)

        # Remove not-used columns
        df_blueprint = df_blueprint[self.feature_names]

        # Re-ordering column names
        column_names = self.feature_names
        x = df_blueprint[column_names]
        price_now = x.close.iloc[0]
        price_predicted = self.predict(x)

        if price_predicted is None:
            return self.actions
        else:
            price_predicted = price_predicted[0]

        if price_predicted > 0.08 or price_predicted < 0.05:
            return self.actions

        price_change = ((price_predicted * 100) / price_now) - 100

        if price_change > 10:
            return self.actions

        self.trade_history = self.trade_history.append({'close': price_now,
                                                        'predicted': price_predicted}, ignore_index=True)
        self.trade_history.to_csv('out/luckyantelope_out.csv', index=False)

        print('price_change:' + str(price_change) + ', close_price: ' + str(x.close.iloc[0]) + ', predicted: ' + str(price_predicted))

        new_action = TradeState.buy if price_predicted > price_now else TradeState.sell
        trade_price = self.get_price(new_action, df.tail(), self.pair)

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #4
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        close = df['close'].values

        # ************** Calc EMA20
        ema20_period = 25
        ema20 = talib.EMA(close[-ema20_period:], timeperiod=ema20_period)[-1]
        close_price = self.get_price(TradeState.none, df.tail(), self.pair)

        print('close_price:', close_price, 'ema:', ema20)
        if close_price <= ema20:
            new_action = TradeState.sell
        else:
            new_action = TradeState.buy

        # ************** Calc EMA Death Cross
        ema_interval_short = 6
        ema_interval_long = 25
        ema_short = talib.EMA(close[-ema_interval_short:],
                              timeperiod=ema_interval_short)[-1]
        ema_long = talib.EMA(close[-ema_interval_long:],
                             timeperiod=ema_interval_long)[-1]
        if ema_short <= ema_long:  # If we are below death cross, sell
            new_action = TradeState.sell

        trade_price = self.get_price(new_action, df.tail(), self.pair)

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #5
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        # Calculate indicators

        df = look_back.tail(self.min_history_ticks)
        close = df['close'].values
        volume = df['volume'].values
        new_action = TradeState.none
        close_price = self.get_price(TradeState.none, look_back, self.pair)

        # ************** OBV (On Balance Volume)
        obv = talib.OBV(close, volume)[-1]
        print('obv:', obv)
        if obv >= 100.0:
            new_action = TradeState.buy
        elif obv < 100.0:
            new_action = TradeState.sell

        # ************** Calc EMA
        ema_period = 6
        ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1]
        if close_price <= ema:
            new_action = TradeState.sell

        if new_action == TradeState.none:
            return self.actions

        trade_price = self.get_price(new_action, df.tail(), self.pair)

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #6
0
파일: ema.py 프로젝트: miro-ka/mosquito
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        close = df['close']

        # ************** Calc EMA
        ema5 = ta.ema(close, length=5).values[-1]
        ema10 = ta.ema(close, length=10).values[-1]
        ema20 = ta.ema(close, length=20).values[-1]

        close_price = self.get_price(TradeState.none, df.tail(), self.pair)

        print('close_price:', close_price, 'ema:', ema20)
        if close_price < ema10 or close_price < ema20:
            new_action = TradeState.sell
        elif close_price > ema5 and close_price > ema10:
            new_action = TradeState.buy

        trade_price = self.get_price(new_action, df.tail(), self.pair)

        # Get stop-loss
        if new_action == TradeState.buy and self.stop_loss.calculate(
                close.values):
            print('stop-loss detected,..selling')
            new_action = TradeState.sell

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #7
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()

        df = look_back.tail(self.min_history_ticks)
        df_blueprint = Model.calculate_features(df)

        # Remove not-used columns
        df_blueprint = df_blueprint.drop(
            ['pair', 'date', 'id', '_id', 'exchange', 'curr_1', 'curr_2'],
            axis=1)

        # Re-ordering column names
        column_names = self.feature_names
        x = df_blueprint[column_names]
        predicted = self.predict(x)[0]

        new_action = TradeState.sell if predicted == 1 else TradeState.buy
        trade_price = self.get_price(new_action, df.tail(), self.pair)

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #8
0
    def calculate(self, look_back, wallet):
        """
        Main Strategy function, which takes recent history data and returns recommended list of actions
        """

        (dataset_cnt,
         pairs_count) = common.get_dataset_count(look_back,
                                                 self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        look_back = look_back.tail(pairs_count * self.min_history_ticks)
        pairs_names = look_back.pair.unique()
        self.sync_active_pairs(wallet.current_balance)

        (current_weights,
         wallet_value) = self.compute_weights_and_value(look_back, wallet)
        current_amounts = list(wallet.current_balance.values())

        currencies = list(wallet.current_balance.keys())
        look_back.reset_index()
        #        converted_look_back = look_back.pivot(index=['date', 'pair'], columns='pair', values='close')
        converted_look_back = look_back.pivot_table(index='date',
                                                    columns='pair',
                                                    values='close')

        converted_look_back['BTC_BTC'] = 1
        converted_look_back = converted_look_back.filter(
            items=self.compute_relevant_pairs(wallet, 'BTC'))
        converted_look_back = converted_look_back.tail(self.min_history_ticks)

        if self.first_values.empty:
            self.first_values = converted_look_back.iloc[0]
            self.algo.init_step(converted_look_back)

        next_weights = self.my_next_weights(converted_look_back,
                                            current_weights)
        #        next_weights = (current_weights + next_weights) / 2
        #        next_weights = self.algo.next_weights(converted_look_back, current_weights)

        # We sell first, then we buy
        # if new_weight < current_weight, we need to sell the related currency
        for i in range(0, len(currencies)):
            if (next_weights[i] < current_weights[i] and currencies[i] != 'BTC'
                    and current_amounts[i] > 0):  # no need to sell BTC
                close_pair_price = self.get_price(TradeState.sell, look_back,
                                                  'BTC_' + currencies[i])
                action = TradeAction('BTC_' + currencies[i],
                                     TradeState.sell,
                                     amount=current_amounts[i] *
                                     (current_weights[i] - next_weights[i]) /
                                     current_weights[i],
                                     rate=close_pair_price,
                                     buy_sell_mode=self.buy_sell_mode)
                self.actions.append(action)

        # if new_weight > current_weight, we need to buy the related currency
        for i in range(0, len(currencies)):
            if (next_weights[i] > current_weights[i] and currencies[i] != 'BTC'
                    and next_weights[i] != 0):
                close_pair_price = self.get_price(TradeState.sell, look_back,
                                                  'BTC_' + currencies[i])
                action = TradeAction(
                    'BTC_' + currencies[i],
                    TradeState.buy,
                    # let's only buy 99% of what the algo recommands to avoid going negative with the fees
                    amount=0.99 * (wallet_value / close_pair_price) *
                    (next_weights[i] - current_weights[i]),
                    rate=close_pair_price,
                    buy_sell_mode=self.buy_sell_mode)
                self.actions.append(action)

        return self.actions
예제 #9
0
파일: tcg.py 프로젝트: Kooshini/mosquito
    def calculate(self, look_back, wallet, tickr):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        close = df['close'].values

        df1 = df['id'].tail(n=1)

        val = df1.iloc[0]
        val = val.split('-')
        loop_time = int(val[2])

        market_pair = 'BTCUSD'
        sentiment = 'Bear'
        timeframe = '4h'
        indicator_type = 'Bear TCG Cross'
        loop_datetime = datetime.fromtimestamp(
            loop_time, tz=pytz.utc).strftime('%Y-%m-%d %H:%M:%S')

        alerts = self.data.load_backtest_epochs(market_pair, sentiment,
                                                timeframe, indicator_type,
                                                loop_datetime)

        for alert_time in alerts['epochs']:
            if alert_time in range(loop_time - 1800, loop_time):
                print(
                    "+!+!+!+!+!++!+!+!+!++!+!++!+! ALERT HIT +!+!+!+!++!+!+! {} {} {} "
                    .format(alert_time, loop_time - 1800, loop_time))
                print(datetime.fromtimestamp(alert_time).strftime('%c'))
                print(datetime.fromtimestamp(loop_time - 1800).strftime('%c'))
                print(datetime.fromtimestamp(loop_time).strftime('%c'))

                new_action = TradeState.sell

        trade_price = self.get_price(new_action, df.tail(), self.pair)
        # print("trade price {}".format(trade_price)

        # Get stop-loss
        if new_action == TradeState.sell and self.stop_loss.calculate(close):
            print(
                '-------- stop-loss detected,..buying!!!!!!!!!!!!!!!!!!!!!!!! '
            )
            new_action = TradeState.buy

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #10
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        self.chartData_ = df

        for i in df[['close']]:
            for j in df[i]:
                last_price = round(j, 10)
                Points.append(last_price)

        for i in df[['high']]:
            for j in df[i]:
                Highs.append(round(j, 8))

        for i in df[['low']]:
            for j in df[i]:
                Lows.append(round(j, 8))

        for i in df[['volume']]:
            for j in df[i]:
                Volumes.append(round(j, 8))

        for i in df[['date']]:
            for j in df[i]:
                last_time = dt.datetime.fromtimestamp(j)
                dates.append(last_time)

        self.appreciationRate_ = self.getAppreciationRate(self.chartData_.open)
        self.quantizer_ = self.quantizer(self.appreciationRate_)

        print("Format appreciation {}".format(self.appreciationRate_))
        print("Format quantizer {}".format(self.quantizer_))

        #self.prediction(self.appreciationRate_, self.quantizer_, 0, 30, 30)
        #bactTest_ = self.backTest(self.appreciationRate_, self.quantizer_, 30, 15, False)
        #print(bactTest_)

        fed_data = feature_engineering(df)
        # feature vector
        X = fed_data.take(list(range(fed_data.shape[1] - 1)), axis=1)
        # target
        y = np.ravel(fed_data.take([fed_data.shape[1] - 1], axis=1))
        X_train, X_test, y_train, y_test = train_test_split(X,
                                                            y,
                                                            test_size=0.3,
                                                            random_state=0)
        print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
        # 定义一个BP神经网络
        reg = MLPRegressor(solver='lbfgs',
                           alpha=1e-5,
                           hidden_layer_sizes=(15, ),
                           random_state=1)
        # 训练
        print("start training...")
        reg.fit(X_train, y_train)
        print("training finished.")
        # 预测
        print("start predicting...")
        y_pred = reg.predict(X_test)
        print("predicting finished.")

        y_pred = pd.DataFrame(y_pred)
        y_pred.index = X_test.index

        y_test = pd.DataFrame(y_test)
        y_test.index = X_test.index
        # 将结果写入文件
        # pd.DataFrame(y_pred).to_excel('y_pred.xlsx')
        # 模型评估
        model_evaluation(y_test, y_pred)
        # 可视化
        model_visualization(y_test, y_pred)

        print(type(X), type(y), type(X_train), type(X_test), type(y_train),
              type(y_test), type(y_pred))

        days = len(df[['close']])

        print("Last time: " + str(last_time) + " " + str(last_price))

        if days > acc:
            decision = algot(Points[:days])

        new_last_time = last_time + dt.timedelta(minutes=self.interval)

        print(
            '-----------------------------------------------------------------------------------------'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )

        #if self.Bought == True:
        if decision == 0:
            self.Bought = False
            print(
                colored(
                    "*           Buy now or wait, price will went UP at {}          *"
                    .format(new_last_time), 'green'))

            #new_action = TradeState.sell
        #else:
        elif decision == 1:
            self.Bought = True
            #new_action = TradeState.buy
            print(
                colored(
                    "*           Sell now or wait, price will went DOWN at {}          *"
                    .format(new_last_time), 'red'))

        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '-----------------------------------------------------------------------------------------'
        )

        trade_price = self.get_price(new_action, df.tail(), self.pair)

        # Get stop-loss
        #if new_action == TradeState.buy and self.stop_loss.calculate(close):
        #    print('stop-loss detected,..selling')
        #    new_action = TradeState.sell

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #11
0
파일: drl.py 프로젝트: xawotihs/mosquito
    def calculate(self, look_back, wallet):
        """
        Main Strategy function, which takes recent history data and returns recommended list of actions
        """

        (current_weights,
         wallet_value) = self.compute_weights_and_value(look_back, wallet)
        print("Current weights:", current_weights)

        (dataset_cnt,
         pairs_count) = common.get_dataset_count(look_back,
                                                 self.group_by_field)
        look_back = look_back.tail(pairs_count * self.min_history_ticks)
        pairs_names = look_back.pair.unique()
        look_back.reset_index()

        if not self.DRL:
            self.DRL = PolicyGradient(
                n_actions=pairs_count,
                n_features=3,  #6*self.min_history_ticks
                output_graph=True,
            )

        if self.last_computed_weights != []:
            self.step += 1
            future_prices = self.compute_future_prices(look_back)
            weights = np.array(self.last_20_measured_weights).transpose(
                (1, 2, 0))
            self.DRL.store_transition(
                self.last_prices,
                weights,
                #np.array(self.last_20_measured_weights).reshape((pairs_count,1,20)),
                future_prices,
                np.array(current_weights).reshape((pairs_count + 1, 1, 1)))

        if (len(self.last_20_measured_weights) >= 20):
            self.last_20_measured_weights.pop()

        self.last_20_measured_weights.insert(
            0, current_weights[1:].reshape((pairs_count, 1)))

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()

        current_amounts = list(wallet.current_balance.values())

        self.DRL.learn()

        currencies = list(wallet.current_balance.keys())
        #        converted_look_back = look_back.pivot(index=['date', 'pair'], columns='pair', values='close')
        #        converted_look_back = look_back.pivot_table(index='date', columns='pair', values='close')
        close = look_back.pivot_table(index='pair',
                                      columns='date',
                                      values='close')
        last_column = close.iloc[:, -1]
        close = close.div(last_column, axis='index')

        high = look_back.pivot_table(index='pair',
                                     columns='date',
                                     values='high')
        high = high.div(last_column, axis='index')

        low = look_back.pivot_table(index='pair', columns='date', values='low')
        low = low.div(last_column, axis='index')

        features = np.array(
            [close.as_matrix(),
             high.as_matrix(),
             low.as_matrix()])
        features = features[np.newaxis, :]
        #        assert(features.shape == (1,3,pairs_count,50))

        #        converted_look_back = converted_look_back.filter(items = self.compute_relevant_pairs(wallet, 'BTC'))
        #        converted_look_back = converted_look_back.tail(self.min_history_ticks)

        #        next_weights = self.DRL.choose_weights(converted_look_back)
        next_weights = self.DRL.choose_weights(features,
                                               self.last_20_measured_weights)
        print("New weights:", next_weights)
        #        assert( (next_weights[0] != next_weights[1]) and (next_weights[1] != next_weights[2]) )

        self.last_computed_weights = next_weights[np.newaxis, :]
        self.last_prices = features

        # let's estimate mu
        mu, _ = self.DRL.compute_mu(next_weights, current_weights,
                                    self.commission)

        # We sell first, then we buy
        # if new_weight < current_weight, we need to sell the related currency
        for i in range(0, len(currencies)):
            if (next_weights[i] < current_weights[i] and currencies[i] != 'BTC'
                    and current_amounts[i] > 0):  # no need to sell BTC
                close_pair_price = self.get_price(TradeState.sell, look_back,
                                                  'BTC_' + currencies[i])
                action = TradeAction('BTC_' + currencies[i],
                                     TradeState.sell,
                                     amount=current_amounts[i] *
                                     (current_weights[i] - next_weights[i]) /
                                     (current_weights[i] * mu),
                                     rate=close_pair_price,
                                     buy_sell_mode=self.buy_sell_mode)
                self.actions.append(action)

        # if new_weight > current_weight, we need to buy the related currency
        for i in range(0, len(currencies)):
            if (next_weights[i] > current_weights[i] and currencies[i] != 'BTC'
                    and next_weights[i] != 0):
                close_pair_price = self.get_price(TradeState.sell, look_back,
                                                  'BTC_' + currencies[i])
                action = TradeAction(
                    'BTC_' + currencies[i],
                    TradeState.buy,
                    # let's only buy 99% of what the algo recommands to avoid going negative with the fees
                    amount=mu * (wallet_value / close_pair_price) *
                    (next_weights[i] - current_weights[i]),
                    rate=close_pair_price,
                    buy_sell_mode=self.buy_sell_mode)
                self.actions.append(action)

        return self.actions
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)

        for i in df[['close']]:
            for j in df[i]:
                last_price = round(j, 10)
                Points.append(last_price)

        for i in df[['high']]:
            for j in df[i]:
                Highs.append(round(j, 8))

        for i in df[['low']]:
            for j in df[i]:
                Lows.append(round(j, 8))

        for i in df[['volume']]:
            for j in df[i]:
                Volumes.append(round(j, 8))

        for i in df[['date']]:
            for j in df[i]:
                last_time = dt.datetime.fromtimestamp(j)
                dates.append(last_time)

        days = len(df[['close']])

        print("Last time: " + str(last_time) + " " + str(last_price))

        if days > acc:
            decision = algot(Points[:days])

        new_last_time = last_time + dt.timedelta(minutes=self.interval)

        print(
            '-----------------------------------------------------------------------------------------'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )

        #if self.Bought == True:
        if decision == 0:
            self.Bought = False
            print(
                colored(
                    "*           Buy now or wait, price will went UP at {}          *"
                    .format(new_last_time), 'green'))

            #new_action = TradeState.sell
        #else:
        elif decision == 1:
            self.Bought = True
            #new_action = TradeState.buy
            print(
                colored(
                    "*           Sell now or wait, price will went DOWN at {}          *"
                    .format(new_last_time), 'red'))

        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '|                                                                                       |'
        )
        print(
            '-----------------------------------------------------------------------------------------'
        )

        trade_price = self.get_price(new_action, df.tail(), self.pair)

        # Get stop-loss
        #if new_action == TradeState.buy and self.stop_loss.calculate(close):
        #    print('stop-loss detected,..selling')
        #    new_action = TradeState.sell

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
예제 #13
0
    def calculate(self, look_back, wallet):
        """
        Main Strategy function, which takes recent history data and returns recommended list of actions
        """
        if not self.pair_delimiter:
            self.pair_delimiter = self.get_delimiter(look_back)

        (dataset_cnt,
         pairs_count) = common.get_dataset_count(look_back,
                                                 self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        look_back = look_back.tail(pairs_count * self.min_history_ticks)
        pairs_names = look_back.pair.unique()
        self.sync_active_pairs(wallet.current_balance)

        positive_pairs = []
        got_all_buffers = True
        for pair in pairs_names:
            df = look_back.loc[look_back['pair'] == pair].sort_values('date')
            # Check if the dataset has required buffer size
            df_size = len(df.index)
            if df_size < self.min_history_ticks:
                continue

            close = df['close'].values
            # volume = df['volume'].values
            close_price = self.get_price(TradeState.none, look_back, pair)

            # ************** Calc EMA20
            ema20_period = 20
            ema20 = talib.EMA(close[-ema20_period:],
                              timeperiod=ema20_period)[-1]
            if close_price <= ema20:
                continue

            # ************** Calc RSI
            rsi = talib.RSI(close[-15:], timeperiod=14)[-1]
            if rsi > 20:
                continue

            # ************** Calc EMA
            ema_interval_short = 6
            ema_interval_long = 25
            ema_short = talib.EMA(close[-ema_interval_short:],
                                  timeperiod=ema_interval_short)[-1]
            ema_long = talib.EMA(close[-ema_interval_long:],
                                 timeperiod=ema_interval_long)[-1]
            if ema_short <= ema_long:  # If we are below death cross, skip pair
                continue

            positive_pairs.append((pair, 0.0))

        # If we didn't get all buffers just return empty actions
        if not got_all_buffers:
            return self.actions

        # Handle all the pairs that have not been selected (are not up-trending)

        positive_pair_names = [
            re.split('[-_]', i[0])[-1] for i in positive_pairs
        ]
        pair_prefix = re.split('[-_]', pairs_names[0])[0]
        for wallet_item in wallet.current_balance:
            if wallet_item == pair_prefix:
                continue
            if wallet_item not in positive_pair_names:
                pair_name = pair_prefix + self.pair_delimiter + wallet_item
                close_pair_price = self.get_price(TradeState.sell, look_back,
                                                  pair_name)
                action = TradeAction(pair_name,
                                     TradeState.sell,
                                     amount=None,
                                     rate=close_pair_price,
                                     buy_sell_mode=self.buy_sell_mode)
                self.actions.append(action)
                if pair_name in self.active_pairs:
                    self.active_pairs.remove(pair_name)

        # Handle positive pairs
        # Sort indicators
        sorted_positives = sorted(positive_pairs,
                                  key=lambda x: x[1],
                                  reverse=True)

        print('sorted_indicators:', len(sorted_positives), 'items:',
              sorted_positives)

        # Take only first 3 pairs
        # if len(sorted_positives) > 3:
        #    sorted_positives = sorted_positives[:3]

        for (positive_pair, _) in sorted_positives:
            # Check if we have already bought the currency. If yes, just skip it
            if positive_pair in self.active_pairs:
                continue

            # If pair is not bought yet, buy it
            close_pair_price = self.get_price(TradeState.buy, look_back,
                                              positive_pair)
            action = TradeAction(positive_pair,
                                 TradeState.buy,
                                 amount=None,
                                 rate=close_pair_price,
                                 buy_sell_mode=self.buy_sell_mode)
            self.active_pairs.append(positive_pair)
            self.actions.append(action)

        return self.actions