Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Help with oandatest.py on samples

    General Code/Help
    5
    42
    12828
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • M
      mahbubk9 last edited by

      Hi,
      I am a new to backtrader, and trying to use backtrader for live trading with oanda api.
      looking at oandatest.py, is it all i need to go live? do i need a separate file for oanda account and token details? what is" token=args.token" doing?
      Also, where is timeframe defined?" timeframe = bt.TimeFrame.TFrame(args.timeframe)" what do i need to do to get 1 min timeframe?
      Lastly, how do i choose an instrument? " data0 = DataFactory(dataname=args.data0, **datakwargs)
      " what is happening here?
      Any kind explanation would be highly appreciated.
      Thanks,
      Mahbub

      1 Reply Last reply Reply Quote 0
      • T
        ThatBlokeDave last edited by

        oandatest.py is a sample script to showcase the oanda store integration.

        I assume you have created an API token on oanda's website right? If not you will need to get the tokens first on their website. Note you need to open a old Rest API account. This cannot be done on the practice server so you will need to ask customer support to help make you one.

        Regarding args.token, when you run the script you can add a set of arguments like so...

        python3 oandatest.py --account <INSERT YOUR ACC NUMBER HERE> --token <INSERT YOUR TOKEN HERE> --data0 GBP_USD --resample --timeframe Minutes --compression 1 --no-backfill_start --stake 1000 --trade
        

        so token=args.token is looking at the argument you enter when running the program and assigning it to a token variable. Notice the above also uses the arguments to select an instrument (GBP_USD)

        I suggest you use oandatest as a reference but start with a very simple script. Something with no arguments that just prints prices for example and then build it up from there:

        Here is a simple example:

        import argparse
        import datetime
        import backtrader as bt
        
        apikey = 'Insert your api key here'
        acc = 'insert your acc num here'
        
        # Create a Stratey
        class TestStrategy(bt.Strategy):
        
            def __init__(self):
                pass
        
            #Provides any noticficaitons about the data.
            def notify_data(self, data, status, *args, **kwargs):
                print('*' * 5, 'DATA NOTIF:', data._getstatusname(status), *args)
        
            def notify_store(self, msg, *args, **kwargs):
                print('*' * 5, 'STORE NOTIF:', msg)
        
            def next(self):
                # Simply log the closing price of the series from the reference
                print('O: {} H: {} L: {} C: {}'.format(
                        self.data.open[0],
                        self.data.high[0],
                        self.data.low[0],
                        self.data.close[0],
                        ))
        
        
            def start(self):
                if self.data0.contractdetails is not None:
                    print('-- Contract Details:')
                    print(self.data0.contractdetails)
                print('Started')
                acc_cash = cerebro.broker.getcash()
                acc_val = cerebro.broker.getvalue()
                print('Account Cash = {}'.format(acc_cash))
                print('Account Value = {}'.format(acc_val))
        
        
        if __name__ == '__main__':
            cerebro = bt.Cerebro()
            oandastore = bt.stores.OandaStore(token=apikey, account=acc, practice=True)
            cerebro.broker = oandastore.getbroker()
        
            data0 = oandastore.getdata(dataname="GBP_USD", timeframe=bt.TimeFrame.Ticks, compression=1, backfill_start=False, backfill=False)
        
            #This is setting what timeframe we want to use.
            cerebro.resampledata(data0, timeframe=bt.TimeFrame.Minutes, compression=5)
        
            cerebro.addstrategy(TestStrategy)
            cerebro.run()
        
        1 Reply Last reply Reply Quote 0
        • M
          mahbubk9 last edited by

          @ThatBlokeDave Many many thanks!

          1 Reply Last reply Reply Quote 0
          • M
            mahbubk9 last edited by

            @ThatBlokeDave
            Getting this ; oandastore = bt.stores.OandaStore(token=apikey, account=acc, practice=True)

            AttributeError: module 'backtrader.stores' has no attribute 'OandaStore'

            after running your code with my credentials,
            please help,
            Mahbub

            T 1 Reply Last reply Reply Quote 0
            • T
              ThatBlokeDave @mahbubk9 last edited by

              @mahbubk9

              Can you post your edited version of the script here? I ran it just now and it is working for me.

              Also can you check the version of back trader you are running?

              What platform are you on?

              B 1 Reply Last reply Reply Quote 0
              • B
                backtrader administrators last edited by

                oandapy is probably not installed and that is the reason for the absence of the store.

                See Docs - Oanda for the installation instructions

                1 Reply Last reply Reply Quote 0
                • M
                  mahbubk9 last edited by

                  @backtrader Hi, oandapy is installed, i also imported (although not necessary) it , still the same error, can't find Oandastore.

                  1 Reply Last reply Reply Quote 0
                  • M
                    mahbubk9 last edited by

                    @ThatBlokeDave Hi, I didn't make any change to your code, apart from oanda account number and token.

                    1 Reply Last reply Reply Quote 0
                    • B
                      backtrader administrators @ThatBlokeDave last edited by

                      @ThatBlokeDave said in Help with oandatest.py on samples:

                      Also can you check the version of backtrader you are running?

                      The question from @ThatBlokeDave can play a role in case an old version is installed.

                      1 Reply Last reply Reply Quote 0
                      • M
                        mahbubk9 last edited by

                        Hi,
                        I just used pip install backtrader from command prompt. How do i check version or install latest?

                        1 Reply Last reply Reply Quote 0
                        • B
                          backtrader administrators last edited by

                          import backtrader
                          print(backtrader.__version__)
                          

                          But because Oanda was integrated already a while ago, the suspect is still the absence of oandapy

                          1 Reply Last reply Reply Quote 0
                          • M
                            mahbubk9 last edited by

                            import backtrader
                            print(backtrader.version)

                            1.9.34.116

                            1 Reply Last reply Reply Quote 0
                            • M
                              mahbubk9 last edited by

                              import oandapy

                              oandapy
                              Out[73]: <module 'oandapy' from 'C:\Users\Mahbub\Anaconda3\lib\site-packages\oandapy\init.py'>

                              1 Reply Last reply Reply Quote 0
                              • B
                                backtrader administrators last edited by backtrader

                                Whether oandapy works under Python 3 is unknown. This code from the package:

                                class Streamer(EndpointsMixin, object):
                                    """ Provides functionality for HTTPS Streaming
                                    """
                                    __metaclass__ = ABCMeta
                                

                                shows it was made for Python 2. It might still work but this can only be confirmed by someone with a setup similar to yours. It's down to your setup.

                                T 1 Reply Last reply Reply Quote 0
                                • T
                                  ThatBlokeDave @backtrader last edited by

                                  Just to confirm, I have a setup similar but not identical to @mahbubk9. I am using python3 with backtrader (1.9.33.116) and oandapy (0.1).

                                  I am not familiar with python on windows though. @mahbubk9 Perhaps it is an environment issue preventing backtrader from accessing oandapy?

                                  1 Reply Last reply Reply Quote 0
                                  • M
                                    mahbubk9 last edited by backtrader

                                    @ThatBlokeDave I ran the code on jypyter qt console and got this output,

                                    Started
                                    Account Cash = 0.0
                                    Account Value = 0.0
                                    ***** DATA NOTIF: NOTSUBSCRIBED
                                    Exception in thread Thread-6:
                                    Traceback (most recent call last):
                                      File "C:\Users\Mahbub\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
                                        self.run()
                                      File "C:\Users\Mahbub\Anaconda3\lib\threading.py", line 864, in run
                                        self._target(*self._args, **self._kwargs)
                                      File "C:\Users\Mahbub\Anaconda3\lib\site-packages\backtrader\stores\oandastore.py", line 335, in _t_streaming_listener
                                        self._transaction(trans)
                                      File "C:\Users\Mahbub\Anaconda3\lib\site-packages\backtrader\stores\oandastore.py", line 565, in _transaction
                                        ttype = trans['type']
                                    KeyError: 'type'
                                    
                                    Exception in thread Thread-10:
                                    Traceback (most recent call last):
                                      File "C:\Users\Mahbub\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
                                        self.run()
                                      File "C:\Users\Mahbub\Anaconda3\lib\threading.py", line 864, in run
                                        self._target(*self._args, **self._kwargs)
                                      File "C:\Users\Mahbub\Anaconda3\lib\site-packages\backtrader\stores\oandastore.py", line 548, in _t_order_cancel
                                        if oref is None:
                                    NameError: name 'oref' is not defined
                                    

                                    is it a backtrader/oandastore.py bug?

                                    1 Reply Last reply Reply Quote 0
                                    • B
                                      backtrader administrators last edited by

                                      It would help if you:

                                      • Show what you have actually executed. The sample code given to you by @ThatBlokeDave contains no trading code

                                        The NOTSUBSCRIBED notification is a good hint that not data will come in, hence nothing else will work.

                                      • Format the input and output so that people can properly read it (see the top of the page). For reference

                                        For code/output blocks: a) Prepend 4 spaces to each line of the block, or b) Use ``` in a single line before and after the block. See: http://commonmark.org/help/
                                        
                                      1 Reply Last reply Reply Quote 0
                                      • M
                                        mahbubk9 last edited by backtrader

                                        import oandapy
                                        
                                        import argparse
                                        import datetime
                                        import backtrader as bt
                                        
                                        apikey = 'my api key'
                                        acc = 'my acc no'
                                        
                                        # Create a Stratey
                                        class TestStrategy(bt.Strategy):
                                        
                                            def __init__(self):
                                                pass
                                        
                                            #Provides any noticficaitons about the data.
                                            def notify_data(self, data, status, *args, **kwargs):
                                                print('*' * 5, 'DATA NOTIF:', data._getstatusname(status), *args)
                                        
                                            def notify_store(self, msg, *args, **kwargs):
                                                print('*' * 5, 'STORE NOTIF:', msg)
                                        
                                            def next(self):
                                                # Simply log the closing price of the series from the reference
                                                print('O: {} H: {} L: {} C: {}'.format(
                                                        self.data.open[0],
                                                        self.data.high[0],
                                                        self.data.low[0],
                                                        self.data.close[0],
                                                        ))
                                        
                                        
                                            def start(self):
                                                if self.data0.contractdetails is not None:
                                                    print('-- Contract Details:')
                                                    print(self.data0.contractdetails)
                                                print('Started')
                                                acc_cash = cerebro.broker.getcash()
                                                acc_val = cerebro.broker.getvalue()
                                                print('Account Cash = {}'.format(acc_cash))
                                                print('Account Value = {}'.format(acc_val))
                                        
                                        
                                            if __name__ == '__main__':
                                            cerebro = bt.Cerebro()
                                            oandastore = bt.stores.OandaStore(token=apikey, account=acc, practice=True)
                                            cerebro.broker = oandastore.getbroker()
                                        
                                            data0 = oandastore.getdata(dataname="GBP_USD", timeframe=bt.TimeFrame.Ticks, compression=1, backfill_start=False, backfill=False)
                                        
                                            #This is setting what timeframe we want to use.
                                            cerebro.resampledata(data0, timeframe=bt.TimeFrame.Minutes, compression=5)
                                        
                                            cerebro.addstrategy(TestStrategy)
                                            cerebro.run()
                                        
                                        Started
                                        Account Cash = 0.0
                                        Account Value = 0.0
                                        ***** DATA NOTIF: NOTSUBSCRIBED
                                        Exception in thread Thread-6:
                                        Traceback (most recent call last):
                                          File "C:\Users\Mahbub\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
                                            self.run()
                                          File "C:\Users\Mahbub\Anaconda3\lib\threading.py", line 864, in run
                                            self._target(*self._args, **self._kwargs)
                                          File "C:\Users\Mahbub\Anaconda3\lib\site-packages\backtrader\stores\oandastore.py", line 335, in _t_streaming_listener
                                            self._transaction(trans)
                                          File "C:\Users\Mahbub\Anaconda3\lib\site-packages\backtrader\stores\oandastore.py", line 565, in _transaction
                                            ttype = trans['type']
                                        KeyError: 'type '''
                                        
                                        1 Reply Last reply Reply Quote 0
                                        • B
                                          backtrader administrators last edited by

                                          A long shot: since you have no cash in your account, there is no permission to download data and hence the NOTSUBSCRIBED.

                                          But the error has changed, so this is for sure not the same code that was run previously.

                                          B 1 Reply Last reply Reply Quote 0
                                          • M
                                            mahbubk9 last edited by

                                            @backtrader I was initially using spyder idle and running programs like oandatest.py from there, while running ThatBlokeDave's code(the one posted before) i got that error ;
                                            '''
                                            File
                                            "C:/Users/Mahbub/Documents/PythonTrading/test1.py", line 50, in <module>
                                            oandastore = bt.stores.OandaStore(token=apikey, account=acc, practice=True)

                                            AttributeError: module 'backtrader.stores' has no attribute 'OandaStore'
                                            '''
                                            Then ThatBlokeDave suggested that there could be problem with environment variable...
                                            Then i put the whole code as console input and got those error msgs

                                            ##So, my main problem is python not finding backtrader.stores.oandastore
                                            Please help!!

                                            1 Reply Last reply Reply Quote 0
                                            • 1
                                            • 2
                                            • 3
                                            • 1 / 3
                                            • First post
                                              Last post
                                            Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
                                            $(document).ready(function () { app.coldLoad(); }); }