Python crypto buy-sell bot - python

This is a simple trading bot working with gate.io api. It does almost what we want but 2 features are missing.
1-When I enter the token name in the terminal, it has to automatically buy it 3% more than the market price.
2-When the price rises as much as I have determined, it has to automatically sell back all the tokens it bought.
How can I add these features?
import ccxt, time
import utils.config
from utils.telegram_bot import post_message
# Create the GateIO exchange object using CCXT
exchange = ccxt.gateio({
'apiKey': utils.config.GATEIO_API_KEY,
'secret': utils.config.GATEIO_SECRET_KEY,
})
# Get the market and balance data from GateIO
markets = exchange.fetch_markets()
balance = exchange.fetch_total_balance()
# Get all the available symbols from GateIO
symbols = [symbol for symbol in [market['symbol'] for market in markets]]
# Placeholder for keeping the price at the time of buying
entryPrice = 0
def symbol_check(symbol):
if symbol in symbols:
print(f"Good news!, {symbol} exists in Gate.io")
return True
else:
print(f"Sorry, {symbol} does not exist in Gate.io")
return False
def buy(symbol):
global entryPrice
# Pick a price more than the last ticker data, to make sure that we can fulfill order
price = exchange.fetch_ticker(symbol)['last'] * 1.01
entryPrice = price
# Get the current USDT balance in GateIO
balance = exchange.fetch_total_balance()
coin = symbol.split('/')[0]
usdt_balance = balance['USDT']
# Calculate the amount of coin that we can buy, apply a small margin for rounding errors in balance
amount = (usdt_balance * 0.999) / (price)
# Create the limit buy order
exchange.create_limit_buy_order(symbol, amount=amount, price=price)
# Notify the user both on Telegram and CLI
message = f"You have {usdt_balance} USDT in your account. Buying {amount} {coin} for {price}"
print(message)
post_message(message)
def sell(symbol):
# Pick a price less than the last ticker data, to make sure that we can fulfill order
price = exchange.fetch_ticker(symbol)['last'] * 0.99
# Get the current coin balance in GateIO
balance = exchange.fetch_total_balance()
coin = symbol.split('/')[0]
coin_balance = balance[coin]
# Create the limit sell order
exchange.create_limit_sell_order(symbol, amount=coin_balance, price=price)
# Notify the user both on Telegram and CLI
message = f"You have {coin_balance} {coin} in your account. Selling them for {price}"
print(message)
post_message(message)
def sellBearish(symbol):
global entryPrice
bestPrice = exchange.fetch_ticker(symbol)['last']
balance = exchange.fetch_total_balance()
while True:
price = exchange.fetch_ticker(symbol)['last']
# Update the best price if we have a new best price
if price > bestPrice:
bestPrice = price
# If the price has dropped 3% percent w.r.t. the best price, sell the coins and get the profit
elif price < (0.97 * bestPrice):
coin = symbol.split('/')[0]
coin_balance = balance[coin]
exchange.create_limit_sell_order(symbol, amount=coin_balance, price=price*0.99)
# Notify the user both on Telegram and CLI
message = f"You have {coin_balance} {coin} in your account.\nSelling them for {price*0.99}\nYour profit is{price/entryPrice*100}"
print(message)
post_message(message)

Related

binance api, i cant put an order with a price in dollar (not in quantity)

i try to put some orders at a specific price.
For example i would like to put 20 dollars to buy some ETHUSDT at 800 usdt but it gives me this error:
binance.exceptions.BinanceAPIException: APIError(code=-1106): Parameter 'quoteOrderQty' sent when not required.
there is my call function:
buy_order = client.create_order(
symbol = "ETHUSDT",
price = 800,
quoteOrderQty = 25,
side = client.SIDE_BUY,
type = client.ORDER_TYPE_LIMIT,
timeInForce = client.TIME_IN_FORCE_GTC)
but i dont have any error when i put this :
buy_order = client.create_test_order(symbol="ETHUSDT", side='BUY', type='MARKET', quoteOrderQty=10)
to be honnest actually i do that:
def putOrderBuy_at_price(self, symbol, amount, price):
monney_price = self.client.get_symbol_ticker(symbol=symbol)
# Calculate how much ETH $200 can buy
print(monney_price['price'])
i = 10
while i != 0:
try:
buy_quantity = round(amount / float(price), i)
print("-----------", buy_quantity)
#ETHUSDT
buy_order = self.client.create_order(
symbol = symbol,
price = price,
quantity = buy_quantity,
side = self.client.SIDE_BUY,
type = self.client.ORDER_TYPE_LIMIT,
timeInForce = self.client.TIME_IN_FORCE_GTC)
break
except Exception:
print(i)
i -= 1
And i think there is a better way for that.
Thanks for yours answers
quoteOrderQty is only for MARKET order.

How can I get the current WBNB balance once every 3 seconds in python/web3.py?

I need help. I want to rotate the FIT token liquidity balance every 3 seconds but I need some help
bsc = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
#WBNB
abi = json.loads('[{"constant":true,"inputs":[],"name":"name","outputs":
[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},
{"constant":false,"inputs":[{"name":"guy","type":"address"},
{"name":"wad","type":"uint256"}],"name":"approve","outputs":
[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},
{"constant":true,"inputs":[],"name":"totalSupply","outputs":
[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},
{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},
{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":
[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},
{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"withdraw","outputs":
[],"payable":false,"stateMutability":"nonpayable","type":"function"},
{"constant":true,"inputs":[],"name":"decimals","outputs":
[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},
{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":
[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},
{"constant":true,"inputs":[],"name":"symbol","outputs":
[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},
{"constant":false,"inputs":[{"name":"dst","type":"address"},
{"name":"wad","type":"uint256"}],"name":"transfer","outputs":
[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},
{"constant":false,"inputs":[],"name":"deposit","outputs":
[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":
[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":
[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},
{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":
[{"indexed":true,"name":"src","type":"address"},
{"indexed":true,"name":"guy","type":"address"},
{"indexed":false,"name":"wad","type":"uint256"}],"name":"Approval","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},
{"indexed":true,"name":"dst","type":"address"},
{"indexed":false,"name":"wad","type":"uint256"}],"name":"Transfer","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"name":"dst","type":"address"},
{"indexed":false,"name":"wad","type":"uint256"}],"name":"Deposit","type":"event"},
{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},
{"indexed":false,"name":"wad","type":"uint256"}],"name":"Withdrawal","type":"event"}]')
address = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'
contract = web3.eth.contract(address=address , abi=abi)
print(contract.functions.name().call())
balance = contract.functions.balanceOf('0x5e8ce185475855E60fA121389331cd6cEd61ea57').call()
print(web3.fromWei(balance, 'ether'))
I'm getting updated information.
But I want to get new updated information every 3 seconds.
I try this ;
Ba = balance
while Ba > 0:
if Ba > 0:
print(web3.fromWei(balance, 'ether'))
time.sleep(3)
else:
print('0')
But this prints me a single result multiple times :(
you need to use .call() every time to refresh the balance!
balance = contract.functions.balanceOf('0x5e8ce185475855E60fA121389331cd6cEd61ea57')
while True:
print(web3.fromWei(balance.call(), 'ether'))
time.sleep(3)

Running backtest on backtrader I get many BUY ORDERS CANCELLED/MARGIN/REJECTED when they should not

Many buy orders are cancelled in the backtests and I cannot find why. Looking at the Writefile log it seems the buy orders are created at the next day's close. In most cases the buy price is in the day's range but still not executed.
I have tried on different assets, different sizes of the data feed, different strategies, with the same result.
Running on Jupyter notebook. I include the code and the log.
Finally I changed the default parameter ('100') in AllInSizerInt() below 100 and it worked. I do not really understand why, I thought the sizer would get the cash position from the broker and adjust the order.
Here is the fix:
''''
python
#Add the sizer. We plan to go 'all in' every time
cerebro.addsizer(bt.sizers.AllInSizerInt, percents = 95)
''''
And here is the original code:
''''
python
#### Import databases
from datetime import datetime
import backtrader as bt
import backtrader.indicators as btind
abspath = '/mypath/'
logfile = 'abs_momentum.csv'
# Create a Strategy
class Abs_momentum(bt.Strategy):
alias = ('Abs_momentum',)
params = (
# period for momentum calculation
('lookback', 252),
('range', 100))
def __init__(self):
# keep track of close price in the series
self.data_close = self.datas[0].close
# keep track of pending orders/buy price/buy commission
self.order = None
self.price = None
self.comm = None
# add a momentum indicator
self.mom = btind.MomentumOsc(self.data_close, \
period = self.p.lookback, \
band = self.p.range)
self.buysig = self.mom
def log(self, txt, dt=None):
''' Logging function fot this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
#self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
def next(self):
# do nothing if an order is pending
if self.order:
return
# check if there is already a position
if not self.position:
# buy condition
if self.buysig > 100:
self.log(f'BUY CREATED --- Price: {self.data_close[0]:.2f}')
self.order = self.buy(size = None)
else:
# sell condition
if self.buysig < 100:
self.log(f'SELL CREATED --- Price: {self.data_close[0]:.2f}')
self.order = self.sell(Size = None)
###
#### Download data from Yahoo Finance
data = bt.feeds.YahooFinanceData(dataname= 'SPY', \
fromdate=datetime(2018, 6, 15),\
todate=datetime(2021, 3, 17),\
reverse = False)
####
# create a Cerebro entity
cerebro = bt.Cerebro(stdstats = False)
### Set up the backtest
# Add the Data Feed to Cerebro
cerebro.adddata(data)
# Set our desired cash start
cerebro.broker.setcash(100000.0)
# Set the commission - 0.1% ... divide by 100 to remove the %
cerebro.broker.setcommission(commission=0.001)
#Add the sizer. We plan to go 'all in' every time
cerebro.addsizer(bt.sizers.AllInSizerInt)
#Add the strategy
cerebro.addstrategy(Abs_momentum)
#Add the observers to the plot
cerebro.addobserver(bt.observers.BuySell)
cerebro.addobserver(bt.observers.Value)
#Write to a csv file
cerebro.addwriter(bt.WriterFile, out = (abspath + logfile), csv=True,\ data(csv) = False)
# Print out the starting conditions
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Run over everything
cerebro.run()
# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
###
### Plot the results
cerebro.plot(iplot=True, volume=False)
###
''''
Here is the log:
>Starting Portfolio Value: 100000.00
>2019-06-18, BUY CREATED --- Price: 282.95
>2019-06-19, Order Canceled/Margin/Rejected
>2019-06-19, BUY CREATED --- Price: 283.58
>2019-06-20, Order Canceled/Margin/Rejected
>2019-06-20, BUY CREATED --- Price: 286.29
>2019-06-21, Order Canceled/Margin/Rejected
>2019-06-21, BUY CREATED --- Price: 285.88
>2019-06-24, BUY EXECUTED, Price: 286.10, Cost: 99848.90, Comm 99.85
>2020-03-12, SELL CREATED --- Price: 243.56
>2020-03-13, SELL EXECUTED, Price: 258.27, Cost: 99848.90, Comm 90.14
>2020-03-13, OPERATION PROFIT, GROSS -9712.67, NET -9902.66
>2020-04-17, BUY CREATED --- Price: 283.04
>2020-04-20, BUY EXECUTED, Price: 279.06, Cost: 88741.08, Comm 88.74
>2020-04-20, SELL CREATED --- Price: 278.05
>2020-04-21, SELL EXECUTED, Price: 273.25, Cost: 88741.08, Comm 86.89
>2020-04-21, OPERATION PROFIT, GROSS -1847.58, NET -2023.21
>2020-04-29, BUY CREATED --- Price: 289.53
>2020-04-30, Order Canceled/Margin/Rejected
>2020-04-30, BUY CREATED --- Price: 286.83
>2020-05-01, Order Canceled/Margin/Rejected
>2020-05-06, BUY CREATED --- Price: 280.68
>2020-05-07, Order Canceled/Margin/Rejected
>2020-05-07, BUY CREATED --- Price: 284.07
>2020-05-08, Order Canceled/Margin/Rejected
>2020-05-08, BUY CREATED --- Price: 288.77
>2020-05-11, BUY EXECUTED, Price: 286.69, Cost: 87153.76, Comm 87.15
>Final Portfolio Value: 121189.86
The reason your adjustment from 100% size trade to 95% size trade corrected the problem is that trying to by all in 100% on a portfolio will always result in some margins along the way . This can be seen here in your logs:
>2019-06-19, Order Canceled/Margin/Rejected
The problem is you are calculating the number of shares to trade off the previous close. If the market price gaps up on the next bar, you won't have enough cash to buy. There is an option called cheat-on-open that allows a peak at the next open price to permit sizing of the shares. This helps.
But in reality, it's best to trade below 100%.

IF/ELSE Control flow in Python to work out price of courier service from 4 choices

I cannot seem to understand how to use if/else in the following question:
You need to design a program for a courier company to calculate the cost of sending a parcel.
Ask the user to enter the price of the package they would like to purchase.
Ask the user to enter the total distance of the delivery in kilometers.
Now, add on the delivery costs to get the final cost of the product. There are four categories to factor in when determining a parcel’s final cost, each with two options based on the customer’s delivery preferences. (Use an if else statement based on the choice they make)
Delivery via air ($0.36 per km) or via freight ($0.25 per km)
Full insurance ($50.00) or limited insurance ($25.00)
Gift option ($15.00) or not ($0.00)
Priority delivery ($100.00) or standard delivery ($20.00)
Write code to work out the total cost of the package based on the options
selected in each category.
#Mohseen Ramjan
I used some of the original code, but simplified it a bit.
I am no expert, and I'm sure even this code can be improved a lot.
===== NOTE: our currency is Rand, thus the use of the 'R' =====
But maybe you'll understand this a bit better:
main_product_price = int(float(input("""Please enter the price of the package you would like to purchase:
(Only use numbers, do not inlcude 'R')\n""")))
total_distance = int(float(input("\nPlease enter the total distance of the delivery in Kilometers:\n")))
print ("\nNow please choose your shipping preferences;")
print ("\nWould you prefere Air at R0.36 per km, or Freight at R0.25 per km?")
freight_choise = input("Enter: 'Air' or 'Freight'\n")
cost_per_distance = 0
if freight_choise in ['Freight']:
cost_per_distance = 0.25
elif freight_choise in ['Air']:
cost_per_distance = 0.36
print ("\nWould you prefere Full insurance (R50.00), or Limited insurance (R25.00)?")
insurance_choise = input("Enter: 'Full' or 'Limited'?\n")
insurance_cost = 0
if insurance_choise in ['Full']:
insurance_cost = 50
elif insurance_choise in ['Limited']:
insurance_cost = 25
print ("\nWould you like to add a Gift for R15.00?")
gift_choise = input("Enter: 'Yes please' or 'No thanks'\n")
gift_cost = 0
if gift_choise in ['Yes please']:
gift_cost = 15
elif gift_choise in ['No thanks']:
gift_cost = 0
print ("\nWould you prefere Priority delivery for R100.00, or Standard delivery for R20.00?")
delivery_choise = input("Enter: 'Priority' or 'Standard'\n")
priority_or_standard_delivery = 0
if delivery_choise in ['Priority']:
priority_or_standard_delivery = 100
elif delivery_choise in ['Standard']:
priority_or_standard_delivery = 20
total_cost = main_product_price + total_distance*cost_per_distance + insurance_cost + gift_cost + priority_or_standard_delivery
print (f"""\nThis is your Total cost:
R{total_cost}""")
# Courier cost of delivering parcel
# You can and should add your own assertions and checks if the user input is valid
# I used a list instead of '==' so that you can expand the response options
# There are many other ways to do it, this is just my quick and dirty method
# But I suppose you could iterate from here
def user_input():
price_of_package = float(input('Input price of package.\n'))
total_distance = float(input('Input total distance in km\n'))
freight_or_air = input('Input freight or air delivery?\n').lower()
full_or_limited_insurance = input('Input full or limited insurance?\n').lower()
gift_or_not = input('Is this a gift?\n').lower()
priority_or_standard = input('Is this priority or standard delivery?\n').lower()
cost_per_distance = 0
if freight_or_air in ['freight']:
cost_per_distance = 0.25
elif freight_or_air in ['air']:
cost_per_distance = 0.36
cost_of_insurance = 0
if full_or_limited_insurance in ['full']:
cost_of_insurance = 50.00
elif full_or_limited_insurance in ['limited']:
cost_of_insurance = 25.00
cost_of_gift = 0
if gift_or_not in ['yes']:
cost_of_gift = 15
cost_of_delivery = 0
if priority_or_standard in ['priority']:
cost_of_delivery = 100
elif priority_or_standard in ['standard']:
cost_of_delivery = 20
print (f'\nThe user has specified that\n\
price of package: {price_of_package}\n\
total distance: {total_distance}\n\
freight or air: {freight_or_air}\n\
cost per distance {cost_per_distance}\n\
type of insurance: {full_or_limited_insurance}\n\
cost of insurance: {cost_per_distance}\n\
if it is a gift: {gift_or_not}\n\
cost of gift: {cost_of_gift}\n\
type of delivery: {priority_or_standard}\n\
cost of delivery: {cost_of_delivery}.')
return price_of_package, total_distance, cost_per_distance,\
cost_of_insurance, cost_of_gift, cost_of_delivery
def total_cost():
price_of_package, total_distance, cost_per_distance,\
cost_of_insurance, cost_of_gift, cost_of_delivery = user_input()
total_cost = price_of_package + total_distance*cost_per_distance +\
cost_of_insurance + cost_of_gift + cost_of_delivery
print (f'\nThe total cost is {total_cost}.')
return total_cost

How to get trade history from Poloniex about BTC to USD in Python?

I would like to get whole trade history from Poloniex about BTC to USD in Python.
I have entered my key and secret.
I have got the code like below:
import urllib
import urllib2
import json
import time
import hmac,hashlib
def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
return time.mktime(time.strptime(datestr, format))
class poloniex:
def __init__(self, APIKey, Secret):
self.APIKey = APIKey
self.Secret = Secret
def post_process(self, before):
after = before
# Add timestamps if there isnt one but is a datetime
if('return' in after):
if(isinstance(after['return'], list)):
for x in xrange(0, len(after['return'])):
if(isinstance(after['return'][x], dict)):
if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]):
after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime']))
return after
def api_query(self, command, req={}):
if(command == "returnTicker" or command == "return24Volume"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
return json.loads(ret.read())
elif(command == "returnOrderBook"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif(command == "returnMarketTradeHistory"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
else:
req['command'] = command
req['nonce'] = int(time.time()*1000)
post_data = urllib.urlencode(req)
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': self.APIKey
}
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def returnTicker(self):
return self.api_query("returnTicker")
def return24Volume(self):
return self.api_query("return24Volume")
def returnOrderBook (self, currencyPair):
return self.api_query("returnOrderBook", {'currencyPair': currencyPair})
def returnMarketTradeHistory (self, currencyPair):
return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair})
# Returns all of your balances.
# Outputs:
# {"BTC":"0.59098578","LTC":"3.31117268", ... }
def returnBalances(self):
return self.api_query('returnBalances')
# Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
# Inputs:
# currencyPair The currency pair e.g. "BTC_XCP"
# Outputs:
# orderNumber The order number
# type sell or buy
# rate Price the order is selling or buying at
# Amount Quantity of order
# total Total value of order (price * quantity)
def returnOpenOrders(self,currencyPair):
return self.api_query('returnOpenOrders',{"currencyPair":currencyPair})
# Returns your trade history for a given market, specified by the "currencyPair" POST parameter
# Inputs:
# currencyPair The currency pair e.g. "BTC_XCP"
# Outputs:
# date Date in the form: "2014-02-19 03:44:59"
# rate Price the order is selling or buying at
# amount Quantity of order
# total Total value of order (price * quantity)
# type sell or buy
def returnTradeHistory(self,currencyPair):
return self.api_query('returnTradeHistory',{"currencyPair":currencyPair})
# Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
# Inputs:
# currencyPair The curreny pair
# rate price the order is buying at
# amount Amount of coins to buy
# Outputs:
# orderNumber The order number
def buy(self,currencyPair,rate,amount):
return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
# Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
# Inputs:
# currencyPair The curreny pair
# rate price the order is selling at
# amount Amount of coins to sell
# Outputs:
# orderNumber The order number
def sell(self,currencyPair,rate,amount):
return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount})
# Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber".
# Inputs:
# currencyPair The curreny pair
# orderNumber The order number to cancel
# Outputs:
# succes 1 or 0
def cancel(self,currencyPair,orderNumber):
return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber})
# Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."}
# Inputs:
# currency The currency to withdraw
# amount The amount of this coin to withdraw
# address The withdrawal address
# Outputs:
# response Text containing message about the withdrawal
def withdraw(self, currency, amount, address):
return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
polo = poloniex('my_key', 'my_security')
print(polo.returnTradeHistory('BTC_ETH'))
#print(polo.returnTradeHistory('BTC_USDT))
I have used method like:
print(polo.returnTradeHistory('BTC_ETH'))
but I get empty array [], I don't know why?
Could you also tell me how can I get this trade history and get info about BTC to USD, because something like BTC_USD hasn't worked.
Make sure you can open the returnTradeHistory-call with your browser (https://poloniex.com/public?command=returnTradeHistory&currencyPair=BTC_ETH)
If your browser shows you the recent trade history, everything is fine. If you need to complete a captcha, your IP address is blocked/marked. If you need to complete the captcha everytime opening the site, you need to contact support.
Poloniex does not support exchanging cryptocurrencies to fiat money, therefore you are not able to find a direct exchange for something like BTC_USD. Youi'll need to get the exchange ratio from another site.
The function your are using (returnTradeHistory) returns your personal history. If you haven't traded anything yet, it will be empty. If you want to get the global trade history, you need to use returnMarketTradeHistory

Categories

Resources