Giter Site home page Giter Site logo

qsforex's Introduction

QuantStart Forex

QSForex is an open-source event-driven backtesting and live trading platform for use in the foreign exchange ("forex") markets, currently in an "alpha" state.

It has been created as part of the Forex Trading Diary series on QuantStart.com to provide the systematic trading community with a robust trading engine that allows straightforward forex strategy implementation and testing.

The software is provided under a permissive "MIT" license (see below).

Current Features

  • Open-Source - QSForex has been released under an extremely permissive open-source MIT License, which allows full usage in both research and commercial applications, without restriction, but with no warranty of any kind whatsoever.
  • Free - QSForex is completely free and costs nothing to download or use.
  • Collaboration - As QSForex is open-source many developers collaborate to improve the software. New features are added frequently. Any bugs are quickly determined and fixed.
  • Software Development - QSForex is written in the Python programming language for straightforward cross-platform support. QSForex contains a suite of unit tests for the majority of its calculation code and new tests are constantly added for new features.
  • Event-Driven Architecture - QSForex is completely event-driven both for backtesting and live trading, which leads to straightforward transitioning of strategies from a research/testing phase to a live trading implementation.
  • Transaction Costs - Spread costs are included by default for all backtested strategies.
  • Backtesting - QSForex features intraday tick-resolution multi-day multi-currency pair backtesting.
  • Trading - QSForex currently supports live intraday trading using the OANDA Brokerage API across a portfolio of pairs.
  • Performance Metrics - QSForex currently supports basic performance measurement and equity visualisation via the Matplotlib and Seaborn visualisation libraries.

Installation and Usage

  1. Visit http://www.oanda.com/ and setup an account to obtain the API authentication credentials, which you will need to carry out live trading. I explain how to carry this out in this article: https://www.quantstart.com/articles/Forex-Trading-Diary-1-Automated-Forex-Trading-with-the-OANDA-API.

  2. Clone this git repository into a suitable location on your machine using the following command in your terminal: git clone https://github.com/mhallsmoore/qsforex.git. Alternative you can download the zip file of the current master branch at https://github.com/mhallsmoore/qsforex/archive/master.zip.

  3. Create a set of environment variables for all of the settings found in the settings.py file in the application root directory. Alternatively, you can "hard code" your specific settings by overwriting the os.environ.get(...) calls for each setting:

# The data directory used to store your backtesting CSV files
CSV_DATA_DIR = "/path/to/your/csv/data/dir"

# The directory where the backtest.csv and equity.csv files 
# will be stored after a backtest is carried out
OUTPUT_RESULTS_DIR = "/path/to/your/output/results/dir"

# Change DOMAIN to "real" if you wish to carry out live trading
DOMAIN = "practice"

# Your OANDA API Access Token (found in your Account Details on their website)
ACCESS_TOKEN = "1234123412341234"

# Your OANDA Account ID (found in your Account Details on their website)
ACCOUNT_ID = "1234123412341234"

# Your base currency (e.g. "GBP", "USD", "EUR" etc.)
BASE_CURRENCY = "GBP"

# Your account equity in the base currency (for backtesting)
EQUITY = Decimal("100000.00")
  1. Create a virtual environment ("virtualenv") for the QSForex code and utilise pip to install the requirements. For instance in a Unix-based system (Mac or Linux) you might create such a directory as follows by entering the following commands in the terminal:
mkdir -p ~/venv/qsforex
cd ~/venv/qsforex
virtualenv .

This will create a new virtual environment to install the packages into. Assuming you downloaded the QSForex git repository into an example directory such as ~/projects/qsforex/ (change this directory below to wherever you installed QSForex), then in order to install the packages you will need to run the following commands:

source ~/venv/qsforex/bin/activate
pip install -r ~/projects/qsforex/requirements.txt

This will take some time as NumPy, SciPy, Pandas, Scikit-Learn and Matplotlib must be compiled. There are many packages required for this to work, so please take a look at these two articles for more information:

You will also need to create a symbolic link from your site-packages directory to your QSForex installation directory in order to be able to call import qsforex within the code. To do this you will need a command similar to the following:

ln -s ~/projects/qsforex/ ~/venv/qsforex/lib/python2.7/site-packages/qsforex

Make sure to change ~/projects/qsforex to your installation directory and ~/venv/qsforex/lib/python2.7/site-packages/ to your virtualenv site packages directory.

You will now be able to run the subsequent commands correctly.

Practice/Live Trading

  1. At this stage, if you simply wish to carry out practice or live trading then you can run python trading/trading.py, which will use the default TestStrategy trading strategy. This simply buys or sells a currency pair every 5th tick. It is purely for testing - do not use it in a live trading environment!

If you wish to create a more useful strategy, then simply create a new class with a descriptive name, e.g. MeanReversionMultiPairStrategy and ensure it has a calculate_signals method. You will need to pass this class the pairs list as well as the events queue, as in trading/trading.py.

Please look at strategy/strategy.py for details.

Backtesting

  1. In order to carry out any backtesting it is necessary to generate simulated forex data or download historic tick data. If you wish to simply try the software out, the quickest way to generate an example backtest is to generate some simulated data. The current data format used by QSForex is the same as that provided by the DukasCopy Historical Data Feed at https://www.dukascopy.com/swiss/english/marketwatch/historical/.

To generate some historical data, make sure that the CSV_DATA_DIR setting in settings.py is to set to a directory where you want the historical data to live. You then need to run generate_simulated_pair.py, which is under the scripts/ directory. It expects a single command line argument, which in this case is the currency pair in BBBQQQ format. For example:

cd ~/projects/qsforex
python scripts/generate_simulated_pair.py GBPUSD

At this stage the script is hardcoded to create a single month's data for January 2014. That is, you will see individual files, of the format BBBQQQ_YYYYMMDD.csv (e.g. GBPUSD_20140112.csv) appear in your CSV_DATA_DIR for all business days in that month. If you wish to change the month/year of the data output, simply modify the file and re-run.

  1. Now that the historical data has been generated it is possible to carry out a backtest. The backtest file itself is stored in backtest/backtest.py, but this only contains the Backtest class. To actually execute a backtest you need to instantiate this class and provide it with the necessary modules.

The best way to see how this is done is to look at the example Moving Average Crossover implementation in the examples/mac.py file and use this as a template. This makes use of the MovingAverageCrossStrategy which is found in strategy/strategy.py. This defaults to trading both GBP/USD and EUR/USD to demonstrate multiple currency pair usage. It uses data found in CSV_DATA_DIR.

To execute the example backtest, simply run the following:

python examples/mac.py

This will take some time. On my Ubuntu desktop system at home, with the historical data generated via generate_simulated_pair.py, it takes around 5-10 mins to run. A large part of this calculation occurs at the end of the actual backtest, when the drawdown is being calculated, so please remember that the code has not hung up! Please leave it until completion.

  1. If you wish to view the performance of the backtest you can simply use output.py to view an equity curve, period returns (i.e. tick-to-tick returns) and a drawdown curve:
python backtest/output.py

And that's it! At this stage you are ready to begin creating your own backtests by modifying or appending strategies in strategy/strategy.py and using real data downloaded from DukasCopy (https://www.dukascopy.com/swiss/english/marketwatch/historical/).

If you have any questions about the installation then please feel free to email me at [email protected].

If you have any bugs or other issues that you think may be due to the codebase specifically, feel free to open a Github issue here: https://github.com/mhallsmoore/qsforex/issues

License Terms

Copyright (c) 2015 Michael Halls-Moore

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Forex Trading Disclaimer

Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. Past performance is not indicative of future results. The high degree of leverage can work against you as well as for you. Before deciding to invest in foreign exchange you should carefully consider your investment objectives, level of experience, and risk appetite. The possibility exists that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose. You should be aware of all the risks associated with foreign exchange trading, and seek advice from an independent financial advisor if you have any doubts.

qsforex's People

Contributors

mhallsmoore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

qsforex's Issues

tick interval from oanda is not constant

Hi Mike, Thanks for sharing the code. I noticed the time interval between two ticks from Oanda is not constant. Sometimes it is short, around 0.1s. Sometimes, it can be more than 5 seconds. I am wondering is it my internet problem or code itself?
Jack

execution error when running for some time.

2016-08-22 20:01:33,803 - qsforex.trading.trading - INFO - Received new order event: Type: ORDER, Instrument: GBPUSD, Units: 2000, Order Type: market, Side: buy
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(_self.__args, *_self.__kwargs)
File "trading/roc.py", line 45, in trade
execution.execute_order(event)
File "/home/weiwu/.virtualenvs/qsforex/local/lib/python2.7/site-packages/qsforex/execution/execution.py", line 73, in execute_order
response = self.conn.getresponse().read().decode("utf-8").replace("\n","").replace("\t","")
File "/usr/lib/python2.7/httplib.py", line 1051, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 415, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 379, in _read_status
raise BadStatusLine(line)
BadStatusLine: ''

2016-08-22 21:15:34,320 - qsforex.trading.trading - INFO - Received new order event: Type: ORDER, Instrument: GBPUSD, Units: 2000, Order Type: market, Side: sell
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(_self.__args, *_self.__kwargs)
File "trading/roc.py", line 45, in trade
execution.execute_order(event)
File "/home/weiwu/.virtualenvs/qsforex/local/lib/python2.7/site-packages/qsforex/execution/execution.py", line 71, in execute_order
params, headers
File "/usr/lib/python2.7/httplib.py", line 979, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py", line 1007, in _send_request
self.putrequest(method, url, **skips)
File "/usr/lib/python2.7/httplib.py", line 877, in putrequest
raise CannotSendRequest()
CannotSendRequest

After this error the trade thread is dead, the program will only show price streaming debug log into the console.
how to solve this? thank you.

V20 Interface

Looks like all new accounts go to the V20 interface. I don't see an option to use the old legacy v1 interface.

Is there any plans on supporting v20?

Would be fun to toy with LSTMs using tensorflow or something lol. I've already started switching some of the code. Pretty much just stream and execution to use v20 using the abstraction layer https://github.com/hootnot/oanda-api-v20. I'll make a pull request when I am done if anyone want to check that out.

Check that Position updates the correct price (re Disqus comment)

"I was reading through your code, specially the 'Position' class and something seemed a bit confusing. When you define 'remove_units' method, it doesn't seem that you are using the 'remove_price', shouldn't that be used to update the 'self.cur_price' instead?"

trading.py - <Response [400]> - how to for request

I see that development ceased about two years ago as per the datetime in the code listing.

  1. Has the code moved elsewhere or has development in fact stopped?
  2. Is qstrader a replacement for qsforex? (I realize that qstrader is explicitly mentioned to be for equities but I figured that I would check)

I ran trading/trading.py but the output to the screen did not occur
(qsforex) gs-macbook-air:qsforex ghbcode$ python trading/trading.py
2017-02-09 10:24:10,978 - qsforex.trading.trading - INFO - Starting trading thread
2017-02-09 10:24:10,978 - qsforex.trading.trading - INFO - Starting price streaming thread

I found a discussion about this but it didn't help. I changed the heartbeat from 0.0 to 0.5 and no luck. So I traced the program and found that 'resp' from trading.py returns
<Response [400]>

In the two years that development ceased the request syntax may have changed.

  1. If I wanted to pick up where would I find out the correct syntax for the request and in fact the syntax for Oanda's forex api currently?

Please excuse me if this is covered elsewhere. I looked around and via google without much luck.

Thanks!

ImportError: No module named urllib3

This is the output I get after running python trading.py
Traceback (most recent call last): File "trading/trading.py", line 12, in <module> from qsforex.execution.execution import OANDAExecutionHandler File "/root/venv/qsforex/local/lib/python2.7/site-packages/qsforex/execution/execution.py", line 13, in <module> import urllib3 ImportError: No module named urllib3

This could just be my setup, but I've tried pip install urllib3 --upgrade and the issue persists

TypeError: Passing a bool to header is invalid with Pandas 0.18.1

$ python qsforex/examples/mac.py
/Users/femto/cache/data/random/GBPUSD_20140101.csv
Traceback (most recent call last):
  File "qsforex/examples/mac.py", line 27, in <module>
    equity=settings.EQUITY
  File "/Users/femto/github/femto/qsforex/backtest/backtest.py", line 29, in __init__
    self.ticker = data_handler(self.pairs, self.events, self.csv_dir)
  File "/Users/femto/github/femto/qsforex/data/price.py", line 107, in __init__
    self.file_dates[self.cur_date_idx]
  File "/Users/femto/github/femto/qsforex/data/price.py", line 144, in _open_convert_csv_files_for_day
    names=("Time", "Ask", "Bid", "AskVolume", "BidVolume")
  File "//anaconda/lib/python3.5/site-packages/pandas/io/parsers.py", line 562, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "//anaconda/lib/python3.5/site-packages/pandas/io/parsers.py", line 315, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "//anaconda/lib/python3.5/site-packages/pandas/io/parsers.py", line 641, in __init__
    self.options, self.engine = self._clean_options(options, engine)
  File "//anaconda/lib/python3.5/site-packages/pandas/io/parsers.py", line 755, in _clean_options
    _validate_header_arg(options['header'])
  File "//anaconda/lib/python3.5/site-packages/pandas/io/common.py", line 265, in _validate_header_arg
    raise TypeError("Passing a bool to header is invalid. "
TypeError: Passing a bool to header is invalid. Use header=None for no header or header=int or list-like of ints to specify the row(s) making up the column names

According docstring

`````` ?pd.read_csv```

header : int or list of ints, default 'infer'
    Row number(s) to use as the column names, and the start of the data.
    Default behavior is as if set to 0 if no ``names`` passed, otherwise
    ``None``. Explicitly pass ``header=0`` to be able to replace existing
    names. The header can be a list of integers that specify row locations for
    a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not
    specified will be skipped (e.g. 2 in this example is skipped). Note that
    this parameter ignores commented lines and empty lines if
    ``skip_blank_lines=True``, so header=0 denotes the first line of data
    rather than the first line of the file

so in https://github.com/mhallsmoore/qsforex/blob/master/data/price.py#L140

        self.pair_frames[p] = pd.io.parsers.read_csv(
            pair_path, header=True, index_col=0, 
            parse_dates=True, dayfirst=True,
            names=("Time", "Ask", "Bid", "AskVolume", "BidVolume")
        )

should be replaced by

        self.pair_frames[p] = pd.io.parsers.read_csv(
            pair_path, header=0, index_col=0, 
            parse_dates=True, dayfirst=True,
            names=("Time", "Ask", "Bid", "AskVolume", "BidVolume")
        )

ImportError: No module named 'qsforex'

Hi,
I use Windows 10. When I've ran "traiding.py" in Spyder appear the following error: ImportError: No module named 'qsforex'

I setup an account to obtain the API authentication credentials, which you will need to carry out live trading.
I made the changes in "settings.py" according to "Forex Trading Diary 1 - Automated Forex Trading with the AONDA API".
I've downloaded the zip file of the current master branch at https://github.com/mhallsmoore/qsforex/archive/master.zip.
I put all the files in the same directory.
I created two directories in it: "QSFOREX_CSV_DATA_DIR" and "QSFOREX_OUTPUT_RESULTS_DIR".
I don't know set environment variables.

Can anyone help to solve the problem?

Best Regards.
Edilson

No result from the screen

Hi Mike,

I previously implemented your code that you provided in Trading Diary #1 and #2, and it seems good. However, after I updated the code according to the Github resource, when I run the trading.py there's no feedback from the screen, and no error information neither. Any suggestions?

Best,

Weibo

Pip package

Hello,

it will be a great idea to provide a pip package.

Kind regards

add a little GUI

Hi,

Would be useful to add a little GUI (Graphic User Interface) to the module.

=> A few entry forms for key parameters
=> A few entry forms for config settings
=> A button to start and stop trading.

I will be doing some work upon it also for my instance of qsforex.

OHLCV bar features

Firstly, thank you very much for the great work on qsforex.

I believe one could develop and backtest strategies based on OHLCV data faster (considering calculations necessary, time jumps faster etc..)... Since I thought considering spread, trading would be profitable at least in the scale of half an hour... As such feature is already established in qstrader, do you think it could also be established on qsforex?

mhallsmoore/qstrader#12

Thank you :)

I would also try to do this on my side as it seems to be very important to me :)

change the instrument pair format from 'aaabbb' to 'aaa_bbb'

the format of pair string is too hard coded. Thus the whole package can only deal with pure currency pairs. But for some new supported product, it doesn't work at all, ex:AU200_AUD, wheat_usd, etc. The format should be changed such that instead of
instrument = "%s_%s" % (event.instrument[:3], event.instrument[3:])
we can simply input the pair string. and we just need pair.split('_') to get the list of the two instrument.

moreover, why not use some oanda api wrapper to do the execution instead of writing our own?
There are well developed python wrappers for v1 and v20 account, we just need to do an conditional import

How can I make my trading system working on a 5 or 15 minutes time frame interval?

Hi Michael,
Can I ask a question about the heartbeat?
Does the thread stop as the heartbeat interval if there is no new ticks coming in? And the thread resumes back to work if there's new ticks coming in?
How can I make my trading system working on a 5 or 15 minutes time frame interval instead of tick by tick?

Thank you.

Regards,
Wei

inverting prices in the PriceHandler

Dear Michael,

when you are inverting prices in the PriceHandler
inv_bid shall be 1/ask and inv_ask shall be 1/bid
since bid is always smaller than ask

Thanks,
Maxim

Support of other brokers (BTC on Kraken)

I would be interested in using qsforex for trading Bitcoins on Kraken and would be willing to implement PriceHandler and ExecutionHandler.
My problem is that I am not sure how these modifications will fit into the overall architecture without making a total mess. If someone could help me or point me to solutions, I would be willing to code the suggested changes if I have time.

Or should I look into qstrader instead?

getting the same error on multiple computer operation systems.

Hi, Michael, I am getting this error under the virtual environment when executing this command:
python trading/trading.py
can you help? thank you.

Traceback (most recent call last): File "trading/trading.py", line 49, in <module> logging.config.fileConfig('../logging.conf') File "/usr/lib/python2.7/logging/config.py", line 77, in fileConfig formatters = _create_formatters(cp) File "/usr/lib/python2.7/logging/config.py", line 113, in _create_formatters flist = cp.get("formatters", "keys") File "/usr/lib/python2.7/ConfigParser.py", line 607, in get raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'formatters'

decimal.InvalidOperation: Invalid literal for Decimal: 'Bid'

When running the backtest for mac.py I get an error as per below.
(qsforex) jbowler@GEN-U-DAE-01:~/Projects/qsforex$ python examples/mac.py

Traceback (most recent call last):
File "examples/mac.py", line 29, in
backtest.simulate_trading()
File "/home/jbowler/venv/qsforex/lib/python2.7/site-packages/qsforex/backtest/backtest.py", line 81, in simulate_trading
self._run_backtest()
File "/home/jbowler/venv/qsforex/lib/python2.7/site-packages/qsforex/backtest/backtest.py", line 57, in _run_backtest
self.ticker.stream_next_tick()
File "/home/jbowler/venv/qsforex/lib/python2.7/site-packages/qsforex/data/price.py", line 182, in stream_next_tick
bid = Decimal(str(row["Bid"])).quantize(
File "/home/jbowler/ProgramData/anaconda2/lib/python2.7/decimal.py", line 547, in new
"Invalid literal for Decimal: %r" % value)
File "/home/jbowler/ProgramData/anaconda2/lib/python2.7/decimal.py", line 3873, in _raise_error
raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'Bid'

How is this fixed?

Thank-you

Check that PnL is being correctly calculated by using bid prices

"Also, when we are calculating the PnL we always hedge back to home currency. So why aren't we using 'Bid' always? For example, say we are short on GBP_USD and the account is denominated in HKD. If we want to close the position then we buy back GBP_USD however we should still use 'bid' price for 'USD_HKD'."

Is project alive?

Hi there!

is this project still alive? I see many pull requests still opened.

Execution module

First run of trading/trading.py:

"Import error: No module named qsforex.execution.execution"

NoneType object passed to os.path.join in portfolio.py

Hello. I am running Ubuntu 14.04 and have tried using this program. When I try to run trading.py I obtain the following error message:

Traceback (most recent call last):
File "trading/trading.py", line 68, in
prices, events, equity=equity, backtest=False
File "/home/justin/forexEnv/local/lib/python2.7/site-packages/qsforex/portfolio/portfolio.py", line 31, in init
self.backtest_file = self.create_equity_file()
File "/home/justin/forexEnv/local/lib/python2.7/site-packages/qsforex/portfolio/portfolio.py", line 74, in create_equity_file
out_file = open(os.path.join(OUTPUT_RESULTS_DIR, filename), "w")
File "/home/justin/forexEnv/lib/python2.7/posixpath.py", line 77, in join
elif path == '' or path.endswith('/'):

I would really appreciate your help, and thanks for making such a helpful blog.

Note: I doubt this would make much of a difference, but I was having a lot of difficulty installing scipy in a virtualenv so I used the --system-site-packages options when creating the virtualenv.

BadStatusLine issue in execution.py

Exception in thread Thread-1:

Traceback (most recent call last):

File "C:\Python27\lib\threading.py", line 810, in

__bootstrap_inner

self.run()


File "C:\Python27\lib\threading.py", line 763, in run

self.__target(_self.__args, *_self.__kwargs)

File "trading.py", line 40, in trade

execution.execute_order(event)

File "c:\documents\qsforex\execution\execution.py", line 71, in

execute_order

response = self.conn.getresponse().read()

File "C:\Python27\lib\httplib.py", line 1132, in getresponse

response.begin()

File "C:\Python27\lib\httplib.py", line 453, in begin

version, status, reason = self._read_status()

File "C:\Python27\lib\httplib.py", line 417, in _read_status

raise BadStatusLine(line)

BadStatusLine: ''

Some people have experienced this bug when holding positions for a long time (20 mins+). Investigate!

Using Enum

Hello,

I see in your code https://github.com/mhallsmoore/qsforex/blob/master/backtest/backtest.py#L60
usage of string

Why not using Enum ?

For Python 3
https://docs.python.org/3/library/enum.html

For Python 2.7 there is enum34 https://pypi.python.org/pypi/enum34

Kind regards

PS: "buy", "sell", "long", "short" should also be Enum

Here is an example usage

in event.py

from enum import Enum
EventType = Enum("EventType", "TICK BAR SIGNAL ORDER FILL")

in backtest.py

if event.type == EventType.TICK:
    self.strategy.calculate_signals(event)
    self.portfolio.update_portfolio(event)
    self.ticks += 1
elif event.type == EventType.SIGNAL:
    self.portfolio.execute_signal(event)
elif event.type == EventType.ORDER:
    self.execution.execute_order(event)

Other Enums to define:

in price_handler/__init__.py

PriceHandlerType = Enum("PriceHandlerType", "TICK BAR")

in portfolio/position.py

PositionType = Enum("PositionType", "LONG", "SHORT")

For qstrader

in position/position.py

PositionActionType = Enum("PositionActionType", "BOT", "SLD")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.