Trailing Stop Loss
Example
Basic Code
// ```python import web3 import time
def trailing_stop_loss(w3, pair, stop_distance, update_interval): """Realizes Trailing Stop Loss.
Args: w3: Web3 object connected to the wallet. pair: Trading pair (e.g., "ETH/XYZ"). stop_distance: Distance of stop loss from current price (in percent). update_interval: Stop loss update interval (in minutes). """ # Get the current price of the asset current_price = get_current_price(pair)
# Calculate the stop loss price stop_loss_price = current_price * (1 - stop_distance / 100)
# Set stop loss order = w3.eth.contract( address=get_exchange_contract_address(pair), abi=get_exchange_abi(pair) ).functions.createStopLossOrder( pair, stop_loss_price ).buildTransaction()
# Send order transaction_hash = w3.eth.sendTransaction(order)
# Wait for the order to be executed receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)
# Check if the order has been executed if receipt["status"] == 1: print("Stop loss order set.") else: print("Failed to set stop loss order.")
while True: # Wait until the next update time.sleep(update_interval * 60)
# Get the current price of the asset current_price = get_current_price(pair)
# Calculate the new stop loss price new_stop_loss_price = current_price * (1 - stop_distance / 100)
# If the asset price has increased, update the stop loss if new_stop_loss_price > stop_loss_price: order = w3.eth.contract( address=get_exchange_contract_address(pair), abi=get_exchange_abi(pair) ).functions.updateStopLossOrder( pair, new_stop_loss_price ).buildTransaction()
# Send order transaction_hash = w3.eth.sendTransaction(order)
# Wait for the order to be executed receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)
# Check if the order has been executed if receipt["status"] == 1: print("Stop loss order updated.") else: print("Failed to update stop loss order.")
# Update stop_loss price stop_loss_price = new_stop_loss_price ```Last updated