Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
API Problems!!!
#2
First off... You posted to a public forum exposing your API keys for something that involves moving real money. Now anybody could theoretically go in and blow up your account. I'd get these changed immediately.

Next a quick look at nonkyc.io shows me that they have two API types - REST and websockets. Both of these are standard API types. I'd recommend ditching library provided by the exchange - they tend to suck and may not always work well if you deploy to a server.

Here is some code that I use to access a REST API from polygon.io -

import requests
import datetime
import urllib3
import json
from urllib3.exceptions import InsecureRequestWarning

def poly_get_aggregates(stock_ticker, multiplier, timespan, from_date, to_date, api_key):
    url = f"https://api.polygon.io/v2/aggs/ticker/{stock_ticker}/range/{multiplier}/{timespan}/{from_date}/{to_date}?limit=50000"
    params = {'apiKey': api_key}
    if "api.polygon.io" in url: urllib3.disable_warnings(InsecureRequestWarning) #Suppress only the specific InsecureRequestWarning for api.polygon.io
    response = requests.get(url, params=params, verify=False) # Disable SSL verification
    if response.status_code == 200: return response.json()
    else: response.raise_for_status()

if __name__ == "__main__":
    # Example usage
    stock_ticker = "TSLA"
    multiplier = 1
    timespan = "hour"
    from_date = "2024-06-27"
    to_date = "2024-06-27"
    api_key = 'NOPENOTPOSTINGTHIS'

    try:
        aggregates = poly_get_aggregates(stock_ticker, multiplier, timespan, from_date, to_date, api_key)
        print(aggregates)
        print(json.dumps(aggregates, indent=4)) 
        print(type(aggregates))
    except requests.exceptions.HTTPError as e:
        print(f"Polygon Get Aggregates HTTP error occurred: {e}")
    except Exception as e:
        print(f"Polygon Get Aggregates general error occurred: {e}")
https://nonkyc.io/api - Your REST API documentation is there. You should be able to change the endpoints from the above code to include your endpoints and it may work - you'd need to play around with it but at least this is a starting point.

A caveat about the above code, for some reason when I connect to polygon's API code it can't ever verify their SSL certificate - so my code above is a bit of a hack that forces python to NOT verify the SSL cert, you may not have that issue. Polygon is just market data, not actual trading so I don't really care about a verified SSL connection to them.

Another caveat, the nonkyc sample code you posted uses asyncio. If you're sending actual trades, I HIGHLY recommend using asyncio. The sample I posted above I just use to download historical market data, so I don't care about real time stuff there but if you're trading in real time asyncio is the way to go. You'll need to look at some tutorials as asynchronous programming is not easy to grasp at first, but with I/O operations in an API it's the way to go. When I get real time market data from polygon using their websockets API, I use asyncio for that.

import asyncio
import aiohttp
import json

#CHECK THESE EVERY DAY
MODE = 'SIM' #LIVE or SIM
REFRESH_TOKEN = 'NOPE'

#THESE SHOULD NOT NORMALLY BE CHANGED
#LIVE_ACCOUNT_ID = ''NOPE'' #1st live account
LIVE_ACCOUNT_ID = ''NOPE''#2nd live account
#SIM_ACCOUNT_ID = ''NOPE'' #1st sim account
SIM_ACCOUNT_ID = ''NOPE'' #2nd sim account
CLIENT_ID = ''NOPE''
CLIENT_SECRET = 'NOPE''

if MODE == 'LIVE': 
    base_url = "https://api.tradestation.com"
    ACCOUNT_ID = LIVE_ACCOUNT_ID
elif MODE == 'SIM': 
    base_url = "https://sim-api.tradestation.com"
    ACCOUNT_ID = SIM_ACCOUNT_ID
else: 
    exit('ERROR: Live or sim not specified')

if not REFRESH_TOKEN: 
    REFRESH_TOKEN = input('Enter refresh token: ')

async def get_access_token():
    url = "https://signin.tradestation.com/oauth/token"
    payload = f'grant_type=refresh_token&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&refresh_token={REFRESH_TOKEN}'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, data=payload) as response:
            response_data = await response.json()
            return response_data['access_token']

async def place_order(session, access_token, symbol, quantity, ordertype, tradeaction, limitprice='error', tif={"Duration": "DAY"}, route='Intelligent'):
    url = base_url + "/v3/orderexecution/orders"
    payload = {
        "AccountID": ACCOUNT_ID,
        "Symbol": symbol,
        "Quantity": quantity,
        "OrderType": ordertype,
        "TradeAction": tradeaction,
        "LimitPrice": limitprice, 
        "TimeInForce": tif,
        "Route": route
    }
    headers = {
        "Content-Type": "application/json",
        "Authorization": f'Bearer {access_token}'
    }
    async with session.post(url, json=payload, headers=headers) as response:
        response_text = await response.text()
        print(response_text)

async def get_balances():
    access_token = await get_access_token()  # get a new access token
    url = base_url + f"/v3/brokerage/accounts/{ACCOUNT_ID}/balances"
    headers = {
        "Authorization": f'Bearer {access_token}'
    }
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers) as response:
            response_text = await response.text()
            print(response_text)
            
async def stream_quotes(symbols):
    access_token = await get_access_token()  # Get a new access token
    url = f"{base_url}/v3/marketdata/stream/quotes/{','.join(symbols)}"
    headers = {"Authorization": f"Bearer {access_token}"}

    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers) as response:
            async for line in response.content:
                if line:
                    print(json.dumps(json.loads(line.decode('utf-8')), indent=4))


# Run the async tasks
symbols = ["AMD"]
asyncio.run(stream_quotes(symbols))
Above is REST API with asyncio that I use to communicate with my broker Tradestation for placing trades. You could possibly adapt it for your use case.
Reply


Messages In This Thread
API Problems!!! - by Dronemaster278 - Jun-29-2024, 01:16 AM
RE: API Problems!!! - by sawtooth500 - Jun-29-2024, 02:50 AM
RE: API Problems!!! - by Dronemaster278 - Jun-29-2024, 07:07 PM
RE: API Problems!!! - by sawtooth500 - Jun-29-2024, 10:45 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020