Skip to content

Instantly share code, notes, and snippets.

@janhohenheim
Created September 8, 2021 11:56
Show Gist options
  • Select an option

  • Save janhohenheim/fc0e65850a64b6bad0394d04af46c239 to your computer and use it in GitHub Desktop.

Select an option

Save janhohenheim/fc0e65850a64b6bad0394d04af46c239 to your computer and use it in GitHub Desktop.
Crypto trading bot generated by OpenAI Codex
#! /usr/env/python3
# Implement a fully automatic cryptocurrency trading bot
import requests
import json
import time
import datetime
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def get_price(url):
"""Get the current price of BTC in USD"""
# Get the page source and parse it with BeautifulSoup4
page = requests.get(url)
soup = bs(page.text, 'html.parser')
# Find the price in the HTML source code and return it as a float value
price = soup.find('span', {'class': 'cmc-details-panel-price__price'}).text[1:] # Remove dollar sign from string
return float(price)
def get_btc_value():
"""Get the current value of BTC in USD"""
url = "https://coinmarketcap.com/currencies/bitcoin/" # URL to scrape data from
return get_price(url)
def buy_btc():
"""Buy BTC using Coinbase"""
url = "https://www.coinbase.com/signin" # URL to scrape data from
# Get the page source and parse it with BeautifulSoup4
page = requests.get(url)
soup = bs(page.text, 'html.parser')
# Find the CSRF token in the HTML source code
csrf_token = soup.find('meta', {'name': 'csrf-token'})['content']
# Set up a dictionary to hold the data we will send to the Coinbase API
payload = {
"user": {
"email": "", # Enter your email address here
"password": "" # Enter your password here
},
"_csrf": csrf_token,
"previous_view_id": None,
"redirect_url": "/dashboard" # This is where we want to be redirected after successfully logging in or out (optional)
}
headers = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrf_token}
response = requests.post(url, json=payload, headers=headers) # Send a POST request to log in to Coinbase
if response.status_code == 200: # If the POST request is successful, proceed with buying BTC
print("Logged in to Coinbase successfully")
url = "https://www.coinbase.com/buys" # URL to scrape data from
# Get the page source and parse it with BeautifulSoup4
page = requests.get(url)
soup = bs(page.text, 'html.parser')
# Find the CSRF token in the HTML source code
csrf_token = soup.find('meta', {'name': 'csrf-token'})['content']
# Set up a dictionary to hold the data we will send to the Coinbase API
payload = {
"button": {
"type": "buy_now", # This is a buy now button (other options are buy_now_card and instant)
"name": "Bitcoin", # Name of what you're buying (optional)
"description": None, # Description of what you're buying (optional)
"price_string": str(get_btc_value()), # Price of what you're buying as string (optional)
"price_currency_iso": "USD", # Currency of what you're buying (optional)
"custom": None, # Custom amount in case of buy_now or buy_now_card (optional)
"style": "buy_now_large", # Style of button (optional)
"include_email": True, # Include your email address in the transaction information (optional)
"callback_url": None, # Callback URL to be POSTed when the payment is completed (optional)
"success_url": None, # Success URL to redirect users back to after completing the payment (optional)
"cancel_url": None, # Cancel URL to redirect users back to after canceling the payment (optional)
},
"_csrf": csrf_token,
"previousViewId": None,
"skipNotificationsViewIds": [],
"redirectUrlAfterSuccessfulPayment": "/dashboard" # This is where we want to be redirected after successfully paying for something (optional)
}
headers = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrf_token}
response = requests.post(url, json=payload, headers=headers) # Send a POST request to buy BTC
if response.status_code == 200: # If the POST request is successful, print the response
print("Bought Bitcoin successfully")
print(response.text)
else: # If the POST request is unsuccessful, raise an error
raise Exception("Error buying Bitcoin")
else: # If the POST request is unsuccessful, raise an error
raise Exception("Error logging in to Coinbase")
def sell_btc():
"""Sell BTC using Coinbase"""
url = "https://www.coinbase.com/signin" # URL to scrape data from
# Get the page source and parse it with BeautifulSoup4
page = requests.get(url)
soup = bs(page.text, 'html.parser')
# Find the CSRF token in the HTML source code
csrf_token = soup.find('meta', {'name': 'csrf-token'})['content']
# Set up a dictionary to hold the data we will send to the Coinbase API
payload = {
"user": {
"email": "", # Enter your email address here
"password": "" # Enter your password here
},
"_csrf": csrf_token,
"previous_view_id": None,
"redirect_url": "/dashboard" # This is where we want to be redirected after successfully logging in or out (optional)
}
headers = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrf_token}
response = requests.post(url, json=payload, headers=headers) # Send a POST request to log in to Coinbase
if response.status_code == 200: # If the POST request is successful, proceed with selling BTC
print("Logged in to Coinbase successfully")
url = "https://www.coinbase.com/sells" # URL to scrape data from
# Get the page source and parse it with BeautifulSoup4
page = requests.get(url)
soup = bs(page.text, 'html.parser')
# Find the CSRF token in the HTML source code
csrf_token = soup.find('meta', {'name': 'csrf-token'})['content']
# Set up a dictionary to hold the data we will send to the Coinbase API
payload = {
"button": {
"type": "sell_now", # This is a sell now button (other options are buy_now_card and instant)
"name": "Bitcoin", # Name of what you're selling (optional)
"description": None, # Description of what you're selling (optional)
"price_string": str(get_btc_value()), # Price of what you're selling as string (optional)
"price_currency_iso": "USD", # Currency of what you're selling (optional)
"custom": None, # Custom amount in case of buy_now or buy_now_card (optional)
"style": "sell_now", # Style of button (optional)
"include_email": True, # Include your email address in the transaction information (optional)
"callback_url": None, # Callback URL to be POSTed when the payment is completed (optional)
"success_url": None, # Success URL to redirect users back to after completing the payment (optional)
"cancel_url": None, # Cancel URL to redirect users back to after canceling the payment (optional)
},
"_csrf": csrf_token,
"previousViewId": None,
"skipNotificationsViewIds": [],
"redirectUrlAfterSuccessfulPayment": "/dashboard" # This is where we want to be redirected after successfully paying for something (optional)
}
headers = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrf_token}
response = requests.post(url, json=payload, headers=headers) # Send a POST request to sell BTC
if response.status_code == 200: # If the POST request is successful, print the response
print("Sold Bitcoin successfully")
print(response.text)
else: # If the POST request is unsuccessful, raise an error
raise Exception("Error selling Bitcoin")
else: # If the POST request is unsuccessful, raise an error
raise Exception("Error logging in to Coinbase")
def main():
"""Main function"""
# Set up a dictionary to hold the data we will send to the Coinbase API
payload = {
"amount": str(get_btc_value()), # Amount of BTC you want to trade with (optional)
"currency": "BTC", # Currency of what you're trading (optional)
"paymentMethodId": None, # ID of a payment method (optional)
"paymentMethodType": None, # Type of payment method (optional)
"preview": False, # Preview true/false whether or not you want to place the order without actually trading (optional)
"_csrf": None, # CSRF token from Coinbase (required if not passed in headers)
"previousViewId": None, # View ID from Coinbase (required if not passed in headers)
"skipNotificationsViewIds": [], # View IDs from Coinbase that should be skipped when returning after successful payment (optional)
"redirectUrlAfterSuccessfulPayment": "/dashboard" # This is where we want to be redirected after successfully paying for something (optional)
}
headers = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': None}
url = "https://www.coinbase.com/checkouts/d8a9b3c1f4e2f7d0aeb6b51cdd5e8b0e" # URL to scrape data from
response = requests.post(url, json=payload, headers=headers) # Send a POST request to buy BTC
if response.status_code == 200: # If the POST request is successful, print the response
print("Bought Bitcoin successfully")
print(response.text)
else: # If the POST request is unsuccessful, raise an error
raise Exception("Error buying Bitcoin")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment