Sending entire Ethereum address balance in post EIP-1559 world - python

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.

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.

Teleporting Traveler, Optimal Profit over time Problem

I'm new to the whole traveling-salesman problem as well as stackoverflow so let me know if I say something that isn't quite right.
Intro:
I'm trying to code a profit/time-optimized multiple-trade algorithm for a game which involves multiple cities (nodes) within multiple countries (areas), where:
The physical time it takes to travel between two connected cities is always the same ;
Cities aren't linearly connected (you can teleport between some cities in the same time);
Some countries (areas) have teleport routes which make the shortest path available through other countries.
The traveler (or trader) has a limit on his coin-purse, the weight of his goods, and the quantity tradeable in a certain trade-route. The trade route can span multiple cities.
Question Parameters:
There already exists a database in memory (python:sqlite) which holds trades based on their source city and their destination city, the shortest-path cities inbetween as an array and amount, and the limiting factor with its % return on total capital (or in the case that none of the factors are limiting, then just the method that gives the highest return on total capital).
I'm trying to find the optimal profit for a certain preset chunk of time (i.e. 30 minutes)
The act of crossing into a new city is actually simultaneous
It usually takes the same defined amount of time to travel across the city map (i.e. 2 minutes)
The act of initiating the first or any new trade takes the same time as crossing one city map (i.e. 2 minutes)
My starting point might not actually have a valid trade ( I would have to travel to the first/nearest/best one )
Pseudo-Solution So Far
Optimization
First, I realize that because I have a limit on the time it takes, and I know how long each hop takes (including -1 for intiating the trade), I can limit the graph to all trades whose hops are under or equal to max_hops=int(max_time/route_time) -1. I cut elements of the trade database that don't fall within this time limit, pruning cities that have shortest-path lengths greater than max_hops.
I make another entry into the trades database that includes the shortest-paths between my current city and the starting cities of all the existing trades that aren't my current city, and give them a return of 0%. I would limit these to where the number of city hops is less than max_hops, and I would also calculate whether the current city to the starting city plus that trades shortest-path-hops would excede max_hops and remove those that exceded this limit.
Then I take the remaining trades that aren't (current_city->starting_city) and add trade routes with return of 0% between all destination and starting cities wheres the hops doesn't excede max_hops
Then I make one last prune for all cities that aren't in the trades database as either a starting city, destination city, or part of the shortest path city arrays.
Graph Search
I am left with a (much) smaller graph of trades feasible within the time limit (i.e. 30 mins).
Because all the nodes that are connected are adjacent, the connections are by default all weighted 1. I divide the %return over the number of hops in the trade then take the inverse and add + 1 (this would mean a weight of 1.01 for a 100% return route). In the case where the return is 0%, I add ... 2?
It should then return the most profitable route...
The Question:
Mostly,
How do I add the ability to take multiple routes when I have left over money or space and keep route finding through path discrete to single trade routes? Due to the nature of the goods being sold at multiple prices and quantities within the city, there would be a lot of overlapping routes.
How do I penalize initiating a new trade route?
Is graph search even useful in this situation?
On A Side Note,
What kinds of prunes/optimizations to the graph should I (or should I not) make?
Is my weighting method correct? I have a feeling it will give me disproportional weights. Should I use the actual return instead of percentage return?
If I am coding in python are libraries such as python-graph suitable for my needs? Or would it save me a lot of overhead (as I understand, graph search algorithms can be computationally intensive) to write a specialized function?
Am I best off using A* search ?
Should I be precalculating shortest-path points in the trade database and maxing optimizations or should I leave it all to the graph-search?
Can you notice anything that I could improve?
If this is a game where you are playing against humans I would assume the total size of the data space is actually quite limited. If so I would be inclined to throw out all the fancy pruning as I doubt it's worth it.
Instead, how about a simple breadth-first search?
Build a list of all cities, mark them unvisited
Take your starting city, mark the travel time as zero
for each city:
if not finished and travel time <> infinity then
attempt to visit all neighbors, only record the time if city is unvisited
mark the city finished
repeat until all cities have been visited
O(): the outer loop executes cities * maximum hops times. The inner loop executes once per city. No memory allocations are needed.
Now, for each city look at what you can buy here and sell there. When figuring the rate of return on a trade remember that growth is exponential, not linear. Twice the profit for a trade that takes twice as long is NOT a good deal! Look up how to calculate the internal rate of return.
If the current city has no trade don't bother with the full analysis, simply look over the neighbors and run the analysis on them instead, adding one to the time for each move.
If you have CPU cycles to spare (and you very well might, anything meant for a human to play will have a pretty small data space) you can run the analysis on every city adding in the time it takes to get to the city.
Edit: Based on your comment you have tons of CPU power available as the game isn't running on your CPU. I stand by my solution: Check everything. I strongly suspect it will take longer to obtain the route and trade info than it will be to calculate the optimal solution.
I think you've defined something that fits into a class of problems called inventory - routing problems. I assume since you have both goods and coin, the traveller is both buying and selling along the chosen route. Let's first assume that EVERYTHING is deterministic - all quantities of goods in demand, supply available, buying and selling prices, etc are known in advance. The stochastic version gets more difficult (obviously).
One objective would be to maximize profits with a constraint on the purse and the goods. If the traveller has to return home its looks like a tour, if not, it looks like a path. Since you haven't required the traveller to visit EVERY node, it is NOT a TSP. That's good - shortest path problems are generally much easier than TSPs to solve.
Because of the side constraints and the limited choice of next steps at each node - I'd consider using dynamic programming first attempt at a solution technique. It will help you enumerate what you buy and sell at each stage and there's a limited number of stages. Also, because you put a time constraint on the decision, that limits the state space of choices.
To those who suggested Djikstra's algorithm - you may be right - the labelling conventions would need to include the time, coin, and goods and corresponding profits. It may be that the assumptions of Djikstra's may not work for this with the added complexity of profit. Haven't thought through that yet.
Here's a link to a similar problem in capital budgeting.
Good luck !

Categories