Giter Club home page Giter Club logo

hzjken / crypto-arbitrage-framework Goto Github PK

View Code? Open in Web Editor NEW
553.0 16.0 172.0 101 KB

A cryptocurrency arbitrage framework implemented with ccxt and cplex. It can be used to monitor multiple exchanges, find a multi-lateral arbitrage path which maximizes rate of return, calculate the optimal trading amount for each pair in the path given flexible constraints, and execute trades with multi-threading implemenation.

Python 100.00%
cryptocurrency arbitrage-bot cplex ccxt linear-programming optimization

crypto-arbitrage-framework's Introduction

Crypto Arbitrage Framework

A cryptocurrency arbitrage framework implemented with ccxt and cplex. It can be used to monitor multiple exchanges, find a multi-lateral arbitrage path which maximizes rate of return, calculate the optimal trading amount for each pair in the path given flexible constraints, and execute trades with multi-threading implemenation.

Why This Framework?

There are quite a few cryptocurrency arbitrage bots open-sourced out there as well, but here are some features that could potentially distinguish this framework from the others.

1. Speed

A majority of the arbitrage bots monitor the market with brute-force solution to calculate the rates of return for all the possible trading path, which requires much computing power and time. This framework leverages linear programming solution with cplex solver to find out the arbitrage path with the max rate of return, which is much faster. In the future, I might continue to develop the framework to support top n arbitrage paths.

2. Flexibility

Most of the brute-force solutions can only check arbitrage path of length 3 (only contains 3 crypto-currencies, known as triangular arbitrage in forex market). With this framework, things become much more flexible. It allows users to think of cryptocurrency market as a big trading network, with each currency in each exchange to be a node in the network. The optimizer can search the whole network and give an return-optimal closed-circle path for arbitrage with no length limit (multi-lateral arbitrage). But of course, you can limit the path length or set any other constraints very easily in the linear programming optimizer to meet your preference.

3. Trading Amount Optimization

Some arbitrage bots tell you there is an profitable arbitrage path, but do not tell you how much you should buy or sell in each trading pair in the path. It's meaningless! This framework utilizes a two-step optimization to tell you what's the optimal path and what's the optimal amount to sell or trade in the path. The trading amount optimization also considers a bunch of practical constraints (trading limit, digit precision, orderbook price level and volume etc.) that traders will meet in real trading environment. It gives a correct solution in a fast and clear way.

4. Multi-threading Order Submission

In the part of order execution, the framework utilizes multi-threading to parallelize order submission of different exchanges when cross-exchange arbitrage is set to be allowed. It helps to accelerate the order execution process and increase success rate. The framework also has a mechanism that if the time an order waits to be executed exceed a threshold, the order and following orders will be cancelled to stop loss from market turbulance.

5. Scalability

Integrated with ccxt, it's pretty easy for users to scale up their arbitrage scope to multiple exchanges by adding new exchanges to the exchanges.py. With such, users can explore a larger trading network and more arbitrage opportunities but not limited to one or two exchanges only.

Components

The framework contains 3 main components, PathOptimizer, AmtOptimizer and TradeExecutor. PathOptimizer and AmtOptimizer runs a two-step optimization to find out a feasible and workable solution (optimal path and optimal trading amount). TradeExecutor executes the solution generated from the previous two components.

PathOptimizer

from crypto.path_optimizer import PathOptimizer
from crypto.exchanges import exchanges

# initiation
path_optimizer = PathOptimizer(exchanges=exchanges)
path_optimizer.init_currency_info()

# initiation with extra params
path_optimizer = PathOptimizer(
    exchanges=exchanges,
    path_length=10,
    simulated_bal=simulated_bal,
    interex_trading_size=2000,
    min_trading_limit=100
)
path_optimizer.init_currency_info()

#usage
path_optimizer.find_arbitrage()

PathOptimizer calculates the optimal arbitrage path (maximizing rate of return) with cplex algorithm given bid-ask prices of each crypto trading pair fetched from ccxt. It takes in exchanges as a required parameter and some other optional parameters that affects the path constraint. It can be used to monitor multiple exchanges as long as it's supported by ccxt and you put it in exhcanges.py.

Before usage, path_optimizer.init_currency_info() is required to load market information. And then, the usage will be very simple by just a call of path_optimizer.find_arbitrage(), where the latest price info will be fetched and used to calculate the arbitrage path. If a feasible arbitrage path is found, it will be saved in the class's path attribute.

There are some optional parameters which could change the modelling constraints of PathOptimizer.

Params: path_length
Type: Int
To set the max feasible length of the arbitrage path, or in other words, the maximum number of trading pairs the path is allowed to go through. Default is set to be 4.

Params: include_fiat
Type: Boolean
Some exchanges allow users to trade fiat-to-crypto pairs. This param sets whether to include fiat-to-crypto trading pairs in the model. Default is set to be False, as fiat trading and money transfer includes some more complex form of commision calculation.

Params: inter_exchange_trading
Type: Boolean
Whether to allow the model to consider inter-exchange arbitrage opportunity. Default is set to be True. Cross-exchange trading will need to consider withdrawal fee but usually contains more arbitrage opportunity.

Params: interex_trading_size
Type: Float
The amount of money that are expected to be traded in inter-exchange arbitrage in terms of USD, which is used to approximate the withdrawal commission rate. Default is set to be 100.

Params: consider_init_bal
Type: Boolean
Whether to consider initial balance. If set to True, the arbitrage path is required to start from one of the cryptocurrencies whose balance is greater than 0. If set to False, the arbitrage path can check all the arbitrage opportunities without considering your balance. Default is set to be True.

Params: consider_inter_exc_bal
Type: Boolean
Whether to consider the balance constraint of inter-exchange arbitrage. In cross-platform cryptocurrency trading, withdrawal and deposit are not like intra-platform trading that the trade is done instantly. Cross-platform withdrawal and deposit usually require several confirmation on the blockchain, which could take up to hours. To avoid rapid price changes which might happen during the withdrawal and deposit. In real arbitrage, we require the deposited wallet to have enough money to do the rest of the arbitrage without waiting for the inter-exchange transfer to complete. If set to be True, the above constraint is considered, else not considered. Default is set to be True.

Params: min_trading_limit
Type: Float
The minimum trading amount in terms of USD for each trading pair that needs to be satisfied. As most of the crypto exchanges will set a minimum trading amount, the default is set to be 10 (US dollars) so that all these constraints can be satisfied.

Params: simulated_bal
Type: Dict or None

simulated_bal = {
    'kucoin': {'BTC': 10, 'ETH': 200, 'NEO': 1000, 'XRP': 30000, 'XLM': 80000},
    'binance': {'BTC': 10, 'ETH': 200, 'NEO': 1000, 'XRP': 30000, 'XLM': 80000},
    'bittrex': {'BTC': 10, 'ETH': 200, 'NEO': 1000, 'XRP': 30000, 'XLM': 80000},
}

The simulated balance in each exchange, format is like above (the amount for each coin is the number of coins, not in terms of USD value). If it's given, the optimizer will calculate optimal path given your simulated balance, if not, it will fetch your real balances on all the exchanges you specify and calulate path based on real balances. (only if you provide api keys in exhcanges.py). Default is set to be None.

AmtOptimizer

from crypto.amount_optimizer import AmtOptimizer

# initiation
amt_optimizer = AmtOptimizer(
    PathOptimizer=path_optimizer, 
    orderbook_n=100
)

# usage
if path_optimizer.have_opportunity():
    amt_optimizer.get_solution()

AmtOptimizer calculates the optimal trading amount for each trading pair in the arbitrage path. It can only work when a feasible arbitrage path is found. Therefore, we need to use path_optimizer.have_opportunity() to check whether a path is found before using the amt_optimizer.get_solution() function. It takes in two required parameters, the PathOptimizer and orderbook_n. PathOptimizer is the class initiated from last step and orderbook_n specifies the number of existing orders that the optimization will find solution from.

The AmtOptimizer calculates optimal trading amount with consideration of available balances, orderbook prices and volumes, minimum trading limit and trading amount digit precision etc (details can be checked in the function _set_constraints() in amount_optimizer.py), which is able to satisfy a real trading environment. It also accelerates the optimal amount calculation process greatly with the help of cplex linear programming in comparison to brute-force enumeration, and allows scalable extension to longer path length and larger orderbook.

TradeExecutor

from crypto.trade_execution import TradeExecutor

# initiation
trade_executor = TradeExecutor(path_optimizer)

# usage
if amt_optimizer.have_workable_solution():
    solution = amt_optimizer.trade_solution
    trade_executor.execute(solution)

TradeExecutor executes the trading solution given from AmtOptimizer with multi-threading implementation to parallelize the order submission of different exchanges to accelerate the process and increase success rate. In the mechanism of TradeExecutor, if an order is submitted but doesn't get executed within 30 seconds, this and all the later orders will be cancelled so as to stop loss from the market turbulance, while the executed orders are kept remained.

The TradeExecutor can only work if a workable solution can be provided from the AmtOptimizer (In many cases, you can find a feasible path but no workable solution can be found due to digit precision or amount limit constraints). Therefore, we need to check if there's workable solution with amt_optimizer.have_workable_solution() before we use trade_executor.execute(solution) to execute.

Before Usage

There are some preparation works you need to do before you can use this arbitrage framework.

  1. pip install ccxt, ccxt is a great open-source library that provides api to more than 100 crypto exchanges.
  2. pip install docplex, docplex is the python api for using cplex solver.
  3. install and setup cplex studio (I use the academic version, because community version has limitation on model size)
  4. add all the exchanges (supported by ccxt) you want to monitor and do arbitrage on in exchanges.py with the same format. If you only want to check whether there's arbitrage opporunity, you don't need to specify keys. But if you want to execute trades with this framework, add keys like this.
exchanges = {
    'binance': ccxt.binance({
        'apiKey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        'secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    }),
    'bittrex': ccxt.bittrex({
        'apiKey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        'secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    }),
}
  1. check the trading commission rates for the exchanges you specify and put them in the variable trading_fee in info.py
  2. get an api key from coinmarketcap in order to fetch cryptocurrencies usd prices, and add it to function get_crypto_prices in utils.py
'X-CMC_PRO_API_KEY': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',

Usage Example

Check main.py

Something Else To Know

  1. This project is done on my personal interest, without rigorous test on the code, so check the code first and use it at your own risk.
  2. I did successfully find arbitrage opportunities with this framework recently (when the bitfinex btc is 300$ higher than other exchanges), but you should check the validity of the arbitrage opportunity on your own (whether an exchange is scam? whether a coin can be withdrawed or deposited? etc.).
  3. There are cases when some minor coins' orderbook information is out of date when fetched from ccxt, maybe because the trading of the minor pair is paused for a while, which leads to a fake opportunity. You should verify this as well.
  4. I myself think this project idea and the solution quite cool and valuable, but it will require some more time to verify the validity of arbitrage opportunities and resource (money) to really utilize it, both of which I don't have currently... So I decided to share it here to people who can utilize it!
  5. Currently it's not perfect yet, but I might continue to improve this project if I have time in the future. I welcome any questions or comments if you want to tell me!

If you think it's good or successfully earn money with this framework, feel free to donate me some money through the following wallet addresses. :p

BTC: 1DQvcRAST4VgPMYKKs9HFJLQVT3i3h8XCg
ETH: 0x04f6874c50b5b4a31e663b8840d233c666aec0c9

crypto-arbitrage-framework's People

Contributors

hzjken 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

crypto-arbitrage-framework's Issues

exchanges.py Formatting Issues

Hi,

I have tried to edit/add exchanges.py to include such attributes as "items" for "exchanges", but I get errors like the following:-

file: path_optimizer.py", line 145, in init_currency_info
for exc_name, exchange in self.exchanges.items():
AttributeError: module 'exchanges' has no attribute 'items'

How should exchanges.py be formatted to include the correct information?
What should be listed in exchange.items ?

Any assistance would be appreciated :)

TypeError: 'NoneType' object is not iterable

PS C:\Users\Luca Cerullo\Desktop\crypto-arbitrage-framework-master> & "C:/Users/Luca Cerullo/AppData/Local/Programs/Python/Python39/python.exe" "c:/Users/Luca Cerullo/Desktop/crypto-arbitrage-framework-master/main.py"
Traceback (most recent call last):
File "c:\Users\Luca Cerullo\Desktop\crypto-arbitrage-framework-master\main.py", line 35, in
path_optimizer.find_arbitrage()
File "c:\Users\Luca Cerullo\Desktop\crypto-arbitrage-framework-master\crypto\path_optimizer.py", line 103, in find_arbitrage
self.update_objectives()
File "c:\Users\Luca Cerullo\Desktop\crypto-arbitrage-framework-master\crypto\path_optimizer.py", line 279, in update_objectives
self.update_transit_price()
File "c:\Users\Luca Cerullo\Desktop\crypto-arbitrage-framework-master\crypto\path_optimizer.py", line 167, in update_transit_price
self.price.update(exc_price)
TypeError: 'NoneType' object is not iterable
PS C:\Users\Luca Cerullo\Desktop\crypto-arbitrage-framework-master>

I have installed all library but when add exchange API Binance and Coinbase-pro program give me this error

Problem with update_commission_fee()

Hello

There is an error when starting, what could be the problem?

path_optimizer.py:241: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
self.commission_matrix[np.meshgrid(indexes, indexes, indexing='ij', sparse=True)] = self.trading_fee[
Traceback (most recent call last):
File "main.py", line 40, in
path_optimizer.find_arbitrage()
File "path_optimizer.py", line 101, in find_arbitrage
self.update_commission_fee()
File "path_optimizer.py", line 241, in update_commission_fee
self.commission_matrix[np.meshgrid(indexes, indexes, indexing='ij', sparse=True)] = self.trading_fee[
IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

Process finished with exit code 1

What does the profit rate represent exactly?

When using the find_arbitrage() function, it outputs the profit rate and the best arbitrage path, but I am not fully sure of what the profit rate represents. Does it represent the possible raw profit in dollar value or the possible percentage of profit gained? Also, what actions would I have to take to obtain a profit rate value similar to what the model output (ex: Trade all 1% of an exchange pairs volume in the arbitrage path to match the model profit rate)?

I am getting the following RuntimeWarning: RuntimeWarning: divide by zero encountered in log final_transit_matrix

Hello ,

i am getting the following runtime warning:

RuntimeWarning: divide by zero encountered in log final_transit_matrix = np.log(self.transit_price_matrix * (1 - self.commission_matrix) * (

in the following part of the code:

self.update_balance()
self.update_transit_price()
self.update_vol_matrix()
self.update_changeable_constraint()

final_transit_matrix = np.log(self.transit_price_matrix * (1 - self.commission_matrix) * (
(self.vol_matrix >= self.min_trading_limit).astype(int)))
final_transit = final_transit_matrix[self.var_location]
x = self.x[self.var_location]
self.maximize(self.sum(x * final_transit))

It calculates the results but I wonder how I can revise the code to avoid this warning?

I think the self.transit_price_matrix part is the problem. When I use dir(str(self.transit_price_matrix) he show me only zeros. And maybe because he makes log from zero then it results in this warning?

So I had to find out why transit_price_matrix is zero so I looked into update_transit_price

this was the following code:

def update_transit_price(self):
'''to update data of the transit_price_matrix'''
self.price = {}
self.transit_price_matrix = np.zeros([self.length, self.length])

    exc_name_list = list(self.exchanges.keys())
    thread_num = len(exc_name_list)
    exc_price_list = multiThread(self.parallel_fetch_tickers, exc_name_list, thread_num)
    for exc_price in exc_price_list:
        self.price.update(exc_price)

    for pair, items in self.price.items():
        from_cur, to_cur = pair.split('/')
        if from_cur in self.currency_set and to_cur in self.currency_set:
            from_index = self.currency2index[from_cur]
            to_index = self.currency2index[to_cur]
            if items['ask'] != 0 and items['bid'] != 0:
                self.transit_price_matrix[from_index, to_index] = items['bid']
                self.transit_price_matrix[to_index, from_index] = 1 / items['ask']

    for from_cur, to_cur in self.inter_convert_list:
        from_index = self.currency2index[from_cur]
        to_index = self.currency2index[to_cur]

        if from_cur in self.withdrawal_fee:
            self.transit_price_matrix[from_index, to_index] = 1
        else:
            self.transit_price_matrix[from_index, to_index] = 0

        if to_cur in self.withdrawal_fee:
            self.transit_price_matrix[to_index, from_index] = 1
        else:
            self.transit_price_matrix[to_index, from_index] = 0

So my guess is that it doesn't update the transit_price properly. Is my way of thinking right? How would a expert proceed to find and fix the problem?

Thank you very much for your help.

lack of function in class 'PathOptimizer'

Do anyone get this work?
I encounter the error as below, anyone can help?
It seem that, there is no function: 'binary_var_list()' in class 'PathOptimizer'
TIA,
##########
\path_optimizer.py in _run_time_init(self)
80 self.get_var_location()
81 var_num = int(np.sum(self.var_location))
---> 82 self.var = self.binary_var_list(var_num, name='x')
83 self.x = np.zeros([self.length, self.length])
84 self.x = self.x.astype('object')

AttributeError: 'PathOptimizer' object has no attribute 'binary_var_list'
##############

Does this perform actual withdraw/deposit cross-exchange?

Most crypto arbitrage bots don’t do actual arbitrage with withdraw/deposit cross-exchange, from reading the docs for this project it is unclear if this supports that?

Also, is it possible to set “min profitability” settings?

Great work, very interest project.

Exceptions

Good day,
would you be so kind to provide exact versions of Python and dependant modules which are enough to run the minimal example? Currently, when I try to run the following:

import ccxt
from crypto.path_optimizer import PathOptimizer

path_optimizer = PathOptimizer(exchanges  = {'binance': ccxt.binance()})
path_optimizer.init_currency_info()
path_optimizer.find_arbitrage()

I get the following:

C:\Users\a\Desktop\crypto\crypto\path_optimizer.py:241: FutureWarning: Using a non-tuple sequence for multidi
mensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be int
erpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.

self.commission_matrix[np.meshgrid(indexes, indexes, indexing = 'ij', sparse = True)] = self.trading_fee[ex
c_name]
Traceback (most recent call last):
File "C:/Users/a/Desktop/crypto/main.py", line 6, in
path_optimizer.find_arbitrage()
File "C:\Users\a\Desktop\crypto\crypto\path_optimizer.py", line 103, in find_arbitrage
self.update_objectives()
File "C:\Users\a\Desktop\crypto\crypto\path_optimizer.py", line 278, in update_objectives
self.update_balance()
File "C:\Users\a\Desktop\crypto\crypto\path_optimizer.py", line 221, in update_balance
for i in list(exc_bal.keys()):
AttributeError: 'NoneType' object has no attribute 'keys'

Process finished with exit code 1

OS: Win 10
Python: 3.7.4 x64
ccxt: 1.20.35
cplex: 12.9.0.0
docplex: 2.9.133
numpy: 1.17.4

Instaled CPLEX but the script doesnt find it

Hi ! I installed CPLEX but im getting the error msg when running the Main.py script:

docplex.mp.utils.DOcplexException: CPLEX runtime not found: please install CPLEX or solve this model on DOcplexcloud

Do you have any suggestions on what could i look for ?

docplex does not work - docplex.mp.utils.DOcplexException: CPLEX runtime not found

Hello,

I have coded a mathematical model and want to solve it using DOCPLEX module. My interpreter is Python 3.7. However, after doing a lot of effort, I will face the following error:

Traceback (most recent call last):
File "C:/Users/xxx/PycharmProjects/pythonProject/EPC _LTC.py", line 155, in <module>
solution = mdl.solve(log_output=True)
File "C:\Users\xxx\PycharmProjects\pythonProject\venv\lib\site-packages\docplex\mp\model.py", line 4222, in solve
return self.fatal("CPLEX runtime not found: please install CPLEX or solve this model on DOcplexcloud")
File "C:\Users\xxx\PycharmProjects\pythonProject\venv\lib\site-packages\docplex\mp\model.py", line 894, in fatal
self._error_handler.fatal(msg, args)
File "C:\Users\xxx\PycharmProjects\pythonProject\venv\lib\site-packages\docplex\mp\error_handler.py", line 210, in fatal
raise DOcplexException(resolved_message)
docplex.mp.utils.DOcplexException: CPLEX runtime not found: please install CPLEX or solve this model on DOcplexcloud

I have already run the following codes in my Pycharm's terminal:

cd C:\Program Files\IBM\ILOG\CPLEX_Studio201\python
python setup.py install

or

cd C:\Program Files\IBM\ILOG\CPLEX_Studio201\python
python setup.py install --home C:\Users\xxx\PycharmProjects\pythonProject\venv\Lib\site-packages\cplex

Finally, I also set the path variables of my own username to something like below:

"C:\Program Files\IBM\ILOG\CPLEX_Studio129\cplex\python\3.6\x64_win64" and
"C:\Program Files\IBM\ILOG\CPLEX_Studio129\cplex\bin\x64_win64\cplex.exe"

Nice work and need support

Hi mate..

Awesome work done... Do you have an enhanced version of this script which you can share with us for pricing.

Regards
Krishna G

Problem starting the bot

crypto-arbitrage-framework-hzjken$ python3.9 main.py
/home/sparky/Lataukset/Binance-Crypto/Crypto-Arbitrage/crypto-arbitrage-framework-hzjken/path_optimizer.py:241: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be interpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.
self.commission_matrix[np.meshgrid(indexes, indexes, indexing='ij', sparse=True)] = self.trading_fee[exc_name]
Traceback (most recent call last):
File "/home/sparky/Lataukset/Binance-Crypto/Crypto-Arbitrage/crypto-arbitrage-framework-hzjken/main.py", line 47, in
path_optimizer.find_arbitrage()
File "/home/sparky/Lataukset/Binance-Crypto/Crypto-Arbitrage/crypto-arbitrage-framework-hzjken/path_optimizer.py", line 101, in find_arbitrage
self.update_commission_fee()
File "/home/sparky/Lataukset/Binance-Crypto/Crypto-Arbitrage/crypto-arbitrage-framework-hzjken/path_optimizer.py", line 241, in update_commission_fee
self.commission_matrix[np.meshgrid(indexes, indexes, indexing='ij', sparse=True)] = self.trading_fee[exc_name]
IndexError: arrays used as indices must be of integer (or boolean) type

OverflowError: Python int too large to convert to C long

Hi. Excelent work!

I managed to successfully run this project slightly modifying the original code to work only with binance and bittrex (removed kucoin). The code seems to work well most of the time and has been able to find some arbitrage opportunities.

However, every now and again, the code crashes with the following error:

Traceback (most recent call last):
  File "C:/crypto-arbitrage-framework/crypto/main.py", line 43, in <module>
    amt_optimizer.get_solution()
  File "C:\crypto-arbitrage-framework\crypto\amount_optimizer.py", line 51, in get_solution
    self._update_path_params()
  File "C:\crypto-arbitrage-framework\crypto\amount_optimizer.py", line 60, in _update_path_params
    self.path_order_book()  # requires internet connection
  File "C:\crypto-arbitrage-framework\crypto\amount_optimizer.py", line 336, in path_order_book
    order_book[0][1] = self.big_m  # infinity amount for inter exchange transfer
OverflowError: Python int too large to convert to C long

Any idea what could be causing this?

Thank you!

OS: Win 10
Python: 3.7 x64
ccxt: 1.41.31
cplex: 20.1.0.0
docplex: 2.19.202
numpy: 1.19.5

Empty arbitrage path :(

I get profit rate 0.0 and an empty arbitrage path :(
-->```
path_optimizer.py:282: RuntimeWarning: divide by zero encountered in log
(self.vol_matrix >= self.min_trading_limit).astype(int)))
profit rate: 0.0, arbitrage path: []

TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'

Hi, hope you are having a wonderful day.

Im Running:
CPLEX Studio IDE 12.9.0 Academic Version
Python 3.7.4
Windows 7 SP1

Modified:
Commented out -- > main.py:36-37 (kucoin_move_to_trade())
API Key --> utils.py

And getting this error:

path_optimizer.py:239: FutureWarning: Using a non-tuple sequence for multidimensiona
l indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the fu
ture this will be interpreted as an array index, `arr[np.array(seq)]`, which wil
l result either in an error or a different result.
  exc_name]
Traceback (most recent call last):
  File "main.py", line 40, in <module>
    path_optimizer.find_arbitrage()
  File "C:\Users\WeilZa01\Downloads\crypto-arbitrage-framework-master\crypto\cry
pto\path_optimizer.py", line 102, in find_arbitrage
    self.update_objectives()
  File "C:\Users\WeilZa01\Downloads\crypto-arbitrage-framework-master\crypto\cry
pto\path_optimizer.py", line 278, in update_objectives
    self.update_vol_matrix()
  File "C:\Users\WeilZa01\Downloads\crypto-arbitrage-framework-master\crypto\cry
pto\path_optimizer.py", line 301, in update_vol_matrix
    usd_values[key] = val['baseVolume'] * self.crypto_prices[base_coin]['price']
 * percentile
TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'

Is this a known issue?

Regards.

Problem occurs when i start the bot

python3 main.py
/home/elliot/Downloads/arbitrage/path_optimizer.py:284: RuntimeWarning: divide by zero encountered in log
final_transit_matrix = np.log(self.transit_price_matrix * (1 - self.commission_matrix) * (
profit rate: 0.0, arbitrage path: []
profit rate: 0.0, arbitrage path: []
profit rate: 0.0, arbitrage path: []
profit rate: 0.0, arbitrage path: []
profit rate: 0.0018326130900521154, arbitrage path: [('kucoin_XRP', 'kucoin_TUSD'), ('kucoin_TUSD', 'kucoin_USDT'), ('kucoin_USDT', 'kucoin_LTC'), ('kucoin_LTC', 'kucoin_USDC'), ('kucoin_USDC', 'kucoin_XRP')]
Traceback (most recent call last):
File "/home/elliot/Downloads/arbitrage/main.py", line 43, in
amt_optimizer.get_solution()
File "/home/elliot/Downloads/arbitrage/amount_optimizer.py", line 52, in get_solution
self._update_model()
File "/home/elliot/Downloads/arbitrage/amount_optimizer.py", line 70, in _update_model
self._set_constraints()
File "/home/elliot/Downloads/arbitrage/amount_optimizer.py", line 105, in _set_constraints
withdraw_fee = self.PathOptimizer.withdrawal_fee[trade[0]]['coin_fee']
KeyError: 'kucoin_XRP'

How to choose an appropriate graph type for highly variable data?

I have a number of busy line graphs, e.g., one of them is presented in the following. To my eyes, this graph is not very readable. I would like to know what factors should I consider when I want to choose an appropriate type of graph. Moreover, I would like to know your opinion on what type of representation might be better for the comparison shown the below graph.

image

attempted relative import with no known parent package

Hi there
Thank you for this wonderful work. I was recently trying to install the script. Unfortunately, I stumbled upon a terminal error message, that looks as given below.

It would be great if someone could give me a hint how to solve this issue.

shlx@ubntqnap64:~/Dokumente/crypto-arbitrage-framework-master/crypto$ python3 main.py

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from path_optimizer import PathOptimizer
  File "/home/shlx/Dokumente/crypto-arbitrage-framework-master/crypto/path_optimizer.py", line 4, in <module>
    from .info import fiat, trading_fee, tokens
ImportError: attempted relative import with no known parent package

skip checking for withdrawal fees

Anyone knows how to skip checking for withdrawal fees when I don't want to do inter exchange trading?
raise ValueError('{} is not an exchange supported by withdrawalfees.com'.format(exchange))
ValueError: bitget is not an exchange supported by withdrawalfees.com

The thing is I just want to do arbitrage on one exchange so the script dosn't need those numbers in a sense but it's constructed in a way that it requests them no matter what. Could you advise which part of code should I erase and replace for it to work?

Error: local variable 'trade_id' referenced before assignment

I get the following runtime error

crypto-arbitrage-framework/crypto/trade_execution.py", line 158, in kucoin_transfer_to
to_id = trade_id
UnboundLocalError: local variable 'trade_id' referenced before assignment

Anyone able to suggest a fix?
The offending loop is:-

@staticmethod
def kucoin_transfer_to(to, exchange, amount, code):
'''function to transfer amount between main and trading account in kucoin'''
accounts = exchange.privateGetAccounts()
data = accounts['data']
for i in data:
if i['currency'] == code and i['type'] == 'main':
main_id = i['id']
elif i['currency'] == code and i['type'] == 'trade': <============(Problem is here, needs an additional elif to check for zero trade balance)
trade_id = i['id']
else:
pass

    if to == 'main':
        from_id, to_id = trade_id, main_id
    elif to == 'trade': 
        from_id, to_id = main_id, trade_id      <=======(ERROR thrown here)
    else:
        raise ValueError('to should be main or trade')

Some issues 1.Non-tuple sequence and 2.NonType object has no attribute get_values

Z:\Downloads\crypto-arbitrage-framework-master\crypto\path_optimizer.py:241: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be interpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.
self.commission_matrix[np.meshgrid(indexes, indexes, indexing='ij', sparse=True)] = self.trading_fee[
Z:\Downloads\crypto-arbitrage-framework-master\crypto\path_optimizer.py:284: RuntimeWarning: divide by zero encountered in log
final_transit_matrix = np.log(self.transit_price_matrix * (1 - self.commission_matrix) * (
profit rate: 0.23583462992170445, arbitrage path: [('kucoin_BTC', 'kucoin_XRP'), ('kucoin_XRP', 'binance_XRP'), ('binance_XRP', 'binance_USDT'), ('binance_USDT', 'binance_AION'), ('binance_AION', 'kucoin_AION'), ('kucoin_AION', 'kucoin_BTC')]
Traceback (most recent call last):
File "Z:/Downloads/crypto-arbitrage-framework-master/crypto/main.py", line 36, in
amt_optimizer.get_solution()
File "Z:\Downloads\crypto-arbitrage-framework-master\crypto\amount_optimizer.py", line 53, in get_solution
self._get_solution()
File "Z:\Downloads\crypto-arbitrage-framework-master\crypto\amount_optimizer.py", line 159, in _get_solution
xs = np.array(ms.get_values(self.int_var)).reshape(self.path_n, self.orderbook_n)
AttributeError: 'NoneType' object has no attribute 'get_values'

Process finished with exit code 1


I am getting the above errors when running the code.

  1. Can someone help my getting this running? This tuple FutureWarning at the beginning seem to not affect the result. How can i avoid this error in the code?
  2. why do get 'NoneType' object has no attribute 'get_values'?

Would appreciate any help to get this running. Thank you

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.