Last active
November 30, 2024 01:22
-
-
Save shivams/fe86a5ab564c4ea615844e4244950743 to your computer and use it in GitHub Desktop.
Place your own limit orders on Coinbase without paying extra fees
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I use this script to place my own limit orders (to purchase) crypto on Coinbase | |
# This saves me the extra fees that Coinbase charges for limit orders | |
# Using Coinbase's API also incurs less fees even on normal purchases | |
import time | |
from coinbase.rest import RESTClient | |
from json import dumps | |
import questionary | |
from datetime import datetime | |
import os | |
# Go to https://www.coinbase.com/settings/api to generate your API key and secret | |
api_key = os.getenv('COINBASE_API_KEY') | |
api_secret = os.getenv('COINBASE_API_SECRET') | |
if not api_key or not api_secret: | |
raise ValueError("Coinbase API key and secret must be set in environment variables, as variables COINBASE_API_KEY and COINBASE_API_SECRET respectively.") | |
client = RESTClient(api_key=api_key, api_secret=api_secret) | |
def preview_order(product_id, quote_size): | |
""" | |
Preview the order and show estimated fees and details. | |
""" | |
try: | |
preview = client.preview_market_order_buy( | |
product_id=product_id, | |
quote_size=quote_size | |
) | |
print("============ Order Preview ============") | |
print("Here is the Order Preview if it were placed at the current price") | |
print("This should give you an idea of the fees") | |
print("=======================================") | |
print(preview) | |
return preview | |
except Exception as e: | |
print(f"Error during order preview: {e}") | |
return None | |
def place_order(product_id, quote_size): | |
""" | |
Place the market order. | |
""" | |
try: | |
order = client.market_order_buy( | |
client_order_id="auto-order-001", | |
product_id=product_id, | |
quote_size=quote_size | |
) | |
if order['success']: | |
print("Order placed successfully!") | |
print("Order Details:") | |
print(dumps(order['success_response'], indent=2)) | |
return True | |
else: | |
print("Failed to place order.") | |
print("Error Response:") | |
print(dumps(order['error_response'], indent=2)) | |
return False | |
except Exception as e: | |
print(f"Error during order placement: {e}") | |
return False | |
def monitor_and_buy(product_id, target_price, quote_size): | |
""" | |
Monitor the price and buy the cryptocurrency when it hits the target price. | |
""" | |
print(f"Monitoring {product_id} for target price: ${target_price}") | |
while True: | |
try: | |
product = client.get_product(product_id) | |
current_price = float(product["price"]) | |
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Current price of {product_id}: ${current_price}; while the target price is ${target_price}.") | |
if current_price <= target_price: | |
print(f"Target price hit! Current price: ${current_price}. Placing order...") | |
if place_order(product_id, quote_size): | |
print("Order fulfilled. Exiting monitor.") | |
break | |
time.sleep(10) # Poll every 10 seconds | |
except Exception as e: | |
print(f"Error during price monitoring: {e}") | |
time.sleep(10) | |
if __name__ == "__main__": | |
# Configuration | |
product_ids = ["SOL-USD", "BTC-USD", "ETH-USD", "XRP-USD", "AVAX-USD", "ATOM-USD", "DOGE-USD"] | |
product_id = questionary.select( | |
"Select a product to monitor:", | |
choices=product_ids, | |
).ask() | |
print(f"Selected product: {product_id}") | |
# First show the current price of the asset | |
product = client.get_product(product_id) | |
current_price = float(product["price"]) | |
print(f"Current price of {product_id}: ${current_price}") | |
target_price = float(questionary.text("Enter the target price in USD: ").ask()) | |
quote_size = questionary.text("Enter the amount in USD to spend: ").ask() | |
print(f"Target price: ${target_price}") | |
print(f"Quote size: ${quote_size}") | |
# Step 1: Preview the order | |
preview = preview_order(product_id, quote_size) | |
if not preview: | |
print("Preview failed. Exiting.") | |
exit(1) | |
# Step 2: Ask for user confirmation | |
confirm = questionary.confirm("Do you want to proceed with the auto-buy process?").ask() | |
if not confirm: | |
print("Exiting without starting the auto-buy process.") | |
exit(0) | |
# Step 3: Verify that the target price is less than the current price | |
if target_price >= current_price: | |
print("\033[31;47m Target price is not less than the current price. Exiting. \033[0m") # red on white background | |
exit(1) | |
# Step 4: Start monitoring and buying | |
monitor_and_buy(product_id, target_price, quote_size) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment