Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
5.4 kB
1
Indexable
Never
import ccxt
import numpy as np
import talib
import time
import hashlib
import hmac

# Constants
API_KEY = 'here comes api' 
API_SECRET = 'here comes secret key'
SYMBOL = 'XRP/USDT'
TIMEFRAME = '1m'
RSI_PERIOD = 2
RSI_OVERBOUGHT = 90
RSI_OVERSOLD = 10
TRADE_AMOUNT = 10
STARTING_BALANCE = 14
RECV_WINDOW = 5000

# Connect to the exchange (assuming you have set up API credentials)
exchange = ccxt.binance({
    'apiKey': API_KEY,
    'secret': API_SECRET,
    'enableRateLimit': True,
})

# Generate signature for signed endpoints
def generate_signature(payload):
    return hmac.new(API_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()

# Calculate RSI
def calculate_rsi(closes):
    closes_np = np.array(closes, dtype=float)
    rsi = talib.RSI(closes_np, RSI_PERIOD)
    return rsi[-1]

# Close any open positions
def close_positions():
    open_orders = exchange.fetch_open_orders(symbol=SYMBOL)
    for order in open_orders:
        exchange.cancel_order(order['id'])
        print(f"Cancelled order: {order['id']}")
    print("All open positions closed.")

# Function to borrow funds for leverage trading
def borrow_funds(amount, leverage, timestamp):
    payload = f"timestamp={timestamp}&amount={amount}&leverage={leverage}"
    signature = generate_signature(payload)
    exchange.sapi_post_margin_loan({
        'asset': 'USDT',
        'symbol': 'XRPUSDT',
        'amount': amount,
        'timestamp': timestamp,
        'leverage': leverage,
        'signature': signature,
        'recvWindow': RECV_WINDOW
    })

# Function to repay borrowed funds
def repay_funds(amount, leverage, timestamp):
    payload = f"timestamp={timestamp}&amount={amount}&leverage={leverage}"
    signature = generate_signature(payload)
    exchange.sapi_post_margin_repay({
        'asset': 'USDT',
        'symbol': 'XRPUSDT',
        'amount': amount,
        'timestamp': timestamp,
        'leverage': leverage,
        'signature': signature,
        'recvWindow': RECV_WINDOW
    })

# Function to calculate account balance
#def calculate_balance():
#    account_balance = exchange.fetch_balance()['total']['USDT']
#    return float(account_balance)



# Live trading function
def run_live():
    balance = STARTING_BALANCE
    long_position = False
    short_position = False

    # Close any open positions before starting
    close_positions()

    while True:
        # Generate timestamp
        timestamp = int(time.time() * 1000)

        # Fetch real-time data
        candles = exchange.fetch_ohlcv(symbol=SYMBOL, timeframe=TIMEFRAME)
        if not candles:
            continue
        closes = [candle[4] for candle in candles]
        current_price = candles[-1][4]

        # Calculate RSI
        rsi = calculate_rsi(closes)

        if not long_position and not short_position:
            # No open positions, check for new entry conditions
            if rsi < RSI_OVERSOLD and current_price < 1000000:
                # Borrow funds and open long position with 5x leverage
                borrow_funds(TRADE_AMOUNT, 5, timestamp)
                buy_order = exchange.create_market_buy_order(
                    SYMBOL,
                    TRADE_AMOUNT,
                    {'timestamp': timestamp}
                )
                print(f"Long position opened: Buy order placed | Price: {current_price:.2f}")
                long_position = True

            elif rsi > RSI_OVERBOUGHT and current_price < 1000000:
                # Borrow funds and open short position with 5x leverage
                borrow_funds(TRADE_AMOUNT, 5, timestamp)
                sell_order = exchange.create_market_sell_order(
                    SYMBOL,
                    TRADE_AMOUNT,
                    {'timestamp': timestamp}
                )
                print(f"Short position opened: Sell order placed | Price: {current_price:.2f}")
                short_position = True

        elif long_position:
            # Check exit conditions for long position
            if rsi > 50:
                # Close long position and repay funds with 5x leverage
                repay_funds(TRADE_AMOUNT, 5, timestamp)
                sell_order = exchange.create_market_sell_order(
                    SYMBOL,
                    TRADE_AMOUNT,
                    {'timestamp': timestamp}
                )
                print(f"Long position closed: Sell order placed | Price: {current_price:.2f}")
                long_position = False

        elif short_position:
            # Check exit conditions for short position
            if rsi < 50:
                # Close short position and repay funds with 5x leverage
                repay_funds(TRADE_AMOUNT, 5, timestamp)
                buy_order = exchange.create_market_buy_order(
                    SYMBOL,
                    TRADE_AMOUNT,
                    {'timestamp': timestamp}
                )
                print(f"Short position closed: Buy order placed | Price: {current_price:.2f}")
                short_position = False

        # Update balance
        #balance = calculate_balance()

        # Print current balance
        #print(f"Current balance: {balance:.2f}")

# Start live trading
run_live()