i have a python script that open 2 trades based on different time frame , but on the same coin , the first on 4h and the second on 8h and the close is on the close of the candle of the time frame ( mean one close each 4h and other each 8h )
the problem is that i don’t know how to separate between both close , because each 4h it close all the trades , because bot not detect witch trade is for 4h and witch is for 8h .
how to solve this problem and be abel to detect trades of 4h and trade of 8h on python using Binance API !
MY FULL SCRIPT
import ccxt import time # Configuration API_KEY = '' API_SECRET = '' SYMBOLS = ['PYTHUSDT'] # List of trading pairs LEVERAGE = 10 # Fixed leverage ORDER_PERCENT = 0.01 # 1% of capital PRICE_OFFSETS = [ -0.06, -0.10,-0.18] # Percentage offsets TIMEFRAME = '4H' # Candle timeframe # Initialize exchange def init_exchange(): try: exchange = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'options': {'defaultType': 'future'}, # For futures trading }) # Test connection by fetching balance balance = exchange.fetch_balance({"type": "future"}) print(f"Exchange initialized successfully. Available balance: {balance['total']['USDT']} USDT") return exchange except ccxt.BaseError as e: print(f"CCXT base error: {e}") except Exception as e: print(f"Unexpected error: {e}") return None # Function to get the opening price of the current candle def get_open_price(exchange, symbol): try: ohlcv = exchange.fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=1) if not ohlcv or len(ohlcv) == 0: raise ValueError("No OHLCV data retrieved.") return ohlcv[0][4] # Open price of the latest candle except Exception as e: print(f"Error fetching open price for {symbol}: {e}") return None # Function to fetch available balance and calculate 1% of it def get_trade_amount(exchange): try: balance = exchange.fetch_balance({"type": "future"}) total_balance = balance['total']['USDT'] # Assuming USDT margin trade_amount = total_balance * ORDER_PERCENT print(f"Total balance: {total_balance:.2f}, Trade amount: {trade_amount:.2f}") return trade_amount except Exception as e: print(f"Error fetching balance: {e}") return 0 # Place limit orders at specified levels def place_limit_orders(exchange, symbol, open_price): order_ids = [] trade_amount = get_trade_amount(exchange) # Automatically calculate trade amount if trade_amount == 0: print("Skipping order placement due to balance issues.") return order_ids for offset in PRICE_OFFSETS: price = open_price * (1 + offset) # Adjust price based on offset amount = trade_amount / price # Calculate order amount in units try: order = exchange.create_limit_buy_order(symbol, amount, price) order_ids.append(order['id']) print(f"Placed limit order for {symbol} at price {price:.5f} with amount {amount:.6f}") except Exception as e: print(f"Error placing limit order for {symbol} at price {price:.2f}: {e}") return order_ids # Cancel all open orders def cancel_open_orders(exchange, symbol): try: open_orders = exchange.fetch_open_orders(symbol) for order in open_orders: exchange.cancel_order(order['id'], symbol) print(f"Cancelled order {order['id']} for {symbol}") except Exception as e: print(f"Error cancelling orders for {symbol}: {e}") # Main function def main(): exchange = init_exchange() if exchange is None: print("Failed to initialize the exchange. Exiting.") return while True: # Keep running indefinitely open_prices = {} order_ids = {} # Process all symbols in parallel for symbol in SYMBOLS: print(f"nProcessing symbol: {symbol}") open_price = get_open_price(exchange, symbol) if open_price is None: print(f"Failed to fetch the open price for {symbol}. Retrying...") time.sleep(10) # Wait before retrying continue print(f"Open price of the candle for {symbol}: {open_price}") order_ids[symbol] = place_limit_orders(exchange, symbol, open_price) open_prices[symbol] = open_price # Wait for the candle to close after placing orders for all symbols try: for symbol in SYMBOLS: ohlcv = exchange.fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=1) candle_close_time = ohlcv[0][ 0] / 1000 + 14400 # Close time of the current candle (1-minute after the current candle's open time) print( f"Candle for {symbol} will close at: {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(candle_close_time))}") # Wait until all candles are closed before cancelling the orders while time.time() < min([candle_close_time for symbol in SYMBOLS]): time.sleep(1) # Cancel all open orders after the candle close for symbol in SYMBOLS: cancel_open_orders(exchange, symbol) except Exception as e: print(f"Error while waiting for candles to close: {e}") time.sleep(10) # Wait before retrying if __name__ == "__main__": main()
submitted by /u/marioraac19
[link] [comments]
r/learnpython i have a python script that open 2 trades based on different time frame , but on the same coin , the first on 4h and the second on 8h and the close is on the close of the candle of the time frame ( mean one close each 4h and other each 8h ) the problem is that i don’t know how to separate between both close , because each 4h it close all the trades , because bot not detect witch trade is for 4h and witch is for 8h . how to solve this problem and be abel to detect trades of 4h and trade of 8h on python using Binance API ! MY FULL SCRIPT import ccxt import time # Configuration API_KEY = ” API_SECRET = ” SYMBOLS = [‘PYTHUSDT’] # List of trading pairs LEVERAGE = 10 # Fixed leverage ORDER_PERCENT = 0.01 # 1% of capital PRICE_OFFSETS = [ -0.06, -0.10,-0.18] # Percentage offsets TIMEFRAME = ‘4H’ # Candle timeframe # Initialize exchange def init_exchange(): try: exchange = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘options’: {‘defaultType’: ‘future’}, # For futures trading }) # Test connection by fetching balance balance = exchange.fetch_balance({“type”: “future”}) print(f”Exchange initialized successfully. Available balance: {balance[‘total’][‘USDT’]} USDT”) return exchange except ccxt.BaseError as e: print(f”CCXT base error: {e}”) except Exception as e: print(f”Unexpected error: {e}”) return None # Function to get the opening price of the current candle def get_open_price(exchange, symbol): try: ohlcv = exchange.fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=1) if not ohlcv or len(ohlcv) == 0: raise ValueError(“No OHLCV data retrieved.”) return ohlcv[0][4] # Open price of the latest candle except Exception as e: print(f”Error fetching open price for {symbol}: {e}”) return None # Function to fetch available balance and calculate 1% of it def get_trade_amount(exchange): try: balance = exchange.fetch_balance({“type”: “future”}) total_balance = balance[‘total’][‘USDT’] # Assuming USDT margin trade_amount = total_balance * ORDER_PERCENT print(f”Total balance: {total_balance:.2f}, Trade amount: {trade_amount:.2f}”) return trade_amount except Exception as e: print(f”Error fetching balance: {e}”) return 0 # Place limit orders at specified levels def place_limit_orders(exchange, symbol, open_price): order_ids = [] trade_amount = get_trade_amount(exchange) # Automatically calculate trade amount if trade_amount == 0: print(“Skipping order placement due to balance issues.”) return order_ids for offset in PRICE_OFFSETS: price = open_price * (1 + offset) # Adjust price based on offset amount = trade_amount / price # Calculate order amount in units try: order = exchange.create_limit_buy_order(symbol, amount, price) order_ids.append(order[‘id’]) print(f”Placed limit order for {symbol} at price {price:.5f} with amount {amount:.6f}”) except Exception as e: print(f”Error placing limit order for {symbol} at price {price:.2f}: {e}”) return order_ids # Cancel all open orders def cancel_open_orders(exchange, symbol): try: open_orders = exchange.fetch_open_orders(symbol) for order in open_orders: exchange.cancel_order(order[‘id’], symbol) print(f”Cancelled order {order[‘id’]} for {symbol}”) except Exception as e: print(f”Error cancelling orders for {symbol}: {e}”) # Main function def main(): exchange = init_exchange() if exchange is None: print(“Failed to initialize the exchange. Exiting.”) return while True: # Keep running indefinitely open_prices = {} order_ids = {} # Process all symbols in parallel for symbol in SYMBOLS: print(f”nProcessing symbol: {symbol}”) open_price = get_open_price(exchange, symbol) if open_price is None: print(f”Failed to fetch the open price for {symbol}. Retrying…”) time.sleep(10) # Wait before retrying continue print(f”Open price of the candle for {symbol}: {open_price}”) order_ids[symbol] = place_limit_orders(exchange, symbol, open_price) open_prices[symbol] = open_price # Wait for the candle to close after placing orders for all symbols try: for symbol in SYMBOLS: ohlcv = exchange.fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=1) candle_close_time = ohlcv[0][ 0] / 1000 + 14400 # Close time of the current candle (1-minute after the current candle’s open time) print( f”Candle for {symbol} will close at: {time.strftime(‘%Y-%m-%d %H:%M:%S’, time.gmtime(candle_close_time))}”) # Wait until all candles are closed before cancelling the orders while time.time() < min([candle_close_time for symbol in SYMBOLS]): time.sleep(1) # Cancel all open orders after the candle close for symbol in SYMBOLS: cancel_open_orders(exchange, symbol) except Exception as e: print(f”Error while waiting for candles to close: {e}”) time.sleep(10) # Wait before retrying if __name__ == “__main__”: main() submitted by /u/marioraac19 [link] [comments]
i have a python script that open 2 trades based on different time frame , but on the same coin , the first on 4h and the second on 8h and the close is on the close of the candle of the time frame ( mean one close each 4h and other each 8h )
the problem is that i don’t know how to separate between both close , because each 4h it close all the trades , because bot not detect witch trade is for 4h and witch is for 8h .
how to solve this problem and be abel to detect trades of 4h and trade of 8h on python using Binance API !
MY FULL SCRIPT
import ccxt import time # Configuration API_KEY = '' API_SECRET = '' SYMBOLS = ['PYTHUSDT'] # List of trading pairs LEVERAGE = 10 # Fixed leverage ORDER_PERCENT = 0.01 # 1% of capital PRICE_OFFSETS = [ -0.06, -0.10,-0.18] # Percentage offsets TIMEFRAME = '4H' # Candle timeframe # Initialize exchange def init_exchange(): try: exchange = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'options': {'defaultType': 'future'}, # For futures trading }) # Test connection by fetching balance balance = exchange.fetch_balance({"type": "future"}) print(f"Exchange initialized successfully. Available balance: {balance['total']['USDT']} USDT") return exchange except ccxt.BaseError as e: print(f"CCXT base error: {e}") except Exception as e: print(f"Unexpected error: {e}") return None # Function to get the opening price of the current candle def get_open_price(exchange, symbol): try: ohlcv = exchange.fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=1) if not ohlcv or len(ohlcv) == 0: raise ValueError("No OHLCV data retrieved.") return ohlcv[0][4] # Open price of the latest candle except Exception as e: print(f"Error fetching open price for {symbol}: {e}") return None # Function to fetch available balance and calculate 1% of it def get_trade_amount(exchange): try: balance = exchange.fetch_balance({"type": "future"}) total_balance = balance['total']['USDT'] # Assuming USDT margin trade_amount = total_balance * ORDER_PERCENT print(f"Total balance: {total_balance:.2f}, Trade amount: {trade_amount:.2f}") return trade_amount except Exception as e: print(f"Error fetching balance: {e}") return 0 # Place limit orders at specified levels def place_limit_orders(exchange, symbol, open_price): order_ids = [] trade_amount = get_trade_amount(exchange) # Automatically calculate trade amount if trade_amount == 0: print("Skipping order placement due to balance issues.") return order_ids for offset in PRICE_OFFSETS: price = open_price * (1 + offset) # Adjust price based on offset amount = trade_amount / price # Calculate order amount in units try: order = exchange.create_limit_buy_order(symbol, amount, price) order_ids.append(order['id']) print(f"Placed limit order for {symbol} at price {price:.5f} with amount {amount:.6f}") except Exception as e: print(f"Error placing limit order for {symbol} at price {price:.2f}: {e}") return order_ids # Cancel all open orders def cancel_open_orders(exchange, symbol): try: open_orders = exchange.fetch_open_orders(symbol) for order in open_orders: exchange.cancel_order(order['id'], symbol) print(f"Cancelled order {order['id']} for {symbol}") except Exception as e: print(f"Error cancelling orders for {symbol}: {e}") # Main function def main(): exchange = init_exchange() if exchange is None: print("Failed to initialize the exchange. Exiting.") return while True: # Keep running indefinitely open_prices = {} order_ids = {} # Process all symbols in parallel for symbol in SYMBOLS: print(f"nProcessing symbol: {symbol}") open_price = get_open_price(exchange, symbol) if open_price is None: print(f"Failed to fetch the open price for {symbol}. Retrying...") time.sleep(10) # Wait before retrying continue print(f"Open price of the candle for {symbol}: {open_price}") order_ids[symbol] = place_limit_orders(exchange, symbol, open_price) open_prices[symbol] = open_price # Wait for the candle to close after placing orders for all symbols try: for symbol in SYMBOLS: ohlcv = exchange.fetch_ohlcv(symbol, timeframe=TIMEFRAME, limit=1) candle_close_time = ohlcv[0][ 0] / 1000 + 14400 # Close time of the current candle (1-minute after the current candle's open time) print( f"Candle for {symbol} will close at: {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(candle_close_time))}") # Wait until all candles are closed before cancelling the orders while time.time() < min([candle_close_time for symbol in SYMBOLS]): time.sleep(1) # Cancel all open orders after the candle close for symbol in SYMBOLS: cancel_open_orders(exchange, symbol) except Exception as e: print(f"Error while waiting for candles to close: {e}") time.sleep(10) # Wait before retrying if __name__ == "__main__": main()
submitted by /u/marioraac19
[link] [comments]