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)
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 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 enterShortSignal(self, bar): thismacd = self.macd[-1] macdsig = self.macd.getSignal()[-1] if self.belowzero: if cross.cross_above(self.macd, self.macd.getSignal()) and macdsig < 0: #print "Entering short trade below zero macd", thismacd, macdsig return True else: if cross.cross_above(self.macd, self.macd.getSignal()) and macdsig > 0: #print "Entering short trade above zero macd", thismacd, macdsig return True
def testCrossAboveWithSMA(self): ds1 = dataseries.SequenceDataSeries() ds2 = dataseries.SequenceDataSeries() sma1 = ma.SMA(ds1, 15) sma2 = ma.SMA(ds2, 25) for i in range(100): ds1.append(i) ds2.append(50) if i == 58: self.assertEqual(cross.cross_above(sma1[:], sma2[:], -2, None), 1) else: self.assertEqual(cross.cross_above(sma1[:], sma2[:], -2, None), 0)
def enterShortSignal(self): # for i in range(3): # print('MA slope',self.__middle_slope[-1]) if cross.cross_above(self.__prices, self.__bbands.getUpperBand() ) > 0 and self.__middle_slope[-1] < 0: print( 'middle slope is', self.__middle_slope[-1], 'sell?', cross.cross_above(self.__prices, self.__bbands.getUpperBand()) > 0 and self.__middle_slope[-1] < 0) return cross.cross_above( self.__prices, self.__bbands.getUpperBand()) > 0 and self.__middle_slope[-1] < 0
def onBars(self, bars): closeDs = self.getFeed().getDataSeries("petr4").getCloseDataSeries() self.sma17 = talibext.MA(closeDs,len(closeDs), timeperiod=5) self.sma34 = talibext.MA(closeDs, len(closeDs), timeperiod=20) bar_close = bars.getBar(self.__instrument).getClose() bar_date = bars.getBar(self.__instrument).getDateTime() if self.__position == None: if cross.cross_above(self.sma17, self.sma34) > 0: self.__position = self.enterLongLimit(self.__instrument, bar_close, 10, True) self.stop_loss = bar_close * 0.97 self.stop_gain = bar_close * 1.05 self.last_buy_price = bar_close self.last_buy_date = bar_date print "%s - try buy at %6.2f - stop loss at %6.2f / stop gain at %6.2f"%(bar_date, bar_close, self.stop_loss, self.stop_gain) elif bar_close <= self.stop_loss: stop_execute = self.stop_loss * 0.995 self.__position.exit(self, stop_execute, stop_execute) print "%s - stoppe d (loss) at %6.2f - stop loss: %6.2f"%(bar_date, stop_execute, self.stop_loss) self.stop_loss = 0 self.stop_gain = 0 self.last_buy_price = 0 elif bar_close >= self.stop_gain and self.stop_gain > 0: self.stop_loss = self.stop_gain * 0.99 self.stop_gain = self.stop_gain * 1.05 print "%s - at %6.2f raised stop loss to %6.2f and stop gain to %6.2f"%(bar_date, bar_close, self.stop_loss, self.stop_gain) elif (bar_date - self.last_buy_date).days > 60: self.__position.cancelExit() print "%s - trend timed out"%(bar_date) self.stop_loss = 0 self.stop_gain = 0 self.last_buy_price = 0 self.last_buy_date = 0
def long(self, bars): global list_info lower = self.__bbands.getLowerBand()[-1] upper = self.__bbands.getUpperBand()[-1] ma= self.getBollingerBands().getMiddleBand() low = self.__bbands.getLowerBand() high=self.__bbands.getUpperBand() prices=self.__prices if lower is None: return False if cross.cross_above(self.__prices, self.__bbands.getLowerBand()) and self.__trend.trend_current_ratio() >=0: #if cross.cross_above(self.__prices, self.__bbands.getLowerBand()) and self.__trend.trend_current() != 'down': #if cross.cross_above(self.__prices, self.__bbands.getLowerBand()) and trend_ratio(ma) >-1: #if cross.cross_above(self.__prices, self.__bbands.getLowerBand()) and prices[-1] - prices[-3] > 0: #if cross.cross_above(self.__prices, self.__bbands.getLowerBand()) :#and prices[-1] - prices[-5] > 0: #if bars[self.__instrument].getClose() < lower: #if cross.cross_above(self.__prices,self.__bbands.getLowerBand() ): #if self.getBollingerBands().getMiddleBand()[-1-1] and (self.getBollingerBands().getMiddleBand()[-1] - self.getBollingerBands().getMiddleBand()[-1-1] ) > 0 :# add trade #print ("ma",ma[-1],ma[-2],ma[-3]) #print ("low",low[-1],low[-2],low[-3]) #print ("high",high[-1],high[-2],high[-3]) #print ("price",prices[-1],prices[-2],prices[-3]) print bars.getDateTime() self.list_info("ma",ma,5) self.list_info("low", low, 5) self.list_info("high", high, 5) self.list_info("price", prices, 5) return True return False
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): # 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")
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
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)
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)
def is_long(self, time): if cross.cross_above(self.__prices, self.__sma) > 0: return True else: return False pass pass
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())
def exitShortSignal(self, bar): shares = self.getBroker().getShares(self.__instrument) Cash = self.getBroker().getCash(False) price = (1000000 - Cash) / float(shares) return cross.cross_above( self.__prices, self.__bbands.getLowerBand()) > 0 or bar.getClose() > 1.05 * price
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)
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 long(self, bars): if cross.cross_above( self.fast_ma, self.slow_ma): #and self.__trend.trend_current_ratio() >=0: return True return False pass
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 long_signal(self): #long signal is acceptable but need and trend lower = self.__bbands.getLowerBand()[-1] upper = self.__bbands.getUpperBand()[-1] ma = self.getBollingerBands().getMiddleBand() low = self.__bbands.getLowerBand() high = self.__bbands.getUpperBand() if lower is None: return False check_point = False # example of acces datatimes #if self.prices.getDateTimes()[-1] : # print self.prices[-1] if cross.cross_above(self.prices, self.__bbands.getLowerBand()): #if self.trend_long(self.__bbands.getUpperBand()) : #if self.trend_long(ma): check_point = True ''' ### remove failling edge if len(low) >5 and low[-5]!= None and check_point == True: check_point = False #print "bband long debug:",self.prices[-1],(low[-1] - low[-5])/low[-5]*100 , low[-5],low[-1] if (low[-1] - low[-5])/low[-5] >= -0.03: check_point = True pass ''' if check_point == True: check_point = False if self.trend_long(self.__bbands.getUpperBand()): check_point = True return check_point
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 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 == 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)
def onBars(self, bars): shares = self.getBroker().getShares(self.__instrument) # If a position was not opened, check if we should enter a long position. if shares == 0: if cross.cross_above(self.__closeDS, self.__sma) > 0: # Enter a buy market order for 10 shares. The order is good till canceled. self.order(self.__instrument, 10, goodTillCanceled=True)
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)
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()
def long(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()) cur_price = bars[self.__instrument].getPrice() # Enter a buy market order. The order is good till canceled. #self.__position = self.enterLong(self.__instrument, shares, True) return True return False
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()
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 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()
def exitLongSignal(self, longPos, extPriceBarDS, extPriceDS): upper, middle, lower = indicator.BBANDS(extPriceDS, count=100, timeperiod=self.bBandsPeriod, matype=MA_Type.SMA, nbdevup=self.numStdDev, nbdevdn=self.numStdDev) longExitFilter_1 = cross.cross_above(extPriceDS, middle) > 0 longExitFilter_2 = longPos.exitActive() return longExitFilter_1 and not longExitFilter_2
def exitShortSignal(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.__LowerBand[-i-2]: m1 += 1 if m1 >= self.__circ-1 and cross.cross_above(self.__close,self.__LowerBand)>0: return True else: return False
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
def enterLongSignal (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.__LowerBand[-i-2]: m1 += 1 if m1 >= self.__circ-1 and cross.cross_above(self.__macd,self.__LowerBand)>0: return True else: return False
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()
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()
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()
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()
def enterLongSignal(self, extPriceBarDS, extPriceDS): trixNear = indicator.TRIX(extPriceDS, count=100, timeperiod=self.trixNearPeriod) trixFar = indicator.TRIX(extPriceDS, count=100, timeperiod=self.trixFarPeriod) longEntryFilter_1 = cross.cross_above(trixNear, trixFar) > 0 return longEntryFilter_1
def testCrossAboveMany(self): count = 100 values1 = [-1 if i % 2 == 0 else 1 for i in range(count)] values2 = [0 for i in range(count)] # Check first value self.assertEqual(cross.cross_above(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_above(values1, values2, i - period + 1, i + 1), 0) else: self.assertEqual(cross.cross_above(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_above(values1, values2, i - period + 1, i + 1), 1) else: self.assertEqual(cross.cross_above(values1, values2, i - period + 1, i + 1), 2) # Check for all values. self.assertEqual(cross.cross_above(values1, values2, 0, count), count / 2)
def testCrossAboveMany(self): count = 100 values1 = [-1 if i % 2 == 0 else 1 for i in range(count)] values2 = [0 for i in range(count)] # Check first value self.assertEqual(cross.cross_above(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_above(values1, values2, i - period + 1, i + 1), 0) else: self.assertEqual( cross.cross_above(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_above(values1, values2, i - period + 1, i + 1), 1) else: self.assertEqual( cross.cross_above(values1, values2, i - period + 1, i + 1), 2) # Check for all values. self.assertEqual(cross.cross_above(values1, values2, 0, count), count / 2)
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
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()
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)
def enterLongSignal (self) : if self.__lastLongPos is not None: if self.__barNum-self.__lastLongPos<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.__LowerBand[-i-2]: m1 += 1 if m1 >= self.__circ-1 and cross.cross_above(self.__close,self.__LowerBand)>0: return 1 else: return 0
def exitShortSignal(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.__LowerBand[-i-2]: m1 += 1 if m1 >= self.__circ-1 and cross.cross_above(self.__macd,self.__LowerBand)>0: return True elif self.__macd[-1]<=self.__LowerBand[-1] and self.__macdMin==self.__macd[-1]: return True elif self.__macd[-1]<=self.__LowerBand[-1]*1.001 and self.__macd[-1]<0.11: return True else: return False
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 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)
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)
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()
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()
def buySignal(self, bars): # a> (价格上穿30日均线) && (价格>SMA价格的3% ||连续三日价格>SMA) return cross.cross_above(self.__prices, self.__sma30) and \ (self.__prices[-1] > (self.__sma[-1] * 1.03) or self.bigger_than_sma())
def enterLongSignal(self) : if cross.cross_above(self.__mals, self.__mall) > 0: return True
def exitShortSignal(self): if cross.cross_above(self.__mass, self.__masl) > 0 and not self.__shortPos.exitActive(): return True
def testCrossAboveOnce(self): values1 = self.__buildSeqDS([1, 1, 1, 10, 1, 1, 1]) values2 = self.__buildSeqDS([2, 2, 2, 2, 2, 2, 2]) # Check every 2 values. self.assertEqual(cross.cross_above(values1, values2, 0, 2), 0) self.assertEqual(cross.cross_above(values1, values2, 1, 3), 0) self.assertEqual(cross.cross_above(values1, values2, 2, 4), 1) self.assertEqual(cross.cross_above(values1, values2, 3, 5), 0) self.assertEqual(cross.cross_above(values1, values2, 4, 6), 0) self.assertEqual(cross.cross_above(values1, values2, 5, 7), 0) # Check every 3 values. self.assertEqual(cross.cross_above(values1, values2, 0, 3), 0) self.assertEqual(cross.cross_above(values1, values2, 1, 4), 1) self.assertEqual(cross.cross_above(values1, values2, 2, 5), 1) self.assertEqual(cross.cross_above(values1, values2, 3, 6), 0) self.assertEqual(cross.cross_above(values1, values2, 4, 7), 0) # Check for all values. self.assertEqual(cross.cross_above(values1, values2, 0, 7), 1) self.assertEqual(cross.cross_above(values1, values2, 0, -1), 1)
def testWithLists(self): self.assertEqual(cross.cross_above([1, 2], [1, 1], -2), 0) self.assertEqual(cross.cross_above([0, 1, 2], [1, 1, 1], -3), 1) self.assertEqual(cross.cross_above([0, 0, 0, 1, 2], [1, 1, 1], -3), 1) self.assertEqual(cross.cross_above([0, 0, 0, 1, 2], [1, 1], -3), 0) self.assertEqual(cross.cross_above([0, 0, 0, 0, 2], [1, 1], -3), 1)
def exitLongSignal(self): return cross.cross_above(self.__priceDS, self.__exitSMA) and not self.__longPos.exitActive()