Example #1
0
def twitter_callback(text, link):
    """Analyzes Trump tweets, makes stock trades, and sends tweet alerts."""

    # Initialize these here to create separate httplib2 instances per thread.
    analysis = Analysis(logs_to_cloud=LOGS_TO_CLOUD)
    trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)

    companies = analysis.find_companies(text)
    logs.debug("Using companies: %s" % companies)
    if companies:
        trading.make_trades(companies)
        twitter.tweet(companies, link)
Example #2
0
def twitter_callback(tweet):
    """Analyzes Trump tweets, makes stock trades, and sends tweet alerts."""

    # Initialize these here to create separate httplib2 instances per thread.
    analysis = Analysis(logs_to_cloud=LOGS_TO_CLOUD)
    trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)

    companies = analysis.find_companies(tweet)
    logs.debug("Using companies: %s" % companies)
    if companies:
        trading.make_trades(companies)
        twitter.tweet(companies, tweet)
Example #3
0
def runDefaultCandleTrading(transaction_name,
                            instrument,
                            strategy,
                            localTrading=False):
    from ticker.latestoandacandle import LastOandaCandleTicker
    from trading import Trading
    from transaction.mssql import MSSQLTransaction
    if localTrading:
        from executor.backtester import BacktestExecutor
        executor = BacktestExecutor()
    else:
        from executor.oandamssql import OandaMSSQLExecutor
        executor = OandaMSSQLExecutor(transaction_name)
    ticker = LastOandaCandleTicker(instrument)
    tran = MSSQLTransaction(transaction_name)
    trading = Trading()
    portofolio, plotelements = trading.run(ticker, executor, strategy, tran)
    return portofolio, plotelements
Example #4
0
    def twitter_callback(self, tweet):
        """Analyzes Trump tweets, trades stocks, and tweets about it."""

        # Initialize the Analysis, Logs, Trading, and Twitter instances inside
        # the callback to create separate httplib2 instances per thread.
        analysis = Analysis(logs_to_cloud=LOGS_TO_CLOUD)
        logs = Logs(name="main-callback", to_cloud=LOGS_TO_CLOUD)

        # Analyze the tweet.
        companies = analysis.find_companies(tweet)
        logs.debug("Using companies: %s" % companies)
        if not companies:
            return

        # Trade stocks.
        trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)
        trading.make_trades(companies)

        # Tweet about it.
        twitter = Twitter(logs_to_cloud=LOGS_TO_CLOUD)
        twitter.tweet(companies, tweet)
Example #5
0
    def twitter_callback(self, tweet):
        """Analyzes Trump tweets, trades stocks, and tweets about it."""

        # Initialize the Analysis, Logs, Trading, and Twitter instances inside
        # the callback to create separate httplib2 instances per thread.
        analysis = Analysis(logs_to_cloud=LOGS_TO_CLOUD)
        logs = Logs(name="main-callback", to_cloud=LOGS_TO_CLOUD)

        # Analyze the tweet.
        companies = analysis.find_companies(tweet)
        logs.info("Using companies: %s" % companies)
        if not companies:
            return

        # Trade stocks.
        trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)
        trading.make_trades(companies)

        # Tweet about it.
        twitter = Twitter(logs_to_cloud=LOGS_TO_CLOUD)
        twitter.tweet(companies, tweet)
Example #6
0
def trading():
    return Trading(logs_to_cloud=False)
Example #7
0
        return False

    # The strategy needs to be active.
    if strategy["action"] == "hold":
        return False

    # We need to know the stock price.
    if not strategy["price_at"] or not strategy["price_eod"]:
        return False

    return True


if __name__ == "__main__":
    analysis = Analysis(logs_to_cloud=False)
    trading = Trading(logs_to_cloud=False)
    twitter = Twitter(logs_to_cloud=False)

    # Look up the metadata for the tweets.
    tweets = twitter.get_tweets(SINCE_TWEET_ID)

    events = []
    for tweet in tqdm(tweets):
        event = {}

        timestamp_str = tweet["created_at"]
        timestamp = trading.utc_to_market_time(
            datetime.strptime(timestamp_str, "%a %b %d %H:%M:%S +0000 %Y"))
        text = twitter.get_tweet_text(tweet)
        event["timestamp"] = timestamp
        event["text"] = text
Example #8
0
        return False

    # The strategy needs to be active.
    if strategy["action"] == "hold":
        return False

    # We need to know the stock price.
    if not strategy["price_at"] or not strategy["price_eod"]:
        return False

    return True


if __name__ == "__main__":
    analysis = Analysis(logs_to_cloud=False)
    trading = Trading(logs_to_cloud=False)
    twitter = Twitter(logs_to_cloud=False)

    # Look up the metadata for the tweets.
    tweets = twitter.get_tweets(SINCE_TWEET_ID)

    events = []
    for tweet in tqdm(tweets):
        event = {}

        timestamp_str = tweet["created_at"]
        timestamp = trading.utc_to_market_time(datetime.strptime(
            timestamp_str, "%a %b %d %H:%M:%S +0000 %Y"))
        text = twitter.get_tweet_text(tweet)
        event["timestamp"] = timestamp
        event["text"] = text
Example #9
0
def close_all_positions():
    trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)
    trading.close_out_all_positions()
    s.enter(300, 1, close_all_positions, ())
Example #10
0
def main(argv):
    """
    Main
    """
    TOKEN = os.environ['telegram_token']
    CHAT_ID = os.environ['telegram_chat_id']
    initial_pip = float(os.environ['initial_pip'])
    html_template_path = "./assets/email/email_template.html"

    tz_MX = pytz.timezone('America/Mexico_City')
    datetime_MX = dt.now(tz_MX)

    hora_now = f'{datetime_MX.strftime("%H:%M:%S")}'

    parser = argparse.ArgumentParser(description='Apollo V 0.1 Beta')

    parser.add_argument('-o',
                        '--order',
                        action='store_true',
                        help='Determine if you want to make an order')
    parser.add_argument('-t',
                        '--time',
                        action='store_true',
                        help='Make order only if market is open')
    parser.add_argument('-m',
                        '--model-version',
                        help='Model version folder simple name')
    parser.add_argument('-i', '--instrument', help='instrument to trade')
    parser.add_argument('-a', '--account', help='suffix of account to trade')
    parser.add_argument('-s',
                        '--save',
                        action='store_true',
                        help='saves the predictions made')

    args = parser.parse_args()
    make_order = args.order or False
    market_sensitive = args.time or False
    model_version = args.model_version
    instrument = args.instrument
    account = args.account
    save_preds = args.save or False
    trading = Trading(model_version, instrument)
    op_buy, op_sell, original_dataset = trading.predict()
    previous_low_bid = str(
        original_dataset[2]['USD_JPY_lowBid'].iloc[-2].round(3))
    previous_high_ask = str(
        original_dataset[2]['USD_JPY_highAsk'].iloc[-2].round(3))

    logging.info(f'\nMarket sensitive: {market_sensitive}')
    if market_sensitive and not market_open():
        logging.info('Market Closed')
        open_trades = openTrades(account)
        current_pips = open_trades.get_pips_traded()
        current_trades = open_trades.get_all_trades()
        check_stop_loss(current_trades, account)
        return

    # Hacer decisón para la posición
    decision = Decide(op_buy,
                      op_sell,
                      100000,
                      direction=0,
                      pips=initial_pip,
                      take_profit=0)
    decision.get_all_pips()
    units = decision.pips * decision.direction * 1000

    # máximo de unidades en riesgo al mismo tiempo

    pip_limit = float(os.environ['pip_limit'])
    open_trades = openTrades(account)
    current_pips = open_trades.get_pips_traded()
    current_trades = open_trades.get_all_trades()

    logging.info(f'Current units: {current_pips}')
    logging.info(f'Max units: {pip_limit}')
    logging.info(f'Units: {units}')

    # si queremos hacer una operación (units puede ser positivo o negativo)
    if units != 0:
        if current_pips < pip_limit:  # vemos si aún podemos hacer operaciones
            # escogemos lo que podamos operar sin pasarnos del límite.
            # el mínimo entre la unidades solicitadas o las disponibles
            units = min(abs(units), pip_limit - current_pips) * \
                decision.direction
            if units == 0.0:  # si encontramos que ya no hay
                decision.decision += '\n*Units limit exceeded. Order not placed.'
        else:  # si ya hemos excedido operaciones
            units = 0.0
            decision.decision += '\n*Units limit exceeded. Order not placed.'

    inv_instrument = 'USD_JPY'
    take_profit = decision.take_profit
    op_buy_new = decision.data_buy
    op_sell_new = decision.data_sell

    logging.info(f'inv_instrument: {inv_instrument}')
    logging.info(f'take_profit: {take_profit}')

    logging.info(f'\n{decision.decision}')
    # Pone orden a precio de mercado
    logging.info(
        f'Units: {units}, inv_instrument: {inv_instrument} , take_profit: {take_profit}\n'
    )

    if make_order and units != 0:
        new_trade = Trade(inv_instrument, units, take_profit=take_profit)
        new_order = Order(new_trade, account)
        new_order.make_market_order()
        previous_low_bid += f' ({new_order.bid_price})'
        previous_high_ask += f' ({new_order.ask_price})'
        end = timer()
        speed_time = end - start
        logging.info('Apollo time to market: ' + str(end - start))
        if save_preds:
            logging.info(
                '\n\n************* Saving predictions in Data Base **************'
            )
            save_order(account, model_version, inv_instrument, new_order,
                       decision.probability)
            logging.info(
                f'\n\n************* Saving dataset in Data Base **************'
            )
            save_input(account,
                       model_version,
                       hora_now,
                       inv_instrument,
                       original_dataset,
                       order_id=new_order.i_d)
    else:
        end = timer()
        speed_time = end - start
        logging.info(f'Apollo prediction time: {str(speed_time)} s')
        logging.info(
            f'\n\n************* Saving dataset in Data Base **************')
        save_input(account, model_version, hora_now, inv_instrument,
                   original_dataset)

    logging.info('\n\n ************* Checando trades activos  **************')
    check_stop_loss(current_trades, account)

    logging.info(f'\nPrevious High Ask:{previous_high_ask}')
    logging.info(op_buy_new)
    logging.info(f'\nPrevious Low Bid: {previous_low_bid}')
    logging.info(op_sell_new)

    # send telegram
    _, html_path = create_html([
        op_buy, op_sell, previous_high_ask, previous_low_bid,
        f'{model_version}'
    ], html_template_path)
    _, image_name = from_html_to_jpg(html_path)
    logging.info('Sending predictions to Telegram')
    bot = telegram_bot(TOKEN)
    bot.send_message(
        CHAT_ID, f"Predictions for the hour: {hora_now} ({model_version})")
    bot.send_photo(CHAT_ID, image_name)
    bot.send_message(
        CHAT_ID,
        f"Best course of action ({model_version}): {decision.decision}\nApollo speed:{str(round(speed_time,3))}s"
    )

    logging.info(f'Apollo prediction time: {str(speed_time)} s')
Example #11
0
def getStockDataBySheet(excelProxy, sheet):
    #from easyExcel import EasyExcel
    #import os,sys
    #root = os.path.abspath(os.path.dirname(sys.argv[0]))
    #print '*******root path*****',root
    #path = root +'\\test.xls'
    #excelProxy = EasyExcel(path)
    #print excelProxy.getSheets()
    #sheet = "2"
    print "***********Excel Sheet******", sheet
    line = 2
    while True:
        if excelProxy.getCell(sheet, line, 1) is None:
            break
        else:
            line = line + 1
    print "***********Overall trading count******", line - 2

    content = excelProxy.getRange(sheet, 2, 1, line - 1, 5)
    #print content
    sum = 0
    revenue = 0
    #trading history
    directory = dict()

    from trading import Trading

    for line in content:
        #print line
        code = line[1]
        #print code
        volume = int(int(line[2]) * float(line[3]))
        #print type(volume)
        #print volume
        tempRev = 0
        if (line[4] != None):
            tempRev = int(line[4])
            revenue += tempRev
        trade = Trading(code, 1, abs(volume), tempRev)
        if code not in directory:
            #trade = Trading(code,1,abs(volume),0)
            #directory[code] = abs(volume)
            directory[code] = trade
        else:
            temp = directory[code]
            #print '**********'+str(trade.volume)
            #print '**********'+str(temp.volume)
            trade.add(temp.volume, temp.revenue)
            #trade.count += 1
            #trade.volume += abs(volume)
            #temp = directory[code]
            #directory[code] = abs(volume)+temp
            directory[code] = trade
        #print volume
        sum += abs(volume)

    #print sum
    #print revenue
    #directory["total"] = sum

    #print directory
    #for trade in directory.values():
    #print trade

    #print len(directory)
    print "************Sum Column*********", sum
    print "************revenue************", revenue

    #directory['sum'] = sum
    #close the Excel file
    #excelProxy.close()
    return directory