Invalid API Key - PLEASE HELP

I have tried everything. When I coinbase assistance, they referred me to here.
I have selected all for when I generated my API key. I checked to make sure it was entered correctly. I even generated API keys several times. So, I know it is not that.

I can strangely access the accounts, but I cannot do a buy or sell order. Please someone help me. I have lost the last of my hair on my head, trying to figure this out.

ERROR MESSAGE - as you can see, I can access information.

Product details fetched
{‘id’: ‘ACS-USD’, ‘base_currency’: ‘ACS’, ‘quote_currency’: ‘USD’, ‘quote_increment’: ‘0.0000001’, ‘base_increment’: ‘1’, ‘display_name’: ‘ACS/USD’, ‘min_market_funds’: ‘1’, ‘margin_enabled’: False, ‘post_only’: False, ‘limit_only’: False, ‘cancel_only’: False, ‘status’: ‘online’, ‘status_message’: ‘’, ‘trading_disabled’: False, ‘fx_stablecoin’: False, ‘max_slippage_percentage’: ‘0.03000000’, ‘auction_mode’: False, ‘high_bid_limit_percentage’: ‘’}
{‘ask’: ‘0.0070707’, ‘bid’: ‘0.0070625’, ‘volume’: ‘75812538’, ‘trade_id’: 744681, ‘price’: ‘0.0070659’, ‘size’: ‘116761’, ‘time’: ‘2023-04-06T07:41:05.255731Z’}
Minimum order size for ACS-USD: 1.0
Minimum base size for the buy order: 141.52478806662987
Headers: {‘Accept’: ‘application/json’, ‘CB-ACCESS-KEY’: ‘’, ‘CB-ACCESS-SIGN’: ‘’, ‘CB-ACCESS-TIMESTAMP’: ‘’, ‘CB-ACCESS-PASSPHRASE’: ‘’}
Response status code: 401
Response text: {“message”:“Invalid API Key”}
Buy order response: {‘message’: ‘Invalid API Key’}
Headers: {‘Accept’: ‘application/json’, ‘CB-ACCESS-KEY’: ‘’, ‘CB-ACCESS-SIGN’: ‘’, ‘CB-ACCESS-TIMESTAMP’: ‘’, ‘CB-ACCESS-PASSPHRASE’: ‘’}
Response status code: 401
Response text: {“message”:“Invalid API Key”}
Sell order response: {‘message’: ‘Invalid API Key’}

PYTHON SCRIPT

import base64
import time
import hmac
import hashlib
import requests
import json

API_KEY = ‘’
API_SECRET = ‘’
API_PASSPHRASE = ‘’
BASE_URL = ‘https://api.pro.coinbase.com’

Add the create_signed_headers function here

def create_signed_headers(method, request_path, body):
timestamp = str(time.time())
signature = generate_signature(timestamp, request_path, method, body, API_SECRET)

headers = {
    'Accept': 'application/json',
    'CB-ACCESS-KEY': API_KEY,
    'CB-ACCESS-SIGN': signature,
    'CB-ACCESS-TIMESTAMP': timestamp,
    'CB-ACCESS-PASSPHRASE': API_PASSPHRASE
}

return headers

def generate_signature(timestamp, request_path, method, body, secret_key):
message = str(timestamp) + method.upper() + request_path + body
hmac_key = base64.b64decode(secret_key)
signature = hmac.new(hmac_key, message.encode(‘utf-8’), hashlib.sha256)
return base64.b64encode(signature.digest()).decode(‘utf-8’)

def get_product_details(product_id):
url = f’https://api.pro.coinbase.com/products/{product_id}’
response = requests.get(url)

if response.status_code == 200:
    return response.json()
else:
    raise Exception(f"Failed to fetch product details: {response.text}")

def get_product_ticker(product_id):
url = f’https://api.pro.coinbase.com/products/{product_id}/ticker’
response = requests.get(url)

if response.status_code == 200:
    return response.json()
else:
    raise Exception(f"Failed to fetch product ticker: {response.text}")

Test the get_product_details function

product_id = ‘ACS-USD’
product_details = get_product_details(product_id)
print(“Product details fetched”)
print(product_details)

Test the get_product_ticker function

product_ticker = get_product_ticker(product_id)
print(product_ticker)

market_price = float(product_ticker[‘price’])

Get the minimum order size

min_order_size = float(product_details.get(‘base_min_size’, 1))
print(f"Minimum order size for {product_id}: {min_order_size}")

Calculate the minimum base size for the buy order

min_base_size = min_order_size / market_price
print(f"Minimum base size for the buy order: {min_base_size}")

def create_order(side, product_id, base_size, limit_price):
method = “POST”
request_path = “/api/v3/brokerage/orders”
body = json.dumps({
“side”: side,
“product_id”: product_id,
“order_configuration”: {
“limit_limit_gtc”: {
“base_size”: base_size,
“limit_price”: limit_price,
“post_only”: True
}
},
“client_order_id”: “”
}) if side in [“BUY”, “SELL”] else None

headers = create_signed_headers(method, request_path, body)
print("Headers:", headers)

response = requests.post(BASE_URL + request_path, headers=headers, data=body)
print("Response status code:", response.status_code)
print("Response text:", response.text)

return response

def buy_order(product_id, base_size, limit_price):
return create_order(“BUY”, product_id, base_size, limit_price)

def sell_order(product_id, base_size, limit_price):
return create_order(“SELL”, product_id, base_size, limit_price)

sell_base_size = max(min_base_size * 1.1, 500) # Adjust the multiplier (1.1) as needed

Example usage

product_id = “ACS-USD”
base_size = “500”
limit_price = “0.0078”

buy_response = buy_order(product_id, base_size, limit_price)
print(f"Buy order response: {buy_response.json()}") # Add this line

sell_response = sell_order(product_id, base_size, limit_price)
print(f"Sell order response: {sell_response.json()}") # Add this line

There are a number of issues I’m seeing (having just dealt with this nightmare for weeks, it’s all a little raw for me :slight_smile: )
1: You don’t need to send the PASSPHRASE header as Adv Trade does not use it.

2: I don’t believe you need to be base64 encoding the SecretKey before HMACing it. Just the raw text as you see me doing here (in JS)

function sign(str, secret) {
  const hash = CryptoJS.HmacSHA256(str, secret);
  return hash.toString();
}

Make sure the HMAC hash is a string before adding it to the header as the SIGN property’s value

3: Make sure your API Key is being sent as a string, not something else. I’m not certain if requests in python does this or not automatically, or if you have to stringify the headers before sending them.

4: Your API URL is wrong for Adv Trade. It should be: https://api.coinbase.com/api/v3/brokerage and then the appropriate endpoints, like /orders or /accounts

5: Something else I hit was making sure the content of the SIGN was in proper JSON format before signing it.

6: I think the structure of your order body is incorrect. Make sure you’re referencing this page when laying out the data property’s value for an order: Create Order | Coinbase Cloud

Given the error is specific to your API key though, I would start with doing all sorts of debugging around making sure the value getting sent to the API endpoint is actually what you intend to make it there.

1 Like

I really appreciate your detailed response. It is very helpful. I will try and apply this, and fingers crossed that it works.

1 Like

Now, I have the {Unauthorized} wall to climb. I swear all the boxes are checked when it comes to the API key.

import time
import hmac
import hashlib
import requests
import json

API_KEY = ‘’
API_SECRET = ‘’
API_PASSPHRASE = ‘’
BASE_URL = ‘https://api.coinbase.com/api/v3/brokerage’

def create_signed_headers(method, request_path, body):
timestamp = str(time.time())
signature = generate_signature(timestamp, request_path, method, body, API_SECRET)

headers = {
    'Accept': 'application/json',
    'CB-ACCESS-KEY': API_KEY,
    'CB-ACCESS-SIGN': signature,
    'CB-ACCESS-TIMESTAMP': timestamp
}

return headers

def generate_signature(timestamp, request_path, method, body, secret_key):
message = str(timestamp) + method.upper() + request_path + body
hmac_key = secret_key.encode(‘utf-8’)
signature = hmac.new(hmac_key, message.encode(‘utf-8’), hashlib.sha256)
return signature.hexdigest()

def create_order(side, product_id, base_size, limit_price):
method = “POST”
request_path = “/orders”
body = json.dumps({
“side”: side.lower(),
“product_id”: product_id,
“size”: base_size,
“price”: limit_price,
“type”: “limit”,
“time_in_force”: “GTC”,
“post_only”: True
})

headers = create_signed_headers(method, request_path, body)
print("Headers:", headers)

# Print debugging information
print(f"Request URL: {BASE_URL + request_path}")
print(f"Request Method: {method}")
print(f"Request Headers: {headers}")
print(f"Request Body: {body}")

response = requests.post(BASE_URL + request_path, headers=headers, data=body)
print("Response status code:", response.status_code)
print("Response text:", response.text)

return response

def buy_order(product_id, base_size, limit_price):
return create_order(“BUY”, product_id, base_size, limit_price)

def sell_order(product_id, base_size, limit_price):
return create_order(“SELL”, product_id, base_size, limit_price)

Example usage

product_id = “ACS-USD”
base_size = “500”
limit_price = “0.0078”

buy_response = buy_order(product_id, base_size, limit_price)
print(f"Buy order response: {buy_response.json()}")

sell_response = sell_order(product_id, base_size, limit_price)
print(f"Sell order response: {sell_response.json()}")

This is my working code if it helps.

auth.py

import time, hmac, hashlib

API_KEY = ''
SECRET = ''

timestamp = str(int(time.time()))

# for websocket
def sign_message(message):
    message = hmac.new(SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
    return message

# for API
class Auth:
    def __init__(self):
        self.API_KEY = API_KEY
        self.SECRET = SECRET
    
    def __call__(self, method, path, payload):
        message = timestamp + method + path + payload
        signature = hmac.new(self.SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()

        headers = {
            'CB-ACCESS-KEY': self.API_KEY,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-SIGN': signature,
            'Content-Type': 'application/json'
        }
        return headers

get_order.py

import json, http.client
from auth import *

def get_order(order_id):
    conn = http.client.HTTPSConnection('api.coinbase.com')
    method = 'GET'
    path = '/api/v3/brokerage/orders/historical/' + order_id
    payload = ''

    auth = Auth()
    headers = auth(method, path, payload)

    conn.request(method, path, payload, headers)
    res = conn.getresponse()
    data = json.loads(res.read())
    print(data)

get_order('') # pass order_id here

create_websocket.py

import json, websocket
from threading import Thread
from auth import *

import time

market = 'BTC-USDT'

def create_websocket():
    channel = 'ticker'
    subscribe_msg = {
        'type': 'subscribe',
        'product_ids': [
            market
            ],
        'channel': 'ticker',
        'api_key': API_KEY,
        'timestamp': timestamp,
        'signature': sign_message(timestamp + channel + market)
    }
    subscribe_msg = json.dumps(subscribe_msg)

    ws = websocket.create_connection('wss://advanced-trade-ws.coinbase.com')
    ws.send(subscribe_msg)

    while True:
        message = json.loads(ws.recv())
        if 'tickers' in message['events'][0]:
            current_price = message['events'][0]['tickers'][0]['price']
            print(current_price)

Thread(target=create_websocket).start()


# main thread
for i in range(100):
    time.sleep(1)
    print('main thread')

Parts of your code has been very helpful for me. The issue I keep running into is placing a sell order through my terminal.

I can check balances, I can check prices, but for some reason I cannot create sells or buys.

ok well this is my order script that works I just haven’t made it a function yet, hopefully this helps. you can buy or sell with it

import json, http.client
import numpy as np
from auth import *

# inputs
market = 'BTC-USDT'
side = 'BUY'
quote_size = '2.8' # required for BUY
base_size = '0.0001' # required for SELL

# choose amount_id
if side == 'BUY':
    amount_id = 'quote_size'
    size_id = quote_size

if side == 'SELL':
    amount_id = 'base_size'
    size_id = base_size


conn = http.client.HTTPSConnection('api.coinbase.com')
method = 'POST'
path = '/api/v3/brokerage/orders'
client_order_id = str(np.random.randint(2**30))

payload = {
    'client_order_id': client_order_id,
    'product_id': market,
    'side': side,
    'order_configuration': {
        'market_market_ioc': {
            amount_id: size_id
        }
    }
}

payload = json.dumps(payload)

auth = Auth()
headers = auth(method, path, payload)

conn.request(method, path, payload, headers)
res = conn.getresponse()
data = json.loads(res.read())

success = data['success']
order_id = data['order_id']
print(success)
print(order_id)

I just tried listing a specific crypto ACS-USD. and one script works, but the other does not.

why does "import http.client
import json

def is_trading_pair_available(pair):
conn = http.client.HTTPSConnection(‘api.pro.coinbase.com’)
method = ‘GET’
path = ‘/products’
headers = {‘User-Agent’: ‘python-coinbase-script’} # Add User-Agent header

conn.request(method, path, headers=headers)  # Add headers to the request
res = conn.getresponse()
data = json.loads(res.read())

print("Data:", data)  # Print the data for debugging

for product in data:
    print("Product:", product)  # Print the product for debugging
    if product['id'] == pair:
        return True
return False

trading_pair = ‘ACS-USD’

if is_trading_pair_available(trading_pair):
print(f"{trading_pair} is an available trading pair.“)
else:
print(f”{trading_pair} is not an available trading pair.")
"

script work, but

"import http.client
import json

def is_trading_pair_available(pair):
conn = http.client.HTTPSConnection(‘api.coinbase.com’)
method = ‘GET’
path = ‘/api/v3/brokerage/products?limit=0’ # Add the query parameter
headers = {
‘User-Agent’: ‘python-coinbase-script’,
‘Content-Type’: ‘application/json’
}

conn.request(method, path, headers=headers)
res = conn.getresponse()
data = json.loads(res.read())

for product in data['products']:
    if product['product_id'] == pair:
        return True
return False

trading_pair = ‘ACS-USD’

if is_trading_pair_available(trading_pair):
print(f"{trading_pair} is an available trading pair.“)
else:
print(f”{trading_pair} is not an available trading pair.")
"

script does not work?

Use markdown syntax, put your code in codeblocks not quotes, it’s impossible to read. Extended Syntax | Markdown Guide

edit - I’m unable to copy your code, paste it into my text editor, paste in my own API_KEY and SECRET, and test it. If you want help you have to make easier for us. Where/what is your auth function? You have to make it so I can easily test it.

Sorry about that. I’ll make sure it is perfectly clear. I have been staring at my screen for two weeks trying to figure this out. so I appreciate the help a lot.

I finally got it to sell through my terminal, and I will just build on the code to get it to function correctly. Thanks for the help. Seriously, thank you

The issue I am dealing with is making the code to run the code at different hours.

I used your code (which worked), and I tried to add to it to make sells at different times, and yet, it is not making the sell order.

“sell script”

import json
import datetime
import time
import http.client
import numpy as np
from auth import Auth

CRYPTO_CURRENCIES = {‘MEDIA’, ‘ETC’, ‘ACS’, ‘FET’, ‘ACH’}
PURCHASE_AMOUNT = 100 # Amount to spend on each purchase
PRICE_THRESHOLD = 0.01 # Percentage change threshold to trigger sell

trading_hours = [datetime.time(hour=h) for h in [1, 5, 6, 8, 9, 10, 16, 18, 19, 20, 22, 23]]

def get_min_base_size(pair):
conn = http.client.HTTPSConnection(‘api.pro.coinbase.com’)
method = ‘GET’
path = ‘/products’
headers = {‘User-Agent’: ‘python-coinbase-script’}

conn.request(method, path, headers=headers)
res = conn.getresponse()
data = json.loads(res.read())

for product in data:
    if product['id'] == pair:
        return float(product['base_min_size'])
return None

def place_order(market, side, quote_size=None, base_size=None):
# Choose amount_id
if side == ‘BUY’:
amount_id = ‘quote_size’
size_id = quote_size
elif side == ‘SELL’:
amount_id = ‘base_size’
size_id = base_size

# Create an HTTPS connection to the Coinbase API
conn = http.client.HTTPSConnection('api.coinbase.com')
method = 'POST'
path = '/api/v3/brokerage/orders'
client_order_id = str(np.random.randint(2**30))

# Build the payload dictionary with the necessary order parameters
payload = {
    'client_order_id': client_order_id,
    'product_id': market,
    'side': side,
    'order_configuration': {
        'market_market_ioc': {
            amount_id: size_id
        }
    }
}

# Convert the payload dictionary to a JSON formatted string
payload = json.dumps(payload)

# Use the Auth class to generate the required headers for the API request
auth = Auth()
headers = auth(method, path, payload)

# Send the request to the API with the provided method, path, payload, and headers
conn.request(method, path, payload, headers)
res = conn.getresponse()
data = json.loads(res.read())

return data

def place_order_v2(crypto, side, amount, price=None):
market = f"{crypto}-USD"
if side.lower() == ‘buy’:
if price is None:
price = get_buy_price(crypto)
quote_size = amount * price
order = place_order(market, side.upper(), quote_size=quote_size)
else:
if price is None:
price = get_buy_price(crypto) * 1.01
base_size = amount
order = place_order(market, side.upper(), base_size=base_size)
return order

def get_buy_price(crypto):
auth = Auth()

conn = http.client.HTTPSConnection('api.pro.coinbase.com')
method = 'GET'
path = f"/products/{crypto}-USD/ticker"

headers = auth(method, path)
headers['User-Agent'] = 'python-coinbase-script'

conn.request(method, path, headers=headers)
res = conn.getresponse()
data = json.loads(res.read())

return float(data['price'])

def sell_crypto(crypto, client):
account_balance = float(client.get_account(crypto)[‘balance’])
current_price = get_buy_price(crypto)
order = place_order_v2(crypto, ‘sell’, account_balance, price=current_price)
print(f"Selling {account_balance} {crypto} at {current_price}")

def main():
while True:
current_time = datetime.datetime.now().time()
if current_time in trading_hours:
for crypto in CRYPTO_CURRENCIES:
purchase_price = get_buy_price(crypto)
buy_order = place_order_v2(crypto, ‘buy’, PURCHASE_AMOUNT, price=purchase_price)
print(f"Buying {PURCHASE_AMOUNT} {crypto} at {purchase_price}")

            # Check the price every minute and sell if the price exceeds the threshold
            while True:
                time.sleep(60)
                current_price = get_buy_price(crypto)
                if current_price >= purchase_price * (1 + PRICE_THRESHOLD):
                    sell_order = place_order_v2(crypto, 'sell', PURCHASE_AMOUNT, price=current_price)
                    print(f"Selling {PURCHASE_AMOUNT} {crypto} at {current_price}")
                    break
                elif current_price <= purchase_price * (1 - PRICE_THRESHOLD):
                    sell_order = place_order_v2(crypto, 'sell', PURCHASE_AMOUNT, price=current_price)
                    print(f"Selling {PURCHASE_AMOUNT} {crypto} at {current_price}")
                    break
    time.sleep(60)

if name == ‘main’:
main()

'auth.py" script

import time, hmac, hashlib

API_KEY = ‘’
SECRET = ‘’

def get_api_credentials():
API_KEY = ‘’
SECRET = ‘’

return API_KEY, SECRET

timestamp = str(int(time.time()))

for websocket

def sign_message(message):
message = hmac.new(SECRET.encode(‘utf-8’), message.encode(‘utf-8’), digestmod=hashlib.sha256).hexdigest()
return message

for API

class Auth:
def init(self):
self.API_KEY = API_KEY
self.SECRET = SECRET

def __call__(self, method, path, payload):
    message = timestamp + method + path + payload
    signature = hmac.new(self.SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()

    headers = {
        'CB-ACCESS-KEY': self.API_KEY,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-SIGN': signature,
        'Content-Type': 'application/json'
    }
    return headers

console log

2023-04-08 00:25:23,615 DEBUG:https://api.pro.coinbase.com:443 “GET /products/ETC-USD/ticker HTTP/1.1” 200 137
2023-04-08 00:25:23,872 DEBUG:https://api.pro.coinbase.com:443 “GET /products/ACS-USD/ticker HTTP/1.1” 200 135
2023-04-08 00:25:24,129 DEBUG:https://api.pro.coinbase.com:443 “GET /products/FET-USD/ticker HTTP/1.1” 200 133
2023-04-08 00:25:24,377 DEBUG:https://api.pro.coinbase.com:443 “GET /products/ACH-USD/ticker HTTP/1.1” 200 139
2023-04-08 00:25:24,381 INFO:Attempting to purchase MEDIA…
2023-04-08 00:25:24,556 DEBUG:https://api.pro.coinbase.com:443 “GET /products/MEDIA-USD/ticker HTTP/1.1” 200 131
2023-04-08 00:25:24,558 ERROR:Failed to purchase MEDIA. Error message: ‘Client’ object has no attribute ‘place_market_order’
2023-04-08 00:25:24,558 INFO:Attempting to purchase ETC…
2023-04-08 00:25:24,746 DEBUG:https://api.pro.coinbase.com:443 “GET /products/ETC-USD/ticker HTTP/1.1” 200 137
2023-04-08 00:25:24,748 ERROR:Failed to purchase ETC. Error message: ‘Client’ object has no attribute ‘place_market_order’
2023-04-08 00:25:24,748 INFO:Attempting to purchase ACS…
2023-04-08 00:25:24,930 DEBUG:https://api.pro.coinbase.com:443 “GET /products/ACS-USD/ticker HTTP/1.1” 200 135
2023-04-08 00:25:24,932 ERROR:Failed to purchase ACS. Error message: ‘Client’ object has no

Ok I’ll look over your code but first,

How to post using markdown codeblocks:

```py

# open codeblock with three backticks followed by the language specifier
then paste your code
then three closing backticks, like displayed here

```
```terminal

# for terminal

```
```shell

# for shell

```

edit - [solution]

Ok, you’re running a while True loop all day? Why not use cron or something?

Anyway I think this is the problem with your question:

import datetime
current_time = datetime.datetime.now().time()
print(current_time)
# output
15:58:28.663407
import datetime
trading_hours = [datetime.time(hour=h) for h in [1, 5, 6, 8, 9, 10, 16, 18, 19, 20, 22, 23]]
print(trading_hours)
# output
[datetime.time(1, 0), datetime.time(5, 0), datetime.time(6, 0), datetime.time(8, 0), datetime.time(9, 0), datetime.time(10, 0), datetime.time(16, 0), datetime.time(18, 0), datetime.time(19, 0), datetime.time(20, 0), datetime.time(22, 0), datetime.time(23, 0)]

Your trading_hours list comprehension is not returning the properly formatted time, so str() it:

import datetime
trading_hours = [str(datetime.time(hour=h)) for h in [1, 5, 6, 8, 9, 10, 16, 18, 19, 20, 22, 23]]
print(trading_hours)
# output
['01:00:00', '05:00:00', '06:00:00', '08:00:00', '09:00:00', '10:00:00', '16:00:00', '18:00:00', '19:00:00', '20:00:00', '22:00:00', '23:00:00']
# You are very patient, and I appreciate that. Let me apply the new information, and I will get back to you. Thank you very much.

1 Like

Are you a real human or a language model?

1 Like

Haha I am very human. but humble enough to know that I am here because I need help, and not because I know what to do.

You’re the one helping me, so I appreciate it.

1 Like

I updated the time slot and still its not making the purchase.

Error message is 
#'Client' object has no attribute 'place_market_order'
# That attribute 'place_market_order' is at the bottom of the 'trade_predic.py' script
# The trade_predic.py script shows account balances, and calls the 'sell_script.py' to place orders. And 'auth.py' passes the keys through.

```console log

2023-04-08 15:00:16,840 DEBUG:https://api.pro.coinbase.com:443 "GET /products/ACH-USD/ticker HTTP/1.1" 200 136
2023-04-08 15:00:16,844 INFO:Attempting to purchase MEDIA...
2023-04-08 15:00:17,106 DEBUG:https://api.pro.coinbase.com:443 "GET /products/MEDIA-USD/ticker HTTP/1.1" 200 131
2023-04-08 15:00:17,107 ERROR:Failed to purchase MEDIA. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,107 INFO:Attempting to purchase ETC...
2023-04-08 15:00:17,296 DEBUG:https://api.pro.coinbase.com:443 "GET /products/ETC-USD/ticker HTTP/1.1" 200 139
2023-04-08 15:00:17,298 ERROR:Failed to purchase ETC. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,298 INFO:Attempting to purchase ACS...
2023-04-08 15:00:17,486 DEBUG:https://api.pro.coinbase.com:443 "GET /products/ACS-USD/ticker HTTP/1.1" 200 138
2023-04-08 15:00:17,487 ERROR:Failed to purchase ACS. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,488 INFO:Attempting to purchase FET...
2023-04-08 15:00:17,678 DEBUG:https://api.pro.coinbase.com:443 "GET /products/FET-USD/ticker HTTP/1.1" 200 134
2023-04-08 15:00:17,679 ERROR:Failed to purchase FET. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,679 INFO:Attempting to purchase ACH.



#trade_predic.py

import time
import pandas as pd
import pytz
import datetime
import json
import requests
import logging
from coinbase.wallet.client import Client
from coinbasepro.public_client import PublicClient
from predict_volume import predict_volume_increase
from sell_script import get_buy_price, place_order_v2
from sell_script import *


logging.basicConfig(filename='tradebot.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s')

CRYPTO_CURRENCIES = {'MEDIA', 'ETC', 'ACS', 'FET', 'ACH'}
fiat_currency = 'USD'


def read_keys(file_path):
    with open(file_path, "r") as f:
        lines = f.readlines()
        api_key = lines[0].strip()
        api_secret = lines[1].strip()
        passphrase = lines[2].strip()

    return api_key, api_secret, passphrase

keys_file_path = "mykeys.txt"
api_key, api_secret, passphrase = read_keys(keys_file_path)

public_client = PublicClient()

client = Client(api_key, api_secret)

# Define cryptocurrencies to trade and fiat currency to trade against
cryptos = ['MEDIA', 'ETC', 'ACS', 'FET', 'ACH']
 # Load data from CSV file into a Pandas DataFrame
df = pd.read_csv('crypto_data.csv')

def print_account_balances(retries=3, delay=5):
    for _ in range(retries):
        try:
            accounts = client.get_accounts()['data']
            for account in accounts:
                balance = account['balance']
                print(f"{balance['currency']}: {balance['amount']}")
            break
        except requests.exceptions.ConnectionError as e:
            print(f"Connection error: {e}. Retrying in {delay} seconds...")
            time.sleep(delay)


def print_account_balances():
    try:
        accounts = client.get_accounts()['data']
    except json.decoder.JSONDecodeError as e:
        logging.error(f"Failed to get accounts. Error message: {e}")
        return

    # continue with the rest of the function
    usd_account = client.get_account(fiat_currency)
    usd_balance = float(usd_account['balance']['amount'])
    print(f"USD Wallet Balance: {usd_balance}")

    balances = {}
    for account in accounts:
        currency = account.get('currency')
        account_type = account.get('type')
        balance = float(account.get('balance').get('amount'))

        if currency in CRYPTO_CURRENCIES and account_type in {'wallet', 'fiat'}:
            balances[currency] = balance

    print("Wallet Balances:")
    for currency in CRYPTO_CURRENCIES:
        if currency in balances:
            print(f"{currency} Wallet Balance: {balances[currency]}")
        else:
            print(f"{currency} Wallet Balance: 0.0")



def get_product_id(crypto):
    return f"{crypto}-{fiat_currency}"

def get_buy_price(crypto):
    product_id = get_product_id(crypto)
    ticker = public_client.get_product_ticker(product_id)
    return float(ticker['price'])

def get_order_status(order_id):
    order = client.get_order(order_id)
    return order['status']

#def place_order(crypto, side, amount, price=None):
    product_id = get_product_id(crypto)
    if side == 'buy':
        if price is None:
            price = get_buy_price(crypto)
        order = client.place_limit_order(product_id=product_id, side=side, funds=amount, price=price)
    else:
        if price is None:
            price = get_buy_price(crypto) * 1.01
        order = client.place_limit_order(product_id=product_id, side=side, size=amount, price=price)
    return order['id']

def sell_crypto(crypto):
    account_balance = float(client.get_account(crypto)['balance'])
    current_price = get_buy_price(crypto)
    place_order_v2(crypto, 'sell', account_balance, price=current_price)
    print(f"Selling {account_balance} {crypto} at {current_price}")


def get_current_price(crypto):
    product_id = get_product_id(crypto)
    ticker = public_client.get_product_ticker(product_id)
    return float(ticker['price'])

USD_BUDGET = 100 # Replace with the amount of USD you want to allocate for trading

def get_account_balance(crypto):
    account = client.get_account(crypto)
    return account['balance']

def update_account_balance(cryptos, balances):
    accounts = client.get_accounts()['data']
    for account in accounts:
        currency = account.get('currency')
        if currency in cryptos:
            account_id = account['id']
            balance = balances[currency]
            client.transfer_money(account_id, balance, currency=currency, to='coinbase')

def main():
    # Initialize invested variable to False
    invested = False
    # Initialize dictionary to store buy prices
    buy_prices = {}

    trading_hours = [str(datetime.time(hour=h)) for h in [1, 5, 8, 10, 14, 18, 19, 20, 22]]

    while True:
        print_account_balances()

        current_time = datetime.datetime.now(pytz.timezone('Asia/Shanghai')).time()

        for crypto in cryptos:
            current_price = get_buy_price(crypto)
            print(f"Current price of {crypto}: {current_price}")

        current_time = datetime.datetime.now(pytz.timezone('Asia/Shanghai'))
        current_hour = current_time.hour
        current_day = current_time.weekday()
        if predict_volume_increase(current_hour, current_day):
            print("Crypto volume is predicted to increase this hour!")
        else:
            print("Crypto volume is not predicted to increase this hour.")

        for crypto in cryptos:
            logging.info(f"Attempting to purchase {crypto}...")
            try:
                buy_price = get_current_price(crypto)
                buy_amount = USD_BUDGET / buy_price
                buy_order = client.place_market_order(product_id=f"{crypto}-USD", side='buy', funds=str(USD_BUDGET))
                logging.info(f"Successfully purchased {buy_order['filled_size']} {crypto} at {buy_price:.2f} USD per {crypto}.")
                USD_BALANCE -= USD_BUDGET
                crypto_balance = float(get_account_balance(crypto)['balance'])
                crypto_balance += float(buy_order['filled_size'])
                update_account_balance(crypto, crypto_balance)
            except Exception as e:
                logging.error(f"Failed to purchase {crypto}. Error message: {e}")

        time.sleep(60)

if __name__ == '__main__':
    main()



#sell_script.py

import json
import datetime
import time
import http.client
import numpy as np
from auth import Auth

CRYPTO_CURRENCIES = {'MEDIA', 'ETC', 'ACS', 'FET', 'ACH'}
PURCHASE_AMOUNT = 100 # Amount to spend on each purchase
PRICE_THRESHOLD = 0.01 # Percentage change threshold to trigger sell

trading_hours = [str(datetime.time(hour=h)) for h in [1, 5, 8, 10, 14, 18, 19, 20, 22]]


def get_min_base_size(pair):
    conn = http.client.HTTPSConnection('api.pro.coinbase.com')
    method = 'GET'
    path = '/products'
    headers = {'User-Agent': 'python-coinbase-script'}

    conn.request(method, path, headers=headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    for product in data:
        if product['id'] == pair:
            return float(product['base_min_size'])
    return None


def place_order(market, side, quote_size=None, base_size=None):
    # Choose amount_id
    if side == 'BUY':
        amount_id = 'quote_size'
        size_id = quote_size
    elif side == 'SELL':
        amount_id = 'base_size'
        size_id = base_size

    # Create an HTTPS connection to the Coinbase API
    conn = http.client.HTTPSConnection('api.coinbase.com')
    method = 'POST'
    path = '/api/v3/brokerage/orders'
    client_order_id = str(np.random.randint(2**30))

    # Build the payload dictionary with the necessary order parameters
    payload = {
        'client_order_id': client_order_id,
        'product_id': market,
        'side': side,
        'order_configuration': {
            'market_market_ioc': {
                amount_id: size_id
            }
        }
    }

    # Convert the payload dictionary to a JSON formatted string
    payload = json.dumps(payload)

    # Use the Auth class to generate the required headers for the API request
    auth = Auth()
    headers = auth(method, path, payload)

    # Send the request to the API with the provided method, path, payload, and headers
    conn.request(method, path, payload, headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    return data


def place_order_v2(crypto, side, amount, price=None):
    market = f"{crypto}-USD"
    if side.lower() == 'buy':
        if price is None:
            price = get_buy_price(crypto)
        quote_size = amount * price
        order = place_order(market, side.upper(), quote_size=quote_size)
    else:
        if price is None:
            price = get_buy_price(crypto) * 1.01
        base_size = amount
        order = place_order(market, side.upper(), base_size=base_size)
    return order


def get_buy_price(crypto):
    auth = Auth()
    
    conn = http.client.HTTPSConnection('api.pro.coinbase.com')
    method = 'GET'
    path = f"/products/{crypto}-USD/ticker"
    
    headers = auth(method, path)
    headers['User-Agent'] = 'python-coinbase-script'

    conn.request(method, path, headers=headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    return float(data['price'])


def sell_crypto(crypto, client):
    account_balance = float(client.get_account(crypto)['balance'])
    current_price = get_buy_price(crypto)
    order = place_order_v2(crypto, 'sell', account_balance, price=current_price)
    print(f"Selling {account_balance} {crypto} at {current_price}")

def main():
    while True:
        current_time = datetime.datetime.now().time()
        if current_time in trading_hours:
            for crypto in CRYPTO_CURRENCIES:
                purchase_price = get_buy_price(crypto)
                buy_order = place_order_v2(crypto, 'buy', PURCHASE_AMOUNT, price=purchase_price)
                print(f"Buying {PURCHASE_AMOUNT} {crypto} at {purchase_price}")
                
                # Check the price every minute and sell if the price exceeds the threshold
                while True:
                    time.sleep(60)
                    current_price = get_buy_price(crypto)
                    if current_price >= purchase_price * (1 + PRICE_THRESHOLD):
                        sell_order = place_order_v2(crypto, 'sell', PURCHASE_AMOUNT, price=current_price)
                        print(f"Selling {PURCHASE_AMOUNT} {crypto} at {current_price}")
                        break
                    elif current_price <= purchase_price * (1 - PRICE_THRESHOLD):
                        sell_order = place_order_v2(crypto, 'sell', PURCHASE_AMOUNT, price=current_price)
                        print(f"Selling {PURCHASE_AMOUNT} {crypto} at {current_price}")
                        break
        time.sleep(60)

if __name__ == '__main__':
    main()

#auth.py

import time, hmac, hashlib

API_KEY = ''
SECRET = ''

def get_api_credentials():
    API_KEY = ''
    SECRET = ''

    return API_KEY, SECRET


timestamp = str(int(time.time()))

# for websocket
def sign_message(message):
    message = hmac.new(SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
    return message

# for API
class Auth:
    def __init__(self):
        self.API_KEY = API_KEY
        self.SECRET = SECRET
    
    def __call__(self, method, path, payload):
        message = timestamp + method + path + payload
        signature = hmac.new(self.SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()

        headers = {
            'CB-ACCESS-KEY': self.API_KEY,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-SIGN': signature,
            'Content-Type': 'application/json'
        }
        return headers



1 Like

Alright well I noticed last night before I went to sleep there was more information in your post but I guess you edited it out, right now I don’t have enough information to help because I don’t have access to your current code. Did you make sure current_time and trading_hours match? On my previous post I don’t think those outputs matched. One is a datetime object and the other is a string. So you would have to make sure those match right. If that’s not the problem you’ll have to give more info.

1 Like

The current time and trading hours do match. I checked based on your help.

As for editing out anything. I did not. You have all the code connected to this bot, other than the script to predict the volume.

Based on the original code you provided. I can successfully make sells, but the new issue I am running into is making the bot make buys at the specific times.

Error message is 
#'Client' object has no attribute 'place_market_order'
# That attribute 'place_market_order' is at the bottom of the 'trade_predic.py' script
# The trade_predic.py script shows account balances, and calls the 'sell_script.py' to place orders. And 'auth.py' passes the keys through.

```console log

2023-04-08 15:00:16,840 DEBUG:https://api.pro.coinbase.com:443 "GET /products/ACH-USD/ticker HTTP/1.1" 200 136
2023-04-08 15:00:16,844 INFO:Attempting to purchase MEDIA...
2023-04-08 15:00:17,106 DEBUG:https://api.pro.coinbase.com:443 "GET /products/MEDIA-USD/ticker HTTP/1.1" 200 131
2023-04-08 15:00:17,107 ERROR:Failed to purchase MEDIA. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,107 INFO:Attempting to purchase ETC...
2023-04-08 15:00:17,296 DEBUG:https://api.pro.coinbase.com:443 "GET /products/ETC-USD/ticker HTTP/1.1" 200 139
2023-04-08 15:00:17,298 ERROR:Failed to purchase ETC. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,298 INFO:Attempting to purchase ACS...
2023-04-08 15:00:17,486 DEBUG:https://api.pro.coinbase.com:443 "GET /products/ACS-USD/ticker HTTP/1.1" 200 138
2023-04-08 15:00:17,487 ERROR:Failed to purchase ACS. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,488 INFO:Attempting to purchase FET...
2023-04-08 15:00:17,678 DEBUG:https://api.pro.coinbase.com:443 "GET /products/FET-USD/ticker HTTP/1.1" 200 134
2023-04-08 15:00:17,679 ERROR:Failed to purchase FET. Error message: 'Client' object has no attribute 'place_market_order'
2023-04-08 15:00:17,679 INFO:Attempting to purchase ACH.

#trade_predic.py

import time
import pandas as pd
import pytz
import datetime
import json
import requests
import logging
from coinbase.wallet.client import Client
from coinbasepro.public_client import PublicClient
from predict_volume import predict_volume_increase
from sell_script import get_buy_price, place_order_v2
from sell_script import *


logging.basicConfig(filename='tradebot.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s')

CRYPTO_CURRENCIES = {'MEDIA', 'ETC', 'ACS', 'FET', 'ACH'}
fiat_currency = 'USD'


def read_keys(file_path):
    with open(file_path, "r") as f:
        lines = f.readlines()
        api_key = lines[0].strip()
        api_secret = lines[1].strip()
        passphrase = lines[2].strip()

    return api_key, api_secret, passphrase

keys_file_path = "mykeys.txt"
api_key, api_secret, passphrase = read_keys(keys_file_path)

public_client = PublicClient()

client = Client(api_key, api_secret)

# Define cryptocurrencies to trade and fiat currency to trade against
cryptos = ['MEDIA', 'ETC', 'ACS', 'FET', 'ACH']
 # Load data from CSV file into a Pandas DataFrame
df = pd.read_csv('crypto_data.csv')

def print_account_balances(retries=3, delay=5):
    for _ in range(retries):
        try:
            accounts = client.get_accounts()['data']
            for account in accounts:
                balance = account['balance']
                print(f"{balance['currency']}: {balance['amount']}")
            break
        except requests.exceptions.ConnectionError as e:
            print(f"Connection error: {e}. Retrying in {delay} seconds...")
            time.sleep(delay)


def print_account_balances():
    try:
        accounts = client.get_accounts()['data']
    except json.decoder.JSONDecodeError as e:
        logging.error(f"Failed to get accounts. Error message: {e}")
        return

    # continue with the rest of the function
    usd_account = client.get_account(fiat_currency)
    usd_balance = float(usd_account['balance']['amount'])
    print(f"USD Wallet Balance: {usd_balance}")

    balances = {}
    for account in accounts:
        currency = account.get('currency')
        account_type = account.get('type')
        balance = float(account.get('balance').get('amount'))

        if currency in CRYPTO_CURRENCIES and account_type in {'wallet', 'fiat'}:
            balances[currency] = balance

    print("Wallet Balances:")
    for currency in CRYPTO_CURRENCIES:
        if currency in balances:
            print(f"{currency} Wallet Balance: {balances[currency]}")
        else:
            print(f"{currency} Wallet Balance: 0.0")



def get_product_id(crypto):
    return f"{crypto}-{fiat_currency}"

def get_buy_price(crypto):
    product_id = get_product_id(crypto)
    ticker = public_client.get_product_ticker(product_id)
    return float(ticker['price'])

def get_order_status(order_id):
    order = client.get_order(order_id)
    return order['status']

#def place_order(crypto, side, amount, price=None):
    product_id = get_product_id(crypto)
    if side == 'buy':
        if price is None:
            price = get_buy_price(crypto)
        order = client.place_limit_order(product_id=product_id, side=side, funds=amount, price=price)
    else:
        if price is None:
            price = get_buy_price(crypto) * 1.01
        order = client.place_limit_order(product_id=product_id, side=side, size=amount, price=price)
    return order['id']

def sell_crypto(crypto):
    account_balance = float(client.get_account(crypto)['balance'])
    current_price = get_buy_price(crypto)
    place_order_v2(crypto, 'sell', account_balance, price=current_price)
    print(f"Selling {account_balance} {crypto} at {current_price}")


def get_current_price(crypto):
    product_id = get_product_id(crypto)
    ticker = public_client.get_product_ticker(product_id)
    return float(ticker['price'])

USD_BUDGET = 100 # Replace with the amount of USD you want to allocate for trading

def get_account_balance(crypto):
    account = client.get_account(crypto)
    return account['balance']

def update_account_balance(cryptos, balances):
    accounts = client.get_accounts()['data']
    for account in accounts:
        currency = account.get('currency')
        if currency in cryptos:
            account_id = account['id']
            balance = balances[currency]
            client.transfer_money(account_id, balance, currency=currency, to='coinbase')

def main():
    # Initialize invested variable to False
    invested = False
    # Initialize dictionary to store buy prices
    buy_prices = {}

    trading_hours = [str(datetime.time(hour=h)) for h in [1, 5, 8, 10, 14, 18, 19, 20, 22]]

    while True:
        print_account_balances()

        current_time = datetime.datetime.now(pytz.timezone('Asia/Shanghai')).time()

        for crypto in cryptos:
            current_price = get_buy_price(crypto)
            print(f"Current price of {crypto}: {current_price}")

        current_time = datetime.datetime.now(pytz.timezone('Asia/Shanghai'))
        current_hour = current_time.hour
        current_day = current_time.weekday()
        if predict_volume_increase(current_hour, current_day):
            print("Crypto volume is predicted to increase this hour!")
        else:
            print("Crypto volume is not predicted to increase this hour.")

        for crypto in cryptos:
            logging.info(f"Attempting to purchase {crypto}...")
            try:
                buy_price = get_current_price(crypto)
                buy_amount = USD_BUDGET / buy_price
                buy_order = client.place_market_order(product_id=f"{crypto}-USD", side='buy', funds=str(USD_BUDGET))
                logging.info(f"Successfully purchased {buy_order['filled_size']} {crypto} at {buy_price:.2f} USD per {crypto}.")
                USD_BALANCE -= USD_BUDGET
                crypto_balance = float(get_account_balance(crypto)['balance'])
                crypto_balance += float(buy_order['filled_size'])
                update_account_balance(crypto, crypto_balance)
            except Exception as e:
                logging.error(f"Failed to purchase {crypto}. Error message: {e}")

        time.sleep(60)

if __name__ == '__main__':
    main()

#sell_script.py

import json
import datetime
import time
import http.client
import numpy as np
from auth import Auth

CRYPTO_CURRENCIES = {'MEDIA', 'ETC', 'ACS', 'FET', 'ACH'}
PURCHASE_AMOUNT = 100 # Amount to spend on each purchase
PRICE_THRESHOLD = 0.01 # Percentage change threshold to trigger sell

trading_hours = [str(datetime.time(hour=h)) for h in [1, 5, 8, 10, 14, 18, 19, 20, 22]]


def get_min_base_size(pair):
    conn = http.client.HTTPSConnection('api.pro.coinbase.com')
    method = 'GET'
    path = '/products'
    headers = {'User-Agent': 'python-coinbase-script'}

    conn.request(method, path, headers=headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    for product in data:
        if product['id'] == pair:
            return float(product['base_min_size'])
    return None


def place_order(market, side, quote_size=None, base_size=None):
    # Choose amount_id
    if side == 'BUY':
        amount_id = 'quote_size'
        size_id = quote_size
    elif side == 'SELL':
        amount_id = 'base_size'
        size_id = base_size

    # Create an HTTPS connection to the Coinbase API
    conn = http.client.HTTPSConnection('api.coinbase.com')
    method = 'POST'
    path = '/api/v3/brokerage/orders'
    client_order_id = str(np.random.randint(2**30))

    # Build the payload dictionary with the necessary order parameters
    payload = {
        'client_order_id': client_order_id,
        'product_id': market,
        'side': side,
        'order_configuration': {
            'market_market_ioc': {
                amount_id: size_id
            }
        }
    }

    # Convert the payload dictionary to a JSON formatted string
    payload = json.dumps(payload)

    # Use the Auth class to generate the required headers for the API request
    auth = Auth()
    headers = auth(method, path, payload)

    # Send the request to the API with the provided method, path, payload, and headers
    conn.request(method, path, payload, headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    return data


def place_order_v2(crypto, side, amount, price=None):
    market = f"{crypto}-USD"
    if side.lower() == 'buy':
        if price is None:
            price = get_buy_price(crypto)
        quote_size = amount * price
        order = place_order(market, side.upper(), quote_size=quote_size)
    else:
        if price is None:
            price = get_buy_price(crypto) * 1.01
        base_size = amount
        order = place_order(market, side.upper(), base_size=base_size)
    return order


def get_buy_price(crypto):
    auth = Auth()
    
    conn = http.client.HTTPSConnection('api.pro.coinbase.com')
    method = 'GET'
    path = f"/products/{crypto}-USD/ticker"
    
    headers = auth(method, path)
    headers['User-Agent'] = 'python-coinbase-script'

    conn.request(method, path, headers=headers)
    res = conn.getresponse()
    data = json.loads(res.read())

    return float(data['price'])


def sell_crypto(crypto, client):
    account_balance = float(client.get_account(crypto)['balance'])
    current_price = get_buy_price(crypto)
    order = place_order_v2(crypto, 'sell', account_balance, price=current_price)
    print(f"Selling {account_balance} {crypto} at {current_price}")

def main():
    while True:
        current_time = datetime.datetime.now().time()
        if current_time in trading_hours:
            for crypto in CRYPTO_CURRENCIES:
                purchase_price = get_buy_price(crypto)
                buy_order = place_order_v2(crypto, 'buy', PURCHASE_AMOUNT, price=purchase_price)
                print(f"Buying {PURCHASE_AMOUNT} {crypto} at {purchase_price}")
                
                # Check the price every minute and sell if the price exceeds the threshold
                while True:
                    time.sleep(60)
                    current_price = get_buy_price(crypto)
                    if current_price >= purchase_price * (1 + PRICE_THRESHOLD):
                        sell_order = place_order_v2(crypto, 'sell', PURCHASE_AMOUNT, price=current_price)
                        print(f"Selling {PURCHASE_AMOUNT} {crypto} at {current_price}")
                        break
                    elif current_price <= purchase_price * (1 - PRICE_THRESHOLD):
                        sell_order = place_order_v2(crypto, 'sell', PURCHASE_AMOUNT, price=current_price)
                        print(f"Selling {PURCHASE_AMOUNT} {crypto} at {current_price}")
                        break
        time.sleep(60)

if __name__ == '__main__':
    main()
#auth.py

import time, hmac, hashlib

API_KEY = ''
SECRET = ''

def get_api_credentials():
    API_KEY = ''
    SECRET = ''

    return API_KEY, SECRET


timestamp = str(int(time.time()))

# for websocket
def sign_message(message):
    message = hmac.new(SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
    return message

# for API
class Auth:
    def __init__(self):
        self.API_KEY = API_KEY
        self.SECRET = SECRET
    
    def __call__(self, method, path, payload):
        message = timestamp + method + path + payload
        signature = hmac.new(self.SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()

        headers = {
            'CB-ACCESS-KEY': self.API_KEY,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-SIGN': signature,
            'Content-Type': 'application/json'
        }
        return headers

How do you explain this? If you run this for more than a minute it should print(‘yes’) but it doesn’t.

import datetime

current_time = datetime.datetime.now().time()
print(current_time)
H = datetime.datetime.now().time().strftime('%H')
print(H)
M = datetime.datetime.now().time().strftime('%M')
print(M)
trading_hours = [str(datetime.time(hour=h, minute=int(M)+1)) for h in [1, 5, 8, 10, 14, 18, 19, 20, 22, int(H)]]
print(trading_hours)

while True:
    current_time = datetime.datetime.now().time()
    if current_time in trading_hours:
        print('yes')

I added the current HOUR and MINUTE(+1) to the trading_hours list, so if you run it for more than a minute that time will pass. Which should trigger the print(‘yes’) statement. But it doesn’t. How do you explain this?

edit

Something’s going on with the check because this is not properly searching for the substring (because of the colons)

# does not work
x = '20:00'
y = ['19:00:00', '20:00:00']
while True:
    if x in y:
        print('yes')

Here’s a jank way to solve the problem

x = '20:00'
y = ['19:00:00', '20:00:00']
while True:
    for i in y:
        stop = i.startswith(x)
    if stop == True:
        break

Which translates to this:

import datetime
current_time = datetime.datetime.now().time()
print(current_time)
current_time = str(datetime.datetime.now().time().strftime('%H:%M'))
print(current_time)
H = datetime.datetime.now().time().strftime('%H')
print(H)
M = datetime.datetime.now().time().strftime('%M')
print(M)
trading_hours = [str(datetime.time(hour=h, minute=int(M)+1)) for h in [1, 5, 8, 10, 14, 18, 19, 20, 22, int(H)]]
print(trading_hours)

while True:
    for i in trading_hours:
        stop = i.startswith(str(datetime.datetime.now().time().strftime('%H:%M')))
    if stop == True:
        print('yes')
        break

I think this works now.


BTW - all of this is inefficient. if you’re script is going to be running all day with mostly downtime use cron.

1 Like

Yes sir. albeit, I do have a cron installed. but I wanted to have the times checked first.

I will update the code and try it out. I really hope it works. No one else is commenting, and if you give up, all hope is lost haha

1 Like