python_binance api buy order buys slightly different amount - python

Let's say I want to buy 0.072 coins of 'XMRUSDT'. And executed buy order like following:
buy_market = client.create_order(symbol='XMRUSDT', side='BUY', type='MARKET', quantity=0.072)
and
print(buy_market['executedQty']) # prints 0.072.
But if check on binance app, actually 0.071928 coins was bought not 0.072.
So when my bot decided to sell, it have to sell 0.071 not 0.072.(bceause of lot size). So 0.000928 coins being left unsellable. This issue happens all the time.
This issue happens all the time, so on my portfolio coins being left is being unsellable being stacked continuously.
Is there any way to solve this problem?
Thanks

It’a not a Python or python_binance problem. It happens so, because your tokens are not sold in one batch. When you create a buy/sell order, binance finds matching orders by rate and sells your tokens in small portions.
What you can do, is increase your bot precision to lower the amount of your leftovers

Related

binance python api margin order incomplete repay loan

I am trying to repay a loan using the binance python API. I retrieve the loan size from the acct dictionary and input that as the quoteOrderQty in the auto repay margin order.
When I run closeLong() the loan is not paid off completely, a small balance remains in the base and a small USDT debt remains in the quote. What am I doing wrong here?
acct = client.get_isolated_margin_account()
def quoteDebt():
quoteLoan = round(Decimal(acct['assets'][1]['quoteAsset']['borrowed']),2)
print("USDT Debt: "+str(quoteLoan))
return quoteLoan
def closeLong():
client.create_margin_order(
symbol=sym,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
sideEffectType= 'AUTO_REPAY',
isIsolated='TRUE',
quoteOrderQty=quoteDebt())
print("Closed Long")
I've had the same issue. I believe it's that interest is compounded continuously, so a tiny amount of interest is incurred between you checking how much is owed and you repaying it. I hacked around this by looping indefinitely: the first loop repays the principal, the second the interest on that, the third the interest on that, and by the 4th or 5th loop the interest rounds down to 0. I'd much prefer if there were a repay_all() API call available, of course, but I'm not aware of anything like that.
Same issue here, not nice from Binance to not enable us to fully repay automatically through API. If you can lock some extra amount on this, ideal solution for me is to buy the borrowed asset on spot account, fees are paid from BNB, which is less vs. isolated margin account, transfer the asset to isolated margin account a repay (2 step approach). You need to have the reserve though, as you can't transfer all money out of margin account, when in position, as it will get liquidated.
If you try to repay isolated account directly, 0.1% fee is deducted, so the loan is not fully repaid. If buy from spot, you can pay fee as 0.075% in BNB and get the full amount of asset you asked for (as fees are paid in BNB). No tiny amounts remaining.
Ideal approach for you, is based on frequency of trades. High frequency trading - fees matters, trades are small and you can allocate extra funds to this. Low frequency trading - fees does not matter that much, you might want to go all-in, not having extra funds, and you might do this manually as well ("Close all positions" in UI), for those tiny amounts...

python FIFO stock portfolio calculations

I'm calculating returns for a stock portfolio with hundreds of symbols over a period of many years. I need to evaluate the tax efficiency of this portfolio, which means that I need to account for stock purchases and sales according to FIFO rules of accounting. If I buy a stock and sell it in less than a year, then I pay one tax rate, but if I hold it for over 1 year, I pay a different tax rate. So, for every date, I'd like to calculate the long-term and short-term capital gains for the portfolio from the trades that happen on that date. I'm trying to think of an efficient way to perform these calculations. Ideally, this would be something that would operate on a Pandas DataFrame that contains all of the trades. Perhaps someone knows of a open source portfolio app that already does this? Thanks.

How to send OCO order to binance

I would like to ask you for help. I´m trying to change python code from sending limit/market order to OCO order through api to binance. I can make limit order, market order, stop loss limit order. I can´t figure out how to place OCO order...
When I used limit order I was sending order_type=ORDER_TYPE_LIMIT then I used order = client.create_order() and it was working. When I wanted to send market order I used order_type=ORDER_TYPE_MARKET but when I want to make OCO order the only option that I found that should work is:
order = client.create_oco_order() without order_type but here I´m getting error 1013 Stop loss is not supported for this symbol...
I checked https://api.binance.com/api/v1/exchangeInfo
and there is this "orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,
So I can´t use order_type. There is not ORDER_TYPE_OCO and ocoAllowed is true so I should be able to send oco order. But I´m getting "error 1013: Stop loss orders are not supported for this symbol. order failed".
What I want is to set "price" as limit sell order to take profit highier when price will get there and to set stop loss "stopPrice" lower if price will go down...at once. This is how OCO should works.
Can somebody please give me an advice how to do it? I´m not python guru I´m just changing one code that I found and what I understand is if oco is allowed stop loss should be allowed too. Thanks
so that all interested have a precise answer about the solution of this problem, I include the code with the comments.
I'll use an OCO sell order as an example in BTCUSDT.
Imagine I have 1 BTC. The current price is at 30157.85 and I want to sell 1 BTC much higher at 32000.07
But the price does not rise and begins to fall, so I place my stopPrice at 29283.03 where the limit sell order will be opened at the price 29000.00
This means that I will sell at 32000.07 or 29000.00 USDT. The order is written as follows:
order= client.order_oco_sell(
symbol= 'BTCUSDT',
quantity= 1.00000,
price= '32000.07',
stopPrice= '29283.03',
stopLimitPrice= '29000.00',
stopLimitTimeInForce= 'FOK')
Note that the OCO order requires the stopLimitTimeInForce parameter. I have used the value 'FOK' but I leave you here the description of the different values that you can use: https://help.bybit.com/hc/en-us/articles/360039749233-What-are-time-in-force-TIF-GTC-IOC-FOK-
Note well that the price, stopPrice, stopLimitPrice and stopLimitTimeInForce parameters are strings and not float or decimal.

Arbitrage algorithm for multiple exchanges, multiple currencies, and multiple amounts

I'm searching for a way to apply an arbitrage algorithm across multiple exchanges, multiple currencies. and multiple trading amounts. I've seen examples of using BellmanFord and FloydWarshall, but the one's I've tried all seem to be assuming the graph data set is made up of prices for multiple currencies on one single exchange. I've tried tinkering and making it support prices across multiple exchanges but I haven't found any success.
One article I read said that I use BellmanFord and simply put only the best exchange's price in the graph (as opposed to all the exchange's prices). While it sounds like that should work, I feel like that could be missing out on value that way. Is this the right way to go about it?
And regarding multiple amounts, should I just make one graph per trade amount? So say I want to run the algorithm for $100 and for $1000, do I just literally populate the graph twice once for each set of data? The prices will be different at $100 than for $1000 so one exchange that has the best price at $100 may be different then that of the $1000 amount.
Examples:
The graph would look like this:
rates = [
[1, 0.23, 0.26, 17.41],
[4.31, 1, 1.14, 75.01],
[3.79, 0.88, 1, 65.93],
[0.057, 0.013, 0.015, 1],
]
currencies = ('PLN', 'EUR', 'USD', 'RUB')
REFERENCES:
Here is the code I've been using, but this assumes one exchange and one single trade quantity
Here is where someone mentions you can just include the best exchange's price in the graph in order to support multiple exchanges
Trying for accuracy over speed, there's a way to represent the whole order book of each exchange inside of a linear program. For each bid, we have a real-valued variable that represents how much we want to sell at that price, ranging between zero and the amount bid for. For each ask, we have a real-valued variable that represents how much we want to buy at that price, ranging between zero and the amount asked for. (I'm assuming that it's possible to get partial fills, but if not, you could switch to integer programming.) The constraints say, for each currency aside from dollars (or whatever you want more of), the total amount bought equals the total amount sold. You can strengthen this by requiring detailed balance for each (currency, exchange) pair, but then you might leave some opportunities on the table. Beware counterparty risk and slippage.
For different amounts of starting capital, you can split dollars into "in-dollars" and "out-dollars" and constrain your supply of "in-dollars", maximizing "out-dollars", with a one-to-one conversion with no limit from in- to out-dollars. Then you can solve for one in-dollars constraint, adjust the constraint, and use dual simplex to re-solve the LP faster than from scratch.

Efficient algorithm to handle system of changing probabilities

I need help in formulating an algorithm. I have a social networking app built in python with a redis backend. One of the features is an advertising server that advertisers can use to create and serve ads to site users.
Advertisers buy clicks. Cost per click is not fixed. One advertiser may pay 1 cent/click, another may pay 2 cents/click, etc. The more an advertiser pays, the greater the probability of her advertisement being displayed. I.e., higher paying advertisers get clicks faster, all else being equal.
E.g. imagine advertiser 1 paid $10 for 1000 clicks, advertiser 2 paid $20 for 1000 clicks and advertiser 3 paid $30 for 1000 clicks. All else equal, at each ad impression, advertiser 1's ad will have a 1/6 probability of appearing, advertiser 2's ad will have a 2/6 probability of appearing and advertiser 3's ad will have a 3/6 probability of appearing. If a 4th advertiser was added to the mix, the probabilities will revise. Once an advertiser's designated clicks are reached, she's taken out of the mix and the probabilities revise again.
How can this be modeled in an efficient algorithm?
One reason I get stumped when trying to model this is because upon adding (or subtracting) an advertiser, the whole system's probabilities are revised on the fly. I haven't been able to wrap my head around this; hopefully experts can help out.
As an advertiser buying ad spots, I'm personally unsure I would want to pay for an uncertain probability my ad would be shown. The closest to reasonable thing I can imagine, (which may be what you were thinking of anyway) is to only guarantee that those who paid the same rate get the same probability. An efficient way to do this would be to keep a cumulative sum of the rates paid to give your random range:
cumsum, rate, company
1, 1, A
2, 1, B
4, 2, C
8, 4, D
if you generate a random number from 0 to 7 (or 1 to 8) you can do a binary search (O log(n)) to determine which ad should be shown.
If you keep the companies sorted by rate, you could probably even do better than (O log(n))... maybe
adding and subtracting companies would be relatively simple: add (or subtract) a line for the company and the rate, then recalculate cumsum.

Categories