Giter VIP home page Giter VIP logo

futures-spot-arbitrage-okex-v5's Introduction

Futures-Spot-Arbitrage-OKEx-V5

Introduction

An asynchronous object-oriented program for arbitrage between perpetual futures and spot on OKEx using V5 API. Initially written in April 2021 for my personal use. Modified and optimized OKEx V3 API SDK according to V5 API documentation.

Chinese and English support, completed with annotations and docstrings.

From the author

This project was started when I was a newbie in Python and software development. I am glad it gathers a decent number of stars and hopefully some usage. However it feels outdated and lacking maintenance even though it still functions and makes money.

Therefore I'm soliciting feedbacks or suggestions to make an improvement plan. Given enough feedbacks and community contribution, an improvement plan will take effect. Please see the list of issues or create new issues.

Features

  • Command line interface;
  • Sort and output historical funding rates over a given period;
  • Analyze historical funding rates and volatility (taken as NATR) to find most profitable underlying for arbitrage;
  • Open a position by longing spot and shorting perpetual futures equally and simultaneously
    • Use historical tickers and statistics to open position when futures have max premium, assuming that the premium over a period of time satisfies Gaussian distribution;
    • Accelerate when a desired premium does not appear by given time;

Premium

  • Close a position by selling spot and closing short on perpetual futures
    • Use historical tickers and statistics to close position when futures have max discount;
    • Accelerate when a desired discount does not appear by given time;
    • Proactively close a position when the predicted funding rate is low enough such that it is better off to reopen later;
  • Monitor existing positions
    • Sell spot and close short to add margin when price rises to avoid liquidation;
    • Reduce margin to buy spot and open short when price drops to maintain exposure;
  • Precise order size control and leverage management;
  • Store tickers, funding rates, portfolio and transactions in MongoDB;
  • Calculate current and historical PnL, APR and APY;
  • Plot the distribution of premium/discount for an underlying over a given period.

Features may be added

  • Typical arbitrage of perpetual futures and spot is passively receiving funding fees while keeping the position open. However it is profitable to proactively close a portion of the position when the futures premium surges and reopen it later when the premium subdues.

Optimizations

Implemented asyncio and websocket. Web IOs are parallelized where possible. AsyncClient is initialzed as a class member instead of Context Manager to avoid constantly creating and killing sessions which has non-negligible overheads. Special care was taken for proper client closure. A custom semaphore was created to control concurrent REST API access. Websocket is used to fetch real time price feed. Websocket streaming functions are used as AsyncGenerators for elegant integration.

Classes are given __await__ attribute where necessary and can be initialized asynchronously. Decorator @call_coroutine was created to call coroutines directly in normal context instead of loop.run_until_complete(coro). So simply call coro in normal context and await coro in async context.

Installation

Install Python 3.8+ and required packages.

python setup.py install or pip install -r requirements.txt

git submodule update --init --recursive

Install MongoDB.

Store API keys in .env (use account 3 for demo trading).

Set language='cn' for Chinese and language='en' for English in config.py.

Simply python main.py.

Contributing

Contributions are welcome. Please open an issue if you have any questions or suggestions.

Background

Futures spot arbitrage in crypto is profitable because there is a huge demand for long leverage in the crypto market. Arbitrageurs act as the counterparty to buyers in the perpetual swap market. They effectively multiply and transfer the buying pressure in the perpetual swap market to the spot market. Leverage comes at a cost. Therefore arbitrageurs or market makers are entitled to charge interest on futures buyers, just like stockbrokers charge interest for margin. As a result the APY depends on the market sentiment, ranging from 10% to 100%+.

Disclaimer

The author does not assume responsibilities for the use of this program, nor is warranty granted.

License

This program is licensed under the AGPL-3.0 License. See LICENSE for full disclosure.

Permissions of this license are conditioned on making available complete source code of licensed works and modifications, which include larger works using a licensed work, under the same license. Copyright and license notices must be preserved. Contributors provide an express grant of patent rights. When a modified version is used to provide a service over a network, the complete source code of the modified version must be made available.

Reference

[1] OKEx V5 API

[2] Cryptocurrency Spot-Futures Arbitrage Strategy Report

[3] Alternative Opportunities In Crypto Space: Spot-Futures Arbitrage

futures-spot-arbitrage-okex-v5's People

Contributors

aureliano90 avatar shuhuiluo 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

futures-spot-arbitrage-okex-v5's Issues

Cross Margin ?

I did a proof of concept doing funding arbitrage on okx, while i was trying to make a production version i found your project which is exactly what i was trying to do. This really is great work.

But I was wondering why wouldnt you go cross margin usdt. It's very unlikely you will get a margin call considering the spread on okx. Like when your short position loose money, your long will gain some anyway. Doing isolated need stoplosses whereas cross shouldnt need any.

Is my thought wrong or please would you clarify on that ?

Thanks you for your work

关于数据库的问题

当初始化程序的时候,按下监控现有仓位这个功能时候,数据库里没有数据,会报一个数据库为空的错误,请问这个问题应该怎么解决呢

local variable 'json_res' referenced before assignment

Hi, Aureliano90, I have this error if I try to monitor existing connections for example:

Monitor__await__(BTC) error
local variable 'json_res' referenced before assignment
Crypto BTC does not exist.

I have MongoDB running, may be I should configure it somehow?

Thank you

Project refactor and overhaul

This project was started when I was a newbie in Python and software development. I am glad it gathers a decent number of stars and hopefully some usage. However it feels outdated and lacking maintenance even though it still functions and makes money.

Therefore I'm soliciting feedbacks or suggestions to make an improvement plan. Given enough feedbacks and community contribution, an improvement plan will take effect.

Monitoring existing position give this warning

So, on debian using virtualenv with python 3.9 when I try to use monitor. (demo account)
Regards.

1
Crypto    Current  Predicted
SOL     -0.016%    -0.001%
SOL    Today's APR: -11.34%, 7 day APR: -1.62%, overall APR: -1211.42%
SOL    Today's APY: -10.72%, 7 day APY: -1.61%, overall APY: -100.00%
menu.py:36: RuntimeWarning: coroutine 'run_with_cancel.<locals>.wrapper.<locals>._coro' was never awaited
  mon.watch()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
menu.py:36: RuntimeWarning: coroutine 'Monitor.watch' was never awaited
  mon.watch()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I'm not sure I really understand the principle. does he manage on his own? I need to close my positions manually, right?
I need to use screen to fetch/monitor ? thanks

Parameter accountid is not passed when creating FundingRate object

In src/menu.py, line 355: fundingRate = FundingRate() , I suggest to change to: fundingRate = FundingRate(accountid) , otherwise the fundingRate object with always initialized with the default accountid, 3 , the object will always uses the test API.

Same issue goes to:

  • src/menu.py line 27, 140
  • src/monitor.py line 84
  • src/record.py line 61

@Aureliano90

Telegram Group Chat

Hi there

Would appreciate a telegram group chat in order to talk FAQ and other bug orientated solutions, this might be quite technical for people that are not very familiar with coding.

For example, my self I can not understand where to enter my priv keys and although I made a .env file I still get error when running the command 1.

looking fine

Hi there,
I'm going through your code checking a little bit the concept.
Out of the box i get this error:

async def get_crypto(accountid: int) -> tuple[str, Monitor]: TypeError: 'type' object is not subscriptable

Do you know what could be wrong here?

Move away from MongoDB

My local MongoDB service is consuming 7 GBs of memory. It also seems to be slow.

Hereby suggestions for alternative dbs are welcomed. A switch will take place if there is enough demand and community contribution.

新版本执行后异常报错

image
大佬,用你昨天刚刚迭代的版本执行后,报非法IP,但是用的还是同一个VPS,所以想请教一下,是我那个地方还需要调整的吗?麻烦帮忙看一下。谢谢!!!
image

Questions on src/monitor.py

你好,在理解运行代码的时候遇到一些问题想请教下:

src/monitor.py开始处的注释来看,该文件主要实现了以下三个功能:

# 1. 监控一个币种,如果当期资金费+预测资金费小于重新开仓成本(开仓期现差价-平仓期现差价-手续费),进行平仓。
# 2. 如果合约仓位到达下级杠杆,进行减仓。如果合约仓位到达上级杠杆,进行加仓。
# 3. 如果距离下期资金费3小时以上,(开仓期现差价-平仓期现差价-手续费)>0.2%,进行套利。

Question 1
1.1 对于注释中功能1. 我的理解是, 如果资金费利润(当期资金费+下期预测资金费)小于期现差价利润(开仓期现差价-平仓期现差价-手续费),则进行平仓直接赚取期现差价利润而舍弃资金费利润。请问这样理解是对的吗?你注释中所写的重新开仓成本就是开仓平仓是期现差价利润的意思吗? 如果不是可否麻烦解释下?

1.2 代码中147行计算重新开仓成本, cost = open_pd - close_pd + 2 * trade_fee 这里的trade_fee 为什么是相加而不是相减呢?

cost = open_pd - close_pd + 2 * trade_fee

1.3 代码143-146行中,开仓期现差价和平仓期现差价都是用该标的的过去一段时间内的统计平均加减标准差得来。为什么不能直接计算该仓位开仓时的期现差价,和当前时间点的期现差价作为平仓期现差价呢?

  assert (recent := Stat.recent_open_stat()), lang.fetch_ticker_first
  open_pd = recent['avg'] + recent['std']
  recent = Stat.recent_close_stat()
  close_pd = recent['avg'] - recent['std']

Question 2
对于注释中功能3.我好像没有在src/monitor.py找到相应的代码,是该功能还没有实现吗?或者是我遗漏了哪部分代码?

P.S. 代码写的好好,感谢无私的分享!!

coroutine 'record' was never awaited

hello, im using the latest version on linux and I get this stdout when I fetch Ticker (5):

Process Process-2:
Traceback (most recent call last):
  File "/usr/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/usr/lib/python3.9/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/panpansh/Projects/Futures-Spot-Arbitrage-OKEx-V5/src/record.py", line 51, in record_ticker
    loop.run_until_complete(record())
  File "/usr/lib/python3.9/asyncio/base_events.py", line 623, in run_until_complete
    self._check_running()
  File "/usr/lib/python3.9/asyncio/base_events.py", line 583, in _check_running
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
/usr/lib/python3.9/multiprocessing/process.py:331: RuntimeWarning: coroutine 'record' was never awaited
  traceback.print_exc()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

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.