예제 #1
0
    def testRanOutOfCoins(self):
        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.errors = 0
                self.bought = False

            def onBars(self, bars):
                if not self.bought:
                    self.limitOrder("BTC", 100, 0.1)
                    self.bought = True
                else:
                    try:
                        self.limitOrder("BTC", 100, -0.1)
                    except Exception:
                        self.errors += 1

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 10)

        brk = broker.PaperTradingBroker(10.05, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertEquals(strat.errors, 1)
        self.assertEquals(brk.getShares("BTC"), 0)
        self.assertEquals(brk.getCash(), 10)
def main():
    # Go to http://dev.twitter.com and create an app.
    # The consumer key and secret will be generated for you after that.
    consumer_key = "<YOUR-CONSUMER-KEY-HERE>"
    consumer_secret = "<YOUR-CONSUMER-SECRET-HERE>"

    # After the step above, you will be redirected to your app's page.
    # Create an access token under the the "Your access token" section
    access_token = "<YOUR-ACCESS-TOKEN-HERE>"
    access_token_secret = "<YOUR-ACCESS-TOKEN-SECRET-HERE>"

    # Create a twitter feed to track BitCoin related events.
    track = ["bitcoin", "btc", "mtgox", "bitstamp", "xapo"]
    follow = []
    languages = ["en"]
    twitterFeed = twitterfeed.TwitterFeed(consumer_key, consumer_secret,
                                          access_token, access_token_secret,
                                          track, follow, languages)

    cli = client.Client()
    barFeed = barfeed.LiveTradeFeed(cli)
    brk = broker.PaperTradingBroker(1000, barFeed)
    strat = Strategy(cli, barFeed, brk, twitterFeed)

    # It is VERY important to add these to the event dispatch loop before running the strategy.
    strat.getDispatcher().addSubject(cli)
    strat.getDispatcher().addSubject(twitterFeed)

    strat.run()
예제 #3
0
    def testBuyWithoutCash(self):
        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.errors = 0

            def onBars(self, bars):
                try:
                    self.limitOrder("BTC", 10, 1)
                except Exception:
                    self.errors += 1

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 101, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 0.2)

        brk = broker.PaperTradingBroker(0, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertEquals(strat.errors, 4)
        self.assertEquals(brk.getShares("BTC"), 0)
        self.assertEquals(brk.getCash(), 0)
예제 #4
0
    def testBuyAndSellWithPartialFill2(self):

        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.pos = None

            def onBars(self, bars):
                if self.pos is None:
                    self.pos = self.enterLongLimit("BTC", 100, 1, True)
                elif bars.getDateTime() == datetime.datetime(2000, 1, 3):
                    self.pos.exitLimit(101)

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 101, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 0.2)
        barFeed.addTrade(datetime.datetime(2000, 1, 4), 1, 100, 0.2)
        barFeed.addTrade(datetime.datetime(2000, 1, 5), 1, 101, 0.2)
        barFeed.addTrade(datetime.datetime(2000, 1, 6), 1, 102, 5)

        brk = broker.PaperTradingBroker(1000, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertFalse(strat.pos.isOpen())
        self.assertEquals(strat.pos.getShares(), 0)
        self.assertEquals(len(strat.posExecutionInfo), 2)
        self.assertEquals(strat.pos.getEntryOrder().getSubmitDateTime().date(), wsclient.get_current_datetime().date())
        self.assertEquals(strat.pos.getExitOrder().getSubmitDateTime().date(), wsclient.get_current_datetime().date())
예제 #5
0
    def testRanOutOfCoins(self):
        tc = self

        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.errors = 0
                self.bought = False

            def onBars(self, bars):
                if not self.bought:
                    self.limitOrder(INSTRUMENT, 100, 0.5)
                    self.bought = True
                elif self.getBroker().getBalance(SYMBOL) > 0:
                    self.limitOrder(INSTRUMENT, 100,
                                    -self.getBroker().getBalance(SYMBOL))
                else:
                    with tc.assertRaisesRegexp(Exception, "Not enough BTC"):
                        self.limitOrder(INSTRUMENT, 100, -1)
                    self.errors += 1

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 10)

        brk = broker.PaperTradingBroker({PRICE_CURRENCY: 50.5}, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertEqual(strat.errors, 1)
        self.assertEqual(brk.getBalance(SYMBOL), 0)
        self.assertEqual(brk.getBalance(PRICE_CURRENCY), 50)
예제 #6
0
    def testBuyWithoutCash(self):
        tc = self

        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.errors = 0

            def onBars(self, bars):
                with tc.assertRaisesRegexp(Exception, "Not enough USD"):
                    self.limitOrder(INSTRUMENT, 10, 3)
                self.errors += 1

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 101, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 0.2)

        brk = broker.PaperTradingBroker({PRICE_CURRENCY: 0}, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertEqual(strat.errors, 4)
        self.assertEqual(brk.getBalance(SYMBOL), 0)
        self.assertEqual(brk.getBalance(PRICE_CURRENCY), 0)
예제 #7
0
    def testRanOutOfCash(self):
        tc = self

        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.errors = 0

            def onBars(self, bars):
                # The first order should work, the rest should fail.
                if self.getBroker().getBalance(PRICE_CURRENCY):
                    self.limitOrder(INSTRUMENT, 100, 0.3)
                else:
                    with tc.assertRaisesRegexp(Exception, "Not enough USD"):
                        self.limitOrder(INSTRUMENT, 100, 0.3)
                    self.errors += 1

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 10)

        brk = broker.PaperTradingBroker({PRICE_CURRENCY: 30.15}, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertEqual(strat.errors, 2)
        self.assertEqual(brk.getBalance(SYMBOL), 0.3)
        self.assertEqual(brk.getBalance(PRICE_CURRENCY), 0)
예제 #8
0
    def testBuyAndSellWithPartialFill1(self):
        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.pos = None

            def onBars(self, bars):
                if self.pos is None:
                    self.pos = self.enterLongLimit(INSTRUMENT, 100, 1, True)
                elif bars.getDateTime() == dt.as_utc(
                        datetime.datetime(2000, 1, 3)):
                    self.pos.exitLimit(101)

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 0.1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 101, 10)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 0.2)
        barFeed.addTrade(datetime.datetime(2000, 1, 4), 1, 100, 0.2)
        barFeed.addTrade(datetime.datetime(2000, 1, 5), 1, 101, 0.2)

        brk = broker.PaperTradingBroker({PRICE_CURRENCY: 1000}, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertTrue(strat.pos.isOpen())
        self.assertEqual(round(strat.pos.getShares(), 3), 0.1)
        self.assertEqual(len(strat.posExecutionInfo), 1)
        self.assertEqual(strat.pos.getEntryOrder().getSubmitDateTime().date(),
                         datetime.datetime.now().date())
        self.assertEqual(strat.pos.getExitOrder().getSubmitDateTime().date(),
                         datetime.datetime.now().date())
예제 #9
0
    def testBuyAndSellWithPartialFill1(self):
        class Strategy(TestStrategy):
            def __init__(self, cli, feed, brk):
                TestStrategy.__init__(self, cli, feed, brk)
                self.pos = None

            def onBars(self, bars):
                if self.pos is None:
                    self.pos = self.enterLongLimit("BTC", 100, 1, True)
                elif bars.getDateTime() == datetime.datetime(2000, 1, 3):
                    self.pos.exit(limitPrice=101)

        cli = MockClient()
        cli.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 0.1)
        cli.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 0.1)
        cli.addTrade(datetime.datetime(2000, 1, 2), 1, 101, 10)
        cli.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 0.2)
        cli.addTrade(datetime.datetime(2000, 1, 4), 1, 100, 0.2)
        cli.addTrade(datetime.datetime(2000, 1, 5), 1, 101, 0.2)

        barFeed = barfeed.LiveTradeFeed(cli)
        brk = broker.PaperTradingBroker(1000, barFeed)
        strat = Strategy(cli, barFeed, brk)

        strat.getDispatcher().addSubject(cli)
        strat.run()

        self.assertTrue(strat.pos.isOpen())
        self.assertEqual(round(strat.pos.getShares(), 3), 0.1)
        self.assertEqual(len(strat.posExecutionInfo), 1)
        self.assertEqual(strat.pos.getEntryOrder().getSubmitDateTime().date(),
                         wsclient.get_current_datetime().date())
        self.assertEqual(strat.pos.getExitOrder().getSubmitDateTime().date(),
                         wsclient.get_current_datetime().date())
예제 #10
0
def main():
    cli = client.Client()
    barFeed = barfeed.LiveTradeFeed(cli)
    brk = broker.PaperTradingBroker(1000, barFeed)
    strat = Strategy(cli, barFeed, brk)

    # It is VERY important to add the client to the event dispatch loop before running the strategy.
    strat.getDispatcher().addSubject(cli)
    strat.run()
예제 #11
0
 def testInvalidOrders(self):
     barFeed = TestingLiveTradeFeed()
     brk = broker.PaperTradingBroker(1000, barFeed)
     with self.assertRaises(Exception):
         brk.createLimitOrder(basebroker.Order.Action.BUY, "none", 1, 1)
     with self.assertRaises(Exception):
         brk.createLimitOrder(basebroker.Order.Action.SELL_SHORT, "none", 1, 1)
     with self.assertRaises(Exception):
         brk.createMarketOrder(basebroker.Order.Action.BUY, "none", 1)
     with self.assertRaises(Exception):
         brk.createStopOrder(basebroker.Order.Action.BUY, "none", 1, 1)
     with self.assertRaises(Exception):
         brk.createStopLimitOrder(basebroker.Order.Action.BUY, "none", 1, 1, 1)
예제 #12
0
    def testRoundingBugWithTrades(self):
        # Unless proper rounding is in place 0.01 - 0.00441376 - 0.00445547 - 0.00113077 == 6.50521303491e-19
        # instead of 0.

        class Strategy(TestStrategy):
            def __init__(self, cli, feed, brk):
                TestStrategy.__init__(self, cli, feed, brk)
                self.pos = None

            def onBars(self, bars):
                if self.pos is None:
                    self.pos = self.enterLongLimit("BTC", 100, 0.01, True)
                elif self.pos.entryFilled() and not self.pos.getExitOrder():
                    self.pos.exitLimit(100, True)

        cli = MockClient()
        cli.addTrade(datetime.datetime(2000, 1, 1), 1, 100, 1)
        cli.addTrade(datetime.datetime(2000, 1, 2), 1, 100, 0.01)
        cli.addTrade(datetime.datetime(2000, 1, 3), 1, 100, 0.00441376)
        cli.addTrade(datetime.datetime(2000, 1, 4), 1, 100, 0.00445547)
        cli.addTrade(datetime.datetime(2000, 1, 5), 1, 100, 0.00113077)

        barFeed = barfeed.LiveTradeFeed(cli)
        brk = broker.PaperTradingBroker(1000, barFeed)
        strat = Strategy(cli, barFeed, brk)

        strat.getDispatcher().addSubject(cli)
        strat.run()

        self.assertEqual(brk.getShares("BTC"), 0)
        self.assertEqual(strat.pos.getEntryOrder().getAvgFillPrice(), 100)
        self.assertEqual(strat.pos.getExitOrder().getAvgFillPrice(), 100)
        self.assertEqual(strat.pos.getEntryOrder().getFilled(), 0.01)
        self.assertEqual(strat.pos.getExitOrder().getFilled(), 0.01)
        self.assertEqual(strat.pos.getEntryOrder().getRemaining(), 0)
        self.assertEqual(strat.pos.getExitOrder().getRemaining(), 0)
        self.assertEqual(strat.pos.getEntryOrder().getSubmitDateTime().date(),
                         wsclient.get_current_datetime().date())
        self.assertEqual(strat.pos.getExitOrder().getSubmitDateTime().date(),
                         wsclient.get_current_datetime().date())

        self.assertFalse(strat.pos.isOpen())
        self.assertEqual(len(strat.posExecutionInfo), 2)
        self.assertEqual(strat.pos.getShares(), 0.0)
예제 #13
0
    def testRoundingBugWithTrades(self):
        # Unless proper rounding is in place 0.03 - 0.01441376 - 0.01445547 - 0.00113077 == 6.50521303491e-19
        # instead of 0.

        class Strategy(TestStrategy):
            def __init__(self, feed, brk):
                TestStrategy.__init__(self, feed, brk)
                self.pos = None

            def onBars(self, bars):
                if self.pos is None:
                    self.pos = self.enterLongLimit(INSTRUMENT, 1000, 0.03,
                                                   True)
                elif self.pos.entryFilled() and not self.pos.getExitOrder():
                    self.pos.exitLimit(1000, True)

        barFeed = TestingLiveTradeFeed()
        barFeed.addTrade(datetime.datetime(2000, 1, 1), 1, 1000, 1)
        barFeed.addTrade(datetime.datetime(2000, 1, 2), 1, 1000, 0.03)
        barFeed.addTrade(datetime.datetime(2000, 1, 3), 1, 1000, 0.01441376)
        barFeed.addTrade(datetime.datetime(2000, 1, 4), 1, 1000, 0.01445547)
        barFeed.addTrade(datetime.datetime(2000, 1, 5), 1, 1000, 0.00113077)

        brk = broker.PaperTradingBroker({PRICE_CURRENCY: 1000}, barFeed)
        strat = Strategy(barFeed, brk)
        strat.run()

        self.assertEqual(brk.getBalance(SYMBOL), 0)
        self.assertEqual(strat.pos.getEntryOrder().getAvgFillPrice(), 1000)
        self.assertEqual(strat.pos.getExitOrder().getAvgFillPrice(), 1000)
        self.assertEqual(strat.pos.getEntryOrder().getFilled(), 0.03)
        self.assertEqual(strat.pos.getExitOrder().getFilled(), 0.03)
        self.assertEqual(strat.pos.getEntryOrder().getRemaining(), 0)
        self.assertEqual(strat.pos.getExitOrder().getRemaining(), 0)
        self.assertEqual(strat.pos.getEntryOrder().getSubmitDateTime().date(),
                         datetime.datetime.now().date())
        self.assertEqual(strat.pos.getExitOrder().getSubmitDateTime().date(),
                         datetime.datetime.now().date())

        self.assertFalse(strat.pos.isOpen())
        self.assertEqual(len(strat.posExecutionInfo), 2)
        self.assertEqual(strat.pos.getShares(), 0.0)
def paper_trade(history=HISTORY):
    """
    Live (paper) trade with RL Trader on Bitstamp,
    with best_model params from backtesting simulations
    :return: Update DB every on every Buy/Sell event
    """
    start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:00:00')
    actions = ['Buy', 'Sell', 'Hold']
    ncoins = 0.0
    bars = barfeed.LiveTradeFeed()
    brk = broker.PaperTradingBroker(INITIAL_CASH, bars)

    engine, con = make_con(db_name="trader")
    sql = "SELECT * FROM rl_backtesting ORDER BY Datetime DESC LIMIT 1"
    latest_simulation = pd.read_sql(sql,
                                    con=con,
                                    parse_dates=True,
                                    index_col='Datetime')
    best_model = latest_simulation['Best model index'].iloc[0]
    RLstrat = RLTraderPaperTrade(bars, brk, actions, history, INITIAL_CASH,
                                 ncoins, best_model, start_time)

    RLstrat.run()
예제 #15
0
def main():
    barFeed = barfeed.LiveTradeFeed()
    brk = broker.PaperTradingBroker(1000, barFeed)
    strat = Strategy(barFeed, brk)

    strat.run()
예제 #16
0
def main():

    config = ConfigParser.ConfigParser()
    config.read('bot.cfg')

    # Create BitStamp feed
    barFeed = barfeed.LiveTradeFeed()

    # cash
    # bars = BitStamp live feed
    # fee = 0.5 % per order
    cash = int(config.get('main', 'cash'))
    brk = broker.PaperTradingBroker(cash, barFeed)

    strat = Strategy(barFeed, brk)

    # Attach the strategy analyzers
    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)
    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawDownAnalyzer)

    try:
        strat.run()

        #Cool down
        time.sleep(5)

        # Collect the analysis results
        fin_port_val = strat.getResult()
        cum_ret = retAnalyzer.getCumulativeReturns()[-1] * 100
        stratReturns = tradesAnalyzer.getAllReturns()
        return_avg = stratReturns.mean() * 100
        return_std = stratReturns.std() * 100
        return_min = stratReturns.min() * 100
        return_max = stratReturns.max() * 100
        sharpe_ratio = sharpeRatioAnalyzer.getSharpeRatio(0.05)
        max_drawdown = drawDownAnalyzer.getMaxDrawDown() * 100
        longest_drawdown_duration = drawDownAnalyzer.getLongestDrawDownDuration(
        )

        #fin_port_val = 0
        #cum_ret = 0
        #return_avg = 0
        #return_std = 0
        #return_min = 0
        #return_max = 0
        #sharpe_ratio = 0
        #max_drawdown = 0
        #longest_drawdown_duration = 0

        params = urllib.urlencode({
            'op':
            'LOG_RETURNS',
            'strategyid':
            strat.getStrategyUUID(),
            'fin_port_val':
            fin_port_val,
            'cum_returns':
            cum_ret,
            'return_avg':
            return_avg,
            'return_std':
            return_std,
            'return_min':
            return_min,
            'return_max':
            return_max,
            'sharpe_ratio':
            sharpe_ratio,
            'max_drawdown':
            max_drawdown,
            'longest_drawdown_duration':
            longest_drawdown_duration
        })

        # Post the returns analysis results
        strat.postRecord(params)

    except:
        strat.info("An exception has occurred during final shutdown.")
        strat.info(traceback.print_exc())
        params = urllib.urlencode({
            'op':
            'LOG_ENTRY',
            'msg':
            "An exception has occurred during final shutdown: " +
            traceback.format_exc(),
            'engine':
            strat.getEngine(),
            'strategyid':
            strat.getStrategyUUID()
        })
        strat.postRecord(params)
        pass

    time.sleep(5)

    command = "sudo /sbin/reboot"
    subprocess.call(command, shell=True)