Help with oandatest.py on samples
-
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 -
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()
-
@ThatBlokeDave Many many thanks!
-
@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 -
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?
-
oandapy
is probably not installed and that is the reason for the absence of the store.See Docs - Oanda for the installation instructions
-
@backtrader Hi, oandapy is installed, i also imported (although not necessary) it , still the same error, can't find Oandastore.
-
@ThatBlokeDave Hi, I didn't make any change to your code, apart from oanda account number and token.
-
@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.
-
Hi,
I just used pip install backtrader from command prompt. How do i check version or install latest? -
import backtrader print(backtrader.__version__)
But because Oanda was integrated already a while ago, the suspect is still the absence of
oandapy
-
import backtrader
print(backtrader.version)1.9.34.116
-
import oandapy
oandapy
Out[73]: <module 'oandapy' from 'C:\Users\Mahbub\Anaconda3\lib\site-packages\oandapy\init.py'> -
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.
-
-
@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?
-
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/
-
-
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 '''
-
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.
-
@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!!