A C Marston
A C Marston

Reputation: 29

How can I make this Python script add a limit to trades made with API?

I'm putting together a python script to make trades on poloniex with the API, and so far I've got it to make trades when certain conditions are met, but I still need it to NOT place anymore trades for the rest of that day (I have the entire script looping every 60 seconds).

So far I have this script:

import requests
import urllib.request
import urllib.parse
import http.client
import hashlib
import hmac
import time
import json
from urllib.request import urlopen

The_Currency_Pair = input('Which Currency Pair?\nPAIRS TO CHOOSE FROM:\nUSDT_BTC\nUSDT_XRP\nUSDT_ETH\nUSDT_BCH\nUSDT_STR\nUSDT_LTC\nUSDT_ETC\nUSDT_XMR\n')


api = 'https://poloniex.com/tradingApi'
key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'


def main():
    poloniexPrices = urlopen('https://poloniex.com/public?command=returnTicker').read()
    poloniexjson = json.loads(poloniexPrices)
    poloniexlastP = poloniexjson[The_Currency_Pair]['last']


    poloniexOCHL = urlopen('https://poloniex.com/public?command=returnChartData&currencyPair=USDT_BCH&start=1538352000&period=86400').read()
    poloniexOCHLjson = json.loads(poloniexOCHL)
    poloniexlasthigh = poloniexOCHLjson[-2]['high']


    print ('Last Price')
    print (poloniexlastP)
    print ('----------------------------------------')
    print ('Last Day High')
    print (poloniexlasthigh)
    print ('----------------------------------------')



    data = {
        'command': 'returnBalances',
        'nonce'  : int(time.time() * 1000)
    }
    data = urllib.parse.urlencode(data).encode()

    signature = hmac.new(secret.encode(), data, hashlib.sha512)

    headers = {
        'Key' : key,
        'Sign': signature.hexdigest()
    }

    request = urllib.request.Request(
        url=api, data=data, headers=headers, method='POST'
    )

    text = urllib.request.urlopen(request).read().decode()

    print ('MY ACCOUNT BALANCE')
    try:
        print(json.loads(text)['USDT'])
    except:
        print(text)
    print ('-----------------------------------------')



    if float(poloniexlastP) > 0:
        print ('PLACING TRADE')
        print ('-----------------------------------------------')

        parms = {"command":"buy",
             "currencyPair":The_Currency_Pair,
             "rate":100,
             "immediateOrCancel":1,
             "amount":0.01,
             "nonce":int(time.time() * 1000)}

        parms = urllib.parse.urlencode(parms).encode()

        signature = hmac.new(secret.encode(), parms, hashlib.sha512)

        headers = {'Key' : key,
                   'Sign': signature.hexdigest()}

        request = urllib.request.Request(
        url=api, data=parms, headers=headers, method='POST')

        text = urllib.request.urlopen(request).read().decode()

        ordernumber = (json.loads(text)['orderNumber'])

        print ('Order Number:')
        print (ordernumber)




while True:
    main()
    time.sleep(60)

Anyway, after a trade has been placed, I need it to make sure that after the 60 second sleep, it doesn't make a second trade unless it is a new day/the day after the trade was made. (Could I use poloniex server time for this?)

So, if it has got as far as print (ordernumber) that means it has placed a trade. But how do I mark it as placed trade for the day or something and use it in the if float(poloniexlastP) > 0: for the next loop to make sure it doesn't place another one?

Upvotes: 1

Views: 87

Answers (2)

loretoparisi
loretoparisi

Reputation: 16271

If you are using a application server like Flask, you could easily setup a limiter

from flask_limiter import Limiter

app = Flask(__name__)
limiter = Limiter(app, global_limits=["100 per hour", "20 per minute"])

and then you can decorate each endpoint with the limiter defined:

@app.route("/slow")
@limiter.limit("1 per day")
def slow():
    return "24"

@app.route("/fast")
def fast():
    return "42"

@app.route("/ping")
@limiter.exempt
def ping():
    return 'PONG'

More detail here: https://github.com/alisaifee/flask-limiter

Upvotes: 0

Kelvin
Kelvin

Reputation: 1367

You probably want a flag of some sort that resets. Maybe something along these lines:

        print ('Order Number:')
        print (ordernumber)
        return True # You've made a trade
    return False # You've didn't make a trade


have_traded = False
while True:
    if not have_traded:
        have_traded = main()
        time.sleep(60)

    if new_date_function():
        have_traded = False

Upvotes: 0

Related Questions