Giter Site home page Giter Site logo

python-binance-profit's Introduction

Welcome to python-binance-profit GitHub repository!

Notes

The script allows you to place a buy order and automatically place an OCO order to secure (and exit) your trade. It's using the binance API python wrapper from @sammchardy python-binance. If you want to create Binance account, here's my referral link: earn 10% commission on the fees from my trades.

Disclaimer

Even if the scripts are easy to understand, errors exists that's why the Issues section is important to report any bug that you may find. I recommend to use the latest release because it has been tested multiple times compared to the other branches.

Requirements

  • Python 3.8+, if you don't have it yet, you can install it:

  • Create an API key after logging in to your Binance account https://www.binance.com/en/my/settings/api-management:

    • Check both Enable Reading and Enable Spot & Margin Trading
    • Save carefully your API key and your Secret key (⚠️ the last one won't be visible again at your next login)
    • Add your Binance API key to a environement variable called API_KEY
    • Add your Binance Secret key to a environement variable called SECRET_KEY

Note: If you're using Windows, you might need to install Microsoft Visual C++ 14.0+

Installation

  • Clone the repository
git clone https://github.com/UPetit/python-binance-profit.git
  • Install the dependencies
pip install -r requirements.txt
  • Linux version without anaconda
# restrict lib install to the local venv
python3 -m venv venv
source ./venv/bin/activate
pip install -r requirements.txt

Use cases

Run a Buy order (limit or market) followed by an OCO Sell order

Script logic

The script will check that both the price and the quantity are compliant with Binance rules for the selected symbol. If both are validated, the buy order will be sent to the market and the script will wait until it's filled. Once it's executed the OCO order will be prepared: the price with profit will be calculated according to the profit percentage that has been provided, same for the stoploss price. The OCO order will be sent to the market and the script will return the two related orders and then quit.

Instructions

  1. First, choose the crypto pair you want to trade. We call it the symbol (string).

Example: If you want to trade BTC with USDT, the symbol will be BTCUSDT (as long as this is an available symbol in Binance).

  1. For a limit buy order:
    • Define how much of the base asset you want to buy. We call it the quantity (Decimal).
    • Define what is the price (for 1 unit of the base asset) you want to buy the quantity defined above. We call it the price (Decimal).

Example: if you trade the symbol BTCUSDT, you need to define the quantity of BTC (base asset) and the BTC price in USDT (quote asset) you're willing to pay.

  1. For a market buy order:
  • Define the amount of quote asset you want to spend. We call it the total (Decimal).

Example: if you trade with BTCUSDT, you need to define how much you want to spend in USDT for BTC.

  1. Finally have to define your profit and stoploss percentages to exit the trade (this will be applied to the OCO sell order). We call them respectively profit (Decimal) and loss (Decimal).

If you want to make 2% of profit and put a stoploss a 1%, your profit should be 2 and the loss 1 (as Decimals between 0.0 and 100.0)

⚠️ Please not that if the quantity and/or price formats are not following Binance rules, your Limit buy order won't be validated and the script will stop before submitting to order to the market.

How to know the prices formats ? Go to the Binance market of your symbol you want to trade, check the current prices and quantities going through the market to know how many decimals you can use for both of them. For instance for BTCUSDT: the BTC quantity is using 6 decimals and the USDT price is using 2 decimals.

  1. Run the script using the parameters you've just defined by replacing with your values: Limit buy order followed by an OCO sell order:
python execute_orders.py --symbol YOUR_SYMBOL --buy_type limit --quantity YOUR_QUANTITY --price YOUR_PRICE --profit YOUR_PROFIT --loss YOUR_LOSS

Example: If you want to trade BTC against USDT, buy 0.251897 BTC at 31488.69 USDT (per BTC) and then you want to sell it to make a 4% profit and a potential loss of 1%, you'll execute the script like this:

python execute_orders.py --symbol BTCUSDT --buy_type limit --quantity 0.251897 --price 31488.69 --profit 4 --loss 1

Market buy order followed by an OCO sell order:

python execute_orders.py --symbol YOUR_SYMBOL --buy_type market --total TOTAL_AMOUNT --profit YOUR_PROFIT --loss YOUR_LOSS 

Example: If you want to trade BTC against USDT, buy 100 USDT of BTC and then you want to sell it to make a 4% profit and a potential loss of 1%, you'll execute the script like this:

python execute_orders.py --symbol BTCUSDT --buy_type market --total 100.0 --profit 4 --loss 1 

Enjoy! Don't hesitate to send me feedbacks and report issues :) Thank you!

python-binance-profit's People

Contributors

philippegalvan avatar upetit 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-binance-profit's Issues

Add a stop price parameter

As the stop price = stop limit price at the moment, if the market is going down fast, the order won't be filled or will be partially filled.

  • Add a new parameter for the trigger (= stop price) that should be slightly higher than the stop limit price
  • Run a check that stop price is >= stop limit price before sending the order

[BUG] (Code 401) API-key format invalid.

Describe the bug
(Code 401) API-key format invalid.
To Reproduce
python execute_orders.py --symbol TRXBTC --buy_type market --total 0.00004 --profit 4 --loss 2

Expected behavior
Order to be placed

Screenshots
image

Environment (please complete the following information):

  • OS: Windows 10
  • Python version : 3.8
  • Release version : 0.0.4

Documentation update

Hello there, hope you could update the documentation for the usage of market order and buying by % of wallet balance. That would be extremely helpful! Thank you!

Invalid JSON error message from Binance: This endpoint has been deprecated

Dears,

When I tried to make a purchase I got the error message below. Does anyone have any tips on how to solve this?

binance.exceptions.BinanceAPIException: APIError(code=0): Invalid JSON error message from Binance: This endpoint has been deprecated, please integrate with “GET@/sapi/v1/system/status”. See details in the announcement: https://www.binance.com/en/support/announcement/f45dde7da58b473aa885349946bed269

python3 execute_orders.py --symbol BNBBUSD --buy_type limit --quantity 10.1 --price 640 --profit 1 --loss 50

image

[BUG] Account has insufficient balance for requested action while placing limit OCO order

Describe the bug
Limit order failed

To Reproduce
python3 execute_orders.py --symbol BNBBUSD --buy_type limit --quantity 15 --price 579.4 --profit 1 --loss 10

Expected behavior
Limit order failed but market order successful

Screenshots
image
image

Environment (please complete the following information):

  • OS: Debian 11.1
  • Python version 3.10.0
  • Release version last

Additional context
Last version of python-binance

Add buy market order choice

Add the possibility to choose between the buy limit order or the buy market order

Idea: --price with an empty value could mean a market order for instance ?

[BUG] Order does not exist

Describe the bug
When the buy order has been executed, it's sometimes not possible to fetch the order (due to Binance network maybe?) and the API returns: binance.exceptions.BinanceAPIException: APIError(code=-2013): Order does not exist.

To Reproduce
Run the scripe execute_orders.py

Expected behavior
The buy order should be fetched using the order id previously stored.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • OS: Mac OS Catalina
  • Python version: 3.7.4
  • Release version: v0.0.1

Additional context
Add any other context about the problem here.

KeyError: sell_order["orderReports"]

(Code 400) Illegal characters found in parameter 'side'; legal range is '^[a-zA-Z]{1,36}$'. Traceback (most recent call last): File "execute_orders.py", line 139, in <module> main(input_args=input_args_validated) File "execute_orders.py", line 67, in main stop_loss_limit_order, limit_maker_order = client.execute_sell_strategy( File "/home/python-binance-profit/app/client.py", line 435, in execute_sell_strategy sell_orders = sell_order["orderReports"] KeyError: 'orderReports'

The buy works perfectly but sell order doesn't work and gives error. How can I solve this issue? Thanks

ECONNRESET while checking current price

pi@raspberrypi:~/python-binance-profit $ python3 execute_orders.py --symbol ATOMUSDT --quantity 125 --price 7.721 --profit 0.03 --loss 0.03
Load client
Client authenticated
Binance API Time: 2021-01-28 20:59:26Z
Binance API status: normal
Trading allowed
OCO orders allowed

Step 1 - Buy order execution
Order validation in progress...
Quantity (limit order) is validated
Quantity: 125.0
Price is validated
Price: 7.721
-> The limit buy order has been sent
The order is not filled yet...
The order is not filled yet...
The order is not filled yet...
The order is not filled yet...
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "", line 3, in raise_from
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.7/http/client.py", line 1336, in getresponse
response.begin()
File "/usr/lib/python3.7/http/client.py", line 306, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.7/http/client.py", line 267, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
File "/usr/lib/python3/dist-packages/urllib3/contrib/pyopenssl.py", line 309, in recv_into
return self.recv_into(*args, **kwargs)
File "/usr/lib/python3/dist-packages/urllib3/contrib/pyopenssl.py", line 299, in recv_into
raise SocketError(str(e))
OSError: (104, 'ECONNRESET')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 367, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/lib/python3/dist-packages/six.py", line 692, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "", line 3, in raise_from
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.7/http/client.py", line 1336, in getresponse
response.begin()
File "/usr/lib/python3.7/http/client.py", line 306, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.7/http/client.py", line 267, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
File "/usr/lib/python3/dist-packages/urllib3/contrib/pyopenssl.py", line 309, in recv_into
return self.recv_into(*args, **kwargs)
File "/usr/lib/python3/dist-packages/urllib3/contrib/pyopenssl.py", line 299, in recv_into
raise SocketError(str(e))
urllib3.exceptions.ProtocolError: ('Connection aborted.', OSError("(104, 'ECONNRESET')"))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "execute_orders.py", line 509, in
float(args.profit), float(args.loss))
File "execute_orders.py", line 469, in main
qty_round, price_round)
File "execute_orders.py", line 374, in execute_buy_strategy
orderId=buy_order_id)
File "/home/pi/.local/lib/python3.7/site-packages/binance/client.py", line 1617, in get_order
return self._get('order', True, data=params)
File "/home/pi/.local/lib/python3.7/site-packages/binance/client.py", line 237, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "/home/pi/.local/lib/python3.7/site-packages/binance/client.py", line 202, in _request_api
return self._request(method, uri, signed, **kwargs)
File "/home/pi/.local/lib/python3.7/site-packages/binance/client.py", line 196, in _request
self.response = getattr(self.session, method)(uri, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 546, in get
return self.request('GET', url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', OSError("(104, 'ECONNRESET')"))

Add % of wallet to spend

Add the possibility to select the % of wallet to spend for the buy order instead of using a fixed price.
(Feature exists on Binance UI where you can select the % using a slider)

[BUG] Account has insufficient balance for requested action while placing OCO order

Describe the bug
Once the buy order is filled, the script was not able to sell what was bought because of this error :

Account has insufficient balance for requested action while placing

I've placed a 67 SUSHI order but probably because of the finance fees, I was only owning 66.970 SUSHI 🍣

Additional context

The order is not filled yet...
The buy order has been filled!
=========================
=== Buy order summary ===
=> Buy price: 15.360 USDT
=> Total price: 1029.120 USDT
=> Buy quantity: 67.000 SUSHI
=> Step 2 - Sell OCO order execution
Selling price (profit): 16.051
Stoploss price: 14.899
(Code 400) Account has insufficient balance for requested action.
Traceback (most recent call last):
  File "execute_orders.py", line 145, in <module>
    input_args=input_args_validated
  File "execute_orders.py", line 74, in main
    input_args.loss,
  File "/home/pi/python-binance-profit/app/client.py", line 515, in execute_sell_strategy
    sell_orders = sell_order["orderReports"]
KeyError: 'orderReports'

[Feature Request]

for OCO order can we specify

  1. --target with a price value.
  2. --stoploss-price to define precise price value.
  3. --quantity-percent to specify how much percentage to go for OCO order.

[BUG]

When Trying to open a market order with 0.1 BNB in size, i get an

python3 ./execute_orders.py --symbol BNBPAX --buy_type market --total 0.1 --profit 6.153844958229082 --loss 3.88300173597268
Binance API Time: 2021-04-18 12:24:22Z
Binance API is up
Trading allowed
OCO orders allowed
=> Step 1 - Buy order execution
(Code 400) Filter failure: MIN_NOTIONAL
Market buy order has not been created

The Account definetly has sufficient balance and 0.1 BNB is definately tradable.

If It was acually too little, it would be nice to be told whats actually the minimum required amount.

Environment :

  • OS: Ubuntu 20.10]
  • Python version [3.8]

thanks for the great work anyhow ;)

Caching Feature

Hello there! I tried the market order function and it works very well. I just got one feedback for the program.

Would it be possible to introduce a caching system into the program such that the order/trading speed can be improved on? In short, the communication and execution time taken between the program and binance api can shortened for rapid order execution.

Cheers!

issue OCO

Hi!

Thanks for the work put into this. I am following instructions in your readme file.

I am buying at market price, but I get this error sometimes, but not all the time. Not sure what the issue could be.

File "/home/user/python-binance-profit/app/client.py", line 424, in execute_sell_strategy
oco_order = OCOOrder(
File "pydantic/main.py", line 400, in pydantic.main.BaseModel.init
pydantic.error_wrappers.ValidationError: 2 validation errors for OCOOrder
root
The price is not valid compared to current avg trades. (type=value_error)
root
The price is not valid compared to current avg trades. (type=value_error)

I have tried selling my spot position and starting all over again, but same error.

Add exit handler that cancels the buy order

Feature: Catch the Ctrl+C script termination in order to trigger the cancellation of the buy order.
Scenario: you submitted a buy order but it's taking too long to be filled (maybe the price increased since), so you want to cancel it and retry with another price.

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.