ccxt / ccxt

A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges
https://docs.ccxt.com
MIT License
32.44k stars 7.46k forks source link

Couldn't fetch order/trade history. got BadRequest errorr code 1104 Not all sent parameters were read; #9281

Closed popomomo closed 3 years ago

popomomo commented 3 years ago

Hi, I'm trying to fetch latest order/trade history query by 'side' parameter (buy or sell). As you can see in code below I always get a BadRequest error " binance {"code":-1104,"msg":"Not all sent parameters were read; read '5' parameter(s) but was sent '6'."} " if I use parameter with 'side'. But if I change it to 'type' with 'market/limit' it work fine.

Test and trying with fetchOrders, fetchClosedOrders, fetchMyTrades all of these got same error

import ccxt

# API Key to connect to exchange
apiKey = "xxxxxxx"
secret = "xxxxxxx" 
market_sm = "spot" # Choose Spot or Margin

# Connect to exchange
exchange = ccxt.binance  ({
    'apiKey' : apiKey ,'secret' : secret ,'enableRateLimit': True, "options": {"defaultType": market_sm}
  })

if (exchange.has['fetchOrders']):
    symbol = 'DOGE/USDT'
    since = None
    limit = 1
    params = {
      'side': 'buy'
    }
    exchange.verbose = True
    exchange.fetchOrders (symbol, since, limit, params)
Request: GET https://api.binance.com/api/v3/exchangeInfo {'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate'} None

Response: GET https://api.binance.com/api/v3/exchangeInfo 200 {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '45497', 'Connection': 'keep-alive', 'Date': 'Fri, 28 May 2021 07:16:42 GMT', 'Server': 'nginx', 'x-mbx-uuid': '566daaf2-ec35-420a-982f-59a779a94e78', 'x-mbx-used-weight': '30', 'x-mbx-used-weight-1m': '30', 'content-encoding': 'gzip', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', 'X-Cache': 'Miss from cloudfront', 'Via': '1.1 1a70506ef88d5d28a7d133d7ccac4682.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'HKG62-C2', 'X-Amz-Cf-Id': 'oRjn3aGF34qy16gGS6KzKR-7UaxHb2nAOKsariAyzLoSMRwZavw8yw=='} {"timezone":"UTC","serverTime":1622186202465,"rateLimits":[{"rateLimitType":"REQUEST_WEIGHT","interval":"MINUTE","intervalNum":1,"limit":1200},{"rateLimitType":"ORDERS","interval":"SECOND","intervalNum":10,"limit":50},{"rateLimitType":"ORDERS","interval":"DAY","intervalNum":1,"limit":160000}],"exchangeFilters":[],"symbols":[{"symbol":"ETHBTC","status":"TRADING","baseAsset":"ETH","baseAssetPrecision":8,"quoteAsset":"BTC","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":true,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"922327.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.00100000","maxQty":"100000.00000000","stepSize":"0.00100000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"1121.95997708","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT","MARGIN"]},{"symbol":"LTCBTC","status":"TRADING","baseAsset":"LTC","baseAssetPrecision":8,"quoteAsset":"BTC","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":true,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"100000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"100000.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"8701.89141666","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT","MARGIN"]},{"symbol":"BNBBTC","status":"TRADING","baseAsset":"BNB","baseAssetPrecision":8,"quoteAsset":"BTC","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":true,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"100000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"100000.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"13192.41565972","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT","MARGIN"]},{"symbol":"NEOBTC","status":"TRADING","baseAsset":"NEO","baseAssetPrecision":8,"quoteAsset":"BTC","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":true,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"100000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"100000.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"6615.24294444","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT","MARGIN"]},{"symbol":"QTUMETH","status":"TRADING","baseAsset":"QTUM","baseAssetPrecision":8,"quoteAsset":"ETH","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":false,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"1000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"90000000.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00500000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"4637.18602777","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT"]},{"symbol":"EOSETH","status":"TRADING","baseAsset":"EOS","baseAssetPrecision":8,"quoteAsset":"ETH","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":true,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"1000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"92141578.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00500000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"31649.09124305","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT","MARGIN"]},{"symbol":"SNTETH","status":"TRADING","baseAsset":"SNT","baseAssetPrecision":8,"quoteAsset":"ETH","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":false,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000001","maxPrice":"1000.00000000","tickSize":"0.00000001"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"1.00000000","maxQty":"90000000.00000000","stepSize":"1.00000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00500000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"271979.53958333","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT"]},{"symbol":"BNTETH","status":"TRADING","baseAsset":"BNT","baseAssetPrecision":8,"quoteAsset":"ETH","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":false,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"1000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"92141578.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00500000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"4472.47371527","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT"]},{"symbol":"BCCBTC","status":"BREAK","baseAsset":"BCC","baseAssetPrecision":8,"quoteAsset":"BTC","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":false,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"1000.00000000","tickSize":"0.00000100"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.00100000","maxQty":"92141578.00000000","stepSize":"0.00100000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT"]},{"symbol":"GASBTC","status":"TRADING","baseAsset":"GAS","baseAssetPrecision":8,"quoteAsset":"BTC","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":false,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00000010","maxPrice":"1000.00000000","tickSize":"0.00000010"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.01000000","maxQty":"90000000.00000000","stepSize":"0.01000000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"19327.94809027","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT"]},{"symbol":"BNBETH","status":"TRADING","baseAsset":"BNB","baseAssetPrecision":8,"quoteAsset":"ETH","quotePrecision":8,"quoteAssetPrecision":8,"baseCommissionPrecision":8,"quoteCommissionPrecision":8,"orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"],"icebergAllowed":true,"ocoAllowed":true,"quoteOrderQtyMarketAllowed":true,"isSpotTradingAllowed":true,"isMarginTradingAllowed":true,"filters":[{"filterType":"PRICE_FILTER","minPrice":"0.00001000","maxPrice":"1000.00000000","tickSize":"0.00001000"},{"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5},{"filterType":"LOT_SIZE","minQty":"0.00100000","maxQty":"9000000.00000000","stepSize":"0.00100000"},{"filterType":"MIN_NOTIONAL","minNotional":"0.00500000","applyToMarket":true,"avgPriceMins":5},{"filterType":"ICEBERG_PARTS","limit":10},{"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"3595.83267291","stepSize":"0.00000000"},{"filterType":"MAX_NUM_ORDERS","maxNumOrders":200},{"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5}],"permissions":["SPOT","MARGIN"]},{"symbol":"BTCUSDT","status":"TRADING","baseAsset":"BTC","baseAssetPrecision":8,"quoteAsset":"USDT","quotePrecision":8,"quoteAssetPrecision":8,"bas

Request: GET https://api.binance.com/api/v3/allOrders?timestamp=1622186202745&recvWindow=5000&symbol=DOGEUSDT&limit=1&side=BUY&signature=ca5130641ebea06362edbb0eb49d44025145b4dbc91893cdc66405bd444fa773 {'X-MBX-APIKEY': 'xxxxxxxx', 'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate'} None

Response: GET https://api.binance.com/api/v3/allOrders?timestamp=1622186202745&recvWindow=5000&symbol=DOGEUSDT&limit=1&side=BUY&signature=ca5130641ebea06362edbb0eb49d44025145b4dbc91893cdc66405bd444fa773 400 {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '97', 'Connection': 'keep-alive', 'Date': 'Fri, 28 May 2021 07:16:42 GMT', 'Server': 'nginx', 'x-mbx-uuid': '02178fea-996b-489c-a17b-88272cfb3697', 'x-mbx-used-weight': '40', 'x-mbx-used-weight-1m': '40', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 1a70506ef88d5d28a7d133d7ccac4682.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'HKG62-C2', 'X-Amz-Cf-Id': '_CW8eOqZn3HY3CVzYEu8Mz7HpoAJ9r2haL5LLW0dkiQghbrk9ypctA=='} {"code":-1104,"msg":"Not all sent parameters were read; read '5' parameter(s) but was sent '6'."}
kroitor commented 3 years ago

Hi! Binance does not support a side parameter for the fetchOrders call (https://binance-docs.github.io/apidocs/spot/en/#current-open-orders-user_data). You should not expect that any arbitrary undocumented parameter will work. Only the documented params will actually work correctly. In order to solve this, you just fetch all orders, and then filter them by their side.

import ccxt
from pprint import pprint
print('CCXT Version:', ccxt.__version__)

exchange = ccxt.binance({
    'apiKey': 'YOUR_API_KEY',
    'secret' : 'YOUR_SECRET',
})

if exchange.has['fetchOrders']:
    symbol = 'DOGE/USDT'
    try:
        orders = exchange.fetch_orders(symbol)
        side = 'buy'
        filtered_orders = [order for order in orders if order['side'] == side]
        print(len(filtered_orders), side, 'orders:')
        pprint(filtered_orders)
    except Exception as e:
        print(type(e).__name__, str(e))

We highly recommend reading the entire CCXT Manual from top to bottom – it will really save your time:

Hope that answers your question, let us know if not.

popomomo commented 3 years ago

Thanks for your fast reply!!

I just trying to use the same code to fetch a order/trade history on margin market instead of spot and it work fine. Why spot can't? haha

Anyway I will try your code that you suggest on a spot market and will let you know.

Thank you

samgermain commented 3 years ago

@popomomo I am trying to do the exact same thing, did you figure this out?

kroitor commented 3 years ago

@samgermain what have you tried already? Have you tried the snippet above?

samgermain commented 3 years ago

@kroitor

I've tried this

import ccxt 

config = {
    "api_key": "xxxxxxxxx",
    "api_secret": "xxxxxxxx"   
}

exchange_id = 'binance'
exchange_class = getattr(ccxt, exchange_id)
exchange = exchange_class({
    'apiKey': config["api_key"],
    'secret': config["api_secret"],
    'timeout': 30000,
    'enableRateLimit': True,
    "useServerTime": True, # If you get timestamp errors, synchronize to server time at startup
    # "test": True # If you want to use sandbox mode where orders are simulated
})

spot_balance = exchange.fetch_balance({'type':'spot'})
exchange.create_order(symbol='ADA/USDT', type='market', side='buy', amount=8, price=1.59, params={'leverage': 3})

it works for regular, just not for leverage

kroitor commented 3 years ago

@samgermain as far as I understand, you want to apply some leverage on futures contracts, is that correct? Also, what is your version of CCXT ?

samgermain commented 3 years ago

Not futures, just regular margin leverage. It would make sense if I also had to make a transfer to a margin account, but that's not anywhwere in the manual.

If that were the problem, I feel that the error would be Inssfficient funds" though anyway

samgermain commented 3 years ago

Versions 1.51.3

kroitor commented 3 years ago

@samgermain afaik, Binance margin API does not let you change your leverage at all. Instead, you just choose your margin mode, either cross-margin (and your max leverage is fixed to 3x in that case, this is the default) or isolated margin (and your max leverage is fixed at 10x in that case). The actual leverage will depend on how much money you borrow against your own funds.

Thus, the following should work:

import ccxt
from pprint import pprint

print('CCXT Version:', ccxt.__version__)

exchange = ccxt.binance({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
    'options': {
        'defaultType': 'margin'
    },
})

markets = exchange.load_markets()

# exchange.verbose = True  # uncomment for debugging purposes

# transfer HOW_MUCH USDT from Main account to Margin account
# you must have a transfer permission on the API key
response = exchange.transfer('USDT', HOW_MUCH, 'main', 'margin')  
pprint(response)

print('-------------------------------------------------------------------------')

margin_balance = exchange.fetch_balance()
pprint(margin_balance)

print('-------------------------------------------------------------------------')

# this will place an order to open a margin position with leverage up to 3 (crossed margin by default)
# you must have at least some USDT balance on your Margin account to place this order
order = exchange.create_order(symbol='ADA/USDT', type='market', side='buy', amount=8, price=1.59)
pprint(order)

UPD. minor edits

samgermain commented 3 years ago

So it turns out you also have to borrow in order to trade with any leverage, this is what a POST request to binance would look like in order to do that. This is what that would looks like

exchange.sapi_post_margin_loan({"asset": "USDT", "isIsolated": False, "symbol": "ADAUSDT", "amount": 27})

But this is specific to binance, is there a general method which can do this for multiple exchanges or is this the only way?

kroitor commented 3 years ago

But this is specific to binance, is there a general method which can do this for multiple exchanges or is this the only way?

This aspect of margin trading is not fully unified yet, it's a work in progress. But you can call any endpoint of any exchange using the implicit methods as described in the Manual: https://github.com/ccxt/ccxt/wiki/Manual#implicit-api. We will do our best to unify the borrowing and lending aspects asap. In the meantime it is exchange-specific.

samgermain commented 3 years ago

It looks like response = exchange.transfer('USDT', HOW_MUCH, 'main', 'margin') is always going to transfer to spot margin Is there a way to transfer to isolated margin with this method?

I see that there's a params argument

def transfer(self, code, amount, fromAccount, toAccount, params={}):

Could one of these params be isIsolated: true or something?

If not, i see that there is sapi_post_margin_isolated_transfer for binance

kroitor commented 3 years ago

Could one of these params be isIsolated: true or something?

We will look into adding something like that.

If not, i see that there is sapi_post_margin_isolated_transfer for binance

In the meantime, yes, you have to do this via the implicit API: