예제 #1
0
def test_bbwidth():
    """test TA.BBWIDTH"""

    bb = TA.BBWIDTH(ohlc)

    assert isinstance(bb, series.Series)
    assert 0 < bb.values[-1] < 1
예제 #2
0
def prep_data(data_1m, t, ma, ma_type, vol_type):
    data = resample(data_1m, t)
    # limit data to latest 10,500 periods for indicator calculations
    data = data[-10500:]

    if ma_type == 'sma':
        data['ma'] = data['close'].rolling(window=ma).mean()
    elif ma_type == 'hma':
        data['ma'] = TA.HMA(data, ma)

    data['roc'] = data['close'].pct_change(periods=roc_p)
    data['ma_roc'] = data['ma'].pct_change(
    )  # is the ma higher or lower than previous period

    if vol_type == 'roc':
        data['vol'] = data['roc']
    if vol_type == 'bbw':
        data['bbw'] = TA.BBWIDTH(data, ma, data['ma'])
        # print('roc', data['roc'].tail())
        # print('atr', data['bbw'].tail())
        data['vol'] = data['roc'] / data['bbw']
        # print('vol min', data['vol'].min(), 'vol max', data['vol'].max())
    elif vol_type == 'atr':
        data['atr'] = TA.ATR(data, 9)
        # print('roc', data['roc'].tail())
        # print('atr', data['atr'].tail())
        data['vol'] = (data['roc'] / data['atr']) * data[
            'close']  # dividing by close price makes it proportional
        # print(t, 'vol min', data['vol'].min(), 'vol max', data['vol'].max())

    # limit data to latest 10,000 periods to trim off NaNs and focus on recent data
    data = data[-10000:]

    return data
예제 #3
0
    def get_bbandwidth(data):
        """Calculate the Bollinger bandwidth for values of given dataframe.

        :param data: a dataframe in OHLC format
        :return: a Pandas series
        """
        if data is None:
            raise EmptyDataError("[!] Invalid data value")

        result = TA.BBWIDTH(data)
        if result is None:
            raise IndicatorException
        return result
예제 #4
0
    def get_bbo(self, contract):  # Get best b/o excluding own orders
        j = self.ohlcv[contract].json()
        fut2 = contract
        #print(contract)
        best_bids = []
        best_asks = []
        o = []
        h = []
        l = []
        c = []
        v = []
        for b in j['result']['open']:
            o.append(b)

        for b in j['result']['high']:
            h.append(b)
        for b in j['result']['low']:
            l.append(b)
        for b in j['result']['close']:
            c.append(b)
        for b in j['result']['volume']:
            v.append(b)
        abc = 0
        ohlcv2 = []
        for b in j['result']['open']:
            ohlcv2.append([o[abc], h[abc], l[abc], c[abc], v[abc]])
            abc = abc + 1

        ddf = pd.DataFrame(ohlcv2,
                           columns=['open', 'high', 'low', 'close', 'volume'])

        if 1 in self.directional:
            sleep(0)

            try:
                self.dsrsi = TA.STOCHRSI(ddf).iloc[-1] * 100
            except:
                self.dsrsi = 50
            ##print(self.dsrsi)
        # Get orderbook
        if 2 in self.volatility or 3 in self.price or 4 in self.quantity_switch:
            self.bands[fut2] = TA.BBANDS(ddf).iloc[-1]
            self.bbw[fut2] = (TA.BBWIDTH(ddf).iloc[-1])
            #print(float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER']))
            if (float(self.bands[fut2]['BB_UPPER'] -
                      self.bands[fut2]['BB_LOWER'])) > 0:
                deltab = (self.get_spot() - self.bands[fut2]['BB_LOWER']) / (
                    self.bands[fut2]['BB_UPPER'] -
                    self.bands[fut2]['BB_LOWER'])
                if deltab > 50:
                    self.diffdeltab[fut2] = (deltab - 50) / 100 + 1
                if deltab < 50:
                    self.diffdeltab[fut2] = (50 - deltab) / 100 + 1
            else:
                self.diffdeltab[fut2] = 25 / 100 + 1
        if 3 in self.volatility:
            self.atr[fut2] = TA.ATR(ddf).iloc[-1]

        if 0 in self.price:
            ob = self.client.getorderbook(contract)
            bids = ob['bids']
            asks = ob['asks']

            ords = self.client.getopenorders(contract)
            bid_ords = [o for o in ords if o['direction'] == 'buy']
            ask_ords = [o for o in ords if o['direction'] == 'sell']
            best_bid = None
            best_ask = None

            err = 10**-(self.get_precision(contract) + 1)

            for b in bids:
                match_qty = sum([
                    o['quantity'] for o in bid_ords
                    if math.fabs(b['price'] - o['price']) < err
                ])
                if match_qty < b['quantity']:
                    best_bid = b['price']
                    break

            for a in asks:
                match_qty = sum([
                    o['quantity'] for o in ask_ords
                    if math.fabs(a['price'] - o['price']) < err
                ])
                if match_qty < a['quantity']:
                    best_ask = a['price']
                    break

            best_asks.append(best_ask)
            best_bids.append(best_bid)
        if 1 in self.price:
            dvwap = TA.VWAP(ddf)
            ##print(dvwap)
            tsz = self.get_ticksize(contract)
            try:
                bid = ticksize_floor(dvwap.iloc[-1], tsz)
                ask = ticksize_ceil(dvwap.iloc[-1], tsz)
            except:
                bid = ticksize_floor(self.get_spot(), tsz)
                ask = ticksize_ceil(self.get_spot(), tsz)

            #print( { 'bid': bid, 'ask': ask })
            best_asks.append(best_ask)
            best_bids.append(best_bid)
        if 2 in self.quantity_switch:

            dppo = TA.PPO(ddf)
            self.buysellsignal[fut2] = 1
            try:
                if (dppo.iloc[-1].PPO > 0):
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 + PRICE_MOD)
                else:
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 - PRICE_MOD)

                if (dppo.iloc[-1].HISTO > 0):
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 + PRICE_MOD)
                else:
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 - PRICE_MOD)
                if (dppo.iloc[-1].SIGNAL > 0):
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 + PRICE_MOD)
                else:
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 - PRICE_MOD)
            except:
                self.buysellsignal[fut2] = 1

            ##print({ 'bid': best_bid, 'ask': best_ask })
        return {
            'bid': self.cal_average(best_bids),
            'ask': self.cal_average(best_asks)
        }
    def get_bbo(self, contract):  # Get best b/o excluding own orders
        vwap = {}
        ohlcv2 = {}
        fut2 = contract
        if contract is 'XBTUSD':
            fut2 = 'BTC/USD'
        if contract is 'ETHUSD':
            fut2 = 'ETH/USD'
        now = datetime.now()
        format_iso_now = now.isoformat()

        then = now - timedelta(minutes=100)
        format_later_iso = then.isoformat()
        thetime = then.strftime('%Y-%m-%dT%H:%M:%S')
        ohlcv = self.client.fetchOHLCV(fut2, '1m',
                                       self.client.parse8601(thetime))

        ohlcv2 = []
        for o in ohlcv:
            ohlcv2.append([o[1], o[2], o[3], o[4], o[5]])
        df = pd.DataFrame(ohlcv2,
                          columns=['open', 'high', 'low', 'close', 'volume'])

        best_bids = []
        best_asks = []
        if 1 in self.directional:
            #print(df)
            try:
                self.dsrsi = TA.STOCHRSI(df).iloc[-1] * 100
            except:
                self.dsrsi = 50
            #print(self.dsrsi)
        # Get orderbook
        if 2 in self.volatility or 3 in self.price or 4 in self.quantity_switch:
            self.bands[fut2] = TA.BBANDS(df).iloc[-1]
            self.bbw[fut2] = (TA.BBWIDTH(df).iloc[-1])
            print(
                float(self.bands[fut2]['BB_UPPER'] -
                      self.bands[fut2]['BB_LOWER']))
            if (float(self.bands[fut2]['BB_UPPER'] -
                      self.bands[fut2]['BB_LOWER'])) > 0:
                deltab = (self.get_spot() - self.bands[fut2]['BB_LOWER']) / (
                    self.bands[fut2]['BB_UPPER'] -
                    self.bands[fut2]['BB_LOWER'])
                if deltab > 50:
                    self.diffdeltab[fut2] = (deltab - 50) / 100 + 1
                if deltab < 50:
                    self.diffdeltab[fut2] = (50 - deltab) / 100 + 1
            else:
                self.diffdeltab[fut2] = 25 / 100 + 1
        if 3 in self.volatility:
            self.atr[fut2] = TA.ATR(df).iloc[-1]

        if 0 in self.price:

            # Get orderbook
            if contract == 'BTC/USD':
                ob = self.ws['XBTUSD'].market_depth()
            else:
                ob = self.ws[contract].market_depth()
            #ob      = self.client.fetchOrderBook( contract )
            #print(ob)
            bids = []
            asks = []
            for o in ob:
                if o['side'] == 'Sell':
                    bids.append([o['price'], o['size']])
                else:
                    asks.append([o['price'], o['size']])

            if contract == 'BTC/USD':
                ords = self.ws['XBTUSD'].open_orders('')
            else:
                ords = self.ws[contract].open_orders('')
            #print(ords)
            bid_ords = [o for o in ords if o['side'] == 'Buy']
            ask_ords = [o for o in ords if o['side'] == 'Sell']
            best_bid = None
            best_ask = None

            err = 10**-(self.get_precision(contract) + 1)

            best_bid = 9999999999999999999
            for a in bids:
                if a[0] < best_bid:
                    best_bid = a[0]
            best_ask = 0
            for a in asks:
                if a[0] > best_ask:
                    best_ask = a[0]

            print({'bid': best_bid, 'ask': best_ask})
            best_asks.append(best_ask)
            best_bids.append(best_bid)
        if 1 in self.price:
            dvwap = TA.VWAP(df)
            #print(dvwap)
            tsz = self.get_ticksize(contract)
            try:
                bid = ticksize_floor(dvwap.iloc[-1], tsz)
                ask = ticksize_ceil(dvwap.iloc[-1], tsz)
            except:
                bid = ticksize_floor(self.get_spot(), tsz)
                ask = ticksize_ceil(self.get_spot(), tsz)

            print({'bid': bid, 'ask': ask})
            best_asks.append(best_ask)
            best_bids.append(best_bid)
        if 2 in self.quantity_switch:

            dppo = TA.PPO(df)
            self.buysellsignal[fut2] = 1
            try:
                if (dppo.iloc[-1].PPO > 0):
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 + PRICE_MOD)
                else:
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 - PRICE_MOD)

                if (dppo.iloc[-1].HISTO > 0):
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 + PRICE_MOD)
                else:
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 - PRICE_MOD)
                if (dppo.iloc[-1].SIGNAL > 0):
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 + PRICE_MOD)
                else:
                    self.buysellsignal[fut2] = self.buysellsignal[fut2] * (
                        1 - PRICE_MOD)
            except:
                self.buysellsignal[fut2] = 1

            #print({ 'bid': best_bid, 'ask': best_ask })
        return {
            'bid': self.cal_average(best_bids),
            'ask': self.cal_average(best_asks)
        }