Example #1
0
def vfi(dataframe,
        length=130,
        coef=0.2,
        vcoef=2.5,
        signalLength=5,
        smoothVFI=False):
    """
    Volume Flow Indicator conversion

    Author: creslinux, June 2018 - Python
    Original Author: Chris Moody, TradingView - Pinescript
    To return vfi, vfima and histogram

    A simplified interpretation of the VFI is:
    * Values above zero indicate a bullish state and the crossing of the zero line is the trigger or buy signal.
    * The strongest signal with all money flow indicators is of course divergence.
    * A crossover of vfi > vfima is uptrend
    * A crossunder of vfima > vfi is downtrend
    * smoothVFI can be set to smooth for a cleaner plot to ease false signals
    * histogram can be used against self -1 to check if upward or downward momentum


    Call from strategy to populate vfi, vfima, vfi_hist into dataframe

    Example how to call:
    # Volume Flow Index: Add VFI, VFIMA, Histogram to DF
    dataframe['vfi'], dataframe['vfima'], dataframe['vfi_hist'] =  \
        vfi(dataframe, length=130, coef=0.2, vcoef=2.5, signalLength=5, smoothVFI=False)

    :param dataframe:
    :param length: - VFI Length - 130 default
    :param coef:  - price coef  - 0.2 default
    :param vcoef: - volume coef  - 2.5 default
    :param signalLength: - 5 default
    :param smoothVFI:  bool - False detault
    :return: vfi, vfima, vfi_hist
    """
    """"
    Original Pinescript
    From: https://www.tradingview.com/script/MhlDpfdS-Volume-Flow-Indicator-LazyBear/

    length = input(130, title="VFI length")
    coef = input(0.2)
    vcoef = input(2.5, title="Max. vol. cutoff")
    signalLength=input(5)
    smoothVFI=input(false, type=bool)

    #### Conversion summary to python
      - ma(x,y) => smoothVFI ? sma(x,y) : x // Added as smoothVFI test on vfi

      - typical = hlc3  // Added to DF as HLC
      - inter = log(typical) - log(typical[1]) // Added to DF as inter
      - vinter = stdev(inter, 30) // Added to DF as vinter
      - cutoff = coef * vinter * close // Added to DF as cutoff
      - vave = sma(volume, length)[1] // Added to DF as vave
      - vmax = vave * vcoef // Added to Df as vmax
      - vc = iff(volume < vmax, volume, vmax) // Added np.where test, result in DF as vc
      - mf = typical - typical[1] // Added into DF as mf - typical is hlc3
      - vcp = iff(mf > cutoff, vc, iff(mf < -cutoff, -vc, 0)) // added in def vcp, in DF as vcp

      - vfi = ma(sum(vcp, length) / vave, 3) // Added as DF vfi. Will sma vfi 3 if smoothVFI flag set
      - vfima = ema(vfi, signalLength) // added to DF as vfima
      - d = vfi-vfima // Added to df as histogram

    ### Pinscript plotout - nothing to do here for freqtrade.
    plot(0, color=gray, style=3)
    showHisto=input(false, type=bool)
    plot(showHisto ? d : na, style=histogram, color=gray, linewidth=3, transp=50)
    plot( vfima , title="EMA of vfi", color=orange)
    plot( vfi, title="vfi", color=green,linewidth=2)
    """
    import talib as ta
    from math import log
    from pyti.simple_moving_average import simple_moving_average as sma
    from numpy import where

    length = length
    coef = coef
    vcoef = vcoef
    signalLength = signalLength
    smoothVFI = smoothVFI
    df = dataframe
    # Add hlc3 and populate inter to the dataframe
    df['hlc'] = ((df['high'] + df['low'] + df['close']) / 3).astype(float)
    df['inter'] = df['hlc'].map(log) - df['hlc'].shift(+1).map(log)
    df['vinter'] = df['inter'].rolling(30).std(ddof=0)
    df['cutoff'] = (coef * df['vinter'] * df['close'])
    # Vave is to be calculated on volume of the past bar
    df['vave'] = sma(df['volume'].shift(+1), length)
    df['vmax'] = df['vave'] * vcoef
    df['vc'] = where((df['volume'] < df['vmax']), df['volume'], df['vmax'])
    df['mf'] = df['hlc'] - df['hlc'].shift(+1)

    # more logic for vcp, so create a def and df.apply it
    def vcp(x):
        if x['mf'] > x['cutoff']:
            return x['vc']
        elif x['mf'] < -(x['cutoff']):
            return -(x['vc'])
        else:
            return 0

    df['vcp'] = df.apply(vcp, axis=1)
    # vfi has a smooth option passed over def call, sma if set
    df['vfi'] = (df['vcp'].rolling(length).sum()) / df['vave']
    if smoothVFI == True:
        df['vfi'] = sma(df['vfi'], 3)
    df['vfima'] = ta.EMA(df['vfi'], signalLength)
    df['vfi_hist'] = df['vfi'] - df['vfima']

    # clean up columns used vfi calculation but not needed for strat
    df.drop('hlc', axis=1, inplace=True)
    df.drop('inter', axis=1, inplace=True)
    df.drop('vinter', axis=1, inplace=True)
    df.drop('cutoff', axis=1, inplace=True)
    df.drop('vave', axis=1, inplace=True)
    df.drop('vmax', axis=1, inplace=True)
    df.drop('vc', axis=1, inplace=True)
    df.drop('mf', axis=1, inplace=True)
    df.drop('vcp', axis=1, inplace=True)

    return df['vfi'], df['vfima'], df['vfi_hist']
Example #2
0
    def loop(self):
        timeout = 3 / float(len(self.products))
        counter = 0

        by_volume = []  # array of dicts

        # TODO: for coins that are in the balance, sell once order book is tending towards selling side
        # maybe also last 10 trades could be checked and if most are sell, then sell as well.

        # TODO: move checker for coins in balance into a separate, faster loop.

        while self._running:
            self._balances = self.get_balance()  # refresh balance

            product = self.products[counter]
            ticker_symbol = product['symbol']

            if ticker_symbol.endswith('BTC'):
                idx = ticker_symbol.index('BTC')
            elif ticker_symbol.endswith('USDT'):
                idx = ticker_symbol.index('USDT')

            coin1 = ticker_symbol[:idx]
            coin2 = ticker_symbol[idx:]

            if self.is_coin_blacklisted(coin1):
                logging.info("{}: blacklisted, skipping.".format(coin1))
            else:

                #logging.info("Check {}...".format(ticker_symbol))

                try:
                    # get klines since close
                    new_klines = self.client.get_klines(
                        symbol=ticker_symbol,
                        interval='5m',
                        startTime=self._klines[ticker_symbol][-1][0])
                    new_klines2 = self.client.get_klines(
                        symbol=ticker_symbol,
                        interval='1h',
                        startTime=self._klines2[ticker_symbol][-1][0])

                    for kline_group in [{
                            'new': new_klines,
                            'old': self._klines
                    }, {
                            'new': new_klines2,
                            'old': self._klines2
                    }]:
                        for kline in kline_group['new']:
                            if kline[0] != kline_group['old'][ticker_symbol][
                                    -1][0]:
                                kline_group['old'][ticker_symbol].append(kline)
                            else:
                                kline_group['old'][ticker_symbol][-1] = kline

                        if len(kline_group['old']
                               [ticker_symbol]) > self._start_size:
                            kline_group['old'][ticker_symbol].pop(0)

                    # short term
                    volumes = list(
                        map(lambda item: float(item[5]),
                            self._klines[ticker_symbol][-30:]))
                    volumes_sorted = sorted(volumes)

                    median_volume = 0
                    mean_volume = reduce(lambda x, y: x + y,
                                         volumes_sorted) / len(volumes_sorted)

                    if len(volumes_sorted) % 2 != 0:
                        mid = len(volumes_sorted) / 2
                        f = floor(mid)
                        c = ceil(mid)

                        assert f < c, "floor should be less than ceiling ({} vs {})".format(
                            f, c)

                        median_volume = (volumes_sorted[f] +
                                         volumes_sorted[c]) / 2
                    else:
                        median_volume = volumes_sorted[len(volumes_sorted) //
                                                       2]

                    # divide median by mean
                    med_mean = median_volume / mean_volume
                    last_volume = volumes[-1]
                    last_volume_mean = last_volume / mean_volume

                    ticker_data = self.client.get_ticker(symbol=ticker_symbol)
                    volume_btc = float(ticker_data['volume']) * float(
                        ticker_data['lastPrice'])

                    if float(self._klines[ticker_symbol][-2][1]) <= float(
                            self._klines[ticker_symbol][-2][4]):
                        if (coin1 not in self._balances
                                or self._balances[coin1]
                                == 0) and (coin2 in self._balances
                                           and self._balances[coin2] > 0):
                            price_closes = list(
                                map(lambda item: float(item[4]),
                                    self._klines[ticker_symbol]))
                            sma7 = sma(price_closes, 7)
                            sma20 = sma(price_closes, 20)

                            logging.info("{}: SMA7: {}, SMA20: {}".format(
                                ticker_symbol, sma7[-1], sma20[-1]))

                            depth = self.client.get_order_book(
                                symbol=ticker_symbol, limit=10)
                            bid_sum = reduce(
                                lambda x, y: x + y,
                                list(
                                    map(lambda item: float(item[1]),
                                        depth['bids'])))
                            ask_sum = reduce(
                                lambda x, y: x + y,
                                list(
                                    map(lambda item: float(item[1]),
                                        depth['asks'])))
                            logging.info("{} bid sum: {}, ask sum: {}".format(
                                ticker_symbol, bid_sum, ask_sum))

                            if (volume_btc > 200) and (
                                    last_volume_mean / med_mean >
                                    2) and (price_closes[-1] > sma7[-1]) and (
                                        sma7[-1] > sma20[-1]):
                                price_closes_lt = list(
                                    map(lambda kline: float(kline[4]),
                                        self._klines2[ticker_symbol]))
                                stoch_rsi_results = stochrsi(
                                    price_closes_lt, 14)

                                logging.info("{} SRSI : {}".format(
                                    ticker_symbol, stoch_rsi_results[-1]))

                                if stoch_rsi_results[-1] >= 60:
                                    logging.info(
                                        "skip {}, already pumped".format(
                                            ticker_symbol))
                                elif bid_sum < ask_sum:
                                    logging.info(
                                        "Not buying {} because bid sum ({}) < ask sum ({})"
                                        .format(ticker_symbol, bid_sum,
                                                ask_sum))
                                else:
                                    self.buy(symbol=ticker_symbol,
                                             coin1=coin1,
                                             coin2=coin2)
                                    self.blacklist_coin(
                                        best_coin['coin1'], THIRTY_MINUTES)

                                # by_volume.append({
                                #   'symbol': ticker_symbol,
                                #   'coin1': coin1,
                                #   'coin2': coin2,
                                #   'value': last_volume_mean / med_mean,
                                #   'sma7': sma7
                                # })

                    # if last_volume_mean / med_mean > 2:
                    #   logging.info("\n\n!! {} Abnormal volume = {} / {}\n\n".format(ticker_symbol, last_volume_mean, med_mean))

                    #   if float(self._klines[ticker_symbol][-2][1]) > float(self._klines[ticker_symbol][-2][4]):
                    #     logging.info("{} is likely falling (red candle), not buying.".format(ticker_symbol))
                    #   else:
                    #     self.buy(ticker_symbol, coin1, coin2)

                    coin_amount_held = 0
                    coin_is_dust = True
                    trailing_stop_triggered = False

                    if coin1 in self._balances:
                        coin_amount_held = self._balances[coin1]
                        coin_price = float(self._klines[ticker_symbol][-1][4])

                        if coin2 == 'BTC':
                            if coin_price * coin_amount_held >= 0.0005:  # lt ~$5 worth of bitcoin
                                coin_is_dust = False
                        elif coin2 == 'USDT':
                            if coin_price * coin_amount_held >= 5:  # lt ~$5
                                coin_is_dust = False
                        else:
                            raise Exception(
                                "Unsure how to handle coin2 type: {}".format(
                                    coin2))

                    if coin_is_dust:
                        self._balances[coin1] = 0  # just set to zero
                    else:
                        if ticker_symbol in self._trailing_stops:
                            if coin_price <= self._trailing_stops[
                                    ticker_symbol]:
                                logging.info(
                                    "{}: Trailing stop triggered @ {}".format(
                                        ticker_symbol, coin_price))
                                self.sell(ticker_symbol, coin1, coin2)
                                self.blacklist_coin(coin1, TWO_HOURS)
                                trailing_stop_triggered = True
                            else:
                                self.update_trailing_stop_for(ticker_symbol)

                except Exception as ex:
                    logging.error("Error: {}".format(ex))

            counter += 1
            counter %= len(self.products)

            if False and counter == 0:
                by_volume_sorted = sorted(by_volume,
                                          key=lambda item: item['value'])

                best_coin = None

                for i in range(len(by_volume_sorted) - 1, -1, -1):
                    item = by_volume_sorted[i]

                    last_sma7 = item['sma7'][-1]
                    # find a recent candle with most volume, determine red or green
                    last_klines = self._klines[item['symbol']][-4:]
                    last_kline = self._klines[item['symbol']][-1]

                    top_kline = None
                    for kline in last_klines:
                        if top_kline is None or (float(kline[5]) > float(
                                top_kline[5])):
                            top_kline = kline

                    assert top_kline is not None
                    logging.info("{} top_kline = {}".format(
                        item['symbol'], top_kline))

                    # determine red or green
                    if float(top_kline[1]) > float(top_kline[4]) or float(
                            last_kline[1]) > float(last_kline[4]):
                        logging.info(
                            "skip {} because dump determined ({} > {})".format(
                                item['symbol'], top_kline[1], top_kline[4]))
                    else:

                        price_closes = list(
                            map(lambda kline: float(kline[4]),
                                self._klines[item['symbol']]))
                        stoch_rsi_results = stochrsi(price_closes, 14)

                        logging.info("{} SRSI : {}".format(
                            item['symbol'], stoch_rsi_results[-1]))

                        if stoch_rsi_results[-1] >= 60:
                            logging.info("skip {}, already pumped".format(
                                item['symbol']))
                        else:
                            if float(last_klines[-2][4]) > last_sma7:
                                best_coin = item
                                break
                            else:
                                logging.info("{} is below sma ({}, {})".format(
                                    item['symbol'], last_sma7,
                                    last_klines[-2][4]))

                assert best_coin is not None

                logging.info("by_volume_sorted = {}".format(by_volume_sorted))
                #logging.info("\nbest_coin = {}\n".format(best_coin))
                self.buy(symbol=best_coin['symbol'],
                         coin1=best_coin['coin1'],
                         coin2=best_coin['coin2'])
                self.blacklist_coin(best_coin['coin1'], THIRTY_MINUTES)

                by_volume = []

            time.sleep(timeout)
Example #3
0
    while cn < 100:
        close = get_historic_klines(symbol, "2 days ago UTC", "now UTC",
                                    Client.KLINE_INTERVAL_5MINUTE)
        ochl = get_historic_klines_ochl(symbol, "2 days ago UTC", "now UTC",
                                        Client.KLINE_INTERVAL_5MINUTE)
        source = close
        data.append(source[-1])
        fastLength = 12
        slowLength = 26  # take from binance
        signalLength = 9

        fastMA = ema(source, fastLength)
        slowMA = ema(source, slowLength)

        macd = fastMA - slowMA
        signal = sma(macd, signalLength)
        hist = macd - signal

        stochastic_data = get_historic_klines_stochastic(
            symbol, "20 days ago UTC", "now UTC", Client.KLINE_INTERVAL_1DAY)
        stochastic_li = stochastic_data['%K'].tolist()
        decision(hist, stochastic_li, data, inventory)
        cn += 1

    #decision(macdo,signalo)
    """
    final = histo.join(macdo, lsuffix='_left', rsuffix='_right')
    final = final.join(signalo, lsuffix='_left', rsuffix='_right')

    fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(20, 20))
    def Update(self):

        self.logMessages = self.logMessages + "\n" + (
            str(dt.datetime.now()) + " " + self.timeframe +
            " Vela Formada - Analizando -  Running Update Function...")

        self.pricedata_stadistics['index'] = self.pricedata['bidclose'].index
        self.pricedata_stadistics['bidclose'] = self.pricedata[
            'bidclose'].values
        self.pricedata_stadistics['bidhigh'] = self.pricedata['bidhigh'].values
        self.pricedata_stadistics['askclose'] = self.pricedata[
            'askclose'].values
        self.pricedata_stadistics['askhigh'] = self.pricedata['askhigh'].values
        self.pricedata_stadistics['asklow'] = self.pricedata['asklow'].values
        self.pricedata_stadistics['askclose'] = self.pricedata[
            'askclose'].values
        self.pricedata_stadistics['bidlow'] = self.pricedata['bidlow'].values
        self.pricedata_stadistics['tickqty'] = self.pricedata['tickqty'].values

        # Calculate Indicators
        iFastSMA = sma(self.pricedata['bidclose'], self.fast_sma_periods)
        iSlowSMA = sma(self.pricedata['bidclose'], self.slow_sma_periods)
        self.pricedata_stadistics['emaFast'] = iFastSMA
        self.pricedata_stadistics['emaSlow'] = iSlowSMA

        # Adds a "n_high" column with max value of previous 14 periods
        self.pricedata_stadistics['n_high'] = self.pricedata_stadistics[
            'bidhigh'].rolling(self.stoK).max()
        # Adds an "n_low" column with min value of previous 14 periods
        self.pricedata_stadistics['n_low'] = self.pricedata_stadistics[
            'bidlow'].rolling(self.stoK).min()
        # Uses the min/max values to calculate the %k (as a percentage)

        self.pricedata_stadistics['per_k'] = \
            (
                    (self.pricedata_stadistics['bidclose'] - self.pricedata_stadistics['n_low']) / \
                    (self.pricedata_stadistics['n_high'] - self.pricedata_stadistics['n_low'])
            ) * 100

        # Uses the %k to calculates a SMA over the past 3 values of %k
        self.pricedata_stadistics['per_d'] = self.pricedata_stadistics[
            'per_k'].rolling(self.stoD).mean()

        # data_per_k = per_k(pricedata['bidclose'], stoK)
        # data_per_d = per_d(pricedata['bidclose'], stoD)

        data_per_k = self.pricedata_stadistics['per_k']
        data_per_d = self.pricedata_stadistics['per_d']
        # pricedata_stadistics['per_k'] = data_per_k
        # pricedata_stadistics['per_d'] = data_per_d
        # self.pricedata_stadistics.loc[index, 'lower_sto'] = 20
        # self.pricedata_stadistics.loc[index, 'upper_sto'] = 80

        self.logMessages = self.logMessages + "\n" + (
            "STO K " + str(data_per_k[len(data_per_k) - 1]))
        self.logMessages = self.logMessages + "\n" + (
            "STO D " + str(data_per_d[len(data_per_d) - 1]))

        # Calcular Indicador
        iRSI = rsi(self.pricedata_stadistics['bidclose'], 15)
        self.logMessages = self.logMessages + "\n" + ("RSI: " +
                                                      str(iRSI[len(iRSI) - 1]))

        for index, row in self.pricedata_stadistics.iterrows():
            self.pricedata_stadistics.loc[index, 'lower_sto'] = 20
            self.pricedata_stadistics.loc[index, 'upper_sto'] = 80
            self.pricedata_stadistics.loc[index, 'macdline0'] = 0.00
            self.pricedata_stadistics.loc[index, 'macdsub'] = self.macdsub
            self.pricedata_stadistics.loc[index, 'macdupper'] = self.macduper

        # ***********************************************************
        # *  Regresion al precio de cierre las velas ================
        # ***********************************************************
        self.pricedata_stadistics['x'] = np.arange(
            len(self.pricedata_stadistics))

        # ************* Calcular la poscion Relativa Y
        for index, row in self.pricedata_stadistics.iterrows():
            self.pricedata_stadistics.loc[index, 'y'] = int('{:.5f}'.format(
                (self.pricedata_stadistics.loc[index,
                                               'bidclose'])).replace('.', ''))
        max_value = max(np.array(self.pricedata_stadistics['y'].values))
        min_value = min(np.array(self.pricedata_stadistics['y'].values))
        for index, row in self.pricedata_stadistics.iterrows():
            value = self.pricedata_stadistics.loc[index, 'y'] - min_value
            NewPricePosition = ((value * 100) / max_value) * 100
            self.pricedata_stadistics.loc[index, 'y'] = NewPricePosition

        # ***********  Calcular la poscion Relativa X
        max_value = max(np.array(self.pricedata_stadistics['x'].values))
        min_value = min(np.array(self.pricedata_stadistics['x'].values))
        for index, row in self.pricedata_stadistics.iterrows():
            value = self.pricedata_stadistics.loc[index, 'x'] - min_value
            NewPricePosition = ((value * 100) / max_value)
            self.pricedata_stadistics.loc[index, 'x'] = NewPricePosition

        regresionLineal_xx = np.array(self.pricedata_stadistics['x'].values)
        regresionLineal_yy = np.array(self.pricedata_stadistics['y'].values)

        regresionLineal_bb = regresionlineal2.estimate_b0_b1(
            regresionLineal_xx, regresionLineal_yy)
        y_pred_sup = regresionLineal_bb[
            0] + regresionLineal_bb[1] * regresionLineal_xx
        self.pricedata_stadistics['y_pred'] = y_pred_sup

        if self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] < \
                self.pricedata_stadistics.iloc[1]['y_pred'] and \
                self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] < \
                self.pricedata_stadistics.iloc[1]['y_pred']:
            lv_Tendency = "Bajista"
        elif self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] > \
                self.pricedata_stadistics.iloc[1]['y_pred'] and \
                self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] > \
                self.pricedata_stadistics.iloc[1]['y_pred']:
            lv_Tendency = "Alcista"

        # MACD        ########################################################################
        exp1 = self.pricedata_stadistics['bidclose'].ewm(span=self.macdFast,
                                                         adjust=False).mean()
        exp2 = self.pricedata_stadistics['bidclose'].ewm(span=self.macdSlow,
                                                         adjust=False).mean()
        macd = exp1 - exp2
        self.pricedata_stadistics[
            'macd'] = self.pricedata_stadistics.index.map(macd)
        self.pricedata_stadistics['signal'] = pd.DataFrame(
            self.pricedata_stadistics['macd'].ewm(span=self.macdSmooth,
                                                  adjust=False).mean())
        self.pricedata_stadistics['hist'] = pd.DataFrame(
            self.pricedata_stadistics['macd'] -
            self.pricedata_stadistics['signal'])

        # Imprimir Precio/Indicador
        # self.logMessages = self.logMessages + "\n" + ("Precio Cierre: " + str(pricedata['bidclose'][len(pricedata) - 1]))

        # self.logMessages = self.logMessages + "\n" + ("Tendencia Regresion Lineal: " + lv_Tendency)
        lv_signal = self.pricedata_stadistics.iloc[
            len(self.pricedata_stadistics) - 1]['signal']
        self.logMessages = self.logMessages + "\n" + (
            "MACD Signal: " + str(lv_signal) + " SubValuacion:  " +
            str(self.macdsub) + " SobreValuacion:  " + str(self.macduper))

        self.logMessages = self.logMessages + "\n" + ("RSI " +
                                                      str(iRSI[len(iRSI) - 1]))

        # data_per_d['lower_sto']
        # if self.crossesOver(data_per_k, data_per_d) and lv_signal <= self.macdsub and \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['signal'] > \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['macd']:

        # if self.crossesOver(data_per_k, data_per_d) and lv_signal <= self.macdsub and \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['signal'] > \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['macd']:

        # if self.crossesOver(data_per_k, data_per_d) and data_per_d[len(data_per_d) - 1] <= 20 and \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['bidclose'] > iFastSMA[
        #    len(iFastSMA) - 1]:

        if self.crossesOver(self.pricedata_stadistics['y'],
                            self.pricedata_stadistics['y_pred']
                            ) and lv_Tendency == "Alcista":
            self.logMessages = self.logMessages + "\n" + "	 SEÑAL DE COMPRA ! \n"
            self.logMessages = self.logMessages + "\n" + ('''        
                  __,_,
                  [_|_/ 
                   //
                 _//    __
                (_|)   |@@|
                 \ \__ \--/ __
                  \o__|----|  |   __
                      \ }{ /\ )_ / _\_
                      /\__/\ \__O (__
                     (--/\--)    \__/
                     _)(  )(_
                    `---''---`
                ''')
            self.logMessages = self.logMessages + "\n" + "	 SEÑAL DE COMPRA !"
            if self.countOpenTrades("S") > 0:
                self.logMessages = self.logMessages + "\n" + "	  Cerrando Ventas Abiertas..."
                self.exit("S")
            self.logMessages = self.logMessages + "\n" + "	  Abrir Operacion de Compra..."
            if self.countOpenTrades("B") == 0:
                self.enter("B")
                # playsound("file_example_MP3_700KB.mp3")
                self.operacioncompra = True

        # Verifica el Cruce del SMA para Abajo.
        if self.crossesUnder(self.pricedata_stadistics['y'],
                             self.pricedata_stadistics['y_pred']
                             ) and lv_Tendency == "Bajista":
            # if crossesUnder(pricedata_stadistics['signal'], 0.0004):
            # if self.crossesUnder(data_per_k, data_per_d) and lv_signal >= self.macduper and \
            #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['signal'] < \
            #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['macd']:

            # if self.crossesUnder(data_per_k, data_per_d) and data_per_d[len(data_per_d) - 1] >= 80 and \
            #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['bidclose'] < iFastSMA[
            #    len(iFastSMA) - 1]:
            self.logMessages = self.logMessages + "\n" + "	  SEÑAL DE VENTA ! \n"
            self.logMessages = self.logMessages + "\n" + ('''
                   __
               _  |@@|
              / \ \--/ __
              ) O|----|  |   __
             / / \ }{ /\ )_ / _\_
             )/  /\__/\ \__O (__
            |/  (--/\--)    \__/
            /   _)(  )(_
               `---''---`

            ''')
            self.logMessages = self.logMessages + "\n" + "	  SEÑAL DE VENTA ! "
            if self.countOpenTrades("B") > 0:
                self.logMessages = self.logMessages + "\n" + "	  Cerrando Operacion de Compras..."
                self.exit("B")
            self.logMessages = self.logMessages + "\n" + "	  Abrir Operacion de Venta..."
            if self.countOpenTrades("S") == 0:
                self.enter("S")
                # playsound("file_example_MP3_700KB.mp3")
                self.operacionventa = True

        self.logMessages = self.logMessages + "\n" + (
            str(dt.datetime.now()) + " " + self.timeframe + "Verificacion "
            "Realizada.\n")
def Update():
    global pricedata_stadistics
    global pricedata_stadistics_sup

    print(str(dt.datetime.now()) + " " + timeframe + " Bar Closed - Running Update Function...")

    pricedata_stadistics['index'] = pricedata['bidclose'].index
    pricedata_stadistics['bidclose'] = pricedata['bidclose'].values

    pricedata_stadistics_sup['index'] = pricedata_sup['bidclose'].index
    pricedata_stadistics_sup['bidclose'] = pricedata_sup['bidclose'].values

    # Calculate Indicators
    iFastSMA = sma(pricedata['bidopen'], fast_sma_periods)
    iSlowSMA = sma(pricedata['bidclose'], slow_sma_periods)

    iSlowSMA2 = sma(pricedata_sup['bidopen'], slow_sma_periods2)

    pricedata_stadistics['emaFast'] = iFastSMA
    pricedata_stadistics['emaSlow'] = iSlowSMA


    pricedata_stadistics_sup['emaSlow2'] = iSlowSMA2

    # Print Price/Indicators
    print("Close Price: " + str(pricedata_stadistics['bidclose'][len(pricedata) - 1]))
    #print("Fast SMA: " + str(iFastSMA[len(iFastSMA) - 1]))
    #print("Slow SMA Open SUP: " + str(iSlowSMA[len(iSlowSMA) - 1]))
    #print("Slow SMA Open SUP2: " + str(iSlowSMA2[len(iSlowSMA2) - 1]))


    # ***********************************************************
    # *  Regresion al precio de cierre las velas ================
    # ***********************************************************
    pricedata_stadistics['x'] = np.arange(len(pricedata_stadistics))
    # ************* Calcular la poscion Relativa Y
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'y'] = int(
            '{:.5f}'.format((pricedata_stadistics.loc[index, 'bidclose'])).replace('.', ''))

    max_value = max(np.array(pricedata_stadistics['y'].values))
    min_value = min(np.array(pricedata_stadistics['y'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'y'] - min_value
        NewPricePosition = ((value * 100) / max_value) * 100
        pricedata_stadistics.loc[index, 'y'] = NewPricePosition

    # ***********  Calcular la poscion Relativa X
    max_value = max(np.array(pricedata_stadistics['x'].values))
    min_value = min(np.array(pricedata_stadistics['x'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'x'] - min_value
        NewPricePosition = ((value * 100) / max_value)
        pricedata_stadistics.loc[index, 'x'] = NewPricePosition

    regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    regresionLineal_yy = np.array(pricedata_stadistics['y'].values)

    regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    pricedata_stadistics['y_pred'] = y_pred_sup

    # Recreacion del Eje X para Presentacion de la Regresion.
    # for index, row in pricedata_stadistics.iterrows():
    #    pricedata_stadistics.loc[index, 'x_pred'] = pricedata_stadistics.loc[0, 'y_pred']

    # Calculo de Angulo
    vx = np.array(pricedata_stadistics['x'])
    vy = np.array(pricedata_stadistics['y_pred'])

    x1 = vx[0]
    y1 = vy[0]

    x2 = vx[-1]
    y2 = vy[-1]

    x = x2 - x1
    y = y2 - y1

    angle = math.atan2(y, x) * (180.0 / math.pi)
    angle = round(angle, 2)
    # angle2 = np.rad2deg(np.arctan2(vy[-1] - vy[0], vx[-1] - vx[0]))

    print("\nAngulo: " + str(angle))

    lv_Tendency = "Lateral"
    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Bajista"
    elif pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Alcista"
    print("\nTendencia Regresion Lineal: " + lv_Tendency)

    # # TRADING LOGIC
    #

    # print("Slow SMA Open SUP: " + str(iSlowSMA[len(iSlowSMA) - 1]))
    # print("Slow SMA Open SUP2: " + str(iSlowSMA2[len(iSlowSMA2) - 1]))

    message_text = ""
    #if crossesOver(iFastSMA, iSlowSMA) and angle >= 1:
    if crossesOver(iFastSMA, iSlowSMA):# and lv_Tendency == "Alcista":
        message_text = message_text + "\n	  BUY SIGNAL!"
        if countOpenTrades("S") > 0:
            message_text = message_text + "\n	  Closing Sell Trade(s)..."
            exit("S")
        if countOpenTrades("B") == 0:
            message_text = message_text + "\n	  Opening Buy Trade..."
            enter("B")

    #if crossesUnder(iFastSMA, iSlowSMA) and angle <= -1:
    if crossesUnder(iFastSMA, iSlowSMA):# and lv_Tendency == "Bajista":
        message_text = message_text + "\n	  SELL SIGNAL!"
        if countOpenTrades("B") > 0:
            message_text = message_text + "\n	  Closing Buy Trade(s)..."
            exit("B")
        if countOpenTrades("S") == 0:
            message_text = message_text + "\n	  Opening Sell Trade..."
            enter("S")

    print(message_text)
    print(str(dt.datetime.now()) + " " + timeframe + " Update Function Completed.\n")
    print("\n")
Example #6
0
 def sma(self, df):
     period = 15
     if len(df) < period:
         period = len(df) // 2
     data = sma(df, 15)
     return (data)
Example #7
0
def Update():
    print(
        str(dt.datetime.now()) + " " + timeframe +
        " Bar Closed - Running Update Function...")
    # *********************************************************************
    # ** Estadistica General - Regresion Lineal Simple 1
    # *********************************************************************

    pricedata_stadistics['bidclose'] = pricedata['bidclose'].values
    pricedata_stadistics['bidopen'] = pricedata['bidopen'].values
    pricedata_stadistics['date'] = pricedata['bidclose'].index
    # pricedata_stadistics['emaFast'] = pricedata_stadistics['bidclose'].rolling(window=fast_sma_periods).mean()
    # pricedata_stadistics['emaSlow'] = pricedata_stadistics['bidclose'].rolling(window=slow_sma_periods).mean()
    # Calculate Indicators
    iFastSMA = sma(pricedata['bidclose'], fast_sma_periods)
    iSlowSMA = sma(pricedata['bidclose'], slow_sma_periods)
    pricedata_stadistics['emaFast'] = iFastSMA
    pricedata_stadistics['emaSlow'] = iSlowSMA
    pricedata_stadistics.index = pricedata['bidclose'].index
    pricedata_stadistics['rowid'] = np.arange(len(pricedata_stadistics))

    # *********************************************************************
    # ** Estadistica General - Regresion Lineal
    # *********************************************************************
    pricedata_stadistics_sup['bidclose'] = pricedata_sup['bidclose'].values
    pricedata_stadistics_sup['date'] = pricedata_sup['bidclose'].index
    pricedata_stadistics_sup['bidhigh'] = pricedata_sup['bidhigh'].values
    pricedata_stadistics_sup['bidlow'] = pricedata_sup['bidlow'].values
    pricedata_stadistics_sup.index = pricedata_sup['bidclose'].index
    pricedata_stadistics_sup['rowid'] = np.arange(
        len(pricedata_stadistics_sup))

    # Regresion al mas Alto de las velas ======================
    regresionLineal_xx_sup = np.array(
        pricedata_stadistics_sup['rowid'].tail(numberofregresion_sup).values)
    regresionLineal_yy_sup = np.array(
        pricedata_stadistics_sup['bidhigh'].tail(numberofregresion_sup).values)
    regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(
        regresionLineal_xx_sup, regresionLineal_yy_sup)
    y_pred_sup = regresionLineal_bb_sup[
        0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup

    numberRegx = len(pricedata_stadistics_sup) - numberofregresion_sup
    posreg = 0
    for index, row in pricedata_stadistics_sup.iterrows():
        if numberRegx <= pricedata_stadistics_sup.loc[index, 'rowid']:
            pricedata_stadistics_sup.loc[index,
                                         'y_pred_bidhigh'] = y_pred_sup[posreg]
            posreg = posreg + 1

    # Regresion al mas bajo de las velas ======================
    regresionLineal_xx_sup = np.array(
        pricedata_stadistics_sup['rowid'].tail(numberofregresion_sup).values)
    regresionLineal_yy_sup = np.array(
        pricedata_stadistics_sup['bidlow'].tail(numberofregresion_sup).values)
    regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(
        regresionLineal_xx_sup, regresionLineal_yy_sup)
    y_pred_sup = regresionLineal_bb_sup[
        0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup

    numberRegx = len(pricedata_stadistics_sup) - numberofregresion_sup
    posreg = 0
    for index, row in pricedata_stadistics_sup.iterrows():
        if numberRegx <= pricedata_stadistics_sup.loc[index, 'rowid']:
            pricedata_stadistics_sup.loc[index,
                                         'y_pred_bidlow'] = y_pred_sup[posreg]
            posreg = posreg + 1

    # *********************************************************************
    # ***    Proyecion de Precios * Se puede Mejorar con Ciclo
    # *********************************************************************
    lv_index_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) -
                                               1]['date']
    lv_rowid_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) -
                                               1]['rowid']
    lv_y_pred_askhigh_1 = pricedata_stadistics_sup.iloc[
        len(pricedata_stadistics_sup) - 1]['y_pred_bidhigh']
    lv_y_pred_asklow_1 = pricedata_stadistics_sup.iloc[
        len(pricedata_stadistics_sup) - 1]['y_pred_bidlow']

    lv_index_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) -
                                               2]['date']
    lv_rowid_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) -
                                               2]['rowid']
    lv_y_pred_askhigh_2 = pricedata_stadistics_sup.iloc[
        len(pricedata_stadistics_sup) - 2]['y_pred_bidhigh']
    lv_y_pred_asklow_2 = pricedata_stadistics_sup.iloc[
        len(pricedata_stadistics_sup) - 2]['y_pred_bidlow']

    lv_index_base = lv_index_1 - lv_index_2
    lv_rowid_base = lv_rowid_1 - lv_rowid_2
    lv_y_pred_askhigh_base = lv_y_pred_askhigh_1 - lv_y_pred_askhigh_2
    lv_y_pred_asklow_base = lv_y_pred_asklow_1 - lv_y_pred_asklow_2

    pricedata_stadistics_proyeccion.loc[lv_index_1] = pd.Series({
        'rowid':
        lv_rowid_1,
        'y_pred_bidhigh':
        lv_y_pred_askhigh_1,
        'y_pred_bidlow':
        lv_y_pred_asklow_1
    })

    pricedata_stadistics_proyeccion.loc[lv_index_1 +
                                        lv_index_base] = pd.Series({
                                            'rowid':
                                            lv_rowid_1 + lv_rowid_base,
                                            'y_pred_bidhigh':
                                            lv_y_pred_askhigh_1 +
                                            lv_y_pred_askhigh_base,
                                            'y_pred_bidlow':
                                            lv_y_pred_asklow_1 +
                                            lv_y_pred_asklow_base
                                        })

    # Calculamos La tendencia con los valores de de la proyection las velas mas altas y mas bajas.
    lv_Tendency = "Lateral"
    if pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidhigh'] < \
            pricedata_stadistics_sup.iloc[1]['y_pred_bidhigh'] and \
            pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidlow'] < \
            pricedata_stadistics_sup.iloc[1]['y_pred_bidlow']:
        lv_Tendency = "Bajista"
    elif pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidhigh'] > \
            pricedata_stadistics_sup.iloc[1]['y_pred_bidhigh'] and \
            pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidlow'] > \
            pricedata_stadistics_sup.iloc[1]['y_pred_bidlow']:
        lv_Tendency = "Alcista"

    print("Tendencia Regresion Lineal: " + lv_Tendency)

    lv_posicion_venta = False
    lv_posicion_compra = False

    if lv_Tendency == "Bajista" and pricedata_stadistics_proyeccion.iloc[
            len(pricedata_stadistics_proyeccion) -
            1]['y_pred_bidhigh'] < pricedata_stadistics.iloc[
                len(pricedata_stadistics) - 1]['bidclose']:
        lv_posicion_venta = True
        lv_posicion_compra = False
    elif lv_Tendency == "Alcista" and pricedata_stadistics_proyeccion.iloc[
            len(pricedata_stadistics_proyeccion) -
            1]['y_pred_bidlow'] > pricedata_stadistics.iloc[
                len(pricedata_stadistics) - 1]['bidclose']:
        lv_posicion_venta = False
        lv_posicion_compra = True
    print("Posicion de Venta: " + str(lv_posicion_venta) +
          " Posicion de Compra: " + str(lv_posicion_compra))

    # Print Price/Indicators
    print("Close Price: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    #print("Fast SMA: " + str(iFastSMA[len(iFastSMA) - 1]))
    #print("Slow SMA: " + str(iSlowSMA[len(iSlowSMA) - 1]))

    # TRADING LOGIC
    if crossesOver(iFastSMA, iSlowSMA) and lv_posicion_compra:
        print("	  BUY SIGNAL!")
        if countOpenTrades("S") > 0:
            print("	  Closing Sell Trade(s)...")
            exit("S")
        if countOpenTrades("B") == 0:
            print("	  Opening Buy Trade...")
            enter("B")

    if crossesUnder(iFastSMA, iSlowSMA) and lv_posicion_venta:
        print("	  SELL SIGNAL!")
        if countOpenTrades("B") > 0:
            print("	  Closing Buy Trade(s)...")
            exit("B")
        if countOpenTrades("S") == 0:
            print("	  Opening Sell Trade...")
            enter("S")
    print(
        str(dt.datetime.now()) + " " + timeframe +
        " Update Function Completed.\n")
    print("\n")
def compute_simple_moving_average(df):
    df['sma'] = sma(df.close, 15)
Example #9
0
 def do_calculation(self, candle):
     dataset = self.market.candles[self.interval][-self.periods:]
     data = list(c[4] for c in dataset)
     self.value = round(sma(data, self.periods)[-1], 6)
     self.close = candle[4]
     self.timestamp = ohlcv_functions.convert_timestamp_to_date(candle[0])
Example #10
0
def mov_av_5(history: List[LastSale]) -> list:
    prices = [i.Price.Amount for i in history]
    prices.reverse()
    mov_av = [i for i in list(sma(prices, 5))]
    mov_av.reverse()
    return mov_av
Example #11
0
def Update():
    global message_text

    message_text = message_text + (
            '\n' + str(dt.datetime.now()) + " " + timeframe + " Bar Closed - Running Update Function..." + symbol)
    # *********************************************************************
    # ** Estadistica General - Regresion Lineal Simple 1
    # *********************************************************************
    pricedata_stadistics.iloc[0:0]
    pricedata_stadistics['bidclose'] = pricedata['bidclose'].values
    pricedata_stadistics['bidopen'] = pricedata['bidopen'].values

    pricedata_stadistics['x'] = np.arange(len(pricedata_stadistics))
    # ************* Calcular la poscion Relativa Y
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'y'] = int(
            '{:.5f}'.format((pricedata_stadistics.loc[index, 'bidclose'])).replace('.', ''))

    max_value = max(np.array(pricedata_stadistics['y'].values))
    min_value = min(np.array(pricedata_stadistics['y'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'y'] - min_value
        NewPricePosition = ((value * 100) / max_value) * 100
        pricedata_stadistics.loc[index, 'y'] = NewPricePosition

    # ***********  Calcular la poscion Relativa X
    max_value = max(np.array(pricedata_stadistics['x'].values))
    min_value = min(np.array(pricedata_stadistics['x'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'x'] - min_value
        NewPricePosition = ((value * 100) / max_value)
        pricedata_stadistics.loc[index, 'x'] = NewPricePosition

    # ***********************************************************
    # *  EMA'S================
    # ***********************************************************
    iFastSMA = sma(pricedata_stadistics['y'], fast_sma_periods)
    iSlowSMA = sma(pricedata_stadistics['y'], slow_sma_periods)
    iTooSlowSMA = sma(pricedata_stadistics['y'], too_slow_sma_periods)
    pricedata_stadistics['emaFast'] = iFastSMA
    pricedata_stadistics['emaSlow'] = iSlowSMA
    pricedata_stadistics['emaTooSlow'] = iTooSlowSMA

    # ***********************************************************
    # *  Regresion al precio de cierre las velas ================
    # ***********************************************************

    regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    regresionLineal_yy = np.array(pricedata_stadistics['y'].values)
    regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)

    y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    pricedata_stadistics['y_pred'] = y_pred_sup

    # Recreacion del Eje X para Presentacion de la Regresion.
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'x_pred'] = pricedata_stadistics.loc[0, 'y_pred']

    # Calculo de Angulo
    vx = np.array(pricedata_stadistics['x'])
    vy = np.array(pricedata_stadistics['y_pred'])

    x1 = vx[0]
    y1 = vy[0]

    x2 = vx[-1]
    y2 = vy[-1]

    x = x2 - x1
    y = y2 - y1

    angle = math.atan2(y, x) * (180.0 / math.pi)
    angle = round(angle, 2)
    # angle2 = np.rad2deg(np.arctan2(vy[-1] - vy[0], vx[-1] - vx[0]))

    message_text = message_text + "\nAngulo: " + str(angle)
    #
    # pricedata_stadistics['y_bidhigh'] = pricedata['bidhigh'].values
    # pricedata_stadistics['y_bidlow'] = pricedata['bidlow'].values
    # # ************* Calcular la poscion Relativa Y
    # for index, row in pricedata_stadistics.iterrows():
    #     pricedata_stadistics.loc[index, 'y_bidhigh'] = int(
    #         '{:.5f}'.format((pricedata_stadistics.loc[index, 'y_bidhigh'])).replace('.', ''))
    #     pricedata_stadistics.loc[index, 'y_bidlow'] = int(
    #         '{:.5f}'.format((pricedata_stadistics.loc[index, 'y_bidlow'])).replace('.', ''))
    #
    # max_value = max(np.array(pricedata_stadistics['y_bidhigh'].values))
    # min_value = min(np.array(pricedata_stadistics['y_bidhigh'].values))
    # for index, row in pricedata_stadistics.iterrows():
    #     value = pricedata_stadistics.loc[index, 'y_bidhigh'] - min_value
    #     NewPricePosition = ((value * 100) / max_value) * 100
    #     pricedata_stadistics.loc[index, 'y_bidhigh'] = NewPricePosition
    #
    # max_value = max(np.array(pricedata_stadistics['y_bidlow'].values))
    # min_value = min(np.array(pricedata_stadistics['y_bidlow'].values))
    # for index, row in pricedata_stadistics.iterrows():
    #     value = pricedata_stadistics.loc[index, 'y_bidlow'] - min_value
    #     NewPricePosition = ((value * 100) / max_value) * 100
    #     pricedata_stadistics.loc[index, 'y_bidlow'] = NewPricePosition
    #
    # # Regresion al precio mas alto velas ======================
    # regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    # regresionLineal_yy = np.array(pricedata_stadistics['y_bidhigh'].values)
    # regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    #
    # y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    # pricedata_stadistics['y_pred_bidhigh'] = y_pred_sup
    #
    # # Regresion al precio de cierre las velas ======================
    # regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    # regresionLineal_yy = np.array(pricedata_stadistics['y_bidlow'].values)
    # regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    # y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    # pricedata_stadistics['y_pred_bidlow'] = y_pred_sup

    # # *********************************************************************
    # # ** Estadistica General - Regresion Lineal
    # # *********************************************************************
    # pricedata_stadistics_sup.iloc[0:0]
    # pricedata_stadistics_sup['bidclose'] = pricedata_sup['bidclose'].values
    # pricedata_stadistics_sup['bidhigh'] = pricedata_sup['bidhigh'].values
    # pricedata_stadistics_sup['bidlow'] = pricedata_sup['bidlow'].values
    # pricedata_stadistics_sup['rowid'] = np.arange(len(pricedata_stadistics_sup))
    #
    # # *************BIDHIGH
    # # ************* Calcular la poscion Relativa Y
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     pricedata_stadistics_sup.loc[index, 'Y_bidhigh'] = int(
    #         '{:.5f}'.format((pricedata_stadistics_sup.loc[index, 'bidhigh'])).replace('.', ''))
    #
    # max_value = max(np.array(pricedata_stadistics_sup['Y_bidhigh'].values))
    # min_value = min(np.array(pricedata_stadistics_sup['Y_bidhigh'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'Y_bidhigh'] - min_value
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'Y_bidhigh'] = NewPricePosition
    #
    # # ***********  Calcular la poscion Relativa X
    # max_value = max(np.array(pricedata_stadistics_sup['rowid'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'rowid']
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'X_bidhigh'] = NewPricePosition
    #
    # # Regresion al precio mas Alto de las velas ======================
    # regresionLineal_xx_sup = np.array(pricedata_stadistics_sup['X_bidhigh'].values)
    # regresionLineal_yy_sup = np.array(pricedata_stadistics_sup['Y_bidhigh'].values)
    # regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(regresionLineal_xx_sup, regresionLineal_yy_sup)
    # y_pred_sup = regresionLineal_bb_sup[0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup
    #
    # pricedata_stadistics_sup['y_pred_bidhigh'] = y_pred_sup
    # pricedata_stadistics_sup['x_pred_bidhigh'] = regresionLineal_xx_sup
    #
    #
    #

    #
    # # *************BIDLOW
    # # ************* Calcular la poscion Relativa Y
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     pricedata_stadistics_sup.loc[index, 'Y_bidlow'] = int(
    #         '{:.5f}'.format((pricedata_stadistics_sup.loc[index, 'bidlow'])).replace('.', ''))
    #
    # max_value = max(np.array(pricedata_stadistics_sup['Y_bidlow'].values))
    # min_value = min(np.array(pricedata_stadistics_sup['Y_bidlow'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'Y_bidlow'] - min_value
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'Y_bidlow'] = NewPricePosition
    #
    # # ***********  Calcular la poscion Relativa X
    # max_value = max(np.array(pricedata_stadistics_sup['rowid'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'rowid']
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'X_bidlow'] = NewPricePosition
    #
    #
    #
    #
    # # Regresion al precio mas Alto de las velas ======================
    # regresionLineal_xx_sup = np.array(pricedata_stadistics_sup['X_bidlow'].values)
    # regresionLineal_yy_sup = np.array(pricedata_stadistics_sup['Y_bidhigh'].values)
    # regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(regresionLineal_xx_sup, regresionLineal_yy_sup)
    # y_pred_sup = regresionLineal_bb_sup[0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup
    #
    # pricedata_stadistics_sup['y_pred_bidlow'] = y_pred_sup
    # pricedata_stadistics_sup['x_pred_bidlow'] = regresionLineal_xx_sup
    #
    #
    #

    #
    #
    # # create circle
    # c = plt.Circle((x1, y1), radius=10, color='red', alpha=.3)
    # plt.gca().add_artist(c)
    #
    # #plt.text(x1, y1, str(round(angle, 2)) + ' °')

    # # Regresion al mas bajo de las velas ======================
    # regresionLineal_xx_sup = np.array(pricedata_stadistics_sup['rowid'].tail(numberofregresion_sup).values)
    # regresionLineal_yy_sup = np.array(pricedata_stadistics_sup['bidlow'].tail(numberofregresion_sup).values)
    # regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(regresionLineal_xx_sup, regresionLineal_yy_sup)
    # y_pred_sup = regresionLineal_bb_sup[0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup
    #
    # numberRegx = len(pricedata_stadistics_sup) - numberofregresion_sup
    # posreg = 0
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     if numberRegx <= pricedata_stadistics_sup.loc[index, 'rowid']:
    #         pricedata_stadistics_sup.loc[index, 'y_pred_bidlow'] = y_pred_sup[posreg]
    #         posreg = posreg + 1
    #
    # # *********************************************************************
    # # ***    Proyecion de Precios * Se puede Mejorar con Ciclo
    # # *********************************************************************
    # lv_index_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['date']
    # lv_rowid_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['rowid']
    # lv_y_pred_askhigh_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidhigh']
    # lv_y_pred_asklow_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidlow']
    #
    # lv_index_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['date']
    # lv_rowid_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['rowid']
    # lv_y_pred_askhigh_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['y_pred_bidhigh']
    # lv_y_pred_asklow_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['y_pred_bidlow']
    #
    # lv_index_base = lv_index_1 - lv_index_2
    # lv_rowid_base = lv_rowid_1 - lv_rowid_2
    # lv_y_pred_askhigh_base = lv_y_pred_askhigh_1 - lv_y_pred_askhigh_2
    # lv_y_pred_asklow_base = lv_y_pred_asklow_1 - lv_y_pred_asklow_2
    #
    # pricedata_stadistics_proyeccion.iloc[0:0]
    # for proyect_times in range(2):
    #     pricedata_stadistics_proyeccion.loc[lv_index_1] = pd.Series(
    #         {'rowid': lv_rowid_1,
    #          'y_pred_bidhigh': lv_y_pred_askhigh_1,
    #          'y_pred_bidlow': lv_y_pred_asklow_1
    #          })
    #     lv_index_1 = lv_index_1 + lv_index_base
    #     lv_rowid_1 = lv_rowid_1 + lv_rowid_base
    #     lv_y_pred_askhigh_1 = lv_y_pred_askhigh_1 + lv_y_pred_askhigh_base
    #     lv_y_pred_asklow_1 = lv_y_pred_asklow_1 + lv_y_pred_asklow_base
    #
    # pricedata_stadistics_proyeccion_tenden.iloc[0:0]
    # for proyect_times in range(3):
    #     pricedata_stadistics_proyeccion_tenden.loc[lv_index_1] = pd.Series(
    #         {'rowid': lv_rowid_1,
    #          'y_pred_bidhigh': lv_y_pred_askhigh_1,
    #          'y_pred_bidlow': lv_y_pred_asklow_1
    #          })
    #     lv_index_1 = lv_index_1 + lv_index_base
    #     lv_rowid_1 = lv_rowid_1 + lv_rowid_base
    #     lv_y_pred_askhigh_1 = lv_y_pred_askhigh_1 + lv_y_pred_askhigh_base
    #     lv_y_pred_asklow_1 = lv_y_pred_asklow_1 + lv_y_pred_asklow_base
    #

    # Calculamos La tendencia con los valores de de la proyection las velas mas altas y mas bajas.
    lv_Tendency = "Lateral"

    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Bajista"
    elif pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Alcista"

    message_text = message_text + "\nTendencia Regresion Lineal: " + lv_Tendency

    lv_posicion_venta = False
    lv_posicion_compra = False

    if lv_Tendency == "Bajista" and (pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['emaTooSlow'] >
                                     pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y']):

        lv_posicion_venta = True
        lv_posicion_compra = False

    elif lv_Tendency == "Alcista" and (pricedata_stadistics.iloc[len(pricedata_stadistics) - 1][
                                           'emaTooSlow'] < pricedata_stadistics.iloc[len(pricedata_stadistics) - 1][
                                           'y']):
        lv_posicion_venta = False
        lv_posicion_compra = True

    message_text = message_text + "\nPosicion de Venta: " + str(lv_posicion_venta) + " Posicion de Compra: " + str(
        lv_posicion_compra)

    # # Print Price/Indicators
    # print("Close Price: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    # # print("Fast SMA: " + str(iFastSMA[len(iFastSMA) - 1]))
    # # print("Slow SMA: " + str(iSlowSMA[len(iSlowSMA) - 1]))
    #
    # # TRADING LOGIC
    #
    if crossesOver(iFastSMA, iSlowSMA) and lv_posicion_compra and angle >= angulo_plus:
        message_text = message_text + "\n	  BUY SIGNAL!"
        if countOpenTrades("S") > 0:
            message_text = message_text + "\n	  Closing Sell Trade(s)..."
            exit("S")
        if countOpenTrades("B") == 0:
            message_text = message_text + "\n	  Opening Buy Trade..."
            enter("B")

    if crossesUnder(iFastSMA, iSlowSMA) and lv_posicion_venta and angle <= angulo_minus:
        message_text = message_text + "\n	  SELL SIGNAL!"
        if countOpenTrades("B") > 0:
            message_text = message_text + "\n	  Closing Buy Trade(s)..."
            exit("B")
        if countOpenTrades("S") == 0:
            message_text = message_text + "\n	  Opening Sell Trade..."
            enter("S")

    message_text = message_text + "\n" + str(
        dt.datetime.now()) + " " + timeframe + " Update Function Completed.========= \n"
    print(message_text)
    message_text = ''
def Update():

    print('''
          [ ]
         (   )
          |>|
       __/===\__
      _/_/| o=o |\_\_ 
    <]  | o=o |  [>
        \=====/
      _/ / | \ \_
      <_________>
    ''')

    print(
        str(dt.datetime.now()) + " " + timeframe +
        " Vela Formada - Analizando -  Running Update Function...")

    iFastSMA = sma(pricedata['bidclose'], fast_sma_periods)
    iSlowSMA = sma(pricedata['bidclose'], slow_sma_periods)

    # Imprimir Precio/Indicador
    print("Precio Cierre: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    print("Fast SMA: " + str(iFastSMA[len(iFastSMA) - 1]))
    print("Slow SMA: " + str(iSlowSMA[len(iSlowSMA) - 1]))
    print("Periodos de validacion:")
    print("fast_sma_periods:" + str(fast_sma_periods))
    print("slow_sma_periods:" + str(slow_sma_periods))
    print(pricedata)

    # Logica Robot
    # Verifica el Cruce del SMA para Arriba.
    if crossesOver(iFastSMA, iSlowSMA):
        print("	 SEÑAL DE COMPRA ! \n")
        print('''        
              __,_,
              [_|_/ 
               //
             _//    __
            (_|)   |@@|
             \ \__ \--/ __
              \o__|----|  |   __
                  \ }{ /\ )_ / _\_
                  /\__/\ \__O (__
                 (--/\--)    \__/
                 _)(  )(_
                `---''---`
            ''')
        print("	 SEÑAL DE COMPRA ! \n")
        if countOpenTrades("S") > 0:
            print("	  Cerrando Ventas Abiertas...\n")
            exit("S")
        print("	  Abrir Operacion de Compra...\n")
        enter("B")

    # Verifica el Cruce del SMA para Abajo.
    if crossesUnder(iFastSMA, iSlowSMA):
        print("	  SEÑAL DE VENTA ! \n")
        print('''
               __
           _  |@@|
          / \ \--/ __
          ) O|----|  |   __
         / / \ }{ /\ )_ / _\_
         )/  /\__/\ \__O (__
        |/  (--/\--)    \__/
        /   _)(  )(_
           `---''---`
        
        ''')
        print("	  SEÑAL DE VENTA ! \n")
        if countOpenTrades("B") > 0:
            print("	  Cerrando Operacion de Compras...\n")
            exit("B")
        print("	  Abrir Operacion de Venta...\n")
        enter("S")
    print(
        str(dt.datetime.now()) + " " + timeframe +
        " Verificacion Realizada.\n")
    print("\n")
Example #13
0
def Update():
    global pricedata_stadistics, operacionventa, operacioncompra

    print(str(dt.datetime.now()) + " " + timeframe + " Vela Formada - Analizando -  Running Update Function...")

    pricedata_stadistics['index'] = pricedata['bidclose'].index
    pricedata_stadistics['bidclose'] = pricedata['bidclose'].values
    pricedata_stadistics['bidhigh'] = pricedata['bidhigh'].values
    pricedata_stadistics['askclose'] = pricedata['askclose'].values
    pricedata_stadistics['askhigh'] = pricedata['askhigh'].values
    pricedata_stadistics['asklow'] = pricedata['asklow'].values
    pricedata_stadistics['askclose'] = pricedata['askclose'].values
    pricedata_stadistics['bidlow'] = pricedata['bidlow'].values

    pricedata_stadistics['tickqty'] = pricedata['tickqty'].values

    # Calculate Indicators
    iFastSMA = sma(pricedata['bidclose'], fast_sma_periods)
    iSlowSMA = sma(pricedata['bidclose'], slow_sma_periods)

    pricedata_stadistics['emaFast'] = iFastSMA
    pricedata_stadistics['emaSlow'] = iSlowSMA

    # Adds a "n_high" column with max value of previous 14 periods
    pricedata_stadistics['n_high'] = pricedata_stadistics['bidhigh'].rolling(stoK).max()
    # Adds an "n_low" column with min value of previous 14 periods
    pricedata_stadistics['n_low'] = pricedata_stadistics['bidlow'].rolling(stoK).min()
    # Uses the min/max values to calculate the %k (as a percentage)
    pricedata_stadistics['per_k'] = (pricedata_stadistics['bidclose'] - pricedata_stadistics['n_low']) * 100 / (
            pricedata_stadistics['n_high'] - pricedata_stadistics['n_low'])
    # Uses the %k to calculates a SMA over the past 3 values of %k
    pricedata_stadistics['per_d'] = pricedata_stadistics['per_k'].rolling(stoD).mean()

    # data_per_k = per_k(pricedata['bidclose'], stoK)
    # data_per_d = per_d(pricedata['bidclose'], stoD)

    data_per_k = pricedata_stadistics['per_k']
    data_per_d = pricedata_stadistics['per_d']
    # pricedata_stadistics['per_k'] = data_per_k
    # pricedata_stadistics['per_d'] = data_per_d

    # Calcular Indicador
    iRSI = rsi(pricedata_stadistics['bidclose'], 15)
    print("RSI: " + str(iRSI[len(iRSI) - 1]))

    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'lower_sto'] = 20
        pricedata_stadistics.loc[index, 'upper_sto'] = 80
        pricedata_stadistics.loc[index, 'macdline0'] = 0.00

    # ***********************************************************
    # *  Regresion al precio de cierre las velas ================
    # ***********************************************************
    pricedata_stadistics['x'] = np.arange(len(pricedata_stadistics))
    # ************* Calcular la poscion Relativa Y
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'y'] = int(
            '{:.5f}'.format((pricedata_stadistics.loc[index, 'bidclose'])).replace('.', ''))

    max_value = max(np.array(pricedata_stadistics['y'].values))
    min_value = min(np.array(pricedata_stadistics['y'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'y'] - min_value
        NewPricePosition = ((value * 100) / max_value) * 100
        pricedata_stadistics.loc[index, 'y'] = NewPricePosition

    # ***********  Calcular la poscion Relativa X
    max_value = max(np.array(pricedata_stadistics['x'].values))
    min_value = min(np.array(pricedata_stadistics['x'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'x'] - min_value
        NewPricePosition = ((value * 100) / max_value)
        pricedata_stadistics.loc[index, 'x'] = NewPricePosition

    regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    regresionLineal_yy = np.array(pricedata_stadistics['y'].values)

    regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    pricedata_stadistics['y_pred'] = y_pred_sup

    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Bajista"
    elif pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Alcista"

    # MACD        ########################################################################
    exp1 = pricedata_stadistics['bidclose'].ewm(span=macdFast, adjust=False).mean()
    exp2 = pricedata_stadistics['bidclose'].ewm(span=macdSlow, adjust=False).mean()
    macd = exp1 - exp2
    pricedata_stadistics['macd'] = pricedata_stadistics.index.map(macd)
    pricedata_stadistics['signal'] = pd.DataFrame(
        pricedata_stadistics['macd'].ewm(span=macdSmooth, adjust=False).mean())
    pricedata_stadistics['hist'] = pd.DataFrame(pricedata_stadistics['macd'] - pricedata_stadistics['signal'])

    # Imprimir Precio/Indicador
    # print("Precio Cierre: " + str(pricedata['bidclose'][len(pricedata) - 1]))

    # print("Tendencia Regresion Lineal: " + lv_Tendency)
    lv_signal = pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['signal']
    print("MACD Signal: " + str(lv_signal) + " SubValuacion:  " + str(macdsub) + " SobreValuacion:  " + str(macduper))
    print("STO D" + str(data_per_d[len(data_per_d) - 1]))

    if iRSI[len(iRSI) - 1] <= 40 and crossesOver(data_per_d,
                                                 pricedata_stadistics['lower_sto']) and lv_signal <= macdsub:
        print("	 SEÑAL DE COMPRA ! \n")
        print('''        
              __,_,
              [_|_/ 
               //
             _//    __
            (_|)   |@@|
             \ \__ \--/ __
              \o__|----|  |   __
                  \ }{ /\ )_ / _\_
                  /\__/\ \__O (__
                 (--/\--)    \__/
                 _)(  )(_
                `---''---`
            ''')
        print("	 SEÑAL DE COMPRA ! \n")
        if countOpenTrades("S") > 0:
            print("	  Cerrando Ventas Abiertas...\n")
            exit("S")
        print("	  Abrir Operacion de Compra...\n")
        if countOpenTrades("B") == 0:
            enter("B")
            operacioncompra = True

    # Verifica el Cruce del SMA para Abajo.
    # if crossesUnder(data_per_d, 0.80):
    # if crossesUnder(pricedata_stadistics['signal'], 0.0004):
    if iRSI[len(iRSI) - 1] >= 60 and crossesUnder(data_per_d, pricedata_stadistics['upper_sto']) and lv_signal >= macduper:
        print("	  SEÑAL DE VENTA ! \n")
        print('''
               __
           _  |@@|
          / \ \--/ __
          ) O|----|  |   __
         / / \ }{ /\ )_ / _\_
         )/  /\__/\ \__O (__
        |/  (--/\--)    \__/
        /   _)(  )(_
           `---''---`

        ''')
        print("	  SEÑAL DE VENTA ! \n")
        if countOpenTrades("B") > 0:
            print("	  Cerrando Operacion de Compras...\n")
            exit("B")
        print("	  Abrir Operacion de Venta...\n")
        if countOpenTrades("S") == 0:
            enter("S")
            operacionventa = True

    # Cerrar Ventas #########################################
    if operacionventa and crossesOver(data_per_d, pricedata_stadistics['lower_sto']):
        if countOpenTrades("S") > 0:
            print("	  Cerrando Ventas Abiertas...\n")
            operacionventa = False
            exit("S")

    # Cerrar Compras #########################################
    if operacioncompra and crossesUnder(data_per_d, pricedata_stadistics['upper_sto']):
        if countOpenTrades("B") > 0:
            print("	  Cerrando Compras Abiertas...\n")
            operacioncompra = False
            exit("B")
    print(str(dt.datetime.now()) + " " + timeframe + " Verificacion Realizada.\n")
Example #14
0
def simple_moving_average(data, period):
    return sma(data, period)