示例#1
0
    def Update(self, datapoint):

        if not isinstance(datapoint, Candle):
            if not self._current_candle:
                openTime = datapoint["now"]
                closeTime = datapoint["now"] + datetime.timedelta(
                    minutes=self._candle_size)
                self._current_candle = Candle(openTime, closeTime)
            else:
                self._current_candle.Update(datapoint)
            self._logging_current_price = datapoint["value"]
        else:
            self._current_candle = datapoint
            self._logging_current_price = datapoint.Close

        # Check if it is Friday night and we should seize trading
        self._timestop.Update(datapoint)
        _state = self._timestop.GetState()
        if _state == MarketTrend.STOP_LONG or _state == MarketTrend.STOP_SHORT:
            if (self._oanda.CurrentPosition() > 0):
                logging.info("Timing Stop fired, TGIF!: " + str(_state) +
                             " price: " + str(self._logging_current_price))
                self.ClosePosition()
                return

        if not self._current_candle.SeenEnoughData():
            return

        self._short_ema.Update(self._current_candle)
        self._long_ema.Update(self._current_candle)

        self._current_candle = None

        if (self._short_ema.value > self._long_ema.value):
            if (self._oanda.CurrentPosition() > 0) and (
                    self._oanda.CurrentPositionSide == MarketTrend.ENTER_LONG):
                return
            else:
                self.ClosePosition()
                self.Buy()

        if (self._long_ema.value > self._short_ema.value):
            if (self._oanda.CurrentPosition() >
                    0) and (self._oanda.CurrentPositionSide
                            == MarketTrend.ENTER_SHORT):
                return
            else:
                self.ClosePosition()
                self.Sell()
示例#2
0
    def GetCandles(self, number_of_last_candles_to_get = 0, size_of_candles_in_minutes = 120):
        Candles = []

        if number_of_last_candles_to_get <= 0 or size_of_candles_in_minutes <= 0:
            return Candles

        _granularity = self._getGranularity(size_of_candles_in_minutes)
        response = self._oanda.get_history(instrument=self._instrument,
                                granularity=_granularity,
                                count=number_of_last_candles_to_get + 1,
                                candleFormat="midpoint"
                                )

        if not response.has_key("candles"):
            return Candles

        for item in response["candles"]:
            if item["complete"] != True:
                continue

            close_ts = datetime.datetime.fromtimestamp(
                        time.mktime(time.strptime(str(item['time']), '%Y-%m-%dT%H:%M:%S.%fZ')))
            open_ts = close_ts - datetime.timedelta(minutes = size_of_candles_in_minutes)

            c = Candle(open_ts, close_ts)
            c.Open  = item["openMid"]
            c.High  = item["highMid"]
            c.Low   = item["lowMid"]
            c.Close = item["closeMid"]
            c._is_closed = True
            Candles.append(c)

        self._oanda_price_streamer.update_necessary = True

        return sorted(Candles, key = lambda candle: candle.CloseTime)
示例#3
0
 def get_candle(self, candle_size):
     _, datapoint = self.get_next_line()
     open_time = datapoint['now']
     close_time = datetime.fromtimestamp(
         datapoint['now']) + timedelta(minutes=candle_size)
     close_time = time.mktime(close_time.timetuple()) + \
         close_time.microsecond * 0.000001
     candle = Candle(open_time, close_time)
     candle.update(datapoint)
     while not candle.seen_enough_data():
         _, datapoint = self.get_next_line()
         candle.update(datapoint)
     return candle
示例#4
0
    def get_candles(self, last_candles=0, size=120):
        candles = []

        if last_candles <= 0 or size <= 0:
            return candles

        _granularity = get_granularity(size)
        response = self._oanda.get_history(instrument=self._instrument,
                                           granularity=_granularity,
                                           count=last_candles + 1,
                                           candleFormat='midpoint')

        if 'candles' not in response:
            return candles

        for item in response['candles']:
            if item['complete'] is not True:
                continue

            close_ts = dateutil.parser.parse(item['time'])
            open_ts = close_ts - \
                datetime.timedelta(minutes=size)

            close_ts = time.mktime(close_ts.timetuple()) + \
                close_ts.microsecond * 0.000001
            open_ts = time.mktime(open_ts.timetuple()) + \
                open_ts.microsecond * 0.000001

            candle = Candle(open_ts, close_ts)
            candle.open = item['mid']['o']
            candle.high = item['mid']['h']
            candle.low = item['mid']['l']
            candle.close = item['mid']['c']
            candle.set_closed(True)
            candles.append(candle)

        self._oanda_price_streamer.update_necessary = True

        return sorted(candles, key=lambda candle: candle.CloseTime)
示例#5
0
class Strategy(object):

    SHORT_EMA_PERIOD = 7
    LONG_EMA_PERIOD = 21

    def __init__(self, oanda, candle_size=120, email=None, risk=2):
        self._oanda = oanda
        self._oanda.SubscribeTicker(self)
        self._current_candle = None
        self._candle_size = candle_size
        self._risk = RiskManager(oanda, risk)
        self._email = email
        self._short_ema = movingaverage.ExponentialMovingAverage(
            Strategy.SHORT_EMA_PERIOD)
        self._long_ema = movingaverage.ExponentialMovingAverage(
            Strategy.LONG_EMA_PERIOD)
        self._timestop = TimeStop()
        self._logging_current_price = 0.0
        self.trading_enabled = False

    def Start(self):
        logging.info("Starting strategy")
        # Prefeed the strategy with historic candles
        candle_count = self._long_ema.AmountOfDataStillMissing() + 1
        Candles = self._oanda.GetCandles(candle_count, self._candle_size)
        for c in Candles:
            self._short_ema.Update(c)
            self._long_ema.Update(c)
        self._oanda.StartPriceStreaming()
        self.trading_enabled = True

    def PauseTrading(self):
        logging.info("Pausing strategy")
        self.trading_enabled = False

    def ResumeTrading(self):
        logging.info("Resuming strategy")
        self.trading_enabled = True

    def TradingStatus(self):
        return self.trading_enabled

    def SetTradingStatus(self, tstatus):
        self.trading_enabled = tstatus

    def Stop(self):
        logging.info("Stop strategy")
        self.SetTradingStatus(False)
        self._oanda.StopPriceStreaming()

    def Update(self, datapoint):

        if not isinstance(datapoint, Candle):
            if not self._current_candle:
                openTime = datapoint["now"]
                closeTime = datapoint["now"] + datetime.timedelta(
                    minutes=self._candle_size)
                self._current_candle = Candle(openTime, closeTime)
            else:
                self._current_candle.Update(datapoint)
            self._logging_current_price = datapoint["value"]
        else:
            self._current_candle = datapoint
            self._logging_current_price = datapoint.Close

        # Check if it is Friday night and we should seize trading
        self._timestop.Update(datapoint)
        _state = self._timestop.GetState()
        if _state == MarketTrend.STOP_LONG or _state == MarketTrend.STOP_SHORT:
            if (self._oanda.CurrentPosition() > 0):
                logging.info("Timing Stop fired, TGIF!: " + str(_state) +
                             " price: " + str(self._logging_current_price))
                self.ClosePosition()
                return

        if not self._current_candle.SeenEnoughData():
            return

        self._short_ema.Update(self._current_candle)
        self._long_ema.Update(self._current_candle)

        self._current_candle = None

        if (self._short_ema.value > self._long_ema.value):
            if (self._oanda.CurrentPosition() > 0) and (
                    self._oanda.CurrentPositionSide == MarketTrend.ENTER_LONG):
                return
            else:
                self.ClosePosition()
                self.Buy()

        if (self._long_ema.value > self._short_ema.value):
            if (self._oanda.CurrentPosition() >
                    0) and (self._oanda.CurrentPositionSide
                            == MarketTrend.ENTER_SHORT):
                return
            else:
                self.ClosePosition()
                self.Sell()

    def Buy(self):

        logging.info("Strategy Buy() called. Going long @ " +
                     str(self._logging_current_price))

        if not self.trading_enabled:
            logging.info("Strategy trading disabled, doing nothing")
            return

        # Enter the long position on the instrument
        units = self._risk.GetLongPositionSize()
        logging.info("Got the number of units to trade from RiskManager: " +
                     str(units))
        if units == 0:
            logging.info("Cant trade zero units, doing nothing")
            return

        try:
            self._oanda.Buy(units)
        except Exception as e:
            self._catchTradeException(e, "enter long")

    def Sell(self):

        logging.info("Strategy Sell() called. Going short @ " +
                     str(self._logging_current_price))
        if not self.trading_enabled:
            logging.info("Trading disabled, doing nothing")
            return

        # Enter the short position on the instrument
        units = self._risk.GetShortPositionSize()
        logging.info("Got the number of units to trade from RiskManager: " +
                     str(units))
        if units == 0:
            logging.info("Cant trade 0 units, doing nothing")
            return

        try:
            self._oanda.Sell(units)
        except Exception as e:
            self._catchTradeException(e, "enter short")

    def ClosePosition(self):

        logging.info("Closing position, and all stops")
        if not self.trading_enabled:
            logging.info("Trading disabled, doing nothing")
            return

        try:
            self._oanda.ClosePosition()
        except Exception as e:
            self._catchTradeException(e, "close")

    def GetStopLossPrice(self):
        return 0.0

    def GetTrailingStopPrice(self):
        return 0.0

    def _catchTradeException(self, e, position):
        logging.critical("Failed to " + position + " position")
        logging.critical(traceback.format_exc())
        if self._email:
            txt = "\n\nError while trying to " + position + " position\n"
            txt += "It was caught, I should still be running\n\n"
            txt += traceback.format_exc() + "\n" + str(e)
            self._email.Send(txt)
    def update(self, datapoint):
        if not isinstance(datapoint, Candle):
            if not self._current_candle or self._current_candle.seen_enough_data(
            ):
                openTime = datapoint["now"]
                closeTime = datetime.datetime.fromtimestamp(
                    datapoint["now"]) + datetime.timedelta(
                        minutes=self._candle_size)
                closeTime = time.mktime(
                    closeTime.timetuple()) + closeTime.microsecond * 0.000001
                self._current_candle = Candle(openTime, closeTime)
                self._current_candle.update(datapoint)
            else:
                self._current_candle.update(datapoint)
            self._sl_indicator.update(datapoint)
            self._tp_indicator.update(datapoint)
            self._logging_current_price = datapoint["value"]
        else:
            self._current_candle = datapoint
            self._logging_current_price = datapoint.close

        # Check if it is Friday night and we should seize trading
        self._timestop.update(datapoint)
        _state = self._timestop.GetState()
        if _state == MarketTrend.STOP_LONG or _state == MarketTrend.STOP_SHORT:
            if (self._oanda.current_position() != 0):
                logging.info("Timing Stop fired, TGIF!: " + str(_state) +
                             " price: " + str(self._logging_current_price))
                self.ClosePosition('short')
                self.ClosePosition('long')
                return

        if not self._current_candle.seen_enough_data():
            return

        self._macross.update(self._current_candle)
        self._sl_indicator.update(self._current_candle)
        self._tp_indicator.update(self._current_candle)

        sl = self._sl_indicator.GetState()
        if sl == MarketTrend.STOP_LONG or sl == MarketTrend.STOP_SHORT:
            if self._oanda.current_position() != 0:
                self.ClosePosition('both')
                logging.info("STOP called @ " +
                             str(self._logging_current_price))
                self._sl_indicator.CancelStop()
                return

        tp = self._tp_indicator.GetState()
        if tp == MarketTrend.STOP_LONG or tp == MarketTrend.STOP_SHORT:
            if self._oanda.current_position() != 0:
                self.ClosePosition('both')
                logging.info("TAKE PROFIT called @ " +
                             str(self._logging_current_price))
                self._tp_indicator.CancelTakeProfit()
                return

        ma = self._macross.GetState()
        if ma == MarketTrend.ENTER_LONG:
            if self._oanda.current_position(
            ) != 0 and self._oanda.current_side() == MarketTrend.ENTER_LONG:
                return
            else:
                self.ClosePosition('short')
                self._tp_indicator.SetTakeProfit(
                    self._logging_current_price - self._take_profit,
                    MarketTrend.ENTER_LONG)
                self._sl_indicator.SetStop(
                    self._logging_current_price - self._stop_loss,
                    MarketTrend.ENTER_LONG)
                self.Buy()
                return
        elif ma == MarketTrend.ENTER_SHORT:
            if self._oanda.current_position(
            ) != 0 and self._oanda.current_side() == MarketTrend.ENTER_SHORT:
                return
            else:
                self.ClosePosition('long')
                self._tp_indicator.SetTakeProfit(
                    self._logging_current_price + self._take_profit,
                    MarketTrend.ENTER_SHORT)
                self._sl_indicator.SetStop(
                    self._logging_current_price - self._stop_loss,
                    MarketTrend.ENTER_SHORT)
                self.Sell()
                return
class Strategy(object):

    SHORT_EMA_PERIOD = 7
    MEDIUM_EMA_PERIOD = 26
    LONG_SMA_PERIOD = 50

    def __init__(self,
                 oanda,
                 candle_size=120,
                 email=None,
                 risk=2,
                 stoploss=20,
                 trailing_period=7,
                 take_profit=20):
        self._oanda = oanda
        self._oanda.subscribe_ticker(self)
        self._current_candle = None
        self._candle_size = candle_size
        self._risk = RiskManager(oanda, risk)
        self._stop_loss = stoploss
        self._take_profit = take_profit
        self._email = email
        self._macross = MACross(Strategy.SHORT_EMA_PERIOD,
                                Strategy.MEDIUM_EMA_PERIOD,
                                Strategy.LONG_SMA_PERIOD)
        self._sl_indicator = StopLoss(trailing_period)
        self._tp_indicator = TakeProfit()
        self._timestop = TimeStop()
        self._logging_current_price = 0.0
        self.trading_enabled = False

    def Start(self):
        logging.info("Starting strategy")
        # Prefeed the strategy with historic candles
        candle_count = self._macross.amount_of_data_still_missing() + 1
        self._oanda.start_price_streaming()
        candles = self._oanda.get_candles(candle_count, self._candle_size)
        for c in candles:
            self._macross.update(c)
            self._sl_indicator.update(c)
            self._tp_indicator.update(c)
        self.trading_enabled = True

    def PauseTrading(self):
        logging.info("Pausing strategy")
        self.trading_enabled = False

    def ResumeTrading(self):
        logging.info("Resuming strategy")
        self.trading_enabled = True

    def TradingStatus(self):
        return self.trading_enabled

    def SetTradingStatus(self, tstatus):
        self.trading_enabled = tstatus

    def stop(self):
        logging.info("Stop strategy")
        self.SetTradingStatus(False)
        self._oanda.StopPriceStreaming()

    def update(self, datapoint):
        if not isinstance(datapoint, Candle):
            if not self._current_candle or self._current_candle.seen_enough_data(
            ):
                openTime = datapoint["now"]
                closeTime = datetime.datetime.fromtimestamp(
                    datapoint["now"]) + datetime.timedelta(
                        minutes=self._candle_size)
                closeTime = time.mktime(
                    closeTime.timetuple()) + closeTime.microsecond * 0.000001
                self._current_candle = Candle(openTime, closeTime)
                self._current_candle.update(datapoint)
            else:
                self._current_candle.update(datapoint)
            self._sl_indicator.update(datapoint)
            self._tp_indicator.update(datapoint)
            self._logging_current_price = datapoint["value"]
        else:
            self._current_candle = datapoint
            self._logging_current_price = datapoint.close

        # Check if it is Friday night and we should seize trading
        self._timestop.update(datapoint)
        _state = self._timestop.GetState()
        if _state == MarketTrend.STOP_LONG or _state == MarketTrend.STOP_SHORT:
            if (self._oanda.current_position() != 0):
                logging.info("Timing Stop fired, TGIF!: " + str(_state) +
                             " price: " + str(self._logging_current_price))
                self.ClosePosition('short')
                self.ClosePosition('long')
                return

        if not self._current_candle.seen_enough_data():
            return

        self._macross.update(self._current_candle)
        self._sl_indicator.update(self._current_candle)
        self._tp_indicator.update(self._current_candle)

        sl = self._sl_indicator.GetState()
        if sl == MarketTrend.STOP_LONG or sl == MarketTrend.STOP_SHORT:
            if self._oanda.current_position() != 0:
                self.ClosePosition('both')
                logging.info("STOP called @ " +
                             str(self._logging_current_price))
                self._sl_indicator.CancelStop()
                return

        tp = self._tp_indicator.GetState()
        if tp == MarketTrend.STOP_LONG or tp == MarketTrend.STOP_SHORT:
            if self._oanda.current_position() != 0:
                self.ClosePosition('both')
                logging.info("TAKE PROFIT called @ " +
                             str(self._logging_current_price))
                self._tp_indicator.CancelTakeProfit()
                return

        ma = self._macross.GetState()
        if ma == MarketTrend.ENTER_LONG:
            if self._oanda.current_position(
            ) != 0 and self._oanda.current_side() == MarketTrend.ENTER_LONG:
                return
            else:
                self.ClosePosition('short')
                self._tp_indicator.SetTakeProfit(
                    self._logging_current_price - self._take_profit,
                    MarketTrend.ENTER_LONG)
                self._sl_indicator.SetStop(
                    self._logging_current_price - self._stop_loss,
                    MarketTrend.ENTER_LONG)
                self.Buy()
                return
        elif ma == MarketTrend.ENTER_SHORT:
            if self._oanda.current_position(
            ) != 0 and self._oanda.current_side() == MarketTrend.ENTER_SHORT:
                return
            else:
                self.ClosePosition('long')
                self._tp_indicator.SetTakeProfit(
                    self._logging_current_price + self._take_profit,
                    MarketTrend.ENTER_SHORT)
                self._sl_indicator.SetStop(
                    self._logging_current_price - self._stop_loss,
                    MarketTrend.ENTER_SHORT)
                self.Sell()
                return

    def Buy(self):
        logging.info("Strategy Buy() called. Going long @ " +
                     str(self._logging_current_price))

        if not self.trading_enabled:
            logging.info("Strategy trading disabled, doing nothing")
            return

        # Enter the long position on the instrument
        units = self._risk.GetLongPositionSize()
        if units == 0:
            logging.info("Cant trade zero units, doing nothing")
            return

        try:
            self._oanda.buy(units)
        except Exception as e:
            self._catchTradeException(e, "enter long")

    def Sell(self):
        logging.info("Strategy Sell() called. Going short @ " +
                     str(self._logging_current_price))
        if not self.trading_enabled:
            logging.info("Trading disabled, doing nothing")
            return

        # Enter the short position on the instrument
        units = self._risk.GetShortPositionSize()
        logging.info("Got the number of units to trade from RiskManager: " +
                     str(units))
        if units == 0:
            logging.info("Cant trade 0 units, doing nothing")
            return

        try:
            self._oanda.sell(units)
        except Exception as e:
            self._catchTradeException(e, "enter short")

    def ClosePosition(self, position):
        logging.info("Closing %s position, and all stops" % position)
        self._sl_indicator.CancelStop()
        if not self.trading_enabled:
            logging.info("Trading disabled, doing nothing")
            return

        try:
            self._oanda.close_position(position)
        except Exception as e:
            self._catchTradeException(e, "close")

    def GetStopLossPrice(self):
        return 0.0

    def GetTakeProfitPrice(self):
        return self._tp_indicator.GetPrice(self._oanda.current_side())

    def GetTrailingStopPrice(self):
        return self._sl_indicator.GetPrice()

    def _catchTradeException(self, e, position):
        logging.critical("Failed to " + position + " position")
        logging.critical(traceback.format_exc())
        if self._email:
            txt = "\n\nError while trying to " + position + " position\n"
            txt += "It was caught, I should still be running\n\n"
            txt += traceback.format_exc() + "\n" + str(e)
            self._email.Send(txt)
示例#8
0
    def Update(self, datapoint):
        logging.info("StrategyUpdate")
        if not isinstance(datapoint, Candle):
            if not self._current_candle:
                openTime = datapoint["now"]
                closeTime = datapoint["now"] + datetime.timedelta(
                    minutes=self._candle_size)
                logging.info("close time test---- put 0300-0330 here")
                logging.info(closeTime)
                self._current_candle = Candle(openTime, closeTime)
            else:
                self._current_candle.Update(datapoint)
                #update July 8 2019
                #round(datapoint["value"],5) fix for invalid precicion error in oanda.py
            self._logging_current_price = round(
                datapoint["value"], 5)  #format(datapoint["value"], '.5f')
        else:
            self._current_candle = datapoint
            self._logging_current_price = round(datapoint.Close, 5)

        # Check if it is Friday night and we should seize trading
        self._timestop.Update(datapoint)
        _state = self._timestop.GetState()
        if _state == MarketTrend.STOP_LONG or _state == MarketTrend.STOP_SHORT:
            if (self._oanda.CurrentPosition() > 0):
                logging.info("Timing Stop fired, TGIF!: " + str(_state) +
                             " price: " + str(self._logging_current_price))
                self.ClosePosition()
                return

        if not self._current_candle.SeenEnoughData():
            return

        self._short_ema.Update(self._current_candle)
        self._long_ema.Update(self._current_candle)

        self._current_candle = None

        logging.info("Price: " + str(round(self._logging_current_price, 5)))
        logging.info("Long EMA: " + str(round(self._long_ema.value, 5)))
        logging.info("short EMA: " + str(round(self._short_ema.value, 5)))
        logging.info("TP Price LONG: " +
                     str(round(self._logging_current_price + self._tp, 5)))
        logging.info("TP Price SHORT: " +
                     str(round(self._logging_current_price - self._tp, 5)))

        #Take Profit
        if (self._logging_current_price > self.takeProfit):
            self.ClosePosition()

        #localtime = time.localtime(time.time())
        #if (localtime.tm_hour-4 == 3 and localtime.tm_min < 31):
        if (self._logging_current_price > self._short_ema.value):
            logging.info("PRICE ABOVE EMA STRATEGY TEST")
            if (self._oanda.CurrentPosition() > 0):
                #if (self._oanda.CurrentPosition() > 0) and (self._oanda.CurrentPositionSide == MarketTrend.ENTER_SHORT):
                return
            else:
                logging.info("PRICE ABOVE EMA STRATEGY TEST")
                #self.ClosePosition()
                #self.Sell()

        #strategy being used
        if (self._logging_current_price < self._short_ema.value):
            logging.info("PRICE BELOW EMA STRATEGY TEST")
            logging.info(self._current_candle)
            #Check if current position is open
            if (self._oanda.CurrentPosition() > 0):
                #if (self._short_ema.value > self._long_ema.value):
                #if (self._oanda.CurrentPosition() > 0) and (self._oanda.CurrentPositionSide == MarketTrend.ENTER_LONG):
                return
            else:
                self.ClosePosition()
                self.Buy()
示例#9
0
class Strategy(object):

    SHORT_EMA_PERIOD = 50
    LONG_EMA_PERIOD = 200

    def __init__(self, oanda, candle_size=120, email=None, risk=2):
        self._oanda = oanda
        self._oanda.SubscribeTicker(self)
        self._current_candle = None
        self._candle_size = candle_size
        self._risk = RiskManager(oanda, risk)
        self._email = email
        self._short_ema = movingaverage.ExponentialMovingAverage(
            Strategy.SHORT_EMA_PERIOD)
        self._long_ema = movingaverage.ExponentialMovingAverage(
            Strategy.LONG_EMA_PERIOD)
        self._timestop = TimeStop()
        self._logging_current_price = 0.0
        self.trading_enabled = False
        self._tp = 0.00035
        self.takeProfit = 0.0

    def Start(self):
        logging.info("Starting strategy")
        #self._catchTradeException("---","email test")
        # Prefeed the strategy with historic candles
        candle_count = self._long_ema.AmountOfDataStillMissing() + 1
        Candles = self._oanda.GetCandles(candle_count, self._candle_size)
        for c in Candles:
            self._short_ema.Update(c)
            self._long_ema.Update(c)
        self._oanda.StartPriceStreaming()
        self.trading_enabled = True

    def PauseTrading(self):
        logging.info("Pausing strategy")
        self.trading_enabled = False

    def ResumeTrading(self):
        logging.info("Resuming strategy")
        self.trading_enabled = True

    def TradingStatus(self):
        return self.trading_enabled

    def SetTradingStatus(self, tstatus):
        self.trading_enabled = tstatus

    def Stop(self):
        logging.info("Stop strategy")
        self.SetTradingStatus(False)
        self._oanda.StopPriceStreaming()

    def Update(self, datapoint):
        logging.info("StrategyUpdate")
        if not isinstance(datapoint, Candle):
            if not self._current_candle:
                openTime = datapoint["now"]
                closeTime = datapoint["now"] + datetime.timedelta(
                    minutes=self._candle_size)
                logging.info("close time test---- put 0300-0330 here")
                logging.info(closeTime)
                self._current_candle = Candle(openTime, closeTime)
            else:
                self._current_candle.Update(datapoint)
                #update July 8 2019
                #round(datapoint["value"],5) fix for invalid precicion error in oanda.py
            self._logging_current_price = round(
                datapoint["value"], 5)  #format(datapoint["value"], '.5f')
        else:
            self._current_candle = datapoint
            self._logging_current_price = round(datapoint.Close, 5)

        # Check if it is Friday night and we should seize trading
        self._timestop.Update(datapoint)
        _state = self._timestop.GetState()
        if _state == MarketTrend.STOP_LONG or _state == MarketTrend.STOP_SHORT:
            if (self._oanda.CurrentPosition() > 0):
                logging.info("Timing Stop fired, TGIF!: " + str(_state) +
                             " price: " + str(self._logging_current_price))
                self.ClosePosition()
                return

        if not self._current_candle.SeenEnoughData():
            return

        self._short_ema.Update(self._current_candle)
        self._long_ema.Update(self._current_candle)

        self._current_candle = None

        logging.info("Price: " + str(round(self._logging_current_price, 5)))
        logging.info("Long EMA: " + str(round(self._long_ema.value, 5)))
        logging.info("short EMA: " + str(round(self._short_ema.value, 5)))
        logging.info("TP Price LONG: " +
                     str(round(self._logging_current_price + self._tp, 5)))
        logging.info("TP Price SHORT: " +
                     str(round(self._logging_current_price - self._tp, 5)))

        #Take Profit
        if (self._logging_current_price > self.takeProfit):
            self.ClosePosition()

        #localtime = time.localtime(time.time())
        #if (localtime.tm_hour-4 == 3 and localtime.tm_min < 31):
        if (self._logging_current_price > self._short_ema.value):
            logging.info("PRICE ABOVE EMA STRATEGY TEST")
            if (self._oanda.CurrentPosition() > 0):
                #if (self._oanda.CurrentPosition() > 0) and (self._oanda.CurrentPositionSide == MarketTrend.ENTER_SHORT):
                return
            else:
                logging.info("PRICE ABOVE EMA STRATEGY TEST")
                #self.ClosePosition()
                #self.Sell()

        #strategy being used
        if (self._logging_current_price < self._short_ema.value):
            logging.info("PRICE BELOW EMA STRATEGY TEST")
            logging.info(self._current_candle)
            #Check if current position is open
            if (self._oanda.CurrentPosition() > 0):
                #if (self._short_ema.value > self._long_ema.value):
                #if (self._oanda.CurrentPosition() > 0) and (self._oanda.CurrentPositionSide == MarketTrend.ENTER_LONG):
                return
            else:
                self.ClosePosition()
                self.Buy()

        #if (self._long_ema.value > self._short_ema.value):
        #if (self._oanda.CurrentPosition() > 0) and (self._oanda.CurrentPositionSide == MarketTrend.ENTER_SHORT):
        #return
        #else:
        #self.ClosePosition()
        #self.Sell()

    def Buy(self):

        logging.info("Strategy Buy() called. Going long @ " +
                     str(self._logging_current_price))

        #backtest take profit
        self.takeProfit = round(self._logging_current_price + self._tp, 5)

        if not self.trading_enabled:
            logging.info("Strategy trading disabled, doing nothing")
            return

        # Enter the long position on the instrument
        units = self._risk.GetLongPositionSize()

        logging.info("Got the number of units to trade from RiskManager: " +
                     str(units) + " with a TP position of: " +
                     str(self._logging_current_price + self._tp))
        if units == 0:
            logging.info("Cant trade zero units, doing nothing")
            return

        try:
            #self.takeProfit = round(self._logging_current_price + self._tp,5)
            logging.info("takeProfit: " + str(self.takeProfit))
            self._oanda.Buy(units, self.takeProfit)
        except Exception as e:
            self._catchTradeException(e, "enter long")

    def Sell(self):

        logging.info("Strategy Sell() called. Going short @ " +
                     str(self._logging_current_price))
        if not self.trading_enabled:
            logging.info("Trading disabled, doing nothing")
            return

        # Enter the short position on the instrument
        units = self._risk.GetShortPositionSize()
        #tp=.0015
        logging.info("Got the number of units to trade from RiskManager: " +
                     str(units) + " with a TP position of: " +
                     str(self._logging_current_price + .0015))
        if units == 0:
            logging.info("Cant trade 0 units, doing nothing")
            return

        try:
            self._oanda.Sell(units, takeProfit)
        except Exception as e:
            self._catchTradeException(e, "enter short")

    def ClosePosition(self):

        logging.info("Closing position, and all stops")
        if not self.trading_enabled:
            logging.info("Trading disabled, doing nothing")
            return

        try:
            self._oanda.ClosePosition()
        except Exception as e:
            self._catchTradeException(e, "close")

    def GetStopLossPrice(self):
        return 0.0

    def GetTrailingStopPrice(self):
        return 0.0

    def _catchTradeException(self, e, position):
        logging.critical("Failed to " + position + " position")
        logging.critical(traceback.format_exc())
        if self._email:
            txt = "\n\nError while trying to " + position + " position\n"
            txt += "It was caught, I should still be running\n\n"
            txt += traceback.format_exc() + "\n" + str(e)
            self._email.Send(txt)