Example #1
0
def net_buy(custom_strategy):
    current_price = custom_strategy.exchange.get_instrument()['lastPrice']
    logger.info("[net_order][normal_buy] current_price(2) : " +
                str(current_price))
    default_Qty = settings.DEFAULT_ORDER_SIZE
    buy_level = math.ceil(settings.DEFAULT_ORDER_SPAN / 10)
    buy_orders = []

    # manual
    #current_price = 9400.0

    for i in range(1, buy_level + 1):
        for j in range(1, 21):
            #buy_orders.append({'price': current_price - ((j * 0.5) + (i - 1) * 10), 'orderQty': default_Qty * i, 'side': "Buy", 'execInst': "ParticipateDoNotInitiate"})
            buy_orders.append({
                'price':
                current_price - ((j * 1.5) + (i - 1) * 30),
                'orderQty':
                default_Qty * i,
                'side':
                "Buy",
                'execInst':
                "ParticipateDoNotInitiate"
            })

    ret = custom_strategy.converge_orders(buy_orders, [])
    logger.info("[net_order][normal_buy] order length : " + str(len(ret)))
    logger.info("[net_order][normal_buy] MAX_ORDER_QUENTITY : " +
                str(settings.MAX_ORDER_QUENTITY))

    singleton_data.getInstance().setAllowBuy(False)
    logger.info("[net_order][normal_buy] getAllowBuy() " +
                str(singleton_data.getInstance().getAllowBuy()))
Example #2
0
    def __init__(self, custom_strategy):
        logger.info("[BuyThread][run] __init__")
        threading.Thread.__init__(self)
        self.custom_strategy = custom_strategy
        singleton_data.getInstance().setAllowSell(False)
        singleton_data.getInstance().setBuyThread(True)

        # 70.0 *  2^n
        p = 2 ** int(singleton_data.getInstance().getAveDownCnt())
        self.averagingUpSize = settings.AVERAGING_UP_SIZE * p

        logger.info("[BuyThread][run] averagingUpSize : " + str(self.averagingUpSize))

        # default(20.0) * (current_quantity / max_order_quantity)
        # The maximum value is the default even if the quantity you have now is greater than max_order.
        # MAX = default(20.0)
        # The more net_buying orders, the higher the price.
        currentQty = self.custom_strategy.exchange.get_currentQty()
        logger.info("[BuyThread][run] MAX_ORDER_QUENTITY : " + str(settings.MAX_ORDER_QUENTITY))

        self.minBuyingGap = 3.0
        if abs(currentQty) > settings.MAX_ORDER_QUENTITY:
            self.minBuyingGap = self.minBuyingGap + settings.MIN_SELLING_GAP
        else :
            self.minBuyingGap = self.minBuyingGap + float(settings.MIN_SELLING_GAP) * float(abs(currentQty) / settings.MAX_ORDER_QUENTITY)

        logger.info("[BuyThread][run] minBuyingGap : " + str(self.minBuyingGap))

        self.waiting_buy_order = {}
        self.wait_cnt = 0
Example #3
0
    def __init__(self, custom_strategy, order_type):
        logger.info("[OrderThread][run] __init__")
        threading.Thread.__init__(self)
        self.custom_strategy = custom_strategy
        self.order_type = order_type
        self.lastClosePrice = self.custom_strategy.analysis_30m['Close']

        singleton_data.getInstance().setOrderThread(True)

        currentQty = self.custom_strategy.exchange.get_currentQty()
        logger.info("[OrderThread][run] currentQty : " + str(currentQty))

        self.waiting_order = {}
Example #4
0
    def check_sell_order(self, avgCostPrice):
        # checking whether or not it's sold
        ret = False

        sell_orders = self.custom_strategy.exchange.get_orders('Sell')
        logger.info("[SellThread][check_sell_order] sell_orders : " +
                    str(sell_orders))

        if len(sell_orders) == 0:
            # selling complete
            logger.info("[SellThread][check_sell_order] selling complete!")
            self.custom_strategy.exchange.cancel_all_orders('All')
            singleton_data.getInstance().setAveDownCnt(0)

            # expectedProfit 수정 필요
            #logger.info("[SellThread][check_sell_order] ######  profit : + " + str(self.expectedProfit) + "$  ######")
            #execute_logger.info("######  profit : + " + str(self.expectedProfit) + "$  ######")

            ret = True
            self.waiting_sell_order = {}

        elif len(sell_orders) == 1:
            current_price = self.custom_strategy.exchange.get_instrument(
            )['lastPrice']

            if not float(current_price) > float(avgCostPrice) + float(
                    self.minSellingGap):
                logger.info("[SellThread][check_sell_order] current_price(" +
                            str(current_price) + ") > avgCostPrice(" +
                            str(avgCostPrice) + ") + minSellingGap(" +
                            str(self.minSellingGap) + ")")
                self.waiting_sell_order = {}
                self.custom_strategy.exchange.cancel_all_orders('Sell')
                ret = False

            # 3.0 move to settings
            elif float(sell_orders[0]['price']) - float(current_price) > 3.0:
                # flee away 3$ form first oder_price, amend order
                # reorder
                self.waiting_sell_order = self.make_sell_order()
                logger.info(
                    "[SellThread][check_sell_order] reorder current_price - 3$ : waiting_sell_order : "
                    + str(self.waiting_sell_order))
            else:
                logger.info(
                    "[SellThread][check_sell_order] The price you ordered has not dropped by more than $ 3 from the current price."
                )

            logger.info("[SellThread][check_sell_order] not yet selling")

        return ret
Example #5
0
    def get_tradeBin(self, bidSize='1m'):
        update_required = False

        #logger.info("[ExchangeInterface][get_tradeBin1m]")

        if bidSize == '1m' or bidSize == '5m':
            bin_data = self.bitmex.get_trade_bin(bidSize)

        update_required = singleton_data.getInstance().appendOHLC_data(
            bin_data, bidSize)

        return update_required
Example #6
0
    def animate(self, i):
        #logger.info("[plotThread][animate] self.update_flag " + str(self.update_flag))

        if self.update_flag:
            sec_id = singleton_data.getInstance().getOHLC_data()

            sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index),
                                                 '1':sec_id.open,
                                                 '2':sec_id.close,
                                                 '3':sec_id.high,
                                                 '4':sec_id.low}))

            #logger.info("[plotThread][animate] sec_id_ochl " + str(sec_id_ochl))

            self.analysis = pd.DataFrame(index = sec_id.index)

            self.analysis['sma_f'] = sec_id.close.rolling(self.SMA_FAST).mean()
            self.analysis['sma_s'] = sec_id.close.rolling(self.SMA_SLOW).mean()
            self.analysis['rsi'] = ta.RSI(sec_id.close.to_numpy(), self.RSI_PERIOD)
            self.analysis['sma_r'] = self.analysis.rsi.rolling(self.RSI_PERIOD).mean()
            self.analysis['macd'], self.analysis['macdSignal'], self.analysis['macdHist'] = ta.MACD(sec_id.close.to_numpy(), fastperiod=self.MACD_FAST, slowperiod=self.MACD_SLOW, signalperiod=self.MACD_SIGNAL)
            self.analysis['stoch_k'], self.analysis['stoch_d'] = ta.STOCH(sec_id.high.to_numpy(), sec_id.low.to_numpy(), sec_id.close.to_numpy(), fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)#slowk_period=self.STOCH_K, slowd_period=self.STOCH_D)

            self.analysis['sma'] = np.where(self.analysis.sma_f > self.analysis.sma_s, 1, 0)

            # Plot candles width=.6/(24*60)
            candlestick(self.ax1, sec_id_ochl, width=.6/(24*60), colorup='g', colordown='r', alpha=1)

            # Draw Moving Averages
            self.analysis['sma_f'] = sec_id.close.rolling(self.SMA_FAST).mean()
            self.analysis['sma_s'] = sec_id.close.rolling(self.SMA_SLOW).mean()

            self.analysis.sma_f.plot(ax=self.ax1, c='r', linewidth=self.LINE_WIDTH)
            self.analysis.sma_s.plot(ax=self.ax1, c='g', linewidth=self.LINE_WIDTH)

            self.analysis.rsi.plot(ax = self.ax2, c='g', label = 'Period: ' + str(self.RSI_PERIOD), linewidth=self.LINE_WIDTH)
            self.analysis.sma_r.plot(ax = self.ax2, c='r', label = 'MA: ' + str(self.RSI_AVG_PERIOD), linewidth=self.LINE_WIDTH)

            self.analysis.macd.plot(ax=self.ax3, color='b', label='Macd', linewidth=self.LINE_WIDTH)
            self.analysis.macdSignal.plot(ax=self.ax3, color='g', label='Signal', linewidth=self.LINE_WIDTH)
            self.analysis.macdHist.plot(ax=self.ax3, color='r', label='Hist', linewidth=self.LINE_WIDTH)

            self.analysis.stoch_k.plot(ax=self.ax4, label='stoch_k:'+ str(self.STOCH_K), color='r', linewidth=self.LINE_WIDTH)
            self.analysis.stoch_d.plot(ax=self.ax4, label='stoch_d:'+ str(self.STOCH_D), color='g', linewidth=self.LINE_WIDTH)

            self.update_flag = False
Example #7
0
    def run(self):
        logger.info("[OrderThread][run]")

        while singleton_data.getInstance().getAllowOrder():
            try:
                # realized profit
                current_price = self.custom_strategy.exchange.get_instrument(
                )['lastPrice']
                avgCostPrice = self.custom_strategy.exchange.get_avgCostPrice()
                currentQty = self.custom_strategy.exchange.get_currentQty()

                logger.info("[OrderThread][run] current_price : " +
                            str(current_price) + ", avgCostPrice : " +
                            str(avgCostPrice) + ", currentQty : " +
                            str(currentQty))

                if len(self.waiting_order) == 0:
                    # ordering condition
                    self.waiting_order = self.make_order()
                    logger.info("[OrderThread][run] NEW : waiting_order : " +
                                str(self.waiting_order))

                #check ordering
                elif len(self.waiting_order) > 0:
                    if self.check_order():
                        singleton_data.getInstance().setAllowOrder(False)
                        break

                else:
                    logger.info("[OrderThread][run] len(waiting_order) : " +
                                str(len(self.waiting_order)))
                    logger.info("[OrderThread][run] waiting_order : " +
                                str(self.waiting_order))

                sleep(1)
            except Exception as ex:
                self.PrintException()
                break

            sleep(1)

        # Cancel all orders
        self.custom_strategy.exchange.cancel_all_orders('All')
        singleton_data.getInstance().setAllowOrder(True)
        singleton_data.getInstance().setOrderThread(False)
        singleton_data.instance().setSwitchMode(False)
Example #8
0
    def run(self):
        logger.info("[BuyThread][run]")

        while not singleton_data.getInstance().getAllowBuy():
            try:
                # realized profit
                current_price = self.custom_strategy.exchange.get_instrument()['lastPrice']
                avgCostPrice = self.custom_strategy.exchange.get_avgCostPrice()
                currentQty = self.custom_strategy.exchange.get_currentQty()

                logger.info("[BuyThread][run] current_price : " + str(current_price) + ", avgCostPrice : " + str(avgCostPrice) + ", currentQty : " + str(currentQty))

                if len(self.waiting_buy_order) == 0:
                    # buying condition
                    if float(current_price) < float(avgCostPrice) - float(self.minBuyingGap):
                        logger.info("[BuyThread][run] current_price(" + str(current_price) +") < avgCostPrice(" + str(avgCostPrice) + ") - minBuyingGap(" + str(self.minBuyingGap) + ")")

                        self.waiting_buy_order = self.make_buy_order()
                        logger.info("[BuyThread][run] NEW : waiting_buy_order : " + str(self.waiting_buy_order))

                    # waiting (default:120) secs condition
                    elif float(current_price) < float(avgCostPrice):
                        self.wait_cnt += 1

                        if self.wait_cnt > settings.SELLING_WAIT:
                            logger.info("[BuyThread][run] stop buying thread because cnt < " + str(settings.SELLING_WAIT))
                            logger.info("[BuyThread][run] wait_cnt : " + str(self.wait_cnt))
                            logger.info("[BuyThread][run] current_price : " + str(current_price) + ", avgCostPrice : " + str(avgCostPrice) + ", currentQty : " + str(currentQty))

                            break

                    # exit buy thread
                    else :
                        # check Additional buying #
                        # even though buying in not allow,
                        # ave_price largger that cur_price + averagingUpSize(default : 50$), making ave_down
                        #logger.info("[BuyThread][run] current_price + averagingUpSize < avgCostPrice : " + str(float(current_price) + float(self.averagingUpSize) < float(avgCostPrice)))
                        if float(current_price) > float(avgCostPrice) + float(self.averagingUpSize):

                            buy_orders = self.custom_strategy.exchange.get_orders('Buy')
                            if len(buy_orders) > 0:
                                logger.info("[BuyThread][run] Additional selling fail because remaining buy orders : " + str(buy_orders))

                            else :
                                logger.info("[BuyThread][run] ##### Additional Selling #####")
                                logger.info("[BuyThread][run] current_price > avgCostPrice + + averagingUpSize(" + str(self.averagingUpSize) + ")")
                                logger.info("[BuyThread][run] current_price : " + str(current_price) + ", avgCostPrice : " + str(avgCostPrice))

                                aveCnt = singleton_data.getInstance().getAveDownCnt() + 1
                                singleton_data.getInstance().setAveDownCnt(aveCnt)
                                logger.info("[BuyThread][run] aveCnt : " + str(aveCnt))

                                singleton_data.getInstance().setAllowSell(True)

                        else :
                            logger.info("[BuyThread][run] Not yet additional buying")

                        break

                #check buying order
                elif len(self.waiting_buy_order) > 0:
                    if self.check_buy_order(avgCostPrice):
                        singleton_data.getInstance().setAllowSell(True)
                        break

                else :
                    logger.info("[BuyThread][run] len(waiting_buy_order) : " + str(len(self.waiting_buy_order)))
                    logger.info("[BuyThread][run] waiting_buy_order : " + str(self.waiting_buy_order))

                sleep(1)
            except Exception as ex:
                self.PrintException()
                break

            logger.info("[BuyThread][run] wait_cnt : " + str(self.wait_cnt))
            sleep(1)

        # Cancel all buy orders
        try:
            self.custom_strategy.exchange.cancel_all_orders('Buy')
        except Exception as ex:
            self.PrintException()
        finally:
            singleton_data.getInstance().setBuyThread(False)
Example #9
0
    def run(self):
        logger.info("[bitmex_plot][run]")

        sec_id = singleton_data.getInstance().getOHLC_data()

        self.sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index),#.to_pydatetime()),
                                             '1':sec_id.open,
                                             '2':sec_id.close,
                                             '3':sec_id.high,
                                             '4':sec_id.low}))


        #self.analysis.Date.dt.tz_localize('UTC')
        self.analysis = analysis.get_analysis(False)

        # Prepare plot
        self.fig, (self.ax1, self.ax2, self.ax3, self.ax4) = plt.subplots(4, 1, sharex=True)
        self.ax1.set_ylabel(ticker, size=20)

        self.ax1.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M:%S'))

        #size plot
        self.fig.set_size_inches(15,30)

        # Plot candles width=.6/(24*60)
        candlestick(self.ax1, self.sec_id_ochl, width=.6/(24*60), colorup='g', colordown='r', alpha=1)

        # Draw Moving Averages
        self.analysis.sma_f.plot(ax=self.ax1, c='r', linewidth=self.LINE_WIDTH)
        self.analysis.sma_s.plot(ax=self.ax1, c='g', linewidth=self.LINE_WIDTH)
        handles, labels = self.ax1.get_legend_handles_labels()
        self.ax1.legend(handles, labels)


        #RSI
        self.ax2.set_ylabel('RSI', size=self.Y_AXIS_SIZE)
        self.analysis.rsi.plot(ax = self.ax2, c='g', label = 'Period: ' + str(self.RSI_PERIOD), linewidth=self.LINE_WIDTH)
        self.analysis.sma_r.plot(ax = self.ax2, c='r', label = 'MA: ' + str(self.RSI_AVG_PERIOD), linewidth=self.LINE_WIDTH)
        self.ax2.axhline(y=30, c='b', linewidth=self.LINE_WIDTH)
        #self.ax2.axhline(y=50, c='black', linewidth=self.LINE_WIDTH)
        self.ax2.axhline(y=70, c='b', linewidth=self.LINE_WIDTH)
        self.ax2.set_ylim([0,100])
        handles, labels = self.ax2.get_legend_handles_labels()
        self.ax2.legend(handles, labels)

        # Draw MACD computed with Talib
        self.ax3.set_ylabel('MACD: '+ str(self.MACD_FAST) + ', ' + str(self.MACD_SLOW) + ', ' + str(self.MACD_SIGNAL), size=self.Y_AXIS_SIZE)
        self.analysis.macd.plot(ax=self.ax3, color='b', label='Macd', linewidth=self.LINE_WIDTH)
        self.analysis.macdSignal.plot(ax=self.ax3, color='g', label='Signal', linewidth=self.LINE_WIDTH)
        self.analysis.macdHist.plot(ax=self.ax3, color='r', label='Hist', linewidth=self.LINE_WIDTH)
        self.ax3.axhline(0, lw=2, color='0', linewidth=self.LINE_WIDTH)
        handles, labels = self.ax3.get_legend_handles_labels()
        self.ax3.legend(handles, labels)

        # Stochastic plot
        self.ax4.set_ylabel('Stoch (k,d)', size=self.Y_AXIS_SIZE)
        self.analysis.stoch_k.plot(ax=self.ax4, label='stoch_k:'+ str(self.STOCH_K), color='r', linewidth=self.LINE_WIDTH)
        self.analysis.stoch_d.plot(ax=self.ax4, label='stoch_d:'+ str(self.STOCH_D), color='g', linewidth=self.LINE_WIDTH)
        handles, labels = self.ax4.get_legend_handles_labels()
        self.ax4.legend(handles, labels)
        self.ax4.axhline(y=20, c='b', linewidth=self.LINE_WIDTH)
        self.ax4.axhline(y=50, c='black', linewidth=self.LINE_WIDTH)
        self.ax4.axhline(y=80, c='b', linewidth=self.LINE_WIDTH)

        self.ani = animation.FuncAnimation(self.fig, self.animate, interval=5000)

        plt.show()
Example #10
0
def get_analysis(getOnlyLast=False, bidSize='1m'):
    sec_id = None

    if bidSize == '1m':
        sec_id = singleton_data.getInstance().getOHLC_1m_data()
    elif bidSize == '5m':
        sec_id = singleton_data.getInstance().getOHLC_5m_data()
    elif bidSize == '30m':
        bin5m_data = singleton_data.getInstance().getOHLC_5m_data()

        first_idx, last_idx = trim_30m(bin5m_data)

        logger.info("[get_analysis] len(bin5m_data) " + str(len(bin5m_data)))

        temp_list = []
        for i in range(first_idx, last_idx + 1):
            if not i % 6 == first_idx:
                continue

            temp_map = {}
            temp_map['trades'] = 0
            temp_map['volume'] = 0
            temp_map['high'] = bin5m_data['high'][i]
            temp_map['low'] = bin5m_data['low'][i]
            temp_map['timestamp'] = bin5m_data['timestamp'][i]
            temp_map['symbol'] = bin5m_data['symbol'][i]
            temp_map['open'] = bin5m_data['open'][i]
            temp_map['close'] = bin5m_data['close'][i + 5]

            for j in range(i, i + 6):
                if temp_map['high'] < bin5m_data['high'][j]:
                    temp_map['high'] = bin5m_data['high'][j]

                if temp_map['low'] > bin5m_data['low'][j]:
                    temp_map['low'] = bin5m_data['low'][j]

                temp_map[
                    'trades'] = temp_map['trades'] + bin5m_data['trades'][j]
                temp_map['volume'] = bin5m_data['volume'][i] + bin5m_data[
                    'volume'][j]

            temp_list.append(temp_map)

        cnt = int((last_idx + 1 - first_idx) / 6)

        df = pd.DataFrame(
            {
                'timestamp':
                [temp_list[i]['timestamp'] for i in range(0, cnt)],
                'symbol': [temp_list[i]['symbol'] for i in range(0, cnt)],
                'open': [temp_list[i]['open'] for i in range(0, cnt)],
                'high': [temp_list[i]['high'] for i in range(0, cnt)],
                'low': [temp_list[i]['low'] for i in range(0, cnt)],
                'close': [temp_list[i]['close'] for i in range(0, cnt)],
                'trades': [temp_list[i]['trades'] for i in range(0, cnt)],
                'volume': [temp_list[i]['volume'] for i in range(0, cnt)],
            },
            index=pd.to_datetime(
                [temp_list[i]['timestamp'] for i in range(0, cnt)]))

        sec_id = df

    #analysis = pd.DataFrame(index = date2num(sec_id.index))
    analysis = pd.DataFrame()

    ret = []
    analysis['timestamp'] = sec_id.timestamp
    analysis['Open'] = sec_id.open.to_numpy()
    analysis['High'] = sec_id.high.to_numpy()
    analysis['Low'] = sec_id.low.to_numpy()
    analysis['Close'] = sec_id.close.to_numpy()

    analysis = getSuperTrend(analysis, 2, 16)

    #analysis['sma_f'] = sec_id.close.rolling(SMA_FAST).mean()
    #analysis['sma_s'] = sec_id.close.rolling(SMA_SLOW).mean()
    analysis['rsi'] = ta.RSI(sec_id.close.to_numpy(), RSI_PERIOD)
    #analysis['sma_r'] = analysis.rsi.rolling(RSI_PERIOD).mean()
    #analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = ta.MACD(sec_id.close.to_numpy(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL)
    analysis['stoch_k'], analysis['stoch_d'] = ta.STOCH(
        sec_id.high.to_numpy(),
        sec_id.low.to_numpy(),
        sec_id.close.to_numpy(),
        fastk_period=5,
        slowk_period=3,
        slowk_matype=0,
        slowd_period=3,
        slowd_matype=0)  #slowk_period=self.STOCH_K, slowd_period=self.STOCH_D)
    #analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)

    ret = analysis

    if (getOnlyLast):
        ret = analysis.iloc[-1:]

    return ret