Beispiel #1
0
    def ListOpenTrades(self, trades):
        for trade in self.openTrades:

            trade.update({
                'Price':
                getattr(ccxt, trade['Exchange'].lower())().fetch_ticker(
                    languageHandler(output_lang="TradeModule",
                                    inputs=[trade['Symbol']],
                                    input_lang=trade['Exchange'])[0])['last']
            })
            if trade['Clip_Size'] < 0:
                trade.update({
                    'R_Return':
                    1 - (trade['Price'] / (trade['Order_Price']))
                })
                trade.update({'R_PnL': trade['R_Return'] * trade['USD']})
                trade.update({'USD': -trade['USD']})
            else:
                trade.update(
                    {'R_Return': (trade['Price'] / trade['Order_Price']) - 1})
                trade.update({'R_PnL': trade['R_Return'] * trade['USD']})

        # self.Open_Trades= pd.DataFrame(openTrades).set_index('Symbol')
        self.Open_Trades = self.openTrades
        for trade in self.Open_Trades:
            print(trade)
        print(self.Open_Trades)
    def WebSocketFunction(self, kline):
        '''
		This is the callback function for the Websocket - Each message that is pushed through is passed to this function and received as the "kline" variable 
		'''
        # print(kline)
        if self.startup == 1:
            time.sleep(4)
        else:
            if self.exchange == 'binance':
                dfName = languageHandler(output_lang="TradeModule",
                                         inputs=[kline.market],
                                         input_lang=kline.exchange)[0] + '_df'
            elif self.exchange == 'bitmex':
                dfName = 'BTC/USD_df'
            candleData = {
                'Time': int(kline.openTime),
                'Low': kline.kLow,
                'High': kline.kHigh,
                'Close': kline.kClose,
                'Open': kline.kOpen,
                'Volume': kline.kVolume,
                'Period': 1
            }

            if getattr(self, dfName)[-1:][0]['Time'] == candleData['Time']:
                setattr(self, dfName, getattr(self, dfName)[:-1])
                getattr(self, dfName).append(candleData)
            else:
                getattr(self, dfName).append(candleData)
                setattr(self, dfName, getattr(self, dfName)[1:])
                y = self.p
                for candle in getattr(self, dfName):
                    candle.update({'Period': y})
                    y = y - 1
            df = pd.DataFrame(getattr(self, dfName))
            df = df.set_index('Period')
            if self.exchange == 'bitmex' and kline.ccxt_data == 1:
                self.ccxt_data = 1
            else:
                self.ccxt_data = 0

            #-- CONFLUENCE SETTINGS UPDATE ---------------------------------------------------------------
            confSet = os.path.getmtime(self.confSetPath)
            if confSet != self.confSetMod:
                self.confSet = pd.read_excel(self.confSetPath, index_col=0)
                self.confSetMod = os.path.getmtime(self.confSetPath)
                self.log('\nConfluence Settings Updated: \n%s' %
                         (self.confSet))
            # print(df)
            self.Conditions(df=df, market=kline.market)
def Close_Trades(openTrades, pkg):
    limiter = pkg['Trade_Limiter']
    logReturn = []
    sql_log = 0
    tradestatus = 0  #Has to be outside of the loop as we only need to know if a trade has occured
    if len(openTrades) > 0:
        for trade in openTrades:
            closegatewayresult = 0
            closeQuery = 0
            if trade['Market'] == pkg['Market'] and trade['Strategy'] == pkg[
                    'Strategy']:
                print('  ! Open Trade Reviewed: %s' % (trade['Market']))
                #LIMITATION: The Trade Check only refers to the same strategy timeperiod... i.e. the 4h confluence cannot affect the 1d trades
                if pkg['CR'] < 50 and trade['ClipSize'] > 0:
                    closeOtype = 'market-sell'
                    closeOtype = closeOtype + pkg['Testing']
                    closeQuery = 1
                    closeMethod = 'CR'

                if pkg['CR'] > -50 and trade['ClipSize'] < 0:
                    closeOtype = 'market-buy'
                    closeOtype = closeOtype + pkg['Testing']
                    closeQuery = 1
                    closeMethod = 'CR'

                if pkg['Price'] <= trade['Stop_Level'] and trade[
                        'ClipSize'] > 0:
                    closeOtype = 'market-sell'
                    closeOtype = closeOtype + pkg['Testing']
                    closeQuery = 1
                    closeMethod = 'Stop_Loss'

                if pkg['Price'] >= trade['Stop_Level'] and trade[
                        'ClipSize'] < 0:
                    closeOtype = 'market-buy'
                    closeOtype = closeOtype + pkg['Testing']
                    closeQuery = 1
                    closeMethod = 'Stop_Loss'

                if pkg['Price'] >= trade['Profit_Level'] and trade[
                        'ClipSize'] > 0:
                    closeOtype = 'market-sell'
                    closeOtype = closeOtype + pkg['Testing']
                    closeQuery = 1
                    closeMethod = 'Profit_Take'

                if pkg['Price'] <= trade['Profit_Level'] and trade[
                        'ClipSize'] < 0:
                    closeOtype = 'market-buy'
                    closeOtype = closeOtype + pkg['Testing']
                    closeQuery = 1
                    closeMethod = 'Profit_Take'

                if time.time() < limiter:
                    closeQuery = 0
                    closegatewayresult = (
                        'FAILED-- Trade Rate Limiter Exceeded')

                if closeQuery == 1:
                    try:
                        TC = TradeClient(exchange=pkg['Exchange'].lower(),
                                         market=languageHandler(
                                             output_lang="TradeModule",
                                             inputs=[pkg['Market']],
                                             input_lang=pkg['Exchange'])[0],
                                         clipSize=abs(trade['ClipSize']),
                                         orderPrice=0.00000001,
                                         orderType=closeOtype)
                        sql_log = [
                            'Close',
                            (trade['UUID'], trade['Open_Time'], TC.tPrice,
                             trade['OrderPrice'], trade['ClipSize'], TC.oid,
                             closeMethod)
                        ]

                        trade.update({'Market': 'Closed'})
                        trade.update({'ClipSize': 0})
                        closegatewayresult = (
                            f"Trade Closed-- {trade['UUID']}")
                        tradestatus = 1
                        limiter = time.time() + pkg['Limiter_Rate']

                    except Exception as error_result:
                        closegatewayresult = f"FAILED-- attempt to close Trade[{trade['UUID']}]: {error_result}"

                if closegatewayresult != 0:
                    logReturn.append(closegatewayresult)

    return {
        'Log': logReturn,
        'Trade_Status': tradestatus,
        'Trade_Limiter': limiter,
        'SQL': sql_log
    }
def Open_Trade(refracList, openTrades, pkg, tpkg):
    print('  ! New Trade Reviewed: %s' % (pkg['Market']))
    limiter = pkg['Trade_Limiter']
    logReturn = []
    eligible = 1
    sql_log = 0
    tradestatus = 0
    if len(refracList) > 0:
        for datum in refracList:
            if datum['Market'] == pkg['Market'] and datum['Strategy'] == pkg[
                    'Strategy'] and time.time() < datum['Epoch']:
                eligible = 0
                gatewayresult = ('FAILED-- %s_%s within refractory period' %
                                 (pkg['Market'], pkg['Strategy']))
    if len(openTrades) > 0:
        symboltotal = 0
        opentotal = 0
        for datum in openTrades:
            if datum['Market'] == pkg['Market'] and datum['Strategy'] == pkg[
                    'Strategy']:
                symboltotal = symboltotal + datum['USD_Value']
            opentotal = opentotal + datum['USD_Value']
        if symboltotal >= tpkg['MaxPair']:

            eligible = 0
            gatewayresult = (
                'FAILED-- Total open %s_%s trades (%.1f) exceeds restriction (%.1f)'
                %
                (pkg['Market'], pkg['Strategy'], symboltotal, tpkg['MaxPair']))
        if opentotal >= tpkg['MaxOpen']:
            eligible = 0
            gatewayresult = (
                'FAILED-- Total open trades (%.1f) exceeds restriction (%.1f)'
                % (opentotal, tpkg['MaxOpen']))
    if pkg['Market'][-4:] != 'USDT' and pkg['Exchange'] == 'Binance':
        eligible = 0
        gatewayresult = (
            'FAILED-- Pair not USDT pair and not recognised by clipSize_USD calculator'
        )

    if pkg['Market'][-3:] != 'USD' and pkg['Exchange'] == 'Bitmex':
        eligible = 0
        gatewayresult = (
            'FAILED-- Pair not USD on Bitmex therefore not supported by clipSize_USD calculator'
        )

    if time.time() < limiter:
        eligible = 0
        gatewayresult = ('FAILED-- Trade Rate Limiter Exceeded')

    if eligible == 1:
        try:
            if pkg['Exchange'] == 'Binance':
                clipSize = (tpkg['usdClipSize'] / pkg['Price'])
            elif pkg['Exchange'] == 'Bitmex':
                clipSize = tpkg['usdClipSize']
            if pkg['Side'] == 'buy':
                oType = 'market-buy'
                oType = oType + pkg['Testing']
            elif pkg['Side'] == 'sell':
                oType = 'market-sell'
                oType = oType + pkg['Testing']
                clipSize = clipSize * -1

            TC = TradeClient(exchange=pkg['Exchange'].lower(),
                             market=languageHandler(
                                 output_lang="TradeModule",
                                 inputs=[pkg['Market']],
                                 input_lang=pkg['Exchange'])[0],
                             clipSize=abs(clipSize),
                             orderPrice=0.00000001,
                             orderType=oType)

            pkg.update({'clipSize': clipSize})
            pkg.update({'Exchange_UUID': TC.oid})
            pkg.update({'tPrice': TC.tPrice})
            if pkg['Exchange'] == 'Binance':
                pkg.update({
                    'USD': (abs(float(pkg['Price']) * float(clipSize)))
                })  #TESTING LINE
            elif pkg['Exchange'] == 'Bitmex':
                pkg.update({'USD': clipSize})

            #pkg.update({'USD':(abs(float(TC.tPrice)*float(clipSize)))})
            sql_log = ['Open', (pkg, tpkg['CR'], tpkg['CF'])]
            gatewayresult = ('SUCCESS-- Trade Sent (Trade OID: %s)' % (TC.oid))

            limiter = time.time() + pkg['Limiter_Rate']
            tradestatus = 1

        except Exception as error_result:
            gatewayresult = ('FAILED attempt to send trade: %s' %
                             (error_result))

    logReturn.append(gatewayresult)
    print('tradestatus', tradestatus)
    return {
        'Log': logReturn,
        'Trade_Status': tradestatus,
        'Trade_Limiter': limiter,
        'SQL': sql_log
    }
    def __init__(self, exchange, logFileName, TimeFrame, ticker_fetch):
        #-- INTRINSIC ---------------------------------------------------------------
        localpath = os.getcwd() + '//'

        ### Logging
        self.logger = logging.getLogger(name="Full")
        #hdlr = logging.FileHandler(str(os.path.dirname(__file__)) +'\\' + logFileName)
        hdlr = logging.FileHandler(localpath + logFileName)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        self.logger.setLevel('INFO')

        self.log('loaded')
        #self.TimeFrame=sys.argv[1]
        self.cortex_version = 4.0
        self.exchange = exchange
        self.TimeFrame = TimeFrame
        self.sc = SlackClient(keychain.slack.TradeAlertApp('BotUser'))
        self.sc_read = SlackClient(keychain.slack.TradeAlertApp('OAuth'))

        #-- TESTING ---------------------------------------------------------------
        testing = 0
        if testing == 1:
            self.testSwitch = '-test'
            self.log('###----------- TESTING MODE -----------###')
        elif testing == 0:
            self.testSwitch = ''

        #-- THREAD MANAGEMENT ----------------------------------------------------------------
        self.threads = {}
        q = Queue()
        self.threads.update({'SQLT': SQL_Thread(q)})
        self.threads['SQLT'].start()

        #-- EXTRINSIC ---------------------------------------------------------------
        self.Profit_Take = 0.02
        self.Stop_Loss = 0.01
        self.ccxt_data = 0
        self.data = {}
        self.startup = 1
        self.trades = {}
        self.tradeRateLimiter = 0
        self.maxTradeRate = 2  #1 trade every [self.maxTradeRate] seconds
        self.p = 131
        self.confSetPath = localpath + 'confluenceValues.xlsx'
        self.confSet = pd.read_excel(self.confSetPath, index_col=0)
        self.databasepath = localpath + 'tradelog.db'
        self.confSetMod = os.path.getmtime(self.confSetPath)
        self.dbModTime = os.path.getmtime(self.databasepath)
        temp_uuid = str(uuid4())
        self.threads['SQLT'].queue.put(['openTrades', temp_uuid])
        self.threads['SQLT'].queue.join()
        self.openTradeList = getattr(self.threads['SQLT'], temp_uuid)
        print(self.openTradeList)
        temp_uuid_2 = str(uuid4())
        self.threads['SQLT'].queue.put(['refracFetch', temp_uuid_2])
        self.threads['SQLT'].queue.join()
        self.refractoryList = getattr(self.threads['SQLT'], temp_uuid_2)
        print(self.refractoryList)
        self.lastPrice = {}
        self.timeUpdate = time.time()

        #-- MARKET MANAGEMENT ---------------------------------------------------------------
        #ticker_fetch=getattr(ccxt,exchange)().fetch_tickers()

        ####### Acceptable Markets for supported exchanges ###########################
        binance_markets = [
            'BTC/USDT', 'ETH/USDT', 'NEO/USDT', 'ADA/USDT', 'XRP/USDT'
        ]
        bitmex_markets = ['BTC/USD']
        bitmex_timeframes = ['1m', '1d', '1h']
        ##############################################################################

        self.market_jar = []

        #-- BINANCE WEBSOCKET MANAGEMENT ----------------------------------------------------
        if exchange == 'binance':
            print('Entered binance loop')
            impass = 0
            for market in ticker_fetch:
                if market not in binance_markets:
                    self.log(f'{market} -NOT SUPPORTED BY- {exchange}')
                    impass = 1
            if impass == 0:
                for market in ticker_fetch:
                    if market[-3:] != 'USD':
                        self.market_jar.append(market)
                        toParse = [market]
                        parsedMarket = languageHandler(
                            output_lang=exchange.capitalize(),
                            inputs=toParse,
                            input_lang="TradeModule")
                        setattr(self, parsedMarket[0], {})
                        #self.data.update({parsedMarket[0]:None})
                        MSname = parsedMarket[0] + '_MS'
                        setattr(self, MSname, 'Unknown')
                        #print(market)

                callbacks = [self.WebSocketFunction]
                bnStream(self.market_jar, self.TimeFrame, callbacks)
                self.FetchPast(exchange)

        #-- BITMEX WEBSOCKET MANAGEMENT -------------------------------------------------------
        elif exchange == 'bitmex':
            impass = 0
            for market in ticker_fetch:
                if market not in bitmex_markets:
                    self.log(f'{market} -NOT SUPPORTED BY- {exchange}')
                    impass = 1
            if len(ticker_fetch) > 1:
                self.log('Bitmex function can only support one market')
                impass = 1
            if self.TimeFrame not in bitmex_timeframes:
                self.log(
                    f'\n\nTimeFrame not supported yet-- supported timeframes: {bitmex_timeframes}\n\n'
                )
                impass = 1
            if impass == 0:
                self.market_jar = ticker_fetch
                try:
                    self.FetchPast(exchange)
                except Exception as e:
                    self.log(f'FetchPast Failed-- {e}')
                    impass = 1
            if impass == 0:
                print('Start WebSocketFunction')
                bmi = bitmex_interface(market=ticker_fetch[0],
                                       tf=self.TimeFrame,
                                       funk=self.WebSocketFunction)
                bmi.start()

        else:
            print('')
            self.log('-- EXCHANGE NOT SUPPORTED --')