Beispiel #1
0
    def __initclist(self):
        '''
        Private function to initialize the CandleList object that goes from self.start
        to self.period

        This will set the self.clist_period class attribute
        '''

        delta_period = periodToDelta(self.period, self.timeframe)
        delta_1 = periodToDelta(1, self.timeframe)
        start = self.start - delta_period  # get the start datetime for this CandleList period
        end = self.start + delta_1  # increase self.start by one candle to include self.start

        oanda = OandaAPI(
            url=config.OANDA_API['url'],
            instrument=self.pair,
            granularity=self.timeframe,
            alignmentTimezone=config.OANDA_API['alignmentTimezone'],
            dailyAlignment=config.OANDA_API['dailyAlignment'])

        oanda.run(start=start.isoformat(), end=end.isoformat(), roll=True)

        candle_list = oanda.fetch_candleset(vol_cutoff=0)

        cl = CandleList(candle_list,
                        self.pair,
                        granularity=self.timeframe,
                        id=self.id,
                        type=self.type)

        self.clist_period = cl
Beispiel #2
0
    def __get_time4candles(self, n, anchor_point, roll=True):
        '''
        This private function takes a a number of candles
        and returns a Datetime corresponding to
        this number of candles

        Parameters
        ----------
        n : int
            Number of candles
        anchor_point : datetime
            Datetime used as the anchor (end point from which it will go back 'n' candles) for calculation
        roll : boolean
               if True, then if will try to go back in time in order to get exactly 'n' number of candles.
               Default: True

        Returns
        -------
        Datetime.datetime
        '''

        delta_from_start = None
        delta_one = None
        if self.timeframe == "D":
            delta_from_start = datetime.timedelta(hours=24 * n)
            delta_one = datetime.timedelta(hours=24)
        else:
            fgran = self.timeframe.replace('H', '')
            delta_from_start = datetime.timedelta(hours=int(fgran) * n)
            delta_one = datetime.timedelta(hours=int(fgran))

        # calculate the cutoff for the first threshold using the number of candles
        oanda = OandaAPI(
            url=config.OANDA_API['url'],
            instrument=self.pair,
            granularity=self.timeframe,
            alignmentTimezone=config.OANDA_API['alignmentTimezone'],
            dailyAlignment=config.OANDA_API['dailyAlignment'])

        start = anchor_point - delta_from_start
        if roll is True:
            if start < config.START_HIST[self.pair]:
                #return the first candle in the record if start goes back before the start of the record
                return config.START_HIST[self.pair]
            else:
                end = anchor_point.isoformat()

                oanda.run(start=start.isoformat(), end=end, roll=True)

                candle_list = oanda.fetch_candleset()

                # if len of candle_list is below n then go back one candle at a time
                while len(candle_list) < n:
                    start = start - delta_one
                    oanda.run(start=start.isoformat(), end=end, roll=True)
                    candle_list = oanda.fetch_candleset()

                return start
        else:
            return start
Beispiel #3
0
def oanda_object():
    '''Returns an  oanda object'''

    oanda = OandaAPI(url='https://api-fxtrade.oanda.com/v1/candles?',
                     instrument='EUR_AUD',
                     granularity='D',
                     dailyAlignment=22,
                     alignmentTimezone='Europe/London')
    oanda.run(start='2015-08-26T22:00:00',
              end='2016-08-15T22:00:00')

    return oanda
Beispiel #4
0
def trend_oanda_object():
    '''Returns an oanda object for a candlelist representing a trend'''

    oanda = OandaAPI(url='https://api-fxtrade.oanda.com/v1/candles?',
                     instrument='AUD_USD',
                     granularity='D',
                     alignmentTimezone='Europe/London',
                     dailyAlignment=22)

    oanda.run(start='2017-12-08T22:00:00',
              end='2018-01-29T22:00:00',
              roll=True)
    return oanda
Beispiel #5
0
def test_OandaAPI13():
    '''

    :return:
    '''

    oanda = OandaAPI(url='https://api-fxtrade.oanda.com/v1/candles?',
                     instrument='AUD_USD',
                     granularity='H6',
                     alignmentTimezone='Europe/London',
                     dailyAlignment=22)

    oanda.run(start='2007-05-29T16:00:00',
              end='2014-04-01T15:00:00',
              roll=True)
Beispiel #6
0
    def __init_clist_period(self):
        '''
        Private function to initialise self.clist_period class attribute

        This function process the candlelist going from self.start-self.period to
        self.start
        '''

        warnings.warn("[INFO] Run __init_clist_period")

        delta_period = None
        delta_1 = None
        if self.timeframe == "D":
            delta_period = datetime.timedelta(hours=24 * self.period)
            delta_1 = datetime.timedelta(hours=24)
        else:
            fgran = self.timeframe.replace('H', '')
            delta_period = datetime.timedelta(hours=int(fgran) * self.period)
            delta_1 = datetime.timedelta(hours=int(fgran))

        start = self.start - delta_period
        end = self.start + delta_1

        oanda = OandaAPI(
            url=config.OANDA_API['url'],
            instrument=self.pair,
            granularity=self.timeframe,
            alignmentTimezone=config.OANDA_API['alignmentTimezone'],
            dailyAlignment=config.OANDA_API['dailyAlignment'])

        oanda.run(start=start.isoformat(), end=end.isoformat(), roll=True)

        candle_list = oanda.fetch_candleset(vol_cutoff=0)

        cl = CandleList(candle_list,
                        self.pair,
                        granularity=self.timeframe,
                        id=self.id)

        warnings.warn("[INFO] Run cl.calc_rsi")

        cl.calc_rsi()

        warnings.warn("[INFO] Done cl.calc_rsi")

        self.clist_period = cl
Beispiel #7
0
    def get_cross_time(self, candle, granularity='M30'):
        '''
        This function is used get the time that the candle
        crosses (go through) HArea

        Parameters
        ----------
        candle :   Candle object that crosses the HArea
        granularity : To what granularity we should descend

        Returns
        ------
        datetime object with crossing time.
                 n.a. if crossing time could not retrieved. This can happens
                 when there is an artifactual jump in the Oanda data
        '''

        if candle.lowAsk <= self.price <= candle.highAsk:
            delta = None
            if self.granularity == "D":
                delta = timedelta(hours=24)
            else:
                fgran = self.granularity.replace('H', '')
                delta = timedelta(hours=int(fgran))

            cstart = candle.time
            cend = cstart + delta

            oanda = OandaAPI(
                url=config.OANDA_API['url'],
                instrument=self.instrument,
                granularity=granularity,
                dailyAlignment=config.OANDA_API['dailyAlignment'],
                alignmentTimezone=config.OANDA_API['alignmentTimezone'])

            oanda.run(start=cstart.isoformat(),
                      end=cend.isoformat(),
                      roll=True)

            candle_list = oanda.fetch_candleset()
            for c in candle_list:
                if c.lowAsk <= self.price <= c.highAsk:
                    return c.time
        else:
            return 'n.a.'
Beispiel #8
0
def cl_object():
    '''Returns CandleList object'''

    oanda = OandaAPI(url='https://api-fxtrade.oanda.com/v1/candles?',
                     instrument='AUD_USD',
                     granularity='D',
                     alignmentTimezone='Europe/London',
                     dailyAlignment=22)

    oanda.run(start='2018-01-25T22:00:00',
              end='2018-10-12T22:00:00',
              roll=True)

    candle_list = oanda.fetch_candleset()

    cl = CandleList(candle_list, instrument='AUD_USD', type='long')

    return cl
Beispiel #9
0
    def __init_clist_trend(self):
        '''
        Private function to initialise self.clist_trend class attribute

        This function process the candlelist going from self.trend_i to self.start
        '''

        warnings.warn("[INFO] Run __init_clist_trend")

        # if trend_i is not defined then calculate it
        if hasattr(self, 'trend_i'):
            self.trend_i = datetime.datetime.strptime(self.trend_i,
                                                      '%Y-%m-%d %H:%M:%S')
        else:
            self.calc_itrend()
        self.__init_clist_trend()

        # checking for feats in trend before 1st bounce
        oanda = OandaAPI(
            url=config.OANDA_API['url'],
            instrument=self.pair,
            granularity=self.timeframe,
            alignmentTimezone=config.OANDA_API['alignmentTimezone'],
            dailyAlignment=config.OANDA_API['dailyAlignment'])

        oanda.run(start=self.trend_i.isoformat(),
                  end=self.start.isoformat(),
                  roll=True)

        candle_list = oanda.fetch_candleset(vol_cutoff=0)

        cl = CandleList(candle_list,
                        instrument=self.pair,
                        granularity=self.timeframe,
                        id=self.id)

        warnings.warn("[INFO] Run cl.calc_rsi")

        cl.calc_rsi()

        warnings.warn("[INFO] Done cl.calc_rsi")

        self.clist_trend = cl
Beispiel #10
0
def pl_object2():
    '''Returns PivotList object'''

    oanda = OandaAPI(url='https://api-fxtrade.oanda.com/v1/candles?',
                     instrument='AUD_USD',
                     granularity='D',
                     alignmentTimezone='Europe/London',
                     dailyAlignment=22)

    oanda.run(start='2016-01-15T22:00:00',
              end='2016-08-17T22:00:00',
              roll=True)

    candle_list = oanda.fetch_candleset()

    cl = CandleList(candle_list, instrument='AUD_USD', type='long')

    pl = cl.get_pivotlist(outfile='test.png', th_up=0.02, th_down=-0.02)

    return pl
Beispiel #11
0
    def set_valley(self):
        '''
        Function to calculate the length of the valley
        between bounce_1st & bounce_2nd

        Returns
        -------
        It will set the 'valley' attribute of the class
        '''

        oanda = OandaAPI(
            url=config.OANDA_API['url'],
            instrument=self.pair,
            granularity=self.timeframe,
            alignmentTimezone=config.OANDA_API['alignmentTimezone'],
            dailyAlignment=config.OANDA_API['dailyAlignment'])

        oanda.run(start=self.bounce_2nd.time.isoformat(),
                  end=self.bounce_1st.time.isoformat())

        candle_list = oanda.fetch_candleset(vol_cutoff=0)

        self.valley = len(candle_list)
Beispiel #12
0
    return bounce_lengths


oanda = OandaAPI(url=config.OANDA_API['url'],
                 instrument=args.instrument,
                 granularity=args.granularity,
                 alignmentTimezone=config.OANDA_API['alignmentTimezone'],
                 dailyAlignment=config.OANDA_API['dailyAlignment'])

delta_period = periodToDelta(config.SRarea['period'], args.granularity)
startObj = datetime.datetime.strptime(args.start, "%Y-%m-%d %H:%M:%S")

start = startObj - delta_period  # get the start datetime for this CandleList period
end = startObj

oanda.run(start=start.isoformat(), end=end.isoformat(), roll=True)

candle_list = oanda.fetch_candleset()

cl = CandleList(clist=candle_list,
                instrument=args.instrument,
                granularity=args.instrument)

plist = cl.get_pivotlist(
    th_down=config.SRarea['th_down'],
    th_up=-config.SRarea['th_up'],
    outfile="/Users/ernesto/PycharmProjects/FOREX/scripts/test.png")

bounce_dict = {}

hr_extension = 30
Beispiel #13
0
    def calc_rsi(self, period=2000, rsi_period=14):
        '''
        Calculate the RSI for a certain candle list

        Parameters
        ----------
        period : int
                 Number of candles before this CandleList start for which close price data will be fetched.
                 The larger the number of candles the more accurate the ewm calculation will be, as the exponential
                 moving average calculated for each of the windows (of size=rsi_period) will be
                 directly affected by the previous windows in the series. Default=2000
        rsi_period : int
                     Number of candles used for calculating the RSI. Default=14

        Returns
        -------
        Nothing
        '''

        start_time=self.clist[0].time
        end_time=self.clist[-1].time

        delta_period = None
        if self.granularity == "D":
            delta_period = datetime.timedelta(hours=24 * period)
        else:
            fgran = self.granularity.replace('H', '')
            delta_period = datetime.timedelta(hours=int(fgran) * period)

        start_calc_time = start_time - delta_period


        #fetch candle set from start_calc_time
        oanda = OandaAPI(url=config.OANDA_API['url'],
                         instrument=self.instrument,
                         granularity=self.granularity,
                         alignmentTimezone=config.OANDA_API['alignmentTimezone'],
                         dailyAlignment=config.OANDA_API['dailyAlignment'])

        '''
        Get candlelist from start_calc_time to (start_time-1)
        This 2-step API call is necessary in order to avoid
        maximum number of candles errors
        '''

        oanda.run(start=start_calc_time.isoformat(),
                  end=start_time.isoformat(),
                  roll=True)
        cl1 = oanda.fetch_candleset()

        '''Get candlelist from start_time to end_time'''
        oanda.run(start=start_time.isoformat(),
                  end=end_time.isoformat(),
                  roll=True)

        cl2 = oanda.fetch_candleset()

        if cl1[-1].time == cl2[0].time:
            del cl1[-1]

        candle_list = cl1 + cl2

        series=[]
        series = [c.closeAsk for c in candle_list]

        df = pd.DataFrame({'close': series})
        chg = df['close'].diff(1)

        gain = chg.mask(chg < 0, 0)
        loss = chg.mask(chg > 0, 0)

        avg_gain = gain.ewm(com=rsi_period - 1, min_periods=rsi_period).mean()
        avg_loss = loss.ewm(com=rsi_period - 1, min_periods=rsi_period).mean()

        rs = abs(avg_gain / avg_loss)

        rsi = 100 - (100 / (1 + rs))

        rsi4cl=rsi[-len(self.clist):]
        # set rsi attribute in each candle of the CandleList
        ix=0
        for c,v in zip(self.clist,rsi4cl):
            self.clist[ix].rsi=v
            ix+=1
Beispiel #14
0
    def run_trade(self):
        '''
        Run the trade until conclusion from a start date
        '''

        print("[INFO] Run run_trade with id: {0}".format(self.id))

        entry = HArea(price=self.entry,
                      pips=1,
                      instrument=self.pair,
                      granularity=self.timeframe)
        SL = HArea(price=self.SL,
                   pips=1,
                   instrument=self.pair,
                   granularity=self.timeframe)
        TP = HArea(price=self.TP,
                   pips=1,
                   instrument=self.pair,
                   granularity=self.timeframe)

        period = None
        if self.timeframe == "D":
            period = 24
        else:
            period = int(self.timeframe.replace('H', ''))

        # generate a range of dates starting at self.start and ending numperiods later in order to assess the outcome
        # of trade and also the entry time

        self.start = datetime.datetime.strptime(str(self.start),
                                                '%Y-%m-%d %H:%M:%S')
        numperiods = 300
        date_list = [
            datetime.datetime.strptime(str(self.start.isoformat()),
                                       '%Y-%m-%dT%H:%M:%S') +
            datetime.timedelta(hours=x * period) for x in range(0, numperiods)
        ]

        entered = False
        for d in date_list:
            oanda = OandaAPI(
                url=config.OANDA_API['url'],
                instrument=self.pair,
                granularity=self.timeframe,
                dailyAlignment=config.OANDA_API['dailyAlignment'],
                alignmentTimezone=config.OANDA_API['alignmentTimezone'])

            oanda.run(start=d.isoformat(), count=1, roll=True)

            cl = oanda.fetch_candleset()[0]

            if entered is False:
                entry_time = entry.get_cross_time(candle=cl)
                warnings.warn("\t[INFO] Trade entered")
                if entry_time != 'n.a.':
                    self.entry_time = entry_time.isoformat()
                else:
                    warnings.warn(
                        "No entry time was identified for this trade")
                    entry_time = self.start
                    self.entry_time = entry_time
            if entry_time is not None and entry_time != 'n.a.':
                entered = True
            if entered is True:
                failure_time = SL.get_cross_time(candle=cl)
                if failure_time is not None and failure_time != 'n.a.':
                    self.outcome = 'failure'
                    self.end = failure_time
                    self.pips = float(
                        calculate_pips(self.pair,
                                       abs(self.SL - self.entry))) * -1
                    warnings.warn("\t[INFO] S/L was hit")
                    break
            if entered is True:
                success_time = TP.get_cross_time(candle=cl)
                if success_time is not None and success_time != 'n.a.':
                    self.outcome = 'success'
                    warnings.warn("\t[INFO] T/P was hit")
                    self.end = success_time
                    self.pips = float(
                        calculate_pips(self.pair, abs(self.TP - self.entry)))
                    break

        assert getattr(self, 'outcome')

        warnings.warn("[INFO] Done run_trade")