def set_leverage(symbol, leverage): try: request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) result = request_client.change_initial_leverage(symbol=symbol, leverage=leverage) return True except Exception as e: print(e) time.sleep(1) return False
class Binance: def __init__(self): self.client = RequestClient(api_key=BINANCE_API_KEY, secret_key=BINANCE_SECRET_KEY) def get_wallet_value(self) -> float: res = self.client.get_balance() for e in res: if e.asset == 'USDT': return e.withdrawAvailable return 0 def buy(self): print("creating order") market_price = self.get_mark_price() quantity = calc_percentage(TOTAL_USDT_INVESTMENT_PERCENTAGE, self.get_wallet_value()) / market_price self.client.change_initial_leverage(SYMBOL, LEVERAGE) try: self.client.change_margin_type( SYMBOL, FuturesMarginType.CROSSED if MARGIN_TYPE == 'CROSS' else FuturesMarginType.ISOLATED) except Exception: pass order = self.client.post_order(symbol=SYMBOL, side=OrderSide.BUY, ordertype=OrderType.MARKET, positionSide=PositionSide.BOTH, quantity=int(quantity)) print( f"order created successfully: market_price: {market_price}, quantity: {quantity}" ) print(f"{PrintBasic.print_obj(order)}") if STOP_LOSS_PERCENTAGE is not None: # STOP LOSS stop_price = market_price - calc_percentage( market_price, int(STOP_LOSS_PERCENTAGE)) try: self.stop_loss(price=float("%.4f" % stop_price)) print( f"stop loss order created successfully: stop_price: {stop_price}" ) except Exception: print( f"something went wrong, could not create stop loss order") if TAKE_PROFIT_PERCENTAGE is not None: # TAKE PROFIT take_profit = market_price + calc_percentage( market_price, int(TAKE_PROFIT_PERCENTAGE)) try: self.take_profit(price=float("%.4f" % take_profit)) print( f"take profit order created successfully: stop_price: {take_profit}" ) except Exception: print( f"something went wrong, could not create take profit order" ) def stop_loss(self, price: float): res = self.client.post_order(symbol=SYMBOL, stopPrice=price, side=OrderSide.SELL, ordertype=OrderType.STOP_MARKET, positionSide=PositionSide.BOTH, closePosition=True, newOrderRespType=OrderRespType.RESULT) print(f"{PrintBasic.print_obj(res)}") return res def take_profit(self, price: float): res = self.client.post_order(symbol=SYMBOL, stopPrice=price, side=OrderSide.SELL, ordertype=OrderType.TAKE_PROFIT_MARKET, positionSide=PositionSide.BOTH, closePosition=True, newOrderRespType=OrderRespType.RESULT) print(f"{PrintBasic.print_obj(res)}") return res def get_mark_price(self, symbol: str = SYMBOL) -> float: return self.client.get_mark_price(symbol).markPrice
from binance_f import RequestClient from binance_f.constant.test import * from binance_f.base.printobject import * from binance_f.model.constant import * request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) result = request_client.change_initial_leverage(symbol="BTCUSDT", leverage=10) PrintBasic.print_obj(result)
def open_position_binance_futures(pair, take_profit, stop_loss, pair_change, quantity, leverage, side): global STOP_LOSS global TARGET global STOP_LOSS_REACHED global STOP_LOSS_ORDER_ID global TAKE_PROFIT_ORDER_ID request_client = RequestClient(api_key=API_KEY, secret_key=SECRET_KEY) # Cancel previous take profit and stop loss orders try: if (TAKE_PROFIT_ORDER_ID): request_client.cancel_order(symbol=pair, orderId=TAKE_PROFIT_ORDER_ID) except: print( red.bold('Take profit order id {} could not be cancelled'.format( TAKE_PROFIT_ORDER_ID))) try: if (STOP_LOSS_ORDER_ID): request_client.cancel_order(symbol=pair, orderId=STOP_LOSS_ORDER_ID) except: print( red.bold( 'Stop loss profit order id {} could not be cancelled'.format( STOP_LOSS_ORDER_ID))) STOP_LOSS_ORDER_ID = None TAKE_PROFIT_ORDER_ID = None # Change leverage try: request_client.change_initial_leverage(pair, leverage) except: print(red.bold('error changing leverage')) try: margin_type = request_client.change_margin_type( symbol=pair, marginType=FuturesMarginType.ISOLATED) except: print(red.bold('error changing margin type')) # Request info of all symbols to retrieve precision exchange_info = request_client.get_exchange_information() price_precision = 0 for item in exchange_info.symbols: if (item.symbol == pair): precision = item.quantityPrecision price_precision = item.pricePrecision # Create order quantity_rounded = float(quantity * leverage) / float(pair_change) quantity_with_precision = "{:0.0{}f}".format(quantity_rounded, precision) stop_loss = "{:0.0{}f}".format(stop_loss, price_precision) take_profit = "{:0.0{}f}".format(take_profit, price_precision) STOP_LOSS = stop_loss STOP_LOSS_REACHED = False TARGET = take_profit print( white.bold( '\n\tOpening future position {} at market ({}) with quantity: {} {} with take profit on: {} and stop loss: {}' .format(side, pair_change, quantity_with_precision, pair, take_profit, stop_loss))) order_side = OrderSide.BUY if (side == MarketSide.SHORT): order_side = OrderSide.SELL result = request_client.post_order(symbol=pair, side=order_side, quantity=quantity_with_precision, ordertype=OrderType.MARKET, positionSide="BOTH") orderId = result.orderId print(green.bold('\n\t\t✓ Market order created.')) # Set take profit and stop loss orders try: order_side = OrderSide.SELL if (side == MarketSide.SHORT): order_side = OrderSide.BUY result = request_client.post_order(symbol=pair, side=order_side, stopPrice=stop_loss, closePosition=True, ordertype=OrderType.STOP_MARKET, positionSide="BOTH", timeInForce="GTC") STOP_LOSS_ORDER_ID = result.orderId print( green.bold( '\n\t\t✓ Stop market order at: {} created.'.format(stop_loss))) result = request_client.post_order( symbol=pair, side=order_side, stopPrice=take_profit, closePosition=True, ordertype=OrderType.TAKE_PROFIT_MARKET, positionSide="BOTH", timeInForce="GTC") TAKE_PROFIT_ORDER_ID = result.orderId print( green.bold('\n\t\t✓ Take profit market at: {} creted.'.format( take_profit))) except: # Cancel order if something did not work as expected request_client.cancel_order(symbol=pair, orderId=orderId) print( red.bold( '\n\t\t x Something did not work as expected. Cancelling order' ))
acc = request_client.get_account_information() print("Welcome Binance User!") print("====== Your Balances ======") print("Total Margin Balance: ", acc.totalMarginBalance) print("Total Wallet Balance: ", acc.totalWalletBalance) print("===========================") bs = int(input("\nInput '1' to place LIMIT ORDER: ")) if (bs == 1): print("\n--------------------------------------") print("\nLIMIT BUY") print("\n--------------------------------------") coin = str(input("\nInput your COIN to BUY: ")) qty = float(input("\nInput your QUANTITY to BUY: ")) price = float(input("\nInput PRICE: ")) lev = str(input("\nInput LEVERAGE: ")) leverage = request_client.change_initial_leverage(symbol=coin, leverage=lev) conf = str(input("\nPLACE ORDER? ( Y / CTRL^C ): ")) if (conf == "Y" or "y"): print("\nPlacing Order...") buy = request_client.post_order(symbol=coin, side=OrderSide.BUY, ordertype=OrderType.LIMIT, price=price, quantity=qty, timeInForce=TimeInForce.GTC) else: print("FAILED TO PLACE ORDER!")