示例#1
0
    def onBars(self, bars):
        if self._active:
            for instrument, bar in bars.items():
                # Wait for enough bars to be available to calculate a SMA.
                if not self._smaLong[instrument] or self._smaLong[instrument][-1] is None:
                    return

                barDs = self.getFeed().getDataSeries(instrument)
                aroon = indicator.AROONOSC(barDs, self._aroonPeriod + 1, self._aroonPeriod)
                self._aroon[instrument].appendWithDateTime(self.getCurrentDateTime(), aroon[-1])

                pri = self._macdPrice[instrument]
                vol = self._macdVol[instrument]
                if instrument in self._posLong:
                    if cross.cross_below(self._smaShort[instrument], self._smaLong[instrument]) and aroon[-1] < -self._aroonOut:
                        position = self._posLong[instrument]
                        self.prepareExit(position)
                elif instrument in self._posShort:
                    if cross.cross_above(pri.getSignal(), pri) and aroon[-1] > 25:
                        position = self._posShort[instrument]
                        self.prepareExit(position)

                if cross.cross_above(self._smaShort[instrument], self._smaLong[instrument]) and aroon[-1] > 25:
                    self.prepareEnter(instrument, bars)
                elif cross.cross_below(pri.getSignal(), pri) and cross.cross_above(vol.getSignal(), vol) and aroon[-1] < -self._aroonIn:
                        self.prepareEnter(instrument, bars, broker.Order.Action.SELL_SHORT)
示例#2
0
    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        if self.__prices > self.__long_sma:
            # just long if price is above long sma
            if self.__position is None:
                if cross.cross_above(self.__short_sma, self.__medium_sma) > 0:
                    shares = int(self.getBroker().getCash() * 0.9 /
                                 bars[self.__instrument].getPrice())
                    # Enter a buy market order. The order is good till canceled.
                    self.__position = self.enterLong(self.__instrument, shares,
                                                     True)
            else:
                if not self.__position.exitActive() and cross.cross_below(
                        self.__short_sma, self.__medium_sma) > 0:
                    self.__position.exitMarket()

        elif self.__prices < self.__long_sma:
            if self.__position is not None:
                if cross.cross_below(self.__short_sma, self.__medium_sma) > 0:
                    shares = int(self.getBroker().getCash() * 0.9 /
                                 bars[self.__instrument].getPrice())
                    self.__position = self.enterShort(self.__instrument,
                                                      shares, True)
            else:
                if not self.__position.exitActive() and cross.cross_above(
                        self.__short_sma, self.__long_sma) > 0:
                    self.__position.exitMarket()
    def onBars(self, bars):
        for instrument, bar in bars.items():
            # Wait for enough bars to be available to calculate a SMA.
            if not self._smaLong[
                    instrument] or self._smaLong[instrument][-1] is None:
                return

            pri = self._macdPrice[instrument]
            vol = self._macdVol[instrument]
            if instrument in self._posLong:
                if cross.cross_below(self._smaShort[instrument],
                                     self._smaLong[instrument]):
                    position = self._posLong[instrument]
                    self.prepareExit(position)

            elif instrument in self._posShort:
                if cross.cross_above(pri.getSignal(), pri):
                    position = self._posShort[instrument]
                    self.prepareExit(position)

            if cross.cross_above(self._smaShort[instrument],
                                 self._smaLong[instrument]):
                self.prepareEnter(instrument, bars)
            elif cross.cross_below(pri.getSignal(), pri) and cross.cross_above(
                    vol.getSignal(), vol):
                self.prepareEnter(instrument, bars,
                                  broker.Order.Action.SELL_SHORT)
 def enterLongSignal(self, bar):  # Conditiond for long
     thismacd = self.macd[-1]
     macdsig = self.macd.getSignal()[-1]
     if self.belowzero:
         if cross.cross_below(self.macd,
                              self.macd.getSignal()) and macdsig < 0:
             #print "Entering long trade below zero macd", thismacd, macdsig
             return True
     else:
         if cross.cross_below(self.macd,
                              self.macd.getSignal()) and macdsig > 0:
             #print "Entering long trade above zero macd", thismacd, macdsig
             return True
示例#5
0
	def onBars(self, bars):
		if self.__position is None:
			if cross.cross_above(self.__prices, self.__sma) >0:
				shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
				self.__position = self.enterLong(self.__instrument, shares, True)

		elif not self.__position.exitActive() and cross.cross_below(self.__prices,self.__sma) >0:
    def onBars(self, bars):
        for instrument in bars.keys():
            # Wait for enough bars to be available to calculate a SMA.
            if not self._entrySmas[instrument] or self._entrySmas[instrument][-1] is None\
            or not self._exitSmas[instrument] or self._exitSmas[instrument][-1] is None:
                return

            # If a position was not opened, check if we should enter a long position.
            if instrument in self._longPositions:
                if cross.cross_above(self._prices[instrument],
                                     self._exitSmas[instrument]):
                    if not self._longPositions[instrument].exitActive():
                        self._longPositions[instrument].exitMarket()
            elif instrument in self._shortPositions:
                if cross.cross_below(self._prices[instrument],
                                     self._exitSmas[instrument]):
                    if not self._shortPositions[instrument].exitActive():
                        self._shortPositions[instrument].exitMarket()
            elif self.posCount() < self._posMax:
                bar = bars[instrument]
                if bar.getPrice(
                ) > self._entrySmas[instrument][-1] and self._rsis[instrument][
                        -1] <= self._overSoldThreshold:
                    self.prepareOrder(broker.Order.Action.BUY, instrument,
                                      bars)
                elif bar.getPrice(
                ) < self._entrySmas[instrument][-1] and self._rsis[instrument][
                        -1] >= self._overBoughtThreshold:
                    self.prepareOrder(broker.Order.Action.SELL_SHORT,
                                      instrument, bars)
示例#7
0
 def short(self, bars):
     if cross.cross_below(
             self.fast_ma,
             self.slow_ma):  #and self.__trend.trend_current_ratio() >=0:
         return True
     return False
     pass
 def onBars(self, bars):
     if self.__position != None and self.__position.getReturn() < -0.05:
         self.__position.exitMarket()
         
     # If a position was not opened, check if we should enter a long position.
     if self.__position is None:
         ds = self.getFeed().getDataSeries(self.__instrument).getCloseDataSeries()
         if self.touchBottom(): # and LINEARREG(ds, 20)[1] > 0:
             shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
             # Enter a buy market order. The order is good till canceled.
             self.__position = self.enterShort(self.__instrument, shares, True)
             self.__pos_kind = "Short"
             print str(bars[self.__instrument].getDateTime()) + " " + "buy Short"
         elif self.touchTop(): # and LINEARREG(ds, 20)[1] < 0:
             shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
             # Enter a buy market order. The order is good till canceled.
             self.__position = self.enterLong(self.__instrument, shares, True)
             self.__pos_kind = "Long"
             print str(bars[self.__instrument].getDateTime()) + " " + "buy Long"
         return
     # Check if we have to exit the position.
     elif (not self.__position.exitActive()):
         if self.__pos_kind == "Long" and (cross.cross_below(self.__prices, self.__sma, -2) > 0 or self.touchBottom()):
             self.__position.exitMarket() #Long exit
             print str(bars[self.__instrument].getDateTime()) + " " + "exit " + self.__pos_kind
         elif self.__pos_kind == "Short" and (cross.cross_above(self.__prices, self.__sma, -2) > 0 or self.touchTop()):
             self.__position.exitMarket() #Short exit
             print str(bars[self.__instrument].getDateTime()) + " " + "exit " + self.__pos_kind
示例#9
0
    def onBars(self, bars):

        # logger.debug('onbars')
        quantity = 10
        if self.realTrade:
            self.sma = talib.SMA(self.prices.values, 10)
            self.sma1 = talib.SMA(self.prices.values, 20)
            logger.debug('sma是')
            logger.debug(str(self.sma[-3:]))
            logger.debug(str(self.sma1[-3:]))
            if self.sma[-2] > self.sma1[-2] and self.sma[-3] < self.sma1[-3]:
                if self.getBroker().getShares(
                        self.transInstrument(self.__instrument)) != 0:
                    ret = self.getBroker().createLimitOrder(
                        broker.Order.Action.BUY_TO_COVER,
                        self.transInstrument(self.__instrument), quantity)
                    self.getBroker().submitOrder(ret)
                    logger.debug('平仓1')
                ret = self.getBroker().createLimitOrder(
                    broker.Order.Action.BUY,
                    self.transInstrument(self.__instrument), quantity)
                self.getBroker().submitOrder(ret)
                logger.debug('买1 ' + str(bars.getDateTime()))
            elif self.sma[-2] < self.sma1[-2] and self.sma[-3] > self.sma1[-3]:
                if self.getBroker().getShares(self.__instrument) != 0:
                    ret = self.getBroker().createLimitOrder(
                        broker.Order.Action.SELL,
                        self.transInstrument(self.__instrument), quantity)
                    self.getBroker().submitOrder(ret)
                    logger.debug('平仓2')
                ret = self.getBroker().createLimitOrder(
                    broker.Order.Action.SELL_SHORT,
                    self.transInstrument(self.__instrument), quantity)
                self.getBroker().submitOrder(ret)
                logger.debug('卖1  ' + str(bars.getDateTime()))
        else:
            if cross.cross_above(self.sma, self.sma1) > 0:
                if self.getBroker().getShares(self.__instrument) != 0:
                    ret = self.getBroker().createMarketOrder(
                        broker.Order.Action.BUY_TO_COVER,
                        self.transInstrument(self.__instrument), quantity)
                    self.getBroker().submitOrder(ret)
                    logger.debug('平仓3')
                ret = self.getBroker().createMarketOrder(
                    broker.Order.Action.BUY,
                    self.transInstrument(self.__instrument), quantity)
                self.getBroker().submitOrder(ret)
                logger.debug('买2' + str(bars.getDateTime()))
            elif cross.cross_below(self.sma, self.sma1) > 0:
                if self.getBroker().getShares(self.__instrument) != 0:
                    ret = self.getBroker().createMarketOrder(
                        broker.Order.Action.SELL,
                        self.transInstrument(self.__instrument), quantity)
                    self.getBroker().submitOrder(ret)
                    logger.debug('平仓4')
                ret = self.getBroker().createMarketOrder(
                    broker.Order.Action.SELL_SHORT,
                    self.transInstrument(self.__instrument), quantity)
                self.getBroker().submitOrder(ret)
                logger.debug('卖2' + str(bars.getDateTime()))
    def onBars(self, bars):
        # NOTE: something weird going on with the cash variable here; why leftover cash?

        shares = self.getBroker().getShares(self.__instrument)
        bar = bars[self.__instrument]

        # self.info(bar.getOpen() * self.prev_shares)
        # self.prev_shares = shares

        if shares == 0 and cross.cross_above(self.__prices, self.__sma) > 0:
            sharesToBuy = self.getBroker().getCash(False) / bar.getClose()
            self.info("{} Bought {} {}, unit price = ${:.2f}, using cash = {} (cash / price = {})".format(
                bars[self.__instrument].getDateTime(),
                sharesToBuy,
                self.__instrument,
                bars[self.__instrument].getClose(),
                self.getBroker().getCash(),
                self.getBroker().getCash() / bar.getClose()))
            self.marketOrder(self.__instrument, sharesToBuy)

        elif shares > 0 and cross.cross_below(self.__prices, self.__sma) > 0:
            self.marketOrder(self.__instrument, -1*shares)
            self.info("{} Gave an order to exit position (1 {} = ${:.2f}), leftover cash?? = {:.2f}".format(
                bars[self.__instrument].getDateTime(),
                self.__instrument,
                bar.getClose(),
                self.getBroker().getCash()))
            self.info("NOTE: the exit will happen at the opening price of the next tick")
示例#11
0
    def onBars(self, bars):
        for instrument, bar in bars.items():
            infoout = None
            if cross.cross_above(self.__dt[instrument],
                                 self.__zeroema[instrument]) > 0:
                # If the derivative crosses above zero (deriv - -> +),
                # buy the instrument.
                now_cash, now_shares = self.inventory(instrument)
                buyqty = self.buyamount(instrument, bar.getClose(),
                                        bar.getVolume(), now_cash, .2)
                self.marketOrder(instrument, buyqty)
                infoout = 'Order %d shares of %s @$%.2f. COH $%.2f' % (
                    buyqty, instrument, bar.getClose(), now_cash)

            elif cross.cross_below(self.__dt[instrument],
                                   self.__zeroema[instrument]) > 0:
                # If the derivative crosses below zero (deriv + -> -),
                # sell the instrument.
                now_cash, now_shares = self.inventory(instrument)
                if now_shares > 0:
                    # Sell all shares
                    self.marketOrder(instrument, -now_shares)
                    infoout = 'Sell %d shares of %s @$%.2f. COH $%.2f' % (
                        now_shares, instrument, bar.getClose(), now_cash)
            if infoout and self.printinfo:
                self.info(infoout)
    def onBars(self, bars):
        self.__halfLifeHelper.update()
        if bars.getBar(self.__instrument):
            hurst = self.getHurstValue()
            halfLife = self.__halfLifeHelper.getHalfLife()
            stdDev = self.__halfLifeHelper.getStdDev()
            ma = self.__halfLifeHelper.getSma()
            bar = bars[self.__instrument]
            open = bar.getOpen()
            currentPos = abs(self.getBroker().getShares(self.__instrument))
            if hurst is not None:
                if hurst < 0.5:
                    if hurst < 0.5 and open < ma - stdDev:
                        self.buy(bars)
                    elif hurst < 0.5 and open > ma - stdDev and currentPos > 0:
                        self.sell(bars)
                if hurst > 0.5:
                    if cross.cross_below(self.__shortWindowMa,
                                         self.__longWindowMa,
                                         10) > 0 and currentPos > 0:
                        self.sell(bars)

                    if cross.cross_above(self.__longWindowMa,
                                         self.__shortWindowMa, 10) > 0:
                        self.buy(bars)
示例#13
0
    def onBars(self, bars):
        # Wait for enough bars to be available to calculate a SMA.
        bar = bars[self.__instrument]
        if self.getFeed().isHistory():
            return
        if self.__sma[60][-1] is None:
            return
        logger.info(
            "onBars %s:%s: close:%.2f" %
            (self.__instrument, bar.getDateTimeLocal(), bar.getPrice()))

        bar = bars[self.__instrument]

        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if cross.cross_above(self.__sma[10], self.__sma[30]) > 0:
                mbroker = self.getBroker()
                shares = mbroker.getCash() / bar.getPrice() * 0.9
                self.__position = self.enterLongLimit(self.__instrument,
                                                      bar.getPrice(), shares,
                                                      True)
        # Check if we have to exit the position.
        elif not self.__position.exitActive() and cross.cross_below(
                self.__sma[10], self.__sma[30]) > 0:
            self.__position.exitLimit(bar.getPrice())
示例#14
0
    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.

        if self.__ma2[-1] is None:
            return

        print "on bars code ", self.__instrument, bars[
            self.__instrument].getDateTime(), bars[
                self.__instrument].getPrice()

        if self.__position is not None:
            if not self.__position.exitActive() and cross.cross_below(
                    self.__ma1, self.__ma2) > 0:
                self.__position.exitMarket()
                print("=== sell")
                print bars[self.__instrument].getDateTime(), bars[
                    self.__instrument].getPrice()
                #self.info("sell %s" % (bars.getDateTime()))

        if self.__position is None:
            if self.buyCon1() and self.buyCon2():
                shares = int(self.getBroker().getCash() * 0.2 /
                             bars[self.__instrument].getPrice())
                self.__position = self.enterLong(self.__instrument, shares)
                print("=== buy")
                print bars[self.__instrument].getDateTime(), bars[
                    self.__instrument].getPrice()
    def onBars(self, bars):
        for instrument, bar in bars.items():
            infoout = None
            if cross.cross_below(self.__shorttrix[instrument],
                                 self.__longtrix[instrument]) > 0:
                # If the derivative crosses above zero (deriv - -> +),
                # buy the instrument.
                now_cash, now_shares = self.inventory(instrument)
                buyqty = self.buyamount(
                    instrument, bar.getClose(), bar.getVolume(), now_cash, .2)
                self.marketOrder(instrument, buyqty)
                infoout = 'Order %d shares of %s @$%.2f. COH $%.2f' % (
                    buyqty, instrument, bar.getClose(), now_cash)

            elif cross.cross_above(self.__shorttrix[instrument],
                                   self.__longtrix[instrument]) > 0:
                # If the derivative crosses below zero (deriv + -> -),
                # sell the instrument.
                now_cash, now_shares = self.inventory(instrument)
                if now_shares > 0:
                    # Sell all shares
                    self.marketOrder(instrument, -now_shares)
                    infoout = 'Sell %d shares of %s @$%.2f. COH $%.2f' % (
                        now_shares, instrument, bar.getClose(), now_cash)
            if infoout and self.printinfo:
                self.info(infoout)
示例#16
0
	def onBars(self, bars):
		if self.__position is None:
			if cross.cross_above(self.__prices, self.__sma) >0:
				shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
				self.__position = self.enterLong(self.__instrument, shares, True)
		
		elif not self.__position.exitActive() and cross.cross_below(self.__prices,self.__sma) >0:
			self.__position.exitMarket()
 def onBars(self, bars):
     if bars.getBar(self.__lead):
         if cross.cross_above(self.__adjClose, self.__slowSMA) == 1 and self.__pos is None:
             shares = self.__calculatePosSize()
             if shares:
                 self.__pos = self.enterLong(self.__lag, shares)
         elif cross.cross_below(self.__adjClose, self.__fastSMA) == 1 and self.__pos is not None:
             self.__pos.exitMarket()
	def onBars(self, bars):
		if bars.getBar(self.__lead):
			if cross.cross_above(self.__adjClose, self.__slowSMA) == 1 and self.__pos == None:
				shares = self.__calculatePosSize()
				if shares:
					self.__pos = self.enterLong(self.__lag, shares)
			elif cross.cross_below(self.__adjClose, self.__fastSMA) == 1 and self.__pos != None:
				self.exitPosition(self.__pos)
示例#19
0
 def onBars(self, bars):
     # If a position was not opened, check if we should enter a long position.
     if self.__position == None:
         if cross.cross_above(self.__adjClose, self.__sma) > 0:
             # Enter a buy market order for 10 shares. The order is good till canceled.
             self.__position = self.enterLong(self.__instrument, 10, True)
     # Check if we have to exit the position.
     elif cross.cross_below(self.__adjClose, self.__sma) > 0:
          self.__position.exit()
示例#20
0
 def onBars(self, bars):
     # If a position was not opened, check if we should enter a long position.
     if self.__position == None:
         if cross.cross_above(self.__adjClose, self.__sma) > 0:
             # Enter a buy market order for 10 shares. The order is good till canceled.
             self.__position = self.enterLong(self.__instrument, 10, True)
     # Check if we have to exit the position.
     elif cross.cross_below(self.__adjClose, self.__sma) > 0:
         self.__position.exit()
示例#21
0
 def doTechnical(self, bars, members, leaders):
     for instrument in members:
         if instrument in bars:
             if not instrument in self._prices:
                 self._prices[instrument] = macd.MACD(self._feed[instrument].getPriceDataSeries(), 12, 26, 9)
                 self._vols[instrument] = macd.MACD(self._feed[instrument].getVolumeDataSeries(), 12, 26, 9)
             elif self._session >= 200:
                 pri = self._prices[instrument]
                 vol = self._vols[instrument]
                 if instrument in self._positions:
                     if cross.cross_below(pri.getSignal(), pri) and cross.cross_below(vol.getSignal(), vol):
                         position = self._positions[instrument]
                         if not position.getExitOrder():
                             position.exitMarket()
                 elif instrument in leaders:
                     if cross.cross_above(pri.getSignal(), pri) and cross.cross_above(vol.getSignal(), vol):
                         if len(self._positions) < self._posMax:
                             self.prepareEnter(instrument, bars)
示例#22
0
 def onBars(self, bars):
     if self.__position is None:
         if cross.cross_above(self.__closed, self.__ma) > 0:
             shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
             print("cross_above shares,", shares)
             # Enter a buy market order. The order is good till canceled.
             self.__position = self.enterLong(self.__instrument, shares, True)
     elif not self.__position.exitActive() and cross.cross_below(self.__closed, self.__ma) > 0:
         print("cross_below")
         self.__position.exitMarket()
示例#23
0
 def onBars(self, bars):
     # If a position was not opened, check if we should enter a long position.
     if self.__position is None:
         if cross.cross_above(self.__prices, self.__sma) > 0:
             shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
             # Enter a buy market order. The order is good till canceled.
             self.__position = self.enterLong(self.__instrument, shares, True)
     # Check if we have to exit the position.
     elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__exit_sma) > 0:
         self.__position.exitMarket()
示例#24
0
 def onBars(self, bars):
     # If a position was not opened, check if we should enter a long position.
     if self.__position is None:
         if cross.cross_above(self.__prices, self.__sma) > 0:
             shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
             # Enter a buy market order. The order is good till canceled.
             self.__position = self.enterLong(self.__instrument, shares, True)
     # Check if we have to exit the position.
     elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
         self.__position.exitMarket()
    def exitShortSignal(self, shortPos, extPriceBarDS, extPriceDS):
        upper, middle, lower = indicator.BBANDS(extPriceDS,
                                                count=100,
                                                timeperiod=self.bBandsPeriod,
                                                matype=MA_Type.SMA,
                                                nbdevup=self.numStdDev,
                                                nbdevdn=self.numStdDev)

        shortExitFilter_1 = cross.cross_below(extPriceDS, middle) > 0
        shortExitFilter_2 = shortPos.exitActive()
        return shortExitFilter_1 and not shortExitFilter_2
示例#26
0
 def exitLongSignal(self) :
     if self.__UpperBand[-1-self.__circ] is None:
         return False
     m1 = 0
     for i in range(self.__circ):
         if self.__close[-i-1] >= self.__UpperBand[-i-2]:
             m1 += 1
     if m1 >= self.__circ-1 and cross.cross_below(self.__close,self.__UpperBand)>0:
         return True
     else:
         return False
示例#27
0
 def enterShortSignal(self) :
     if self.__UpperBand[-1-self.__circ] is None:
         return False
     m1 = 0
     for i in range(self.__circ):
         if self.__macd[-i-1] >= self.__UpperBand[-i-2]:
             m1 += 1
     if m1 >= self.__circ-1 and cross.cross_below(self.__macd,self.__UpperBand)>0:
         return True
     else:
         return False
示例#28
0
 def handle_data(self,bars):
     for instrument in bars.getInstruments():
         # If a position was not opened, check if we should enter a long position.
         if self.__position[instrument] is None:
             if cross.cross_above(self.__prices[instrument], self.__sma[instrument]) > 0:
                 shares = int(self.getBroker().getCash() * 0.9 / bars[instrument].getPrice())
                 # Enter a buy market order. The order is good till canceled.
                 self.__position[instrument] = self.enterLong(instrument, shares, True)
         # Check if we have to exit the position.
         elif not self.__position[instrument].exitActive() and cross.cross_below(self.__prices[instrument], self.__sma[instrument]) > 0:
             self.__position[instrument].exitMarket()
示例#29
0
    def onBars(self, bars):
        if len(self.__longsma) < 2:
            return
        bar = bars[self.__instrument]
        shares = self.getBroker().getShares(self.__instrument)
        if self.__position is None:
            if cross.cross_above(self.__shortsma, self.__longsma) > 0:
                self.__position = self.enterLong(self.__instrument, 100, True)

        elif not self.__position.exitActive() and cross.cross_below(self.__shortsma, self.__longsma) > 0:
            self.__position.exitMarket()
示例#30
0
 def calcSignal(self):
     self.buySignal, self.sellSignal = False, False
     if (self.longAllowed):
         if self.longPosition is None:
             #mid 无多仓,检查是否需要开多仓
             if cross.cross_above(self.__sma, self.__lma) > 0:
                 self.buySignal = True
     if (self.shortAllowed):
         if self.shortPosition is None:
             if cross.cross_below(self.__sma, self.__lma) > 0:
                 self.sellSignal = True
示例#31
0
    def onBars(self, bars):
        if len(self.__longsma) < 2:
            return
        bar = bars[self.__instrument]
        shares = self.getBroker().getShares(self.__instrument)
        if self.__position is None:
            if cross.cross_above(self.__shortsma, self.__longsma) > 0:
                self.__position = self.enterLong(self.__instrument, 100, True)

        elif not self.__position.exitActive() and cross.cross_below(
                self.__shortsma, self.__longsma) > 0:
            self.__position.exitMarket()
示例#32
0
 def short_signal(self):
     if cross.cross_below(self.kd.getKD_k(), self.kd.getKD_d()) :#and self.__trend.trend_current_ratio() >=0:
             return True
     #if self.trend_short(self.slow_ma):
      #   return True
     ''' adjust'''
     #if self.kd.getKD_d()[-1] < 30  :
     #    return True
     #if self.trend_short(self.fast_ma)  :
     #    return True
     return False
     pass
    def enterShortSignal(self, extPriceBarDS, extPriceDS):
        trixNear = indicator.TRIX(extPriceDS,
                                  count=100,
                                  timeperiod=self.trixNearPeriod)

        trixFar = indicator.TRIX(extPriceDS,
                                 count=100,
                                 timeperiod=self.trixFarPeriod)

        shortEntryFilter_1 = cross.cross_below(trixNear, trixFar) > 0

        return shortEntryFilter_1
示例#34
0
    def testCrossBelowMany(self):
        count = 100
        values1 = [0 for i in range(count)]
        values2 = [-1 if i % 2 == 0 else 1 for i in range(count)]

        # Check first value
        self.assertEqual(cross.cross_below(values1, values2, 0, 0), 0)

        # Check every 2 values.
        period = 2
        for i in range(1, count):
            if i % 2 == 0:
                self.assertEqual(
                    cross.cross_below(values1, values2, i - period + 1, i + 1),
                    0)
            else:
                self.assertEqual(
                    cross.cross_below(values1, values2, i - period + 1, i + 1),
                    1)

        # Check every 4 values.
        period = 4
        for i in range(3, count):
            if i % 2 == 0:
                self.assertEqual(
                    cross.cross_below(values1, values2, i - period + 1, i + 1),
                    1)
            else:
                self.assertEqual(
                    cross.cross_below(values1, values2, i - period + 1, i + 1),
                    2)

        # Check for all values.
        self.assertEqual(cross.cross_below(values1, values2, 0, count),
                         count / 2)
    def testCrossBelowMany(self):
        count = 100
        values1 = [0 for i in range(count)]
        values2 = [-1 if i % 2 == 0 else 1 for i in range(count)]

        # Check first value
        self.assertEqual(cross.cross_below(values1, values2, 0, 0), 0)

        # Check every 2 values.
        period = 2
        for i in range(1, count):
            if i % 2 == 0:
                self.assertEqual(cross.cross_below(values1, values2, i - period + 1, i + 1), 0)
            else:
                self.assertEqual(cross.cross_below(values1, values2, i - period + 1, i + 1), 1)

        # Check every 4 values.
        period = 4
        for i in range(3, count):
            if i % 2 == 0:
                self.assertEqual(cross.cross_below(values1, values2, i - period + 1, i + 1), 1)
            else:
                self.assertEqual(cross.cross_below(values1, values2, i - period + 1, i + 1), 2)

        # Check for all values.
        self.assertEqual(cross.cross_below(values1, values2, 0, count), count / 2)
示例#36
0
    def checkBB(self, bars):
        signal = 0
        bb = self.__bb[['bull', 'bear', 'bb']][self.__bb.index <= bars.getDateTime()].tail(2)
        self.__bull, self.__bear = bb.bull.values, bb.bear.values

        if bb is None:  # to check the first item is Nan
            return signal

        if cross.cross_above(self.__prices, self.__bull):
            signal = 1
        elif cross.cross_below(self.__prices, self.__bear):
            signal = -1
        return signal
示例#37
0
 def short(self, bars):
     lower = self.__bbands.getLowerBand()[-1]
     upper = self.__bbands.getUpperBand()[-1]
     prices = self.__prices
     if upper is None:
         return False
     #if bars[self.__instrument].getClose() > upper:
     #if cross.cross_below(self.__prices, self.__bbands.getUpperBand()):
     #if cross.cross_below(self.__prices, self.__bbands.getUpperBand()) or treand_check(prices) <= -1:
     #if cross.cross_below(self.__prices, self.__bbands.getUpperBand()) or  self.__trend.trend_current() == 'down':
     if cross.cross_below(self.__prices, self.__bbands.getUpperBand()) or self.__trend.trend_current_ratio() < 0 :
         return True
     return False
示例#38
0
 def calcSignal(self):
     self.buySignal,self.sellSignal = {},{}
     for instrument in self.instruments:
         self.buySignal[instrument],self.sellSignal[instrument] = False,False
         #if(self.longAllowed):
         if self.longPosition[instrument] is None:
             #mid 无多仓,检查是否需要开多仓
             if cross.cross_above(self.__sma[instrument], self.__lma[instrument]) > 0:
                 self.buySignal[instrument] = True   
         #if(self.shortAllowed ):
         if self.shortPosition[instrument] is None:
             if cross.cross_below(self.__sma[instrument], self.__lma[instrument]) > 0:
                 self.sellSignal[instrument] = True 
示例#39
0
 def onBars(self, bars):        
     if self.__position is None:            
         if cross.cross_above(self.__Close, self.__sma) > 0:
             self.buyPrice = bars.getBar("btc").getClose()
             
             quantity = self.getBroker().getCash() / bars.getBar("btc").getClose() * 0.99
             self.__position = self.enterLong(self.__instrument, quantity)
             
             self.numOrder += 1
     elif cross.cross_below(self.__Close, self.__sma) > 0:
         # if (abs(self.buyPrice - bars.getBar("btc").getClose()) > 0.002 * (bars.getBar("btc").getClose())):
         if (abs(self.buyPrice - bars.getBar("btc").getClose()) > 10):            
             self.__position.exitMarket()
示例#40
0
 def sellSignal(self, bars):
     #         a> 价格下穿20日均线 并且 价格<SMA价格的97%
     #         b> 亏损超10%
     #         c> RSI>80
     #         c> 价格小于买入后最高价的90%
     if self.__buy_pos is None or self.__sell_pos is None:
         high_period = 0
     else:
         high_period = self.__buy_pos - self.__sell_pos
     return (cross.cross_below(self.__prices, self.__sma20) and self.__prices[-1] < self.__sma[-1] * 0.97) \
            or (self.__last_buy * 0.9 > self.getResult()) \
            or (self.__rsi > 80) \
            or (self.__prices < highlow.High(self.__prices, high_period) * 0.9)
    def onBars(self, bars):
        bar = bars.getBar("orcl")
        self.printDebug("%s: O=%s H=%s L=%s C=%s" % (bar.getDateTime(), bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose()))

        if cross.cross_above(self.__fastSMADS, self.__slowSMADS) == 1:
            if self.__shortPos:
                self.exitShortPosition(bars, self.__shortPos)
            assert(self.__longPos is None)
            self.__longPos = self.enterLongPosition(bars)
        elif cross.cross_below(self.__fastSMADS, self.__slowSMADS) == 1:
            if self.__longPos:
                self.exitLongPosition(bars, self.__longPos)
            assert(self.__shortPos is None)
            self.__shortPos = self.enterShortPosition(bars)
示例#42
0
    def checkkdj(self,bars):
        signal = 0
        # this time we can use k[-1]'s data
        ##########################  using talib
        # If a position was not opened, check if we should enter a long position.
        # self.__stoch = indicator.STOCH(self.__feed[self.__instrument],len(self.__feed[self.__instrument]),
        #                               self.__param[0],self.__param[1],self.__param[2],self.__param[3],self.__param[4])
        # self.__k,self.__d = self.__stoch[0],self.__stoch[1]

        ########################## using utils.formular for kdj:this is true
        kd = self.__kd[['KDJ_K', 'KDJ_D']][self.__kd.index <= bars.getDateTime()].tail(2)
        self.__k, self.__d = kd.KDJ_K.values, kd.KDJ_D.values
        if self.__k.__len__() < 2:
            return signal
        #########################
        if cross.cross_above(self.__k, [self.__param[6], self.__param[6]]) > 0 \
            or cross.cross_above(self.__k,   [self.__param[5],self.__param[5]]) > 0:  # 得取其high前一天的值cross 参数为2,所以high中至少应当有3个值
            signal = 1
        elif cross.cross_below(self.__k, [self.__param[6],self.__param[6]]) > 0 \
            or cross.cross_below(self.__k, [self.__param[5],self.__param[5]]) > 0:
            signal = -1

        return signal
示例#43
0
    def checkAroon(self,bars):
        signal = 0
        self.__aroondown,self.__aroonup = indicator.Adx(self.__feed[self.__instrument],len(self.__feed[self.__instrument]),20)
        self.__aroon = self.__aroonup[-2:] - self.__aroondown[-2:]

        if self.__aroon is None or np.isnan(self.__aroon[0]):  # to check the first item is Nan
            return signal

        if cross.cross_above(self.__aroon,[15,15]):
            signal = 1
        elif cross.cross_below(self.__aroon,[15,15]):
            signal = -1

        return signal
    def onBars(self, bars):
        bar = bars.getBar("orcl")
        self.printDebug("%s: O=%s H=%s L=%s C=%s" % (bar.getDateTime(), bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose()))

        if cross.cross_above(self.__fastSMADS, self.__slowSMADS) == 1:
            if self.__shortPos:
                self.exitShortPosition(bars, self.__shortPos)
            assert(self.__longPos is None)
            self.__longPos = self.enterLongPosition(bars)
        elif cross.cross_below(self.__fastSMADS, self.__slowSMADS) == 1:
            if self.__longPos:
                self.exitLongPosition(bars, self.__longPos)
            assert(self.__shortPos is None)
            self.__shortPos = self.enterShortPosition(bars)
示例#45
0
 def enterShortSignal(self) :
     if self.__lastShortPos is not None:
         if self.__barNum-self.__lastShortPos<60:
             return 0
     if self.__UpperBand[-1-self.__circ] is None:
         return 0
     m1 = 0
     for i in range(self.__circ):
         if self.__close[-i-1] >= self.__UpperBand[-i-2]:
             m1 += 1
     if m1 >= self.__circ-1 and cross.cross_below(self.__close,self.__UpperBand)>0:
         return 1
     else:
         return 0
示例#46
0
 def exitLongSignal(self) :
     if self.__UpperBand[-1-self.__circ] is None:
         return False
     m1 = 0
     for i in range(self.__circ):
         if self.__macd[-i-1] >= self.__UpperBand[-i-2]:
             m1 += 1
     if m1 >= self.__circ-1 and cross.cross_below(self.__macd,self.__UpperBand)>0:
         return True
     elif self.__macd[-1]>=self.__UpperBand[-1] and self.__macdMax==self.__macd[-1]:
         return True
     elif self.__macd[-1]*1.001>=self.__UpperBand[-1] and self.__macd[-1]>-0.1:
         return True
     else:
         return False
示例#47
0
    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.

        if self.__ma3[-1] is None:
            return

        if self.__position is not None:
            if not self.__position.exitActive() and cross.cross_below(self.__ma1, self.__ma2) > 0:
                self.__position.exitMarket()
                # self.info("sell %s" % (bars.getDateTime()))

        if self.__position is None:
            if self.buyCon1() and self.buyCon2():
                shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice())
                self.__position = self.enterLong(self.__instrument, shares)
示例#48
0
    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))

        # Wait until we get the current bid/ask prices.
        if self.__ask is None:
            return

        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if cross.cross_above(self.__prices, self.__sma) > 0:
                self.info("Entry signal. Buy at %s" % (self.__ask))
                self.__position = self.enterLongLimit(self.__instrument, self.__ask, self.__posSize, True)
        # Check if we have to close the position.
        elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
            self.info("Exit signal. Sell at %s" % (self.__bid))
            self.__position.exitLimit(self.__bid)
示例#49
0
    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        closeDs = self.getFeed().getDataSeries(instrument).getCloseDataSeries()
        self.__ma1 = indicator.MA(closeDs, 40, self.__malength1)
        self.__ma2 = indicator.MA(closeDs, 40, self.__malength2)

        if self.__ma2[-1]is None:
            return 
            
        if self.__position is not None:
            if not self.__position.exitActive() and cross.cross_below(self.__ma1, self.__ma2) > 0:
                self.__position.exitMarket()
                #self.info("sell %s" % (bars.getDateTime()))
        
        if self.__position is None:
            if cross.cross_above(self.__ma1, self.__ma2) > 0:
                shares = int(self.getBroker().getEquity() * 0.2 / bars[self.__instrument].getPrice())
                self.__position = self.enterLong(self.__instrument, shares)
                print bars[self.__instrument].getDateTime(), bars[self.__instrument].getPrice()
示例#50
0
 def onBars(self, bars):
     inst0_cond = cross.cross_above(self.__prices[self.__instrumentList[0]], self.__sma[self.__instrumentList[0]])
     inst2_cond = cross.cross_above(self.__prices[self.__instrumentList[2]], self.__sma[self.__instrumentList[2]])
     # If a position was not opened, check if we should enter a long position.
     if not self.__positions:
         if inst0_cond > 0 or inst2_cond > 0:
             if inst0_cond > 0:
                 shares_0 = int(self.getBroker().getCash() * 0.6 / bars[self.__instrumentList[0]].getPrice())
                 shares_2 = int(self.getBroker().getCash() * 0.3 / bars[self.__instrumentList[2]].getPrice())
             else:
                 shares_0 = int(self.getBroker().getCash() * 0.3 / bars[self.__instrumentList[0]].getPrice())
                 shares_2 = int(self.getBroker().getCash() * 0.6 / bars[self.__instrumentList[2]].getPrice())
             # Enter a buy market order. The order is good till canceled.
             print "%%%%%$$$$: ", shares_0, shares_2
             self.__positions[self.__instrumentList[0]] = self.enterLong(self.__instrumentList[0], int(shares_0), True)
             self.__positions[self.__instrumentList[2]] =self.enterLong(self.__instrumentList[2], int(shares_2), True)
             self.__activePosition = self.__instrumentList[0]
     # Check if we have to exit the position.
     elif cross.cross_below(self.__prices[self.__activePosition], self.__sma[self.__activePosition]) > 0:
         self.__position[self.__instrumentList[0]].exitMarket()
         self.__position[self.__instrumentList[2]].exitMarket()
示例#51
0
    def onBars(self, bars):
        bar = bars[self.instrument]
        for m in self.s:
            if m[-1] is None:
                return
        if self.atr[-1] is None:
            return

        # test if it is open day
        if bar.getVolume() <= 0:
            return

        if self.position is None:
            open_long = False
            if cross.cross_above(self.price, self.s[0]):
            # if bar.getPrice()> self.s[0][-1]:
                open_long = True
                for i in range(0,len(self.s)-1):
                    if self.s[i][-1] < self.s[i+1][-1]:
                        open_long = False
            if open_long:
                shares = min(math.floor(self.getBroker().getCash()*0.01/self.atr[-1]), 0.9*math.floor(self.getBroker().getCash()/bar.getPrice()))
                # print('shares {}'.format(shares))
                self.position = self.enterLong(self.instrument, shares, True)
        elif not self.position.exitActive():
            open_short = False
            # the mv exit
            if cross.cross_below(self.price, self.s[0]):
            # if bar.getPrice() < self.s[0][-1]:
                open_short = True
                for i in range(0,len(self.s)-1):
                    if self.s[i][-1] > self.s[i+1][-1]:
                        open_short=False
            # if bar.getPrice() < self.atr_stop_loss(bar):
            #     open_short = True
            if open_short:
                self.position.exitMarket()
示例#52
0
 def sellCon1(self):
     if cross.cross_below(self.__ma1, self.__ma2) > 0:
         return True
示例#53
0
    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        
        bar = bars[self.__instrument]
        
        # filter datetime    
        ###################################################################################        
        filterCon = len(self.__close) < max(self.__bollingerlength, self.__malength, self.__closelength)
        self.__filterCon.append(filterCon)
        
        if filterCon:
            return
     
        # record position      
        ####################################################################################
        if self.__longPos is not None and self.__shortPos is None:
            self.__p.append(1) 
        elif self.__longPos is None and self.__shortPos is not None:
            self.__p.append(-1)
        else:
            self.__p.append(0)   
  
        # calculate ccMA     
        ####################################################################################           
        ccMACon1 = self.__longPos is not None or self.__shortPos is not None
        ccMACon2 = self.__malength > self.__ccMAlength
        
        if ccMACon1 and ccMACon2: 
            self.__malength = self.__malength - 1
        elif not ccMACon1:
            self.__malength = 50

        self.__ccMA = np.mean(self.__close[-self.__malength:])
#        print self.__malength, self.__ccMA
        self.__MA.append(self.__ccMA)
        self.__ccMACon1.append(ccMACon1)
        self.__ccMACon2.append(ccMACon2)
        
        #open and close condition   
        ######################################################################################   
        self.__enterLong1 = (cross.cross_above(self.__high, self.__UpperBand) > 0)
        self.__enterLong2 = (bar.getClose() >= max(self.__close[-self.__closelength:]))
        self.__enter = ((self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() > float(self.__space) / 1000)
#        print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose()
        self.__enterShort1 = cross.cross_below(self.__low, self.__LowerBand) > 0 
        self.__enterShort2 = bar.getClose() <= min(self.__close[-self.__closelength:])
        self.__exitLong1 = (bar.getClose() < self.__ccMA)
        self.__exitLong2 = (self.__ccMA < self.__UpperBand[-1])
        self.__exitShort1 = (bar.getClose() > self.__ccMA)
        self.__exitShort2 = (self.__ccMA > self.__LowerBand[-1])
        
        self.__enterCon.append(self.__enter)
        self.__enterLongCon1.append(self.__enterLong1)
        self.__enterLongCon2.append(self.__enterLong2)
        self.__enterShortCon1.append(self.__enterShort1)
        self.__enterShortCon2.append(self.__enterShort2)
        self.__exitLongCon1.append(self.__exitLong1)
        self.__exitLongCon2.append(self.__exitLong2)
        self.__exitShortCon1.append(self.__exitShort1)
        self.__exitShortCon2.append(self.__exitShort2)
  
        #open and close  
        #######################################################################################        
        if self.__longPos is not None:         
             if self.exitLongSignal():
                 self.__longPos.exitMarket()
#             if self.__shortPos is not None:
#                 print 11
#                 self.info("intend long close")
#                 print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose()
                 
        elif self.__shortPos is not None:
             if self.exitShortSignal():
                  self.__shortPos.exitMarket()
#                  self.info("intend short close")
#                  print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose()
                  
        else:
             if self.enterLongSignal():
                 shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice())
                 self.__longPos = self.enterLong(self.__instrument, shares)
#                 self.info("intend long open")
#                 print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose()
              
             elif self.enterShortSignal():
                 shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice())
                 self.__shortPos = self.enterShort(self.__instrument, shares)
示例#54
0
 def exitLongSignal(self, bar):
     slope = self.__slope.getValueAbsolute(len(self.__slope) - 1)
     return cross.cross_below(self.__prices, self.__sma) > 0 or slope < 0.05
    def testCrossBelowOnce(self):
        values1 = self.__buildSeqDS([2, 2, 2,  2, 2, 2, 2])
        values2 = self.__buildSeqDS([1, 1, 1, 10, 1, 1, 1])

        # Check every 2 values.
        self.assertEqual(cross.cross_below(values1, values2, 0, 2), 0)
        self.assertEqual(cross.cross_below(values1, values2, 1, 3), 0)
        self.assertEqual(cross.cross_below(values1, values2, 2, 4), 1)
        self.assertEqual(cross.cross_below(values1, values2, 3, 5), 0)
        self.assertEqual(cross.cross_below(values1, values2, 4, 6), 0)
        self.assertEqual(cross.cross_below(values1, values2, 5, 7), 0)

        # Check every 3 values.
        self.assertEqual(cross.cross_below(values1, values2, 0, 3), 0)
        self.assertEqual(cross.cross_below(values1, values2, 1, 4), 1)
        self.assertEqual(cross.cross_below(values1, values2, 2, 5), 1)
        self.assertEqual(cross.cross_below(values1, values2, 3, 6), 0)
        self.assertEqual(cross.cross_below(values1, values2, 4, 7), 0)

        # Check for all values.
        self.assertEqual(cross.cross_below(values1, values2, 0, 7), 1)
        self.assertEqual(cross.cross_below(values1, values2, 0, -1), 1)
示例#56
0
文件: rsi.py 项目: llmofang/backtest
 def exitShortSignal(self):
     return cross.cross_below(self.__priceDS, self.__exitSMA) and not self.__shortPos.exitActive()
示例#57
0
 def exitLongSignal(self) :
     if cross.cross_below(self.__mass, self.__masl) > 0 and not self.__longPos.exitActive():
         return True
示例#58
0
 def enterShortSignal(self) :
     if cross.cross_below(self.__mals, self.__mall) > 0:
         return True
示例#59
0
 def enterShortSignal(self, bar):
     slope = self.__slope.getValueAbsolute(len(self.__slope) - 1)
     return cross.cross_below(self.__prices, self.__sma) > 0 and slope < -0.1