Monitoring Price
The sample trading bot makes decisions based on price movements. Because the asset being traded is hedged with Binance it's appropriate to monitor the price using their endpoints. In our sample, we are executing a basic strategy: longing when price is below or equal to our defined ENTRY_PRICE
and closing our position when the price is equal or above our EXIT_PRICE
.
Setting Up Price Monitoring
We define entry and exit prices in the configuration:
CONFIG = {
"SYMBOL": "XRPUSDT",
"ENTRY_PRICE": "3.05", # Enter when price falls below this
"EXIT_PRICE": "3.1", # Exit when price rises above this
"QUANTITY": "6",
# ... other configuration options
}
Monitoring Loop
The bot continuously monitors the price and compares it to our thresholds:
# Main trading loop
while True:
# Get current price from Binance
current_price = get_binance_price(CONFIG["SYMBOL"])
# Check for entry conditions
if not in_position and current_price <= entry_price:
# Open a position
# Check for exit conditions
elif in_position and current_price >= exit_price:
# Close the position
time.sleep(CONFIG["POLL_INTERVAL"])
The get_binance_price
function fetches the current price from Binance's API:
def get_binance_price(symbol):
"""Get the current price of a symbol from Binance."""
try:
params = {"symbol": symbol}
response = requests.get(BINANCE_API_URL, params=params)
response.raise_for_status()
data = response.json()
price = Decimal(data["price"])
print(f"[PRICE] Current {symbol} price: {price}")
return price
except Exception as e:
print(f"[ERROR] Failed to get Binance price: {e}")
return None
Last updated