Code Monkey home page Code Monkey logo

oandapyv20-examples's Introduction

Hi there ๐Ÿ‘‹

I'm a software developer with strong finance roots from the early eighties. (Stocks, options, Forex, ...). I am also a huge fan of REST-API's and author of some Python libraries to enable trading by algorithm and have easy access to the REST-API's of OANDA and SAXO Bank, to make trading 24 hrs/day possible (Forex). Check the repositories for details:

  • oanda-api-v20 (pypi: oandapyV20)
  • saxo_openapi (pypi: saxo_openapi)

Recently I've created the virtual_finance_api library to have easy access to financial data from multiple sources on the web.

When it comes to development, I like to see the full picture, so components like Redis, Postgesql, Docker, ... are key products for me as well.

Further more I love Pandas to deal with data.

Beside development I also have a strong background in unix/linux system administration. Though I use mostly Ubuntu these days, I'm also familiar with CentOS, RedHat, OpenBSD, FreeBSD and a bit SuSE and of course: virtualisation using KVM and Proxmox

oandapyv20-examples's People

Contributors

hootnot avatar paulfjacobs 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

oandapyv20-examples's Issues

Edit stoploss and takeprofit of open trade

I use the code of contrib_mo_tp_sl.py more or less to place a market order with a stop loss and take profit order. I was wondering how to change stoploss and takeprofit of an open trade?

ModuleNotFoundError: No module named 'urwid'

When launchign the pip install -r requirements.txt command, I have this ModuleNotFoundError :

Collecting urwidtrees (from -r requirements.txt (line 5))
  Using cached https://files.pythonhosted.org/packages/88/9d/981617fa083a75cf0b5ebb0ae47c3af6fb69183be1c74cc3ac6d9a0c5964/urwidtrees-1.0.1.1.tar.gz
    ERROR: Complete output from command python setup.py egg_info:
    ERROR: Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/y7/dpr7h0314j39547v43hlj2c40000gn/T/pip-install-bgli1tzw/urwidtrees/setup.py", line 4, in <module>
        import urwidtrees.version as v
      File "/private/var/folders/y7/dpr7h0314j39547v43hlj2c40000gn/T/pip-install-bgli1tzw/urwidtrees/urwidtrees/__init__.py", line 6, in <module>
        from .decoration import DecoratedTree, CollapsibleTree
      File "/private/var/folders/y7/dpr7h0314j39547v43hlj2c40000gn/T/pip-install-bgli1tzw/urwidtrees/urwidtrees/decoration.py", line 4, in <module>
        import urwid
    ModuleNotFoundError: No module named 'urwid'
    ----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/y7/dpr7h0314j39547v43hlj2c40000gn/T/pip-install-bgli1tzw/urwidtrees/

In order to solve this issue, I had to install urwid manually before installing the projects requirements : pip install urwid
Maybe we can find a way to solve this problem?

I'm using pip version 19.1.1 and python version 3.7.3

UnboundLocalError: local variable 'e' referenced before assignment

getting this error when running several examples in stream.py , concurrent_Stream.py and others

i am running Python 3.5 on UBUNTU 16.04 . I have all the requirements install and working . It seems the error is being raised after the local variable has beeb deleted as in Python 3.X

dev@developer:~/Downloads/ALGODEV/oandapyV20-examples-master# python src/oanda_console.py
Traceback (most recent call last):
File "/home/anaconda3/lib/python3.5/site-packages/gevent/greenlet.py", line 536, in run
result = self._run(*self.args, **self.kwargs)
File "/dev/Downloads/ALGODEV/oandapyV20-examples-master/src/console/greenlets/accountdetails.py", line 24, in _run
rv = self.api.request(r)
File "/home/anaconda3/lib/python3.5/site-packages/oandapyV20/oandapyV20.py", line 306, in request
request_args, headers=headers)
File "/home/anaconda3/lib/python3.5/site-packages/oandapyV20/oandapyV20.py", line 243, in __request
response.content.decode('utf-8'))
oandapyV20.exceptions.V20Error
Sun Jan 29 21:40:34 2017 <GAccountDetails at 0x7f0372cf8898> failed with V20Error

Traceback (most recent call last):
File "/home/anaconda3/lib/python3.5/site-packages/gevent/greenlet.py", line 536, in run
result = self._run(*self.args, **self.kwargs)
File "/dev/Downloads/ALGODEV/oandapyV20-examples-master/src/console/greenlets/stream.py", line 59, in _run
raise e
UnboundLocalError: local variable 'e' referenced before assignment

in candle_data.py i am able to pull down the Data without any issues. The issues start when it goes through a try/except block

In concurrent_stream.py

def _run(self):
throws the above error

in stream.py
the try/except block throws an error also

examples requirements

When trying to install examples requirements.txt, with pip3, I get the following error:
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-qjxqjbw7/urwidtrees/setup.py", line 4, in
import urwidtrees.version as v
File "/tmp/pip-build-qjxqjbw7/urwidtrees/urwidtrees/init.py", line 6, in
from .decoration import DecoratedTree, CollapsibleTree
File "/tmp/pip-build-qjxqjbw7/urwidtrees/urwidtrees/decoration.py", line 4, in
import urwid
ModuleNotFoundError: No module named 'urwid'
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-qjxqjbw7/urwidtrees/

DH_KEY_TOO_SMALL

I have set up a docker image with this Dockerfile:

FROM debian:latest
apt-get update
yes | apt-get upgrade
yes | apt-get install python
yes | apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install oandapyV20
yes | apt-get install git
git clone https://github.com/hootnot/oandapyV20-examples
cd oandapyV20-examples/
pip install urwid
pip install -r requirements.txt
CMD tail -f /dev/null

It sets everything up nicely - but when i run
root@ed209233d1bb:/oandapyV20-examples# python src/instruments_list.py

i get:

Traceback (most recent call last):
  File "src/instruments_list.py", line 13, in <module>
    rv = client.request(r)
  File "/usr/local/lib/python2.7/dist-packages/oandapyV20/oandapyV20.py", line 306, in request
    request_args, headers=headers)
  File "/usr/local/lib/python2.7/dist-packages/oandapyV20/oandapyV20.py", line 234, in __request
    raise err
requests.exceptions.SSLError: HTTPSConnectionPool(host='api-fxpractice.oanda.com', port=443): Max retries exceeded with url: /v3/accounts/thomasschindler/instruments (Caused by SSLError(SSLError(1, u'[SSL: DH_KEY_TOO_SMALL] dh key too small (_ssl.c:727)'),))

All i can find on this is that the server must be operating on an outdated TLS version.
Do you have any experience with that?

Issue with granularity

Hello! First of all, thank you very much for posting these Oanda examples, its hard to find many of these out there. As for my question. I keep running the candle-data.py and I get the error

candle-data: error: the following arguments are required: --granularity

What could be causing this? I am sorry if this question seems general, I am still relatively new with python. Also I was wondering what does "clargs" mean and what does it do?

Thank you!

concurrent_stream.py gives max recursion error

python concurrent_stream.py --instrument 'EUR_USD,EUR_AUD'
C:\Users\horse\Documents\myprojects\oandapyV20-examples\src\concurrent_stream.py:36: MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7. Please monkey-patch earlier. See gevent/gevent#1016. Modules that had direct imports (NOT patched): ['urllib3.util.ssl_ (C:\Users\horse\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl_.py)', 'urllib3.util (C:\Users\horse\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\init.py)']. monkey.patch_all()
The Log says:
2022-04-01 13:25:26,926 [DEBUG] urllib3.connectionpool : Starting new HTTPS connection (1): api-fxpractice.oanda.com:443
2022-04-01 13:25:26,949 [DEBUG] urllib3.connectionpool : Starting new HTTPS connection (1): stream-fxpractice.oanda.com:443
2022-04-01 13:25:27,090 [ERROR] main : Generic exception <class 'RecursionError'> concurrent_stream.py 232
2022-04-01 13:25:27,091 [ERROR] main : Some exception: maximum recursion depth exceeded while calling a Python object 0

how to get latest price

Hello,I would like to know how to get the latest price in OANDA-V20 API? My market data application need to display the latest price on the screen, thanks in advance.

Modifying Trade

Is it possible to modify a trade and change it's StopLoss?

Please add -- An example on trading using this library

Is it possible to put together a small single example for trading demonstration only i.e

  1. automatically connect to oanda
  2. Start receiving real-time streaming data and at the same time store the received data for further calculations in step 3 --strategy calculations . Maybe Store it in a database or somewhere that it can be pulled fast to be used algo trading calculation or backtesting etc
  3. Simple strategy for demonstrations only e.g a moving average strategy in 1 minute timeframe
  4. Calculate whether to enter market order -- buy or sell with automated TP and SL
  5. Track the trade
  6. Close the trade
  7. get the portfolio update

just something simple for illustrations

exception error in console program --V20Error

developer@DEV:~/Downloads/ALGODEV/oandapyV20-examples-master# python src/oanda_console.py
Traceback (most recent call last):
File "/home/anaconda3/lib/python3.5/site-packages/gevent/greenlet.py", line 536, in run
result = self._run(*self.args, **self.kwargs)
File "/dev/Downloads/ALGODEV/oandapyV20-examples-master/src/console/greenlets/accountdetails.py", line 24, in _run
rv = self.api.request(r)
File "/home/anaconda3/lib/python3.5/site-packages/oandapyV20/oandapyV20.py", line 306, in request
request_args, headers=headers)
File "/home/anaconda3/lib/python3.5/site-packages/oandapyV20/oandapyV20.py", line 243, in __request
response.content.decode('utf-8'))
oandapyV20.exceptions.V20Error
Sun Jan 29 23:11:39 2017 <GAccountDetails at 0x7f1d5419a898> failed with V20Error

Question -Can you execute trades based on margin or is there a way to convert margin into units for different assets?

Is there any way to set a certain amount of margin to open a position so you don't have to calculate the units? Hope this question makes sense. Let me know if you have any recommendation.

Example:
I want to use only 1% margin but want to buy a higher priced item and then short another asset with 1% margin of my total margin. It would take time to calculate between the two assets. Trying to keep both positions equal for my use case. Decimals would have to be rounded.

Error of oanda_console.py-----NameError: name 'fcntl' is not defined

Hi,
After i set my token and accountID to file respectively and installed all packages in requirements.txt followed the steps, i found this error.

Traceback (most recent call last):
  File "oanda_console.py", line 370, in <module>
    event_loop=GeventLoop())
  File "C:\Users\jingjue\AppData\Local\Programs\Python\Python35\lib\site-packages\urwid\main_loop.py", line 111, in __init__
    screen = raw_display.Screen()
  File "C:\Users\jingjue\AppData\Local\Programs\Python\Python35\lib\site-packages\urwid\raw_display.py", line 89, in __init__
    fcntl.fcntl(self._resize_pipe_rd, fcntl.F_SETFL, os.O_NONBLOCK)
NameError: name 'fcntl' is not defined

how can i fix it?
Thank you!

Unable to fill SHORT orders

Using simplebot, it executes appropriate long trades; however when the state switches from LONG to SHORT the order gets placed and immediately canceled. Is there anyway to correct this?

"orderCreateTransaction": {
    "batchID": "604", 
    "positionFill": "DEFAULT", 
    "stopLossOnFill": {
      "timeInForce": "GTC", 
      "price": "1.19335"
    }, 
    "userID": ......, 
    "takeProfitOnFill": {
      "timeInForce": "GTC", 
      "price": "1.19293"
    }, 
    "timeInForce": "FOK", 
    "instrument": "EUR_USD", 
    "reason": "CLIENT_ORDER", 
    "requestID": "42343179345476034", 
    "time": "2017-09-15T09:01:02.427915503Z", 
    "units": "1000000", 
    "type": "MARKET_ORDER", 
    "id": "604", 
    "accountID": "....."
  }, 
  "orderCancelTransaction": {
    "orderID": "604", 
    "userID": ......, 
    "batchID": "604", 
    "reason": "TAKE_PROFIT_ON_FILL_LOSS", 
    "requestID": "42343179345476034", 
    "time": "2017-09-15T09:01:02.427915503Z", 
    "type": "ORDER_CANCEL", 
    "id": "605", 
    "accountID": "......"
  }, 

ContentDecodingError with InstrumentsCandles

Hi,

I'm seeing intermittent issues with the response ContentDecodingError when using instruments.InstrumentsCandles. Appreciate any help.

Issue

Received response with content-encoding: gzip, but failed to decode it

To reproduce

event = { "ticker": "UK100_GBP", "granularity": "M15"}

granularity = event["granularity"]
ticker = event["ticker"]
  count = 500
  params = {
            "count": count,
            "granularity": granularity,
            "dailyAlignment": 0,
            "alignmentTimezone": "UTC",
        }
r = instruments.InstrumentsCandles(instrument=ticker, params=params)
oandaData = client.request(r)

stackTrace

{
  "errorMessage": "('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect data check'))",
  "errorType": "ContentDecodingError",
  "requestId": "fdc8726c-bbbe-4b50-beed-e2c198a4e54f",
  "stackTrace": [
    "  File \"/var/task/handler.py\", line 3662, in sls_getOandaData\n    oandaData = client.request(r)\n",
    "  File \"/var/task/oandapyV20/oandapyV20.py\", line 337, in request\n    response = self.__request(method, url,\n",
    "  File \"/var/task/oandapyV20/oandapyV20.py\", line 266, in __request\n    raise err\n",
    "  File \"/var/task/oandapyV20/oandapyV20.py\", line 262, in __request\n    response = func(url, stream=stream, headers=headers,\n",
    "  File \"/var/task/requests/sessions.py\", line 600, in get\n    return self.request(\"GET\", url, **kwargs)\n",
    "  File \"/var/task/requests/sessions.py\", line 587, in request\n    resp = self.send(prep, **send_kwargs)\n",
    "  File \"/var/task/requests/sessions.py\", line 745, in send\n    r.content\n",
    "  File \"/var/task/requests/models.py\", line 899, in content\n    self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n",
    "  File \"/var/task/requests/models.py\", line 820, in generate\n    raise ContentDecodingError(e)\n"
  ]
}

Thanks

Question: PriceTable (simplebot)

Is there a way to pull all candle data (Time, Open, High, Low , Close, Volume) using PriceTable? Or is the information limited to requesting only close and volume?

Multiple trades

I've changed the example "conrtib_mo_tp_sl.py" a little bit to take a short position on EUR_DOL by changing the units to a negative value (e.g. -10 units). If I take a long position of 10 units EUR_DOL subsequently I end up ending the short position. How do I get a separate trade for that long position instead of modifying the short position taken earlier?

However, if I take a short position and after that another short position, I get two separate trades. Thanks in advance for your response!

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.