Skip to content

Instantly share code, notes, and snippets.

@classicvalues
Created September 2, 2024 22:40
Show Gist options
  • Save classicvalues/0e2d1652bc73b2d6560b40d6c20f9b7a to your computer and use it in GitHub Desktop.
Save classicvalues/0e2d1652bc73b2d6560b40d6c20f9b7a to your computer and use it in GitHub Desktop.

Revisions

  1. classicvalues created this gist Sep 2, 2024.
    108 changes: 108 additions & 0 deletions binance_all.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,108 @@
    from binance.client import Client
    from datetime import datetime, timedelta
    import time

    # Set up Binance API credentials
    api_key = 'YOUR_BINANCE_API_KEY'
    api_secret = 'YOUR_BINANCE_API_SECRET'

    # Login to Binance
    client = Client(api_key, api_secret)

    # Define the trading parameters
    symbol = 'BTCUSDT' # Trading Bitcoin against USDT
    investment_amount = 10.0 # Amount to use per transaction

    # Define the time for trading (adjust according to your preferred trading hours)
    time_after_open = timedelta(minutes=2)
    time_before_close = timedelta(minutes=2)

    # Helper function to get the current price
    def get_current_price(symbol):
    ticker = client.get_symbol_ticker(symbol=symbol)
    return float(ticker['price'])

    # Helper function to get the current account balance in USDT
    def get_account_balance(asset='USDT'):
    balance = client.get_asset_balance(asset=asset)
    return float(balance['free'])

    # Helper function to place orders
    def place_order(symbol, quantity, side):
    if side == 'buy':
    order = client.order_market_buy(symbol=symbol, quantity=quantity)
    elif side == 'sell':
    order = client.order_market_sell(symbol=symbol, quantity=quantity)
    return order

    # Helper function to close all positions
    def close_all_positions():
    # Get all positions (in this case only for the specified symbol)
    balance = client.get_asset_balance(asset=symbol[:-4]) # Assuming trading a pair like BTCUSDT
    quantity = float(balance['free'])
    if quantity > 0:
    place_order(symbol, quantity, 'sell')
    print("Closed all positions.")

    # Trading logic
    def trade():
    initial_price = get_current_price(symbol)
    peak_price = initial_price
    trough_price = initial_price

    while True:
    current_time = datetime.now()

    # Since crypto markets are open 24/7, adjust according to your needs
    market_open_time = datetime.combine(current_time.date(), datetime.strptime('09:30', '%H:%M').time())
    market_close_time = datetime.combine(current_time.date(), datetime.strptime('16:00', '%H:%M').time())

    # Calculate trade start and stop times
    start_trading_time = market_open_time + time_after_open
    stop_trading_time = market_close_time - time_before_close

    # Check if current time is within trading hours
    if start_trading_time <= current_time <= stop_trading_time:
    current_price = get_current_price(symbol)
    balance = get_account_balance()

    # Update the peak and trough prices
    if current_price > peak_price:
    peak_price = current_price
    if current_price < trough_price:
    trough_price = current_price

    # Calculate the quantity to buy based on available balance and price
    quantity_to_buy = round(investment_amount / current_price, 6) # Adjust precision as needed

    # Buy when there's a gain, using all available balance
    if current_price > initial_price and balance >= investment_amount:
    place_order(symbol, quantity_to_buy, 'buy')
    print(f"Bought {quantity_to_buy} {symbol[:-4]} at {current_price} due to price gain.")
    wait_for_balance_to_update()

    # Sell when there's a loss
    holdings = client.get_asset_balance(asset=symbol[:-4])
    quantity = float(holdings['free'])
    if quantity > 0 and current_price < initial_price:
    place_order(symbol, quantity, 'sell')
    print(f"Sold all {symbol[:-4]} at {current_price} due to price loss.")
    wait_for_balance_to_update()

    # Close all positions a couple of minutes before market close
    if current_time > stop_trading_time:
    close_all_positions()
    break # Exit the loop after closing positions for the day

    time.sleep(1) # Check as frequently as possible

    # Helper function to wait until the account balance updates after a sell
    def wait_for_balance_to_update():
    while True:
    balance = get_account_balance()
    if balance >= investment_amount:
    break
    time.sleep(1)

    # Run the trading strategy
    trade()