Ejemplo n.º 1
0
    def run(cls, stdcsr):
        """Returns: void
        This is the main program loop.
        """
        # initialize user interface
        cls._curses_init(stdcsr)

        # Read in existing trades
        while not cls.stopped and cls.recover_trades() == None:
            Log.write('"daemon.py" run(): Recovering trades...')
            cls._curses_refresh(stdcsr)

        # logging
        if Config.live_trading:
            Log.write('"daemon.py" start(): Using live account.')
        else:
            Log.write('"daemon.py" start(): Using practice mode.')

        """
        Main loop:
        1. Gather opportunities from each strategy.
        2. Decide which opportunities to execute.
        3. Clear the opportunity list.
        """
        while not cls.stopped:
            # refresh user interface
            cls._curses_refresh(stdcsr)

            # Let each strategy suggest an order
            for s in cls.strategies:
                new_opp = s.refresh()
                if new_opp == None:
                    Log.write('daemon.py run(): {} has nothing to offer now.'
                        .format(s.get_name()))
                    pass
                else:
                    cls.opportunities.push(new_opp)
        
            # Decide which opportunity (or opportunities) to execute
            Log.write('"daemon.py" run(): Picking best opportunity...')
            best_opp = cls.opportunities.pick()
            if best_opp == None:
                # Nothing is being suggested.
                pass
            else:
                # An order was suggested by a strategy, so place the order.
                #   Don't use all the money available.
                SLIPPAGE_WIGGLE = 0.95
                ###available_money = Broker.get_margin_available(Config.account_id) * SLIPPAGE_WIGGLE
                available_money = 100 # USD - testing
                #   Get the current price of one unit.
                instrument_price = 0
                Log.write('best opp: {}'.format(best_opp))
                go_long = best_opp.order.units > 0
                if go_long:
                    instrument_price = Broker.get_ask(best_opp.order.instrument)
                else:
                    instrument_price = Broker.get_bid(best_opp.order.instrument)
                #   How much leverage available:
                margin_rate = Broker.get_margin_rate(best_opp.order.instrument) 
                #   TODO: A bit awkward, but overwrite the existing value that was used to 
                #   determine long/short.
                units = available_money
                units /= cls.num_strategies_with_no_positions() # save money for other strategies
                units /= margin_rate
                units = int(units) # floor
                if units <= 0: # verify
                    Log.write('daemon.py run(): units <= 0')
                    raise Exception # abort
                if not go_long: # negative means short
                    units = -units
                best_opp.order.units = units
                Log.write('daemon.py run(): Executing opportunity:\n{}'.format(best_opp))
                order_result = Broker.place_order(best_opp.order)
                # Notify the strategies.
                if 'orderFillTransaction' in order_result:
                    try:
                        opened_trade_id = order_result['orderFillTransaction']['tradeOpened']['tradeID']
                        best_opp.strategy.trade_opened(trade_id=opened_trade_id)
                    except:
                        Log.write(
                            'daemon.py run(): Failed to extract opened trade from order result:\n{}'
                            .format(order_result) )
                        raise Exception
                elif 'tradesClosed' in order_result:
                    try:
                        for trade in order_result['orderFillTransaction']['tradesClosed']:
                            best_opp.strategy.trade_closed(trade_id=trade['tradeID'])
                    except:
                        Log.write(
                            'daemon.py run(): Failed to extract closed trades from order result:\n{}'
                            .format(order_result) )
                        raise Exception
                elif 'tradeReduced' in order_result:
                    try:
                        closed_trade_id = order_result['orderFillTransaction']['tradeReduced']['tradeID']
                        best_opp.strategy.trade_reduced(
                            closed_trade_id,
                            instrument_id=Instrument.get_id_from_name(order_result['instrument'])
                        )
                    except:
                        Log.write(
                            'daemon.py run(): Failed to extract reduced trades from order result:\n{}'
                            .format(order_result) )
                        raise Exception
                else:
                    Log.write(
                        '"daemon.py" run(): Unrecognized order result:\n{}'
                        .format(order_result) )
                    raise Exception

            """
            Clear opportunity list.
            Opportunities should be considered to exist only in the moment,
            so there is no need to save them for later.
            """
            cls.opportunities.clear()
        """
        Shutdown stuff. This runs after shutdown() is called, and is the
        last code that runs before returning to algo.py.
        """
        DB.shutdown()  # atexit() used in db.py, but call to be safe.
Ejemplo n.º 2
0
    def run(cls, stdcsr):
        """Returns: void
        This is the main program loop.
        """
        # initialize user interface
        cls._curses_init(stdcsr)

        # Read in existing trades
        while not cls.stopped and cls.recover_trades() == None:
            Log.write('"daemon.py" run(): Recovering trades...')
            cls._curses_refresh(stdcsr)

        # logging
        if Config.live_trading:
            Log.write('"daemon.py" start(): Using live account.')
        else:
            Log.write('"daemon.py" start(): Using practice mode.')
        """
        Main loop:
        1. Gather opportunities from each strategy.
        2. Decide which opportunities to execute.
        3. Clear the opportunity list.
        """
        while not cls.stopped:
            # refresh user interface
            cls._curses_refresh(stdcsr)

            # Let each strategy suggest an order
            for s in cls.strategies:
                new_opp = s.refresh()
                if new_opp == None:
                    Log.write(
                        'daemon.py run(): {} has nothing to offer now.'.format(
                            s.get_name()))
                    pass
                else:
                    cls.opportunities.push(new_opp)

            # Decide which opportunity (or opportunities) to execute
            Log.write('"daemon.py" run(): Picking best opportunity...')
            best_opp = cls.opportunities.pick()
            if best_opp == None:
                # Nothing is being suggested.
                pass
            else:
                # An order was suggested by a strategy, so place the order.
                #   Don't use all the money available.
                SLIPPAGE_WIGGLE = 0.95
                ###available_money = Broker.get_margin_available(Config.account_id) * SLIPPAGE_WIGGLE
                available_money = 100  # USD - testing
                #   Get the current price of one unit.
                instrument_price = 0
                Log.write('best opp: {}'.format(best_opp))
                go_long = best_opp.order.units > 0
                if go_long:
                    instrument_price = Broker.get_ask(
                        best_opp.order.instrument)
                else:
                    instrument_price = Broker.get_bid(
                        best_opp.order.instrument)
                #   How much leverage available:
                margin_rate = Broker.get_margin_rate(best_opp.order.instrument)
                #   TODO: A bit awkward, but overwrite the existing value that was used to
                #   determine long/short.
                units = available_money
                units /= cls.num_strategies_with_no_positions(
                )  # save money for other strategies
                units /= margin_rate
                units = int(units)  # floor
                if units <= 0:  # verify
                    Log.write('daemon.py run(): units <= 0')
                    raise Exception  # abort
                if not go_long:  # negative means short
                    units = -units
                best_opp.order.units = units
                Log.write('daemon.py run(): Executing opportunity:\n{}'.format(
                    best_opp))
                order_result = Broker.place_order(best_opp.order)
                # Notify the strategies.
                if 'orderFillTransaction' in order_result:
                    try:
                        opened_trade_id = order_result['orderFillTransaction'][
                            'tradeOpened']['tradeID']
                        best_opp.strategy.trade_opened(
                            trade_id=opened_trade_id)
                    except:
                        Log.write(
                            'daemon.py run(): Failed to extract opened trade from order result:\n{}'
                            .format(order_result))
                        raise Exception
                elif 'tradesClosed' in order_result:
                    try:
                        for trade in order_result['orderFillTransaction'][
                                'tradesClosed']:
                            best_opp.strategy.trade_closed(
                                trade_id=trade['tradeID'])
                    except:
                        Log.write(
                            'daemon.py run(): Failed to extract closed trades from order result:\n{}'
                            .format(order_result))
                        raise Exception
                elif 'tradeReduced' in order_result:
                    try:
                        closed_trade_id = order_result['orderFillTransaction'][
                            'tradeReduced']['tradeID']
                        best_opp.strategy.trade_reduced(
                            closed_trade_id,
                            instrument_id=Instrument.get_id_from_name(
                                order_result['instrument']))
                    except:
                        Log.write(
                            'daemon.py run(): Failed to extract reduced trades from order result:\n{}'
                            .format(order_result))
                        raise Exception
                else:
                    Log.write(
                        '"daemon.py" run(): Unrecognized order result:\n{}'.
                        format(order_result))
                    raise Exception
            """
            Clear opportunity list.
            Opportunities should be considered to exist only in the moment,
            so there is no need to save them for later.
            """
            cls.opportunities.clear()
        """
        Shutdown stuff. This runs after shutdown() is called, and is the
        last code that runs before returning to algo.py.
        """
        DB.shutdown()  # atexit() used in db.py, but call to be safe.