FTX Sample Code
FTX is a cryptocurrency derivatives exchange.
You can find the REST API docs here, websocket API docs here, and FIX docs here.
You can create API keys on your profile page.
FTX is integrated with CCXT here:
FTX Sample Code
Home Page: https://ftx.com
FTX is a cryptocurrency derivatives exchange.
You can find the REST API docs here, websocket API docs here, and FIX docs here.
You can create API keys on your profile page.
FTX is integrated with CCXT here:
Hi, if I make a request to get the borrow rates for sport margin, I get the following response:
{"success":false,"error":"Not logged in"}
If I'm logged in, and go to: https://ftx.com/api/spot_margin/borrow_rates in my browser, I get the same message.
If I go "back" then "forward" in the browser, I get the data.
can someone help?
Thanks.
With /positions endpoint, an optional parameter named showAvgPrice is usable. What is it for?
I'm able to succesfully read information about my wallet, so I know i'm specifying authentication info correctly. But whenever I attempt to create an order I receive this response:
`{"error":"Not logged in","success":false}'
Any suggestions? I took this straight from your documentation.
My simple class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
namespace FTX
{
public class Runner
{
public string PublicKey = "pub_key";
public string PrivateKey = "priv_key";
public string BaseUrl = "https://ftx.com";
public void Run()
{
GetWallet();
var method = HttpMethod.Post;
string endpoint = $"api/orders";
var request = new HttpRequestMessage(method, $"{BaseUrl}/{endpoint}");
var nonce = Util.GetMillisecondsFromEpochStart();
var postBody = "{\"market\": \"XRP-PERP\", \"side\": \"sell\", \"type\": \"limit\", \"size\": 31431.0}";
request.Headers.Add("FTX-KEY", PublicKey);
request.Headers.Add("FTX-SIGN", signatureFromProject(nonce, method.ToString().ToUpper(), endpoint, postBody));
request.Headers.Add("FTX-TS", nonce.ToString());
request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
HttpResponseMessage response = client.SendAsync(request).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(apiResponse);
}
}
public void GetWallet()
{
var method = HttpMethod.Get;
string endpoint = $"api/wallet/coins";
var request = new HttpRequestMessage(method, $"{BaseUrl}/{endpoint}");
var nonce = Util.GetMillisecondsFromEpochStart();
request.Headers.Add("FTX-KEY", PublicKey);
request.Headers.Add("FTX-SIGN", SignatureFromDocumentation(nonce, method.ToString().ToUpper(), endpoint, "")); ;
request.Headers.Add("FTX-TS", nonce.ToString());
using (var client = new HttpClient())
{
HttpResponseMessage response = client.SendAsync(request).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(apiResponse);
}
}
private string SignatureFromDocumentation(long nonce, string method, string endpoint, string requestBody)
{
var hashMaker = new HMACSHA256(Encoding.UTF8.GetBytes(PrivateKey));
var signaturePayload = $"{nonce}{method}{endpoint}";
var hash = hashMaker.ComputeHash(Encoding.UTF8.GetBytes(signaturePayload));
var hashString = BitConverter.ToString(hash).Replace("-", string.Empty);
return hashString.ToLower();
}
private string signatureFromProject(long nonce, string method, string endpoint, string requestBody)
{
var signature = $"{nonce}{method}{endpoint}{requestBody}";
var hashMaker = new HMACSHA256(Encoding.UTF8.GetBytes(PrivateKey));
var hash = hashMaker.ComputeHash(Encoding.UTF8.GetBytes(signature));
var hashStringBase64 = BitConverter.ToString(hash).Replace("-", string.Empty);
return hashStringBase64.ToLower();
}
}
}
Hi all,
I am trying to send a limit order using the following code:
import socket
from urllib.parse import urlparse
import ssl
import datetime
import simplefix
from simplefix import FixMessage, FixParser
from simplefix.message import fix_val
import hmac
from uuid import uuid4
from decimal import Decimal
url = 'tcp+ssl://fix.ftx.com:4363'
parsed_url = urlparse(url)
sock = socket.create_connection((parsed_url.hostname, parsed_url.port))
context = ssl.create_default_context()
sock = context.wrap_socket(sock, server_hostname=parsed_url.hostname)
next_seq_num = 1
client_id = <API KEY>
target_id = 'FTX'
secret = <API SECRET>
send_time_str = datetime.datetime.utcnow().strftime('%Y%m%d-%H:%M:%S')
### Order parameters
symbol = "BTC/USDT"
side = "sell"
price = Decimal(40000)
size = Decimal(0.0001)
values = {
# simplefix.TAG_SENDING_TIME: send_time_str, ### flag 1
simplefix.TAG_MSGTYPE: simplefix.MSGTYPE_NEW_ORDER_SINGLE,
simplefix.TAG_HANDLINST: simplefix.HANDLINST_AUTO_PRIVATE,
simplefix.TAG_CLORDID: uuid4() ,
simplefix.TAG_SYMBOL: symbol,
simplefix.TAG_SIDE: (simplefix.SIDE_BUY if side == 'buy'
else simplefix.SIDE_SELL),
simplefix.TAG_PRICE: price,
simplefix.TAG_ORDERQTY: size,
simplefix.TAG_ORDTYPE: simplefix.ORDTYPE_LIMIT,
simplefix.TAG_TIMEINFORCE: simplefix.TIMEINFORCE_GOOD_TILL_CANCEL ,
**({}),
}
msg = FixMessage()
msg.append_pair(simplefix.TAG_BEGINSTRING, 'FIX.4.2')
msg.append_pair(simplefix.TAG_SENDER_COMPID, client_id)
msg.append_pair(simplefix.TAG_TARGET_COMPID, target_id)
msg.append_pair(simplefix.TAG_MSGSEQNUM, next_seq_num)
# msg.append_utc_timestamp(simplefix.TAG_SENDING_TIME) ### flag 2
for key, value in values.items():
if isinstance(value, datetime.datetime):
msg.append_utc_timestamp(key, value)
else:
msg.append_pair(key, value)
# if not msg.get(simplefix.TAG_SENDING_TIME): ### flag 3
# msg.append_utc_timestamp(simplefix.TAG_SENDING_TIME) ### flag 3
encoded = msg.encode()
sock.sendall(encoded)
parser = FixParser()
buf = sock.recv(4096)
parser.append_buffer(buf)
msg = parser.get_message()
print(msg)
And the message I receive is the following:
8=FIX.4.2|9=134|35=3|49=FTX|56=<API KEY>|34=1|52=20210629-09:42:02.277|45=1|372=H|58=Missing sending time|373=1|371=52|10=228
If then I try to add sending time by uncommenting any one string from the strings with flags in the code sample above, I obtain None as the msg
value and b'' as buf
value.
The same thing happens when I try to request order status for some of my orders.
I have no idea how to add sending time to the request values correctly. Hope for you help!
Thank you in advanced.
https://github.com/hahaharsh7/ftx-issues
check this repository for a single python file , which is debugged and can be run in a cell of jupyter notebook or anywhere without any errors
"""
To send a Stop Market order, set type='stop' and supply a trigger_price
To send a Stop Limit order, also supply a limit_price
To send a Take Profit Market order, set type='trailing_stop' and supply a trigger_price
To send a Trailing Stop order, set type='trailing_stop' and supply a trail_value
"""
This is commented in the client.py. Every way i try to post a take profit or trailing stop or even a stop (as a take_profit value) i receive an error, usually saying the trigger price is too high, which is not possible when putting a take profit on a long position.
Has anyone else had similar issues with placing orders?
Appreciate any suggestions. Thanks
Hello! I was trying to implement the get order status endpoint in the client.py.
According to the REST API documentation it sounds simple enough right? Just add a method:
def get_order_status(self, order_id: str) -> dict:
return self._get(f'/orders/{order_id}')
But when I test it I get Exception: Not logged in on the _process_response method
Does anyone have any idea how to fix it?
In general the python client works very well, it's been pretty easy to extend it to include other API endpoints, it was just this one that didn't work
Thanks!
ex. I want to get USD history borrow/lending rates all the way back to 2019. Do we have APIs that support this scenario? (similar to getting history funding rate for BTC-PERP)
Hello,
I noticed that there is no C# API in this repository. Are you seeking the creation of a REST and/or Websocket FTX C# API client?
I have experience writing a C# API client for Monero (the cryptocurrency), which can be found on the Monero project's official website here. You can find the original source-code here.
Please let me know if you are interested. It's worth mentioning that, while the C# JSON-RPC client I wrote for Monero was a passion-project, I'd like to be compensasted for working on and delivering an FTX C# API client.
Cheers,
Agorist-Action
I've downloaded cmake followed through README.md instructions; however I'm confused what the Buid make means and how do I run this on VS2019. so far when I try to run rest_test.cc, the compiler returns a bunch of "command line error D8021: invalid numeric argument '/Werror'" for many of the flags.
`def _handle_orderbook_message(self, message: Dict) -> None:
market = message['market']
subscription = { 'op': 'subscribe', 'channel': 'orderbook', 'market': market }
if subscription not in self._subscriptions:
return
data = message['data']
if data['action'] == 'partial':
self._reset_orderbook(market)
for side in {'bids', 'asks'}:
book = self._orderbooks[market][side]
for price, size in data[side]:
if size:
book[price] = size
else:
del book[price]
self._orderbook_timestamps[market] = data['time']
checksum = data['checksum']
orderbook = self.get_orderbook(market)
checksum_data = [
':'.join([f'{float(order[0])}:{float(order[1])}' for order in (bid, offer) if order]) for (bid, offer) in zip_longest(orderbook['bids'][:100], orderbook['asks'][:100])]
computed_result = int(zlib.crc32(':'.join(checksum_data).encode()))
print(checksum, computed_result, 'verification===')
if computed_result != checksum:
self._last_received_orderbook_data_at = 0
self._reset_orderbook(market)
self._unsubscribe({'market': market, 'channel': 'orderbook'})
self._subscribe({'market': market, 'channel': 'orderbook'})
else:
self._orderbook_update_events[market].set()
self._orderbook_update_events[market].clear()`
Sometimes ws updates for orders/fills are not arriving , especially in high volatility times.
I have tried lots of time with the below code but it prints nothing from get_fills and get_orders websocket (but public channel orderbook have message coming back). I have using the FtxWebsocketClient with api_key and api_secret, so i guess it should be authenticated correctly, liked what i got in Res verson.
May I know what I am missing in order to have fills and orders even i have put lots of fills and orders in the Ftx account?
Please help. Many thanks!!!!
import time
from FTX_websocket import FtxWebsocketClient
'''
#Update init with the api_key and api_secret
class FtxWebsocketClient(WebsocketManager):
_ENDPOINT = 'wss://ftx.com/ws/'
def __init__(self, api_key=None, api_secret=None) -> None:
super().__init__()
self._trades: DefaultDict[str, Deque] = defaultdict(lambda: deque([], maxlen=10000))
self._fills: Deque = deque([], maxlen=10000)
self._api_key = api_key # TODO: Place your API key here
self._api_secret = api_secret # TODO: Place your API secret here
self._orderbook_update_events: DefaultDict[str, Event] = defaultdict(Event)
self._reset_data()
'''
#### Websocket client ####
api_key = os.environ.get('ftx_api')
api_secret = os.environ.get('ftx_secret')
time.sleep(2)
ws = FtxWebsocketClient(api_key=api_key, api_secret=api_secret)
ws.connect()
for i in range(1, 10):
print(ws.get_orderbook('BTC-PERP'))
print(ws.get_fills())
print(ws.get_orders())
time.sleep(1)
function _process_response in the rest has wrongly been indented to the right.
Hello, in the official FTX REST API documentation, the description is blank for some API calls:
The documentation is also missing for some of the options-related endpoints.
Unable to pass clientId for trigger orders. This feature is essential to know when a stop-loss order gets triggered.
Requirement:
I have a requirement to place stop-loss orders and track them using "fills" or "orders" event, using websocket API. The challenge is that we cannot pass clientid for trigger orders. I tried using the order id returned by the REST API when a stop-loss order is placed, but even that doesn't match with the order id returned in the "fills" or "orders" event.
The current websocket api doesn't have the capability to monitor account balances real time. Please add this capability as every other crypto exchange has this feature. Given that the REST api is limited to 30 req/sec, this feature should have been available already in the socket api!
Hi
Golang FTX gives unauthorized error 401 when trying to get orders for a market : BTC-PREP
{401 Unauthorized 401 HTTP/2.0 2 0 map[Account-Id:[None] Alt-Svc:[h3=":443"; ma=86400, h3-29=":443"; ma=86400, h3-28=":443"; ma=86400, h3-27=":443"; ma=86400] Cache-Control:[private, max-age=0, no-cache] Cf-Cache-Status:[MISS] Cf-Ray:[698738e358885ffe-SEA] Content-Length:[42] Content-Type:[application/json] Date:[Sun, 03 Oct 2021 15:32:16 GMT] Expect-Ct:[max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"] Server:[cloudflare] Strict-Transport-Security:[max-age=31536000; includeSubDomains; preload] Vary:[Origin, Accept-Encoding] X-Content-Type-Options:[nosniff]] {0xc0003ca2c0} 42 [] false false map[] 0xc0003c8000 0xc0002b40b0}
orders?market=BTC-PERP...
Pls let me know what is causing the error as the api and secret keys i got from the account are right, are there anybody else who is facing this ?
how to get/post a quote_id?
I copy pasted the client and websocket_manager.py files and imported them into my current project.
However, upon running I encounter:
Exception has occurred: ModuleNotFoundError
No module named 'gevent'
File "/Users/gladosiii/Developer/decentrabank/basisbot/ftx/client.py", line 9, in
from gevent.event import Event
File "/Users/gladosiii/Developer/decentrabank/basisbot/basis_bot/strategyManager.py", line 5, in
from ftx.client import FtxWebsocketClient
File "/Users/gladosiii/Developer/decentrabank/basisbot/runstrategy.py", line 2, in
from basis_bot.strategyManager import strategyManager
I am running MacOS and virtualenv Python 3.9.6
I am getting an invalid signature reject even though my signature follows the client.py example exactly.
import socket
from urllib.parse import urlparse
import ssl
import datetime
import simplefix
from simplefix import FixMessage, FixParser
from simplefix.message import fix_val
import hmac
url = 'tcp+ssl://fix.ftx.com:4363'
parsed_url = urlparse(url)
sock = socket.create_connection((parsed_url.hostname, parsed_url.port))
context = ssl.create_default_context()
sock = context.wrap_socket(sock, server_hostname=parsed_url.hostname)
next_seq_num = 1
client_id = <api key>
target_id = 'FTX'
secret = <api secret>
send_time_str = datetime.datetime.now().strftime('%Y%m%d-%H:%M:%S')
sign_target = b'\x01'.join([fix_val(val) for val in [
send_time_str,
simplefix.MSGTYPE_LOGON,
next_seq_num,
client_id,
target_id]])
signed = hmac.new(secret.encode(), sign_target, 'sha256').hexdigest()
values = {
simplefix.TAG_MSGTYPE: simplefix.MSGTYPE_LOGON,
simplefix.TAG_SENDING_TIME: send_time_str,
simplefix.TAG_ENCRYPTMETHOD: 0,
simplefix.TAG_HEARTBTINT: 30,
simplefix.TAG_RAWDATA: signed}
msg = FixMessage()
msg.append_pair(simplefix.TAG_BEGINSTRING, 'FIX.4.2')
msg.append_pair(simplefix.TAG_SENDER_COMPID, client_id)
msg.append_pair(simplefix.TAG_TARGET_COMPID, target_id)
msg.append_pair(simplefix.TAG_MSGSEQNUM, next_seq_num)
for key, value in values.items()
:
msg.append_pair(key, value)
encoded = msg.encode()
sock.sendall(encoded)
parser = FixParser()
buf = sock.recv(4096)
parser.append_buffer(buf)
msg = parser.get_message()
print(msg)
def getAccount():
import time, hmac
s= requests.Session()
url = "https://ftx.com/api/orders"
ts = int(time.time()*1000)
params={
"market": "DOT-PERP",
"side": "buy",
"price": 31,
"type": "limit",
"size": 0.5,
"reduceOnly": False,
"ioc": False,
"postOnly": False,
"clientId": None
}
request=requests.Request("POST",url,params=params)
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
signature = hmac.new(api_secret.encode(),signature_payload,'sha256').hexdigest()
request.headers = {'FTX-KEY':api_key,'FTX-SIGN':signature,'FTX-TS':str(ts)}
r = s.send(request.prepare())
r.json()
RESPONSE = {'success': False, 'error': 'Missing parameter market'}
pls need help, cant solve whats missing....
I tried to clone and run the repository but upon calling the RequestWithdrawalAsync function I get the following response:
"{"success":false,"error":"The browser (or proxy) sent a request that this server could not understand."}"
FIX API is very hard to implement. I had difficulties with rest and websockets, but I have been crunching on FIX API for about 2 weeks now and can't seem to figure it out. Does anyone have a bit of sample code to share with the curious? Anything just to get started would brighten up my day :)
I can't get a successful authentication using PHP. All I get is the following:
( [error] => Not logged in [success] => )
My code below. What am I doing wrong here ?
`$end_point = 'https://ftx.com/api/' . $args['end_point'];
$ts = intval(microtime(true) * 1000);
$signature = hash_hmac('sha256', $ts . 'GET' . '/' . $args['end_point'], $api_secret);
$curl = curl_init();
$headers[] = 'Accept: application/json';
$headers[] = 'FTX-KEY: ' . $api_key;
$headers[] = 'FTX-TS: ' . $ts;
$headers[] = 'FTX-SIGN: ' . $signature;
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_URL => $end_point,
]);
$resp = curl_exec($curl);
$response = json_decode($resp, true);
return $response;`
i can't figure out how to import websocket.client
without modifying the file. i have the websocket
package installed globally as a dependency for docker-compose
so i can't remove it. it seems like the import
in client.py
is looking in the global websocket
package and not the relative websocket
directory.
the best i can do is download the files to ftx/websocket and then attempt to load with this:
sys.path.insert(0, os.path.abspath('ftx'))
from ftx.websocket.client import FtxWebsocketClient
Hi,
I see in the client.py how to place a conditional order, but how to modify conditional order, (or cancel it) please ?
Regard
Hi there- there seems to be something wrong on the spot_margin/lending_history
endpoint as regards the way items are sorted. How is it possible that by changing the limit from 4 to 3, the item that is not returned anymore is the 2d one and not the 4th or 1st one?
The API does not offer any sort order parameter so I really don't see how I should query in order to get all the data points in a given time window?
Also, there are more than 5000 lending history items on my account- why would a call with limit=4
return items ranging over 5 months? Wouldn't it be normal to expect that items are returned sorted in chronological order?
Thanks in advance for your help
import ftx;
import os;
import pandas as pd
client = ftx.FtxClient(api_key=os.environ["API_KEY"], api_secret=os.environ["API_SECRET"])
def get_lending_history(limit):
result = client._get(f'spot_margin/lending_history', {"limit": limit})
print(f'*'*30)
print(f'Downloading lending history with limit={limit}')
print(pd.DataFrame(result))
print('\n\n')
for limit in [4, 3]:
get_lending_history(limit)
Returns:
******************************
Downloading lending history with limit=4
coin time size rate proceeds
0 USD 2021-05-22T04:00:00+00:00 650000.0 0.000003 2.223000
1 EUR 2021-09-20T20:00:00+00:00 47500.0 0.000023 1.084425 <-- this one will not be returned in the next call
2 USD 2021-09-20T21:00:00+00:00 850000.0 0.000005 3.884500
3 EUR 2021-09-20T21:00:00+00:00 47500.0 0.000023 1.084425
******************************
Downloading lending history with limit=3
coin time size rate proceeds
0 USD 2021-05-22T04:00:00+00:00 650000.0 0.000003 2.223000
1 USD 2021-09-20T21:00:00+00:00 850000.0 0.000005 3.884500
2 EUR 2021-09-20T21:00:00+00:00 47500.0 0.000023 1.084425
Hi, I am trying to subscribe to multiple futures markets orderbooks (30~), but as FTX sends live orderbook data, my cpu isn't catching up and the data is delayed. Is there some way to limit the websocket data is received? e.g. every 100ms.
I am using Python.
Many thanks.
Thanks for building this awesome library for us.
It should only take a few more minutes to tell us how to use it, add comments to explain what it's doing, and implement some tests... - then it's ready to release. (I'm specifically looking at the fix.py stuff, but the same problem is probably throughout.)
It might be worthwhile finishing it (e.g. adding "markets") and making it useful (e.g. providing any way to actually get data back out, or stop the lists growing indefinitely).
Hi,
I try to use client.py on Ubuntu and Xubuntu 20.04, with Python3 (.8)
As I cant create a curl to post new order FTX API, and allways sent to client.py by the support, I try to use this script.
I don't know Python and include it in PERL with Inline::Python perl module.
I verified that all require module are present (and sometime add them with pip), so now time, urllib.parse, typing, requests, hmac, ciso8601 are all available.
When I call the script for create an object
my $object = Inline::Python::Object->new('main', 'FtxClient', 'api_key=".$key."', 'api_secret=".$secret."');
I receive <main.FtxClient object at 0x7f8675f82940>
When then I call $object->get_balances(); it crash with error AttributeError: 'bytes' object has no attribute 'encode'
How to call the function ?
Regards.
def get_order_status(self, order_id: str) -> dict:
return self._get(f'/orders/{order_id}')
/account etc. work ย
Not working: /orders/{order_id}
raise Exception(data['error'])
Exception: Not logged in
I am setting up the c++ code for ftx. And I am using the c++ code from the GitHub.
I am using my API keys. But on sending the rest API request. It says "not logged in" success : false.
And on sending login request I am getting no response?
I am using everything from GitHub c++ code except keys.
I get this error
{"error":"Not logged in","success":false}
Whenever there's a problem with the API key, but the same error comes whenever there is any other problem for example wrong signature, timestamp, or even endpoint.
It would be better if you could give a different error, or add error code or something for different problems so that it's easier to know where the problem comes from. If I wrongly copy the secret key, for example, there's no way I'd know that was the problem because I can't see it again once I close the dialog.
Hello,
The API documentation states that when placing a market order, the price should be NULL. However, if I pass nil into the function an error occurs.
order, _ := client.PlaceOrder("BTC-PERP", "sell", nil, "market", 0.5, false, false, true)
The error is "cannot use nil (untyped nil value) as float64 value in argument to client.PlaceOrder"
Where the function is
func (client *FtxClient) PlaceOrder(market string, side string, price float64,
_type string, size float64, reduceOnly bool, ioc bool, postOnly bool) (NewOrderResponse, error)
Hi guys! when subscribing to your Websockets, some of the data is coming across in Scientific Notation (9.669E-05 instead of 0.00009669). Since we are converting this information to decimal, it is causing an issue with the checksum. We are not storing the original partial, so when the updates come in, we do not know how the original data was formatted. Can you remove the scientific notation please? This is happening with SUSHI/BTC quite a lot and ETH/BTC occasionally. Thanks!
I think self
should be the first argument in this get_all_trades
function https://github.com/ftexchange/ftx/blob/master/rest/client.py#L163.
After making the above change, I don't think .json
works on this line either https://github.com/ftexchange/ftx/blob/master/rest/client.py#L171, since you'll get error:
File "/Users/me/ftx/rest/client.py", line 170, in get_all_trades
'start_time': start_time,
AttributeError: 'list' object has no attribute 'json'
The WS subscription seems to recycle daily on python - is there a known fix that needs to be applied?
Hey,
My question is exactly the title. I starting a project, but I cannot seem to figure out how to install this library. I cannot find any instructions. How do I install the ./ftx library?
import (
"./ftx"
"fmt"
)
Hi all,
I've been looking to get the FIX client sample code working using the following python script:
from uuid import uuid4
from ftx.fix.client import FixClient
# To start up:
api_key = 'MY_KEY_HERE'
secret = 'MY_SECRET_HERE'
print('Connecting FIX client...')
client = FixClient('tcp+ssl://fix.ftx.com:4363', client_id=api_key, target_id='FTX')
print('Sending logon...')
client.login(secret)
if client._have_connected:
print('Connection established...')
else:
print('Connection failed...')
exit()
order_id = uuid4()
print('Sending order id = ' + format(order_id) + '...')
client.send_order(
symbol = 'ETHBULL/USDT',
side = 'buy',
price = '180.5',
size = '0.001',
client_order_id = order_id,
ioc = False
)
print('Requesting order status...')
client.request_order_status(order_id)
print('Done...')
The results I get when I run the above are as follows:
Connecting FIX client...
Sending logon...
send b'8=FIX.4.2|9=162|35=A|49=<MY_KEY_HERE>|56=FTX|34=1|52=20200517-08:43:15|98=0|108=30|96=f8df9b105bd520116441b45bec6ec24318847c48690ba40c008c57cb44096367|10=217|'
Connection established...
Sending order id = 580346c1-0a58-4865-9970-b958f0e08187...
send b'8=FIX.4.2|9=180|35=D|49=<MY_KEY_HERE>|56=FTX|34=2|21=1|11=580346c1-0a58-4865-9970-b958f0e08187|55=ETHBULL/USDT|54=1|44=180.5|38=0.001|40=2|59=1|52=20200517-12:44:05.842|10=235|'
Requesting order status...
send b'8=FIX.4.2|9=126|35=H|49=<MY_KEY_HERE>|56=FTX|34=3|37=580346c1-0a58-4865-9970-b958f0e08187|52=20200517-12:44:05.844|10=062|'
Done...
Sending logon hangs there for some time (approx 30 seconds) and then the program continues... It looks to me like the logon attempt is timing out, however the client does report it has a connection.
The send order call does not result in an order being placed.
Obviously I've edited the above to remove my key and secret from the code and results, I have left the encrypted signature in the secret as-is to show the results. I've not changed anything in the sample client.py.
I also tried setting up using QuickFIX and got to the point that it is sending the logon message to the server and does not get a logon response back. So tend to think it is a networking issue but can't find any info on what needs to be setup at this level to allow this to work.
I've tried telneting to the server and it does allow me to connect, so I am able to at least reach the server from my machine.
I've been doing my development in a "Ubuntu on Windows" environment, but I also attempted to deploy this on a Ubuntu 20,04 server as well which is on my same network. Results are the same.
I am unsure what is wrong at this time. Do I need to open any ports in my firewall to allow the server to connect back to me?
Any help / insight would be appreciated.
According to the docs (https://docs.ftx.com/?python#funding-payments) funding_payments
supports pagination.
However, hitting the endpoint returns:
Exception: Request failed for https://ftx.com returned code 400. Truncated server response: {"success":false,"error":"Invalid parameter start_time"} (use muteHttpExceptions option to examine full response)
Could you please confirm if pagination is supported? If so, how do I return more than 100 records?
Currently if you use the client just for endpoints that don't need authentication, such as the list_markets, you will need to provide a real or fake api_key otherwise it will give an error as it will try to encode a None value which is not possible.
e.g.
Traceback (most recent call last):
File "test.py", line 9, in <module>
print(ftx.list_markets())
File "C:\Users\Andre\Documents\Code\test\ftx_client\client.py", line 63, in list_markets
return self._get('markets')
File "C:\Users\Andre\Documents\Code\test\ftx_client\client.py", line 21, in _get
return self._request('GET', path, params=params)
File "C:\Users\Andre\Documents\Code\test\ftx_client\client.py", line 31, in _request
self._sign_request(request)
File "C:\Users\Andre\Documents\Code\test\ftx_client\client.py", line 41, in _sign_request
signature = hmac.new(self._api_secret.encode(), signature_payload, 'sha256').hexdigest()
AttributeError: 'NoneType' object has no attribute 'encode'
The workaround is quite simple as just assigning a random api_key and api_secret will solve this
FtxClient(
api_key="0",
api_secret="0"
)
However, this could also be avoided if unauthenticated endpoints didn't call _sign_request()
as this shouldn't be needed for these.
Thank you.
I am missing the python dependencies to be able to run the example within few minutes. Unfortunately, I had to look myself and doing try and error. It would be good, if the documentation would be extended; also with real world examples.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.