Пример #1
0
class TempGonseRunner:
    # ! Will deprecate when kafka backend is done
    def __init__(self, *args):
        self.api_key = os.getenv("TDA_API_KEY")
        self.account_id = os.getenv("TDA_ACCOUNT_NUMBER")
        self.tda_client = None
        self.stream_client = None
        self.symbols = symbols
        self.queue = asyncio.Queue(1)
        self._consumers = *args

    def initialize(self):
        self.tda_client = easy_client(
            api_key=self.api_key,
            redirect_uri="http://localhost",
            token_path="/home/dkasabovn/Dev/python/ameritrade/token.pickle",
            webdriver_func=make_webdriver)
        self.stream_client = StreamClient(self.tda_client,
                                          account_id=self.account_id)

        self.stream_client.add_chart_equity_handler(self.handle_ohlc)

    async def stream(self):
        loop = asyncio.get_event_loop()
        signals = (SIGHUP, SIGTERM, SIGINT, SIGQUIT)
        for s in signals:
            loop.add_signal_handler(
                s, lambda s=s: asyncio.create_task(self.shutdown(s, loop)))

        await self.stream_client.login()
        await self.stream_client.quality_of_service(
            StreamClient.QOSLevel.EXPRESS)
        await self.stream_client.chart_equity_subs(self.symbols)

        asyncio.ensure_future(self.handle_queue())

        while True:
            await self.stream_client.handle_message()

    async def shutdown(self, signal, loop):
        tasks = [
            t for t in asyncio.all_tasks() if t is not asyncio.current_task()
        ]

        [task.cancel() for task in tasks]

        await asyncio.gather(*tasks)

        loop.stop()

    async def handle_ohlc(self, msg):
        if self.queue.full():
            await self.queue.get()
        await self.queue.put(msg)

    async def handle_queue(self):
        while True:
            msg = await self.queue.get()
            for update in msg["content"]:
                ticker = update["key"]
                self._consumers
Пример #2
0
class GonseProducer:
    def __init__(self, client, tickers):
        super().__init__()
        self._c = client
        self._p = KafkaProducer(
            bootstrap_servers='localhost:9092',
            api_version=(2, 0, 2),
            value_serializer=lambda x: json.dumps(x).encode('utf-8'))
        self._sc = None
        self.symbols = tickers
        self.account_id = os.getenv("TDA_ACCOUNT_NUMBER")
        self.queue = asyncio.Queue(1)

    def initialize(self):
        self._sc = StreamClient(self._c, account_id=self.account_id)
        self._sc.add_chart_equity_handler(self.handle_updates)

    async def stream(self):
        loop = asyncio.get_event_loop()
        signals = (SIGHUP, SIGTERM, SIGINT, SIGQUIT)
        for s in signals:
            loop.add_signal_handler(
                s, lambda s=s: asyncio.create_task(self.shutdown(s, loop)))

        await self._sc.login()
        await self._sc.quality_of_service(StreamClient.QOSLevel.EXPRESS)
        await self._sc.chart_equity_subs(self.symbols)

        while True:
            await self._sc.handle_message()
            sleep(1)
        self._p.flush()
        self._p.close()
        return

    async def shutdown(self, signal, loop):
        tasks = [
            t for t in asyncio.all_tasks() if t is not asyncio.current_task()
        ]

        [task.cancel() for task in tasks]
        await asyncio.gather(*tasks)
        loop.stop()

    async def test_produce(self):
        loop = asyncio.get_event_loop()
        signals = (SIGHUP, SIGTERM, SIGINT, SIGQUIT)
        for s in signals:
            loop.add_signal_handler(
                s, lambda s=s: asyncio.create_task(self.shutdown(s, loop)))

        while True:

            await self.handle_updates(
                {"content": [{
                    "key": "AAPL",
                    "data": "test"
                }]})
            print("Sent message")
            await asyncio.sleep(2)
        self._p.flush()
        self._p.close()
        return

    async def handle_updates(self, msg):
        for update in msg["content"]:
            ticker = update["key"]
            print(update)
            self._p.send(ticker, value=update)
class Bot():
    barsize = 1
    currentBar = Bar()
    bars = []
    client = ''
    account_id = 0
    accountSize = 10000
    firstTime = True
    inPosition = False
    #Common Indicators
    rsi = []
    vol = []
    ema50 = []
    ema200 = []
    min_vol = 99999999
    #Parameters
    risPeriod = 14
    stream_client = ''
    status = None
    initialbartime = datetime.datetime.now() #.astimezone(pytz.timezone())
    
    #Connect to TD Ameritrade
    def __init__(self):
        try:
            #Global variables
            API_KEY = '@AMER.OAUTHAP'               ### INSERT YOUR PRIVATE API KEY ###
            REDIRECT_URI = 'http://localhost:8080'  ### INSERT localhost address ###
            TOKEN_PATH = 'token.pickle'
            
            #New client
            self.client = tda.auth.easy_client(API_KEY,
                                              REDIRECT_URI,
                                              TOKEN_PATH,
                                              self.make_webdriver)
            
            #Account ID
            r = self.client.get_accounts()
            assert r.status_code == 200, r.raise_for_status()
            data = r.json()
            self.account_id = data[0]['securitiesAccount']['accountId']
            self.accountSize = data[0]['securitiesAccount']['currentBalances']['cashBalances']
            self.stream_client = StreamClient(self.client, account_id=self.account_id)
            print("You are logged in to your TD Ameritrade Account.")
            
            #Get symbol info
            self.symbol = input("Enter the ticker you want to trade : ")
            
            #Get candle stick
            self.barsize = int(input("Enter the barsize you want to trade in minutes : "))
            self.stream_client = StreamClient(self.client, account_id=self.account_id)
            #run program asynchronously
            asyncio.run(self.read_stream())
            
        except Exception as e:
            print(e)
    
    #Stream realtime updates
    async def read_stream(self):
        try:
            await self.stream_client.login()
            await self.stream_client.quality_of_services(StreamClient.QOSLevel.EXPRESS)
            await self.stream_client.chart_equity_subs([self.symbol])
            self.stream_client.add_chart_equity_handler(self.onBarUpdate)
            print("Streaming real-time date now.")
            while True:
                try:
                    await self.stream_client.handle_message()
                except Exception as e:
                    print(e)
        except Exception as e:
            print(e)
            
    #Update everytime there is a bar
    def OnBarUpdates(self, msg):
        try:
            msg = json.dumps(msg, indent=4)
            msg = json.loads(msn)
                
             #Retrieve Bar
            for bar in msg['content']:
                
                #Check The Strategy
                bartime = datetime.datetime.fromtimestamp(msg['timestamp'] / 1000) #.astimezone(pytz.timezone())
                minutes_diff = (bartime-self.initialbartime).total_seconds() / 60.0
                self.currentBar.date = bartime
                    
                #On Bar Close
                if (minutes_diff > 0 and math.floor(minutes_diff) % self.barsize == 0):
                    self.initialbartime = bartime
                    """
                    INSERT ENTRY AND EXIT STRATEGY
                    """
                    #Investment strategy based on RSI
                    #Calculate RSI
                    closes = []
                    for histbar in self.bars:
                        closes.append(histbar.close)
                    self.close_array = pd.Series(np.asarray(closes))
                    if len(self.bars) > 0:
                        #Calculate RSI on bar close
                        self.rsi  = ta.momentum.rsi(self.close_array, self.rsiPeriod, True)
                        #Print last rsi
                        print(self.rsi[len(self.rsi)-1])
                        """
                        If the rsi <= 30 and we are not in position, buy
                        If the rsi >= 70 and we are in position, sell
                        """    
                        if self.rsi[len(self.rsi)-1] <= 30 and not inPosition:
                            order = tda.orders.equities.equity_buy_market(self.symbol,1)
                            inPosition = True
                        if self.rsi[len(self.rsi)-1] >= 70 and inPosition:
                            order = tda.orders.equities.equity_sell_market(self.symbol,1)
                            inPosition = False       
                    """
                    ALTERNATIVE STRATEGY
                    """
                    #Investment strategy based on EMA
                    #Calculate ema50 and ema200 on bar close
#                     self.ema50 = ta.trend.EMAIndicator(self.close_array,50,True)
#                     self.ema200 = ta.trend.EMAIndicator(self.close_array,200,True)
                        """
                        If ema50 > ema200 and today's volume is > 7 bar volume min and we are not in position, buy
                        If price < ema50 and we are in position, sell
                        """
#                         if self.ema50[len(self.ema50)-1] > self.ema200[len(self.ema200)-1] \
#                         and self.currentBar.volume > self.min_vol and not inPosition:
#                             order = tda.orders.equities.equity_buy_market(self.symbol,1)
#                             inPosition = True
#                         if self.ema50[len(self.ema50)-1] <= self.ema200[len(self.ema200)-1] and inPosition:
#                             order = tda.orders.equities.equity_sell_market(self.symbol,1)
#                             inPosition = False

                    #Bar closed append
                    self.currentBar.close = bar['CLOSE_PRICE']
                    print("New bar!")
                    self.bars.append(self.currentBar)
                    self.currentBar = Bar()
                    self.currentBar.open = bar['OPEN_PRICE']
                    
                #Build realtime bar
                if self.currentBar.open == 0:
                    self.currentBar.open = bar['OPEN_PRICE']
                if self.currentBar.open == 0 or bar['HIGH_PRICE'] > self.currentBar.high:
                    self.currentBar.open = bar['HIGH_PRICE']
                if self.currentBar.open == 0 or bar['LOW_PRICE'] < self.currentBar.low:
                    self.currentBar.open = bar['LOW_PRICE']
                
                #Volume append
                self.currentBar.volume += bar['VOLUME']
                #Set minimum volume
                for bar in self.bars[-7:-1]:
                    if bar.volume < self.min_vol:
                        self.min_vol = bar.volume
                
        except Exception as e:
            print(e)
                
    #Connect to TD Ameritrade OAUTH Login
    def make_webdriver(self):
        #from selenium import webdriver here if slow to import
        driver = webdriver.Chrome(ChromeDriverManager().install())
        atexit.register(lambda: driver.quit())
        return driver