Exemplo n.º 1
0
def handle_open_sell_orders(brokerage, journal, trades_db):
    trades = trades_db.get_trades_being_sold()

    for trade in trades:
        order = brokerage.get_order(trade.sell_order_id)

        if order is None:
            logging.error(
                f'Brokerage API failed to return an order. (Order ID: {trade.sell_order_id})'
            )
            continue

        # Remove the price record from the state database and mark the sale as complete based on status
        if order.status == 'canceled':
            logging.critical(
                f'{trade.ticker}: Trade sell order {trade.create_date} canceled. (Order ID: {order.order_id})'
            )
            trade = trades_db.cancel_sale(trade)
            journal.update_trade_record(trade)
        elif order.status == 'expired':
            logging.critical(
                f'{trade.ticker}: Trade sell order {trade.create_date} expired. (Order ID: {order.order_id})'
            )
            trade = trades_db.expire_sale(trade)
            journal.update_trade_record(trade)
        elif order.status == 'filled':
            logging.critical(
                f'{trade.ticker}: Trade sell order {trade.create_date} filled at {order.sale_price}. (Order ID: {order.order_id})'
            )
            trade = trades_db.close(trade, order.sale_price)
            journal.update_trade_record(trade,
                                        sale_metadata=json.dumps(
                                            ta.analyze(trade.ticker,
                                                       brokerage)))
        elif order.status == 'replaced':
            logging.critical(
                f'{trade.ticker}: Trade sell order {trade.create_date} replaced. (Order ID: {order.order_id})'
            )
            trade = trades_db.replace_sale(trade, order.replacement_order_id)
            journal.update_trade_record(trade)
Exemplo n.º 2
0
def create(ticker, entry, exit, stop_loss, expiration, sell_at_end_of_day,
           notes):
    j = trade_journal.TradeJournal(configuration.TRADE_JOURNAL_TITLE)
    j.bootstrap()
    b = brokerage.Brokerage(True, configuration.ALPACA_KEY_ID,
                            configuration.ALPACA_SECRET_KEY,
                            configuration.DATA_FOLDER)
    t = trade.Trade(datetime.timestamp(datetime.now()), ticker, 0.0, 0.0, 0.0,
                    exit, entry, stop_loss, 0.0, 0.0, 'QUEUED', '', '', 'long',
                    0, expiration, sell_at_end_of_day)
    metadata = json.dumps(technical_analysis.analyze(ticker, b))

    count = 0
    for row in j.journal[0].getRows():
        if row[0] != '':
            count += 1
        else:
            break

    j.create_queued_trade(count + 1, ticker, 'long', entry, exit, stop_loss,
                          notes, expiration, metadata, sell_at_end_of_day)
    print("Trade Created.")
Exemplo n.º 3
0
def handle_open_buy_orders(brokerage, trades_db, s):
    trades = trades_db.get_trades_being_bought()

    for trade in trades:
        order = brokerage.get_order(trade.buy_order_id)

        if order is None:
            logging.error(
                f'Brokerage API failed to return an order. (Order ID: {trade.buy_order_id})'
            )
            continue

        # Remove the price record from the state database and mark the purchase as complete based on status
        if order.status == 'canceled':
            logging.critical(
                f'{trade.ticker}: Trade buy order {trade.create_date} canceled. (Order ID: {order.order_id})'
            )
            trades_db.cancel(trade.create_date)
            s.remove_buy_price_marker(trade.ticker, trade.id)
        elif order.status == 'expired':
            logging.critical(
                f'{trade.ticker}: Trade buy order {trade.create_date} expired. (Order ID: {order.order_id})'
            )
            trades_db.expire(trade.create_date)
            s.remove_buy_price_marker(trade.ticker, trade.id)
        elif order.status == 'filled':
            logging.critical(
                f'{trade.ticker}: Trade buy order {trade.create_date} filled at {order.sale_price}. (Order ID: {order.order_id})'
            )
            trades_db.open(trade.create_date, order.shares, order.sale_price,
                           json.dumps(ta.analyze(trade.ticker, brokerage)))
            s.remove_buy_price_marker(trade.ticker, trade.id)
        elif order.status == 'replaced':
            logging.critical(
                f'{trade.ticker}: Trade buy order {trade.create_date} replaced. (Order ID: {order.order_id})'
            )
            trades_db.replace_buy(trade.create_date,
                                  order.replacement_order_id)
            s.remove_buy_price_marker(trade.ticker, trade.id)
Exemplo n.º 4
0
def screen(ticker):
    stock_profiles = []

    print('Fetching profile...')
    stock_profiles.append(
        stockprofile.build_profile(ticker, configuration.DATA_FOLDER))

    # Add description and bid ask prices
    profile = alphaadvanage.add_description_to_profile(
        stock_profiles[0], ticker, configuration.ALPHA_API,
        configuration.DATA_FOLDER)

    print('Fetching analyst feed...')
    price_analysis = stockprofile.get_analyst_feed(ticker,
                                                   configuration.DATA_FOLDER)

    print('Fetching news feed...')
    news = stockprofile.get_news_feed(ticker, configuration.DATA_FOLDER)

    print('Processing news feed...')
    rendered_news = stockprofile.parse_news(news)
    stockprofile.build_bar_charts(
        news, configuration.DATA_FOLDER + 'news-sentiment.png')

    print('Fetching technical analysis...')
    b = brokerage.Brokerage(True, configuration.ALPACA_KEY_ID,
                            configuration.ALPACA_SECRET_KEY,
                            configuration.DATA_FOLDER)
    tech = technical_analysis.analyze(ticker, b)

    print('Fetching Stock Twits...')
    twits = stocktwits.get_messages(ticker, configuration.DATA_FOLDER)

    print('Processing Stock Twits...')
    rendered_twits = stocktwits.process_messages(twits)

    print('Fetching and processing competitors...')
    stock_profiles.extend(
        competitors.build_competitors_list(stock_profiles[0]['industry'],
                                           ticker, configuration.DATA_FOLDER))

    print('Building quarterly finacials chart...')
    alphaadvanage.create_quarterly_financials_chart(
        ticker, configuration.DATA_FOLDER + 'quarterly-reports.png',
        configuration.ALPHA_API, configuration.DATA_FOLDER)

    print('Building report...')

    # Rednder the html template with all the data
    rendered_html = template.get('screener.html').render(
        ticker=ticker,
        stocks=stock_profiles,
        news=rendered_news,
        price_analysis=price_analysis,
        twits=rendered_twits,
        tech=tech)
    rendered_html.encode('utf8')

    # Add the html file to data folder
    with open(configuration.DATA_FOLDER + 'screener.html',
              'w',
              encoding='utf8') as file:
        file.write(rendered_html)

    # Open the html file using the default web browser
    webbrowser.open(configuration.DATA_FOLDER + 'screener.html', new=2)