Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reorganize example folder and add a python example #80

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/python/oracle_arb_finder/.env-example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BLOCKCHAIN_PROVIDER=
148 changes: 148 additions & 0 deletions examples/python/oracle_arb_finder/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

.vscode/
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace

# Local History for Visual Studio Code
.history/
38 changes: 38 additions & 0 deletions examples/python/oracle_arb_finder/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Oracle OrFeed

Oracle OrFeed is a Python program which retrieves the prices of the tokens provided by the oracle OrFeed, and try to find arb opportunities.

## Environnement
You have to rename `.env-example` to `.env`. Then insert your BLOCKCHAIN_PROVIDER in `.env` file. This can be
NB : Leave the variable network as is.
```
BLOCKCHAIN_PROVIDER=
NETWORK=mainnet
```

## Installation

Create a virtual environment and nstall the package listed in requirements.txt

```bash
python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt
```

## Usage

```python
python3 app.py
```

## Author
This project is forked from [https://github.com/edd34/oracle_orfeed](https://github.com/edd34/oracle_orfeed)

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## License
[MIT](https://choosealicense.com/licenses/mit/)
26 changes: 26 additions & 0 deletions examples/python/oracle_arb_finder/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from helper.get_price import (
get_raw_price_async,
get_clean_price,
compute_arb_opportunities,
get_output,
)
from pprint import pprint


def get_list_arb():
"""Run the arb finder

Returns:
List: List sorted by % of all arb opportunities found.
"""
dict_price_raw = get_raw_price_async()
dict_clean_price = get_clean_price(dict_price_raw)
list_arb_price = compute_arb_opportunities(dict_clean_price)
res = get_output(list_arb_price)
sorted_list_arb = sorted(res.items(), key=lambda i: i[1]["%"], reverse=True)
pprint(sorted_list_arb)
return sorted_list_arb


if __name__ == "__main__":
get_list_arb()
Empty file.
83 changes: 83 additions & 0 deletions examples/python/oracle_arb_finder/core/functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import os
import time
import pprint
from core.token_infos import init_dict_token_dex
from core.orfeed import Orfeed
from dotenv import load_dotenv

load_dotenv()
import web3
from web3 import Web3
from tqdm import tqdm


def getTokenToTokenPrice(orfeed_i, tokenSrc, tokenDst, dex, amount_src_token=1):
"""Get the rate of swap tokenSrc to tokenDst in a given Dex

Args:
orfeed_i (OrFeed): The instance of OrFeed class
tokenSrc (Symbol): Symbol of src token
tokenDst (Symbol): Symbol of dst token
dex (str): The Dex where the rate is going to be requested
amount_src_token (int, optional): Amount of src token. Defaults to 1 src token unit.

Returns:
Dict: Return a dict containing all relevant infos about the request
"""
res = orfeed_i.getExchangeRate(tokenSrc, tokenDst, dex, amount_src_token)

return {
"tokenSrc": tokenSrc,
"tokenDst": tokenDst,
"tokenPair": tokenSrc + "-" + tokenDst,
"provider": dex,
"price": res,
}


def simple_getTokenToTokenPrice(
orfeed_i, src_token, src_token_infos, dst_token, dst_token_infos
):
"""For a pair of token, retrieve prices between Uniswap Dex and Kyber Dex.

Args:
orfeed_i (OrFeed): Instance of OrFeed
src_token (Symbol): : Symbol of src token
src_token_infos (Dict): Dict containing src token infos (number of decimals and address)
dst_token (Symbol): Symbol of dst_token
dst_token_infos (Symbol): Dict containing dst token infos (number of decimals and address)

Returns:
Dict: Dict containing all infos about buy/sell.
"""
result = {}
providers_list = ["UNISWAPBYSYMBOLV2", "KYBERBYSYMBOLV1"]
tmp_res = {}
for provider in providers_list:
buy = getTokenToTokenPrice(
orfeed_i,
src_token,
dst_token,
provider,
amount_src_token=10 ** src_token_infos["decimals"],
)
sell = getTokenToTokenPrice(
orfeed_i, dst_token, src_token, provider, amount_src_token=buy["price"]
)
tmp_res[provider] = {
"buy_price_wei": buy["price"] / (10 ** dst_token_infos["decimals"]),
"sell_price_wei": sell["price"]
* buy["price"]
/ (10 ** (dst_token_infos["decimals"] + src_token_infos["decimals"])),
}
if buy["price"] > 0 and sell["price"] > 0:
tmp_res[provider] = {
"buy_price_wei": buy["price"] / (10 ** dst_token_infos["decimals"]),
"sell_price_wei": sell["price"]
* buy["price"]
/ (10 ** (dst_token_infos["decimals"] + src_token_infos["decimals"])),
}
else:
return None
result[provider] = tmp_res[provider]
return result
69 changes: 69 additions & 0 deletions examples/python/oracle_arb_finder/core/orfeed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from web3 import Web3
from core.smartcontracts import my_smartcontracts


class Orfeed:
"""OrFeed class
Initialise the blockchain provider
Implement some methods in order to call method in OrFeed smartcontract
https://etherscan.io/address/0x8316b082621cfedab95bf4a44a1d4b64a6ffc336
"""
def __init__(self, web3):
"""Initialize the blockchain provider

Args:
web3 (string): url of blockchain provider, can be Infura or AlchemyAPI
"""
self.orfeed_address = Web3.toChecksumAddress(
my_smartcontracts["orfeed"]["address"]
)
self.w3 = web3
self.orfeed_contract = self.w3.eth.contract(
address=self.orfeed_address, abi=my_smartcontracts["orfeed"]["abi"]
)

def getExchangeRate(self, _from, _to, _provider, _amount):
"""getExchange rate between two ERC20 tokens on a given DEX

Args:
_from (str): symbol of ERC20 token. Source token.
_to (str): symbol of ERC20 token. Destination token.
_provider (str): the Dex where you want to swap your tokens.
_amount (str): amount of source token you want to exchange.

Returns:
str: The amount of destination you get.
"""
if _from == _to or _amount <= 0:
return -1
try:
return self.orfeed_contract.functions.getExchangeRate(
_from, _to, _provider, _amount
).call()
except Exception:
return -1

def getTokenAddress(self, symbol):
"""Return address of a ERC20 token.

Args:
symbol (str): ERC20 token.

Returns:
str: address of ERC20 token in the blockchain.
"""
try:
return self.orfeed_contract.functions.getTokenAddress(symbol).call()
except Exception:
return -1

def getTokenDecimalCount(self, address):
"""Retrieve number of decimals of an ERC20 token.

Args:
address (str): address of ERC20 token.

Returns:
str: Number of decimals of the ERC20 token given in arg.
"""
return self.orfeed_contract.functions.getTokenDecimalCount(address).call()
22 changes: 22 additions & 0 deletions examples/python/oracle_arb_finder/core/registry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import web3
from web3 import Web3
from smartcontracts import my_smartcontracts


class Registry:
def __init__(self, web3):
self.registry_address = Web3.toChecksumAddress(
my_smartcontracts["registry"]["address"]
)
self.w3 = web3
self.registry_contract = self.w3.eth.contract(
address=self.registry_address, abi=my_smartcontracts["registry"]["abi"]
)

def getAllOracles(self):
res = self.registry_contract.functions.getAllOracles().call()
return res

def getOracleInfo(self, name_reference=None):
res = self.registry_contract.functions.getOracleInfo(name_reference).call()
return res
Loading