binance python api margin order incomplete repay loan - python

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...

Related

python_binance api buy order buys slightly different amount

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

Sending entire Ethereum address balance in post EIP-1559 world

I'm trying to figure out how to send an entire address balance in a post EIP-1559 transaction (essentially emptying the wallet). Before the London fork, I could get the actual value as Total balance - (gasPrice * gas), but now it's impossible to know the exact remaining balance after the transaction fees because the base fee is not known beforehand.
Is there an algorithm that would get me as close to the actual balance without going over? My end goal is to minimize the remaining Ether balance, which is essentially going to be wasted.
This can be done by setting the 'Max Fee' and the 'Max Priority Fee' to the same value. This will then use a deterministic amount of gas. Just be sure to set it high enough - comfortably well over and above the estimated 'Base Fee' to ensure it does not get stuck.

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.

Regex working in online tester (https://regexr.com/) but not in python/google colab [duplicate]

This question already has answers here:
re.findall behaves weird
(3 answers)
Closed 2 years ago.
I am trying to capture the footnotes of the attached text. So, logic is that a footnote begins with a number on a newline (\n\d+\s) and ends with a number on a newline (\n\d+\s) or the word "Page". The logic seems to work on multiple online regular expression testers but is returning a bunch of empty strings as output on python script in google colab.
Here is the code:
m=re.findall('\n\d+(?:(?!\n\d+\s)(?!Page)(.|\n))*', text)
Output is list of empty strings
Here are two examples of text:
However, we also urge the Commission to go further, and revisit the entire NMS Plan
process -- which is fundamentally conflicted and severely outdated.3 The NMS Plan
process was devised over forty years ago at a time of fewer exchanges that were also
mutually owned, not-for-profit entities. In stark contrast, today, these entities are
for-profit publicly traded entities with third-party shareholders. While the proposed
reforms would assert the Commission’s ability to more effectively regulate NMS Plan
fee filings, it would not directly address the conflicts of interest of having for-profit
entities acting as both regulators and fee setters on essential capital market utilities. We
ask the Commission to boldly address these bigger issues, and to the extent necessary,
seek assistance from Congress.
1 The Healthy Markets Association is an investor-focused not-for-profit coalition working to educate
market participants and promote data-driven reforms to market structure challenges. Our members, who
range from a few billion to hundreds of billions of dollars in assets under management, have come
together behind one basic principle: Informed investors and policymakers are essential for healthy capital
markets. To learn more about Healthy Markets or our members, please see our website at
http://healthymarkets.org.
2 Rescission of Effective-Upon-Filing Procedure for NMS Plan Fee Amendments, Sec. and Exch.
Comm’n, 84 Fed. Reg. 54794 (Oct. 11, 2019), available at
https://www.govinfo.gov/content/pkg/FR-2019-10-11/pdf/2019-21770.pdf (“Rescission Proposal”).
3 See, e.g., Remarks of Hon. Dan Gallagher, before the 2014 SRO Outreach Conference, Sept. 16,
2014, available at https://www.sec.gov/news/speech/2014-spch091614dmg-sro
Page 1 of 12
http://www.healthymarkets.org/
https://www.govinfo.gov/content/pkg/FR-2019-10-11/pdf/2019-21770.pdf
https://www.sec.gov/news/speech/2014-spch091614dmg-sro
rule-comments#sec.gov
Background on NMS Plans Generally
In the early 1970s, it became clear that the government needed to step into the markets
to provide a mechanism to consolidate information and accountability across a myriad
of trading venue. The Commission began outlining the contours of a “central market
system for listed securities.”4
The Commission has asked whether, as an alternative to rescinding the Fee Exception and
instating the standard procedure, it should consider permitting NMS plan fee applications to
take effect 60 days after filing if the Commission does not act. In our view, this approach –
while preferable to the current Fee Exception – essentially establishes a Fee Exception by
another name. As is the case under the current Fee Exception, the alternative, 60-day
9 Proposal at 17.
10 Proposal at 38.
4
https://transition.10
process, as described by the Commission, would still allow a fee change to take effect without
an affirmative determination by the Commission during the 60-day abrogation period that the
fee change comports with the requirements of the Exchange Act. More fundamentally, the
Commission has taken notice of the fact that NMS plan fees are not economically de minimis
or otherwise trivial; to the contrary, the total revenues generated by fees for core data totaled
more than $500 million in just 2017. Given that fact alone, we are hard-pressed to understand
why fee-related applications should be subject to a lesser standard of review than applications
that pertain to other matters and that may be less significant economically to investors and
other market participants.
In this second output, our desired output would be:
m=['9 Proposal at 17.', '10 Proposal at 38.']
In summary, each item in the list m should be a separate footnote. How should we approach this using regex in google colab using python
I works when you put parenthesis around the capture group in regex:
m=re.findall('(\n\d+\s(?:(?!\n\d+\s)(?!Page)(.|\n))*)', text)

Categories