Última atualização em Outubro/2021
Foxbit Api
Foxbit disponibiliza acesso à plataforma através de uma aplicação WebSocket.
Rate Limit
As API’s da Foxbit têm como limite de requisições.:
rate limit: 500 requisições à cada 5 min |
Após exceder esta quantidade máxima, será enviada uma mensagem de erro informando que o limite foi excedido.
Introdução WebSocket
No exemplo descrito nesta documentação, utilizamos NodeJs e a biblioteca ws.
• Instale a última versão estável do NodeJs em: https://nodejs.org/en/download/
• Abra Terminal (Mac), Cmd (Windows) ou Bash (Linux) e entre com o comando:
Na mesma pasta que você ira salvar os scripts exemplificados abaixo
npm install ws |
ref link: https://www.npmjs.com/package/ws
GitHub – Exemplo WebSocket
Você pode fazer o download do exemplo diretamente do repositório no GitHub:
Conectando Websocket
Uso em NodeJs.:
//Instantiate Websocket module const WebSocket = require(‘ws’);
//WebSocketAPI Address //Setup WebSocket client Address |
Message Frame
Objeto em formato JSON-formatted utilizado como frame para enviar e receber dados.:
//Message Frame var messageFrame = { "m":0, //MessageType ( 0_Request/1_Reply/2_Subscribe /3_Event /4_Unsubscribe /Error ) "i":0, //Sequence Number "n":"", //Endpoint "o":"" //Payload |
String | Value |
“m” message type | integer (0 request / 1 reply / 2 subscribe to event / 3 event / 4 unsubscribe from event / 5 error) |
“i” sequence number | long integer |
“n” function name | integer |
“o” payload | string |
Payload
Objeto em formato JSON-formatted qual contém campos obrigatórios (e diferentes) para o envio de dados o endpoint acionado.
Cada endpoint tem um pacote específico, consulte o formato do payload na documentação.
//Exemplo de construção do payload para o endpoint *WebAuthenticateUser* var payload = { "UserName": "[email protected]", "Password": "jsPassword" }; |
Eventos
Defina o evento Open para tratar o retorno da conexão.:
Cada endpoint tem um pacote específico, consulte o formato do payload na documentação.
//Event Open Connection ws.on('open', function open() { console.log('Conected'); }); };
|
Defina evento para receber a mensagem do socket.:
//Event Receiving Message ws.on('message', function incoming(data) { //data contém o payload de resposta console.log(data); }); |
Defina evento para tratamento de erros.:
//Event Error Message ws.on('error', function() { console.log('Error'); }); |
Defina evento tratar a finalização da conexão.:
//Event Close Message ws.on('close', function() { console.log('Connection Closed'); }); |
Enviando Dados
Para enviar dados ao servidor você deve utilizar o objeto “messageFrame” descrito acima, utilize o campo “n” para informar o Endpoint a acionar e o campo “o” para envio do payload.
//Indique para qual endpoint será enviado. messageFrame.n = "WebAuthenticateUser" //Adicione o payload referente ao endpoint indicado messageFrame.o = JSON.stringify(payload); ws.send(JSON.stringify(messageFrame), function ack(error) { //Se encontrar erros, dispara console.log(error); });
|
Dados enviados, caso não retorne erro finaliza a mensagem no evento mensagem.
Autenticação
Abaixo seguem os endpoints para autenticação de usuário no websocket
WebAuthenticateUser (parcialmente descontinuado)
WebAuthenticateUser autentica um usuário no WebSession corrente.
Você precisa chama-lo para utilizar os métodos que requerem um SessionToken ativo.
Ao realizar a autenticação, um SessionToken é informado. Guarde-o em uma variável.
Estamos descontinuando o uso desta função via E-mail e Senha, utilize autenticação via API Key/Secret (https://foxbit.com.br/api/#AuthenticateUser).
Request:
{ "UserName": "UserName", "Password": "Password" } >>> Nota: UserName é o e-mail do usuário |
Sem sucesso na autenticação:
{ "Authenticated": false } |
Resposta quando o usuário já está logado:
{ "Authenticated": true, "SessionToken":"7d0ccf3a-ae63-44f5-a409-2301d80228bc", "UserId": 1 } >>> Nota: Voce deve guardar o SessionToken em uma variável. |
Resposta entregando um SessionToken ativo
String | Value |
Authenticated | Boolean. |
SessionToken | string. |
UserId | integer. |
AuthenticateUser
AuthenticateUser autentica um usuário no WebSession corrente utilizando APIKEY definido previamente
Você precisa chama-lo para utilizar os métodos que requerem um SessionToken ativo.
AuthenticateUser pode ser chamado sempre que for necessária uma autenticação.
Request:
{ "APIKey": "APIKey", "Signature": "Signature" "UserId": "UserId", "Nonce": "Nonce" } >>> Nota 1: Nonce = Date.now(); >>> Nota 2: Signature = crypto.HmacSHA256(nonce + userId + APIKey, APISecret).toString(crypto.enc.Hex); |
Sem sucesso na autenticação:
{ "Authenticated": false } |
String | Value |
Authenticated | Boolean. |
SessionToken | string. |
UserId | integer. |
Authenticate2FA (descontinuado)
Completa a segunda parte da autenticação em dois passos, segue abaixo os passos da autenticação 2FA.
Estamos descontinuando o uso desta função, utilize autenticação via API Key/Secret (https://foxbit.com.br/api/#AuthenticateUser).
Request:
{ "Code": "YourCode" } |
String | Value |
Code | string. Insira o código 2FA. |
Reponse:
{ "Authenticated": true, "SessionToken": "YourSessionToken" } |
O SessionToken é válido durante sessão corrente paraq o mesmo IP (IPAddress).
A sessão dura até 1 hora após a última atividade ou até ser executado endpoint LogOut.
Se a conexão for interrompida você pode reativa-la utilizando o SessionToken e chamando novament o Endpoint Authenticate2FA sem a necessidade de logar novamente ou informar o 2FA Key.
{ "SessionToken": "YourSessionToken" } |
String | Value |
Authenticated | Boolean. Autenticação com sucesso retorna True. Sem sucesso retorna False |
SessionToken | string. O SessionToken é válido para sessão atual para conexões com o mesmo endereço IP. Se a comunicação for interrompida você pode informar retornando o SessionToken ao invés de repetir o processo 2FA completo. |
Uma sessão dura até 1 hora de inatividade, ou até ser executado o LogOut.
Para enviar o SessionToken para restabelecer a conexão envie:
{ "SessionToken": "YourSessionToken" } |
Exemplo Websocket Completo
Abaixo você pode visualizar exemplo completo da aplicação em Nodejs consumindo Websocket da Foxbit.
//Instantiate Websocket module |
const WebSocket = require(‘ws’); |
//WebSocketAPI Address |
var wsAddress = ‘wss://api.foxbit.com.br/’; |
//Instantiate SleepModule |
var sleep = require(‘system-sleep’); |
//Setup WebSocket client Address |
var ws = new WebSocket(wsAddress); |
//Flag Authenticated |
var authenticated = false; |
//User & Password |
var userLogin = “”; |
var userPass = “”; |
var userId = “0”; |
var sessionToken = “”; |
//Wait PromptInformation |
var stdin2FA = process.openStdin(); |
//side variable = Buy/Sell |
var side = 1; |
//Message Frame |
var messageFrame = { |
“m”:0, //MessageType ( 0_Request / 1_Reply / 2_Subscribe / 3_Event / 4_Unsubscribe / Error ) |
“i”:0, //Sequence Number |
“n”:””, //Function Name |
“o”:”” //Payload |
}; |
//WebSocket Event Area |
//Event Open Connection |
ws.on(‘open’, function open() { |
consoleMessage(‘————————————————————————‘,’startup’); |
consoleMessage(‘Got connection’,’open.event’); |
//Start first command |
WebAuthenticateUser(messageFrame); |
consoleMessage(‘End connection’,’open.event’); |
}); |
//Event Receiving Message |
ws.on(‘message’, function incoming(data) { |
dealMessage(messageFrame, data); |
}); |
//Event Error Message |
ws.on(‘error’, function() { |
consoleMessage(‘WebService’,’error! ‘); |
}); |
//Event Close Message |
ws.on(‘close’, function() { |
consoleMessage(‘WebService’,’close! ‘); |
WebAuthenticateUser(frame); |
}); |
/* |
//Event End Message |
ws.on(‘end’, function(data) { |
consoleMessage(‘WebService’,’end! ‘ + data); |
}); |
*/ |
//Function AskUserInfo |
function AskPrompt(message){ |
consoleMessage(message); |
stdin.addListener(“data”, function(d) { |
var ret = d.toString().trim(); |
consoleMessage(‘!AskPrompt’, ret); |
return ret; |
}); |
} |
//Function DealMessage |
function dealMessage(frame, message){ |
var ret = JSON.parse(message); |
if (ret.n == “WebAuthenticateUser”){ |
consoleMessage(‘<-‘ + ret.n, JSON.stringify(ret)); |
if (authenticated == false){ |
Authenticate2FA(frame); |
} |
}else if (ret.n == “GetUserInfo”){ |
consoleMessage(‘<-‘ + ret.n, JSON.stringify(ret)); |
}else if (ret.n == ‘SendOrder’){ |
consoleMessage(‘<-‘ + ret.n, JSON.stringify(ret)); |
}else if(ret.n == ‘Authenticate2FA’) { |
authenticated = true; |
consoleMessage(‘<-‘ + ret.n, JSON.stringify(ret)); |
var paramO; |
if (ret.o != undefined){ |
paramO = JSON.parse(ret.o); |
sessionToken = JSON.stringify(paramO.SessionToken); |
userId = JSON.stringify(paramO.UserId); |
consoleMessage(‘<- sessionToken’, sessionToken); |
consoleMessage(‘<- userId’, userId); |
Authenticate2FA(frame); |
} |
}else{ |
consoleMessage(‘<-‘ + ret.n, JSON.stringify(ret)); |
} |
} |
//Startup Function |
function startTrading(frame){ |
SendOrder(frame); |
} |
//Function WebAuthenticateUser |
function WebAuthenticateUser(frame){ |
frame.n = “WebAuthenticateUser”; |
var requestPayload = {“UserName”: userLogin, “Password”: userPass}; |
frame.o = JSON.stringify(requestPayload); |
consoleMessage(frame.n, JSON.stringify(frame)); |
ws.send(JSON.stringify(frame), function ack(error) { |
if (error != undefined){ |
consoleMessage(‘Error’, JSON.stringify(error)); |
} |
}); |
} |
//Function Authenticate2FA |
function Authenticate2FA(frame){ |
frame.n = “Authenticate2FA”; |
var twoFA = “0000”; |
if (sessionToken == “”){ |
consoleMessage(frame.n, ‘Enter with 2FA Code:’); |
stdin2FA.addListener(“data”, function(d) { |
twoFA = d.toString().trim(); |
if (twoFA != “0000”){ |
var requestPayload = { “Code”: twoFA }; |
frame.o = JSON.stringify(requestPayload); |
consoleMessage(frame.n, JSON.stringify(frame)); |
ws.send(JSON.stringify(frame), function ack(error) { |
if (error != undefined){ |
console.log(‘<- Authenticate2FA.error: (‘ + error + ‘)’); |
} |
}); |
} |
}); |
}else{ |
consoleMessage(‘Already logged! SessionToken + UserId’, sessionToken + ‘ + ‘ + userId); |
frame.n = “WebAuthenticateUser”; |
var requestPayload = { “UserId”: userId , “SessionToken”: JSON.parse(sessionToken) }; |
frame.o = JSON.stringify(requestPayload); |
consoleMessage(frame.n, JSON.stringify(frame)); |
ws.send(JSON.stringify(frame), function ack(error) { |
if (error != undefined){ |
console.log(‘<- Authenticate2FA.error: (‘ + error + ‘)’); |
} |
}); |
GetUserInfo(frame); |
} |
} |
//Function SendOrder |
function SendOrder(frame){ |
frame.n = “SendOrder”; |
var requestPayload = { |
“AccountId”: 84437, |
“ClientOrderId”: 0, |
“Quantity”: 0.00001, |
“DisplayQuantity”: 0, |
“UseDisplayQuantity”: true, |
“LimitPrice”: 0, |
“OrderIdOCO”: 0, |
“OrderType”: 1, //ORDEM A MERCADO = 1 |
“PegPriceType”: 1, |
“InstrumentId”: 1, |
“TrailingAmount”: 1.0, |
“LimitOffset”: 2.0, |
“Side”: side, |
“StopPrice”: 0, |
“TimeInForce”: 1, |
“OMSId”: 1, |
}; |
frame.o = JSON.stringify(requestPayload); |
if (side == 0){ |
side = 1; |
}else{ |
side = 0; |
} |
console.log(‘\r\n-> ‘ + JSON.stringify(frame)); |
ws.send(JSON.stringify(frame), function ack(error) { |
ws = new WebSocket(‘wss://api.foxbit.com.br/’) |
console.log(‘SendOrder.error: (‘ + error + ‘)’); |
}); |
} |
function CancelOrder(frame, OrderId){ |
frame.n = “CancelOrder”; |
requestPayload2 = { |
“OMSId”: 1, |
“AccountId”:81 |
}; |
frame.o = JSON.stringify(requestPayload2); |
ws.send(JSON.stringify(frame), function ack(error) { |
console.log(‘CancelOrder.error: (‘ + error + ‘)’); |
}); |
} |
function GetOrderHistory(frame){ |
frame.n = “GetOrderHistory”; |
requestPayload2 = { |
“OMSId”: 1, |
“AccountId”:81 |
}; |
frame.o = JSON.stringify(requestPayload2); |
ws.send(JSON.stringify(frame), function ack(error) { |
console.log(‘GetOrderHistory.error: (‘ + error + ‘)’); |
}); |
} |
function GetOpenOrders(frame){ |
frame.n = “GetOpenOrders”; |
requestPayload2 = { |
“AccountId”:81, |
“OMSId”: 1 |
}; |
frame.o = JSON.stringify(requestPayload2); |
ws.send(JSON.stringify(frame), function ack(error) { |
console.log(‘GetOpenOrders.error: (‘ + error + ‘)’); |
}); |
} |
function GetUserInfo(frame){ |
frame.n = “GetUserInfo”; |
requestPayload2 = { |
}; |
frame.o = JSON.stringify(requestPayload2); |
ws.send(JSON.stringify(frame), function ack(error) { |
console.log(‘GetUserInfo.error: (‘ + error + ‘)’); |
}); |
} |
function GetUserConfig(frame){ |
frame.n = “GetUserConfig”; |
requestPayload2 = { |
}; |
frame.o = JSON.stringify(requestPayload2); |
ws.send(JSON.stringify(frame), function ack(error) { |
console.log(‘GetUserInfo.error: (‘ + error + ‘)’); |
}); |
} |
//Function Console |
function consoleMessage(prefix, sulfix){ |
console.log(‘\r\n’ + prefix + ‘: (‘ +sulfix + ‘)\r\n’); |
} |
Endpoint Público
Os Endpoints públicos são acessados sem necessidade de autenticação.
GetInstrument
Retorna detalhado do par. Ex. BTC/BRL
Request:
{ "OMSId": 1, "InstrumentId": 1 } |
Response:
{ "OMSId": 0, "InstrumentId": 0, "Symbol": "", "Product1": 0, "Product1Symbol": "", "Product2": 0, "Product2Symbol": "", "InstrumentType": { "Options": [ "Unknown", "Standard" ]}, "VenueInstrumentId": 0, "VenueId": 0, "SortIndex": 0, "SessionStatus": { "Options": [ "Unknown", "Running", "Paused", "Stopped", "Starting" ]}, "PreviousSessionStatus": { "Options": [ "Unknown", "Running", "Paused", "Stopped", "Starting" ]}, "SessionStatusDateTime": "0001-01-01T05:00:00Z", "SelfTradePrevention": false, "QuantityIncrement": 0, } |
[Response]: Case request login is already logged
String | Value |
OMSId | integer |
InstrumentId | long integer. |
Symbol | string Símbolo Ex. BTCBRL |
Product1 | integer |
Product1Symbol | string. |
Product2 | integer. |
Product2Symbol | string. |
InstrumentType | string. |
VenueInstrumentId | string. |
VenueId | string. |
SortIndex | string. |
SessionStatus | string. |
PreviousSessionStatus | string. |
SessionStatusDateTime | string. |
SelfTradePrevention | string. |
QuantityIncrement | string. |
GetProducts
Retorna array detalhado sobre o par solicitado.
Request:
{ "OMSId": 1 } |
String | Value |
OMSId | integer |
Response:
{ "OMSId": 0, "ProductId": 0, "Product": "", "ProductFullName": "", "ProductType": { "Options": [ "Unknown", "NationalCurrency", "CryptoCurrency", "Contract" ] }, "DecimalPlaces": 0, "TickSize": 0, "NoFees": false, } |
String | Value |
OMSId | integer The ID of the Order Management System that offers the product. |
ProductId | long integer The ID of the product. |
Product | string “Nickname” or shortened name of the product. For example, NZD (New Zealand Dollar). |
ProductFullName | string Full and official name of the product. For example, New Zealand Dollar. |
ProductType | string The nature of the product. One of: |
– | 0 Unknown (an error condition) |
– | 1 NationalCurrency |
– | 2 CryptoCurrency |
– | 3 Contract |
DecimalPlaces | integer The number of decimal places in which the product is divided. For example, US Dollars are divided into 100 units, or 2 decimal places. Other products may be different. Burundi Francs use 0 decimal places and the Rial Omani uses 3. |
TickSize | integer Minimum tradable quantity of the product. See also GetInstrument, where this value is called QuantityIncrement. For example, with a US Dollar, the minimal tradable quantity is $0.01. |
NoFees | Boolean Shows whether trading the product incurs fees. The default is false; that is, if NoFees is false, fees will be incurred. If NoFees is true, no fees are incurred. |
LogOut
Finaliza a conexão atual.
Request:
{ } >> Não é necessário enviar qualquer dado. |
Response:
{ "result":true, "errormsg":null, "errorcode":0, "detail":null } |
GetL2Snapshot
Retorna snapshot do book level2 de um instrumento específico. (array)
Request:
{ "OMSId": 1, "InstrumentId": 1, "Depth": 100 } |
String | Value |
OMSId | integer |
InstrumentId | integer |
Depth | integer Default 100 |
Response:
[ { "MDUpdateID": 0, "Accounts": 0, "ActionDateTime": 635872032000000000, "ActionType": 0, "LastTradePrice": 0, "Orders": 0, "Price": 0, "ProductPairCode": 0, "Quantity": 0, "Side": 0, } ] |
String | Value |
MDUpdateID | integer |
Accounts | integer |
ActionDateTime | string |
ActionType | string |
LastTradePrice | decimal |
Orders | integer |
Price | decimal |
ProductPairCode | integer |
Quantity | decimal |
Side | integer 0 Buy | 1 Sell | 2 Short | 3 Unknown |
GetTickerHistory
Retorna histórico de Ticker do instrumento específico:
Request:
{ "InstrumentId": 1, "Interval": 60, // interval in seconds. Possible values are 60, 300, 900, 1800, 3600, 21600, 43200, 86400, 604800 "FromDate": "2021-10-22T02:00:00", // POSIX-format date and time "ToDate": "2021-10-22T20:00:00", // POSIX-format date and time } |
Params:
Key | Value |
InstrumentId | Integer |
Interval | Integer |
FromDate | DateTime as String |
ToDate | DateTime as String |
Response:
>>> Retorna o seguinte array [ 1501604532000, // UTC Date/Time End 2792.73, // High 2667.95, // Low 2687.01, // Open 2700.81, // Close 242.61340767, // Volume 0, // Bid price 2871, // Ask price 0 // InstrumentId 1501604532000, // UTC Date/Time Initial |
SubscribeLevel1
Retorna Ticker level1 de um instrumento específico. (array)
Request:
{ "OMSId": 1, "InstrumentId": 1 } ou { "OMSId": 1, "Symbol": "BTCUSD" } |
String | Value |
OMSId | integer |
InstrumentId | integer |
Symbol | string |
Response:
{ "OMSId": 1, "InstrumentId": 1, "BestBid": 0.00, "BestOffer": 0.00, "LastTradedPx": 0.00, "LastTradedQty": 0.00, "LastTradeTime": 635872032000000000, "SessionOpen": 0.00, "SessionHigh": 0.00, "SessionLow": 0.00, "SessionClose": 0.00, "Volume": 0.00, "CurrentDayVolume": 0.00, "CurrentDayNumTrades": 0, "CurrentDayPxChange": 0.0, "Rolling24HrVolume": 0.0, "Rolling24NumTrades": 0.0, "Rolling24HrPxChange": 0.0, "TimeStamp": 635872032000000000, } |
String | Value |
OMSId | integer |
InstrumentId | integer |
BestBid | decimal |
BestOffer | decimal |
LastTradedPx | decimal |
LastTradedQty | decimal |
LastTradeTime | long integer |
SessionOpen | decimal |
SessionHigh | decimal |
SessionLow | decimal |
SessionClose | decimal |
Volume | decimal |
CurrentDayVolume | decimal |
CurrentDayVolume | integer |
CurrentDayPxChange | decimal |
Rolling24HrVolume | decimal |
Rolling24HrNumTrades | integer |
Rolling24HrPxChange | decimal |
TimeStamp | long integer |
SubscribeLevel2
Retorna Ticker level1 de um instrumento específico. (array)
Request:
{ "OMSId": 1, "InstrumentId": 1 "Depth": 10 } |
String | Value |
OMSId | integer |
InstrumentId | integer |
Symbol | string |
Depth |
integer |
Response:
{ "MDUpdateID": 0, "Accounts": 0, "ActionDateTime": 635872032000000000, "ActionType": 0, "LastTradePrice": 0, "Orders": 0, "Price": 0, "ProductPairCode": 0, "Quantity": 0, "Side": 0, } |
String | Value |
MDUpdateID | integer |
Accounts | integer |
ActionDateTime | string |
ActionType | string |
LastTradePrice | decimal |
Orders | integer |
Price | decimal |
ProductPairCode | integer |
Quantity | decimal |
Side | integer 0 Buy | 1 Sell | 2 Short | 3 Unknown |
SubscribeTicker
Assina o evento Ticker com um retorno periódico.
Request:
{ "OMSId": 1, "InstrumentId": 1, "Interval": 60, "IncludeLastCount": 100 } |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Interval | integer Default 60 |
IncludeLastCount | integer Default 100 |
Response:
[ { "EndDateTime": 0, // POSIX format "HighPX": 0, "LowPX": 0, "OpenPX": 0, "ClosePX": 0, "Volume": 0, "Bid": 0, "Ask": 0, "InstrumentId": 1, "BeginDateTime": 0 // POSIX format } ] |
UnsubscribeLevel1
Revoga assinatura do evento Market data feed Level1.
Request:
{ "OMSId": 1, "InstrumentId": 1 } |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Response:
{ "result": true, "errormsg": null, "errorcode":0, "detail": null } |
String | Value |
result | Boolean |
errormsg | string |
errorcode | integer |
detail | string |
UnsubscribeLevel2
Revoga assinatura do evento Market data feed Level2.
Request:
{ "OMSId": 1, "InstrumentId": 1 } |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Response:
{ "result": true, "errormsg": null, "errorcode":0, "detail": null } |
String | Value |
result | Boolean |
errormsg | string |
errorcode | integer |
detail | string |
UnsubscribeTicker
Revoga assinatura do evento Ticker.
Request:
{ "OMSId": 1, "InstrumentId": 1 } |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Response:
{ "result": true, "errormsg": null, "errorcode":0, "detail": null } |
String | Value |
result | Boolean |
errormsg | string |
errorcode | integer |
detail | string |
UnsubscribeTrades
Revoga assinatura do evento Trades Mareket Data Feed.
Request:
{ "OMSId": 1, "InstrumentId": 1 } |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Response:
{ "result": true, "errormsg": null, "errorcode":0, "detail": null } |
String | Value |
result | Boolean |
errormsg | string |
errorcode | integer |
detail | string |
Endpoint Autenticado
Aqui estão os Endpoints que necessitam de autenticação prévia.
GetUserConfig
Retorna configurações definidas pelo usuário.
Request:
{ "UserId": 1, "UserName": "jsmith", } |
String | Value |
UserID | integer |
UserName | string |
Response:
[ "Street": "Hillside Road", "Office Number": 158, "Mobile Phone": "1-702-555-1212", "City": "Las Vegas", ] |
GetUserInfo
Retorna informações básicas sobre o usuário que solicita.
Request:
{ }
|
Response:
{ "UserId": 1, "UserName": "John Smith", "Email": "[email protected]", "PasswordHash": "", "PendingEmailCode": "", "EmailVerified": true, "AccountId": 1, "DateTimeCreated":"2017-10-26T17:25:58Z", "AffiliateId": 1, "RefererId": 1, "OMSId": 1, "Use2FA": false, "Salt": "", "PendingCodeTime": "0001-01-01T00:00:00Z", } |
String | Value |
UserID | integer |
UserName | string |
string | |
PasswordHash | string |
PendingEmailCode | string |
EmailVerified | Boolean |
AccountId | integer |
DateTimeCreated | long integer |
AffiliateId | integer |
RefererId | integer |
OMSId | integer |
Use2FA | Boolean |
Salt | string |
PendingCodeTime | long integer |
GetUserPermissions
Retorna permissões específicas para o usuário solicitante.
Request:
{ "UserId": 1, } |
String | Value |
UserID | integer |
Response:
[ "Withdraw", "Deposit", "Trading" ] |
SetUserConfig
Define um array arbitrário no campo Config com par key/value.
Request:
{ "UserId": 1, "UserName": "jsmith", "Config": [ {"Key": "Street Name", "Value": "Hillside Road"}, {"Key": "Suite Number", "Value": 158} ] } |
String | Value |
UserID | integer |
UserName | string |
Config | array Par key/value |
Response:
{ "result": true, "errormsg": null, "errorcode":0, "detail": null } |
String | Value |
result | string |
errormsg | string |
errorcode | integer |
detail | string |
CancelAllOrders
Cancela todas as ordens abertas para o instrumento especificado.
Request:
{ "OMSId": 0, "AccountId": 0 // conditionally optional "ClientOrderId": 0 // conditionally optional "OrderId": 0, // conditionally optional } |
String | Value |
OMSId | integer |
AccountId | integer |
ClientOrderId | integer |
OrderId |
long integer |
Response:
{ "result": true, "errormsg": null, "errorcode":0, "detail": null } |
String | Value |
result | Boolean |
errormsg | string |
errorcode | integer |
detail | string |
GetAccountInfo
Retorna informação sobre a conta do usuário logado.
Request:
{ "OMSId": 0, "AccountId": 0, "AccountHandle": "", } |
String | Value |
OMSId | integer |
AccountId | integer |
AccountHandle | string |
Response:
{ "OMSID": 0, "AccountId": 0, "AccountName": "", "AccountHandle": "", "FirmId": "", "FirmName": "", "AccountType": { "Options": [ "Asset", "Liability", "ProfitLoss" ] }, "FeeGroupID": 0, "ParentID": 0, "RiskType": { "Options": [ "Unknown", "Normal", "NoRiskCheck", "NoTrading" ] }, "VerificationLevel": 0, "FeeProductType": { "Options": [ "BaseProduct", "SingleProduct" ] }, "FeeProduct": 0, "RefererId": 0, "SupportedVenueIds": [ 0 ], } } |
String | Value |
OMSId | integer |
AccountId | integer |
AccountName | string |
AccountHandle | string |
FirmId | string |
FirmName | string |
AccountType | string |
FeeGroupID | integer |
ParentID |
integer |
RiskType | string |
VerificationLevel | integer |
FeeProductType | string |
FeeProduct | integer |
RefererId | integer |
SupportedVenueIds | integer |
GetAccountPositions
Retorna um array com o histórico do balanço do usuário
Request:
{ "AccountId": 0, "OMSId": 0, } |
String | Value |
AccountId | integer |
OMSId | integer |
Response:
[ { // first position "OMSId":1, "AccountId":4, "ProductSymbol":"BTC" "ProductId":1 "Amount":0, "Hold":0, "PendingDeposits":0, "PendingWithdraws":0, "TotalDayDeposits":0, "TotalDayWithdraws":0, "TotalMonthWithdraws":0 }, { //second position "OMSId":1, "AccountId":4, "ProductSymbol":"USD", "ProductId":2, "Amount":0, "Hold":0, "PendingDeposits":0, "PendingWithdraws":0, "TotalDayDeposits":0, "TotalDayWithdraws":0, "TotalMonthWithdraws":0 } ] |
String | Value |
OMSId |
integer |
AccountId | integer |
ProductSymbol | string |
ProductId | integer |
Amount | decimal |
Hold | decimal |
PendingDeposits | decimal |
PendingWithdraws | decimal |
TotalDayDeposits | decimal |
TotalDayWithdraws | decimal |
TotalMonthWithdraws | decimal |
GetAccountTrades
Request:
{ "AccountId":4, "OMSId": 1, "StartIndex":0, "Count":2 } |
String | Value |
AccountId | integer |
OMSId | integer |
StartIndex | integer |
Count | integer |
Response:
[ { "TradeTimeMS": -62135446664520, "Fee": 0, "FeeProductId": 0, "OrderOriginator": 1, "OMSId": 1, "ExecutionId": 1, "TradeId": 1, "OrderId": 1, "AccountId": 4, "SubAccountId": 0, "ClientOrderId": 0, "InstrumentId": 1, "Side": "Buy", "Quantity": 1, "RemainingQuantity": 0, "Price": 100, "Value": 100, "TradeTime": 1501354796406, "CounterParty": null, "OrderTradeRevision": 1, "Direction": "NoChange", "IsBlockTrade": false } ] |
String | Value |
TradeTimeMS | long integer |
Fee | decimal |
FeeProductId | integer |
OrderOriginator | integer |
OMSId | integer |
ExecutionId | integer |
TradeId | integer |
OrderId | long integer |
AccountId | integer |
SubAccountId | integer |
InstrumentId | long integer |
Side | string |
Quantity | decimal |
RemainingQuantity | integer |
Price | decimal |
Value | decimal |
TradeTime | integer |
CounterParty | long integer |
OrderTradeRevision | integer |
Direction | string |
IsBlockTrade | Boolean |
GetAccountTransactions
Request:
{ "OMSId": 1, "AccountId": 1, "Depth": 200 } |
String | Value |
AccountId | integer |
OMSId | integer |
StartIndex | integer |
Count | integer |
Response:
[ { { "TransactionId": 0, "OMSId": 0, "AccountId": 0, "CR": 0, "DR": 0, "Counterparty": 0, "TransactionType": { "Options": [ "Fee", "Trade", "Other", "Reverse", "Hold" ] }, "ReferenceId": 0, "ReferenceType": { "Options": [ "Trade", "Deposit", "Withdraw", "Transfer", "OrderHold", "WithdrawHold", "DepositHold", "MarginHold" ] }, "ProductId": 0, "Balance": 0, "TimeStamp": 0, }, } ] |
String | Value |
TransactionId | integer |
OMSId | integer |
AccountId | integer |
CR | decimal |
DR | decimal |
Counterparty | long integer |
TransactionType |
string |
ReferenceId | long integer |
ReferenceType | string |
ProductId | integer |
Balance | decimal |
TimeStamp | long integer |
GetInstrument
Request:
{ "OMSId": 1, "InstrumentId": 1 } |
String | Value |
OMSId | integer |
InstrumentId | integer |
Response:
{ "OMSId": 0, "InstrumentId": 0, "Symbol": "", "Product1": 0, "Product1Symbol": "", "Product2": 0, "Product2Symbol": "", "InstrumentType": { "Options": [ "Unknown", "Standard" ] }, "VenueInstrumentId": 0, "VenueId": 0, "SortIndex": 0, "SessionStatus": { "Options": [ "Unknown", "Running", "Paused", "Stopped", "Starting" ] }, "PreviousSessionStatus": { "Options": [ "Unknown", "Running", "Paused", "Stopped", "Starting" ] }, "SessionStatusDateTime": "0001-01-01T05:00:00Z", "SelfTradePrevention": false, "QuantityIncrement": 0, } |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Symbol | string |
Product1 | integer |
Product1Symbol | string |
Product2 | integer |
Product2Symbol | string |
InstrumentType | string |
VenueInstrumentId | long integer |
VenueId | integer |
SortIndex | integer |
SessionStatus | string |
PreviousSessionStatus | string |
SessionStatusDateTime | string |
SelfTradePrevention | Boolean |
QuantityIncrement | integer |
GetInstruments
Request:
{ "OMSId": 1 } |
String | Value |
OMSId | integer |
Response:
[ { { "OMSId": 0, "InstrumentId": 0, "Symbol": "", "Product1": 0, "Product1Symbol": "", "Product2": 0, "Product2Symbol": "", "InstrumentType": { "Options": [ "Unknown", "Standard" ] }, "VenueInstrumentId": 0, "VenueId": 0, "SortIndex": 0, "SessionStatus": { "Options": [ "Unknown", "Running", "Paused", "Stopped", "Starting" ] }, "PreviousSessionStatus": { "Options": [ "Unknown", "Running", "Paused", "Stopped", "Starting" ] }, "SessionStatusDateTime": "0001-01-01T05:00:00Z", "SelfTradePrevention": false, "QuantityIncrement": 0, }, } ] |
String | Value |
OMSId | integer |
InstrumentId | long integer |
Symbol | string |
Product1 | integer |
Product1Symbol | string |
Product2 | integer |
Product2Symbol | string |
InstrumentType | string |
VenueInstrumentId | long integer |
VenueId | integer |
SortIndex | integer |
SessionStatus | string |
PreviousSessionStatus | string |
SessionStatusDateTime | string |
SelfTradePrevention | Boolean |
QuantityIncrement | integer |
GetOpenOrders
Request:
{ "AccountId":4, "OMSId": 1 } |
String | Value |
OMSId | integer |
Response:
[ { "Side": "Buy", "OrderId": 1, "Price": 100, "Quantity": 1, "DisplayQuantity": 1, "Instrument": 1, "Account": 4, "OrderType": "Limit", "ClientOrderId": 0, "OrderState": "Working", "ReceiveTime": 1501354241987, "ReceiveTimeTicks": 636369510419870950, "OrigQuantity": 1, "QuantityExecuted": 0, "AvgPrice": 0, "CounterPartyId": 0, "ChangeReason": "NewInputAccepted", "OrigOrderId": 1, "OrigClOrdId": 0, "EnteredBy": 1, "IsQuote": false, "InsideAsk": 9223372036.854775807, "InsideAskSize": 0, "InsideBid": 100, "InsideBidSize": 1, "LastTradePrice": 0, "RejectReason": "", "IsLockedIn": false, "OMSId": 1 } ] |
String | Value |
Side | string |
OrderId | long integer |
Price | decimal |
Quantity | decimal |
DisplayQuantity | decimal |
Instrument | integer |
Account | integer |
OrderType | string |
ClientOrderId | long integer |
OrderState | string |
ReceiveTime | long integer |
ReceiveTimeTicks | long integer |
OrigQuantity | integer |
QuantityExecuted | integer |
AvgPrice | decimal |
CounterPartyId | long integer |
ChangeReason | string |
OrigOrderId | long |
EnteredBy | integer |
IsQuote | Boolean |
InsideAsk/InsideBid | decimal |
InsideAskSize/InsideBidSize | decimal |
LastTradePrice | decimal |
RejectReason | string |
IsLockedIn | Boolean |
OMSId | integer |
SendOrder
Envia uma ordem de compra/venda.
Request:
{ "AccountId": 5, "ClientOrderId": 99, "Quantity": 1, "DisplayQuantity": 0, "UseDisplayQuantity": true, "LimitPrice": 95, "OrderIdOCO": 0, "OrderType": 2, "PegPriceType": 1, "InstrumentId": 1, "TrailingAmount": 1.0, "LimitOffset": 2.0, "Side": 0, "StopPrice": 96, "TimeInForce": 1, "OMSId": 1, } |
String | Value |
AccountId | integer |
ClientOrderId | long integer |
Quantity | decimal |
DisplayQuantity | decimal |
UseDisplayQuantity | Boolean |
LimitPrice | decimal |
OrderIdOCO | integer |
OrderType | integer |
PegPriceType | integer |
InstrumentId | long integer |
TrailingAmount | decimal |
LimitOffset | decimal |
Side | integer |
StopPrice | decimal |
TimeInForce | integer |
OMSId |
integer |
Response:
[
{ "status":"Accepted", "errormsg":"", "OrderId": 123 // Server order id } |
String | Value |
status | string |
errormsg | string |
OrderId | long integer |
Erro Response:
{
|
}
GetOrderFee
Request:
{
"OMSId": 0, "AccountId": 0, "InstrumentId": 0, "ProductId": 0, "Amount": 0, "Price": 0, "OrderType": { "Options": [ "Unknown", "Market", "Limit", "StopMarket", "StopLimit", "TrailingStopMarket", "TrailingStopLimit", "BlockTrade" ] }, "MakerTaker": { "Options": [ "Unknown", "Maker", "Taker" ] }, } |
String | Value |
OMSId | integer |
AccountId | integer |
InstrumentId | long integer |
ProductId | integer |
Amount | decimal |
Price | decimal |
OrderType | string |
MakerTaker | string |
Response:
{
"OrderFee": 0.01, "ProductId": 1 }
|
String | Value |
OrderFee | decimal |
ProductId | integer |
GetOrderHistory
Request:
{ "OMSId": 1, "AccountId": 1 } |
String | Value |
OMSId | integer |
AccountId | integer |
Response:
{ { "Side": { "Options": [ "Buy", "Sell", "Short", "Unknown" ] }, "OrderId": 0, "Price": 0, "Quantity": 0, "DisplayQuantity": 0, "Instrument": 0, "Account": 0, "OrderType": { "Options": [ "Unknown", "Market", "Limit", "StopMarket", "StopLimit", "TrailingStopMarket", "TrailingStopLimit", "BlockTrade" ] }, "ClientOrderId": 0, "OrderState": { "Options": [ "Unknown", "Working", "Rejected", "Canceled", "Expired", "FullyExecuted" ] }, "ReceiveTime": 0, "ReceiveTimeTicks": 0, "OrigQuantity": 0, "QuantityExecuted": 0, "AvgPrice": 0, "CounterPartyId": 0, "ChangeReason": { "Options": [ "Unknown", "NewInputAccepted", "NewInputRejected", "OtherRejected", "Expired", "Trade", "SystemCanceled_NoMoreMarket", "SystemCanceled_BelowMinimum", "NoChange", "UserModified" ] }, "OrigOrderId": 0, "OrigClOrdId": 0, "EnteredBy": 0, "IsQuote": false, "InsideAsk": 0, "InsideAskSize": 0, "InsideBid": 0, "InsideBidSize": 0, "LastTradePrice": 0, "RejectReason": "", "IsLockedIn": false, "OMSId": 0, }, } ]
|
String | Value |
Side | string |
OrderId | string |
Price | decimal |
Quantity | decimal |
DisplayQuantity | decimal |
Instrument | integer |
Account | integer |
OrderType | string |
ClientOrderId | long integer |
OrderState | string |
ReceiveTime | long integer |
ReceiveTimeTicks | long integer |
OrigQuantity | decimal |
QuantityExecuted | decimal |
AvgPrice | decimal |
CounterPartyId | long integer |
ChangeReason | string |
OrigOrderId | integer |
OrigClOrdId | long integer |
EnteredBy | integer |
IsQuote | Boolean |
InsideAsk | decimal |
InsideAskSize | decimal |
InsideBid | decimal |
InsideBidSize | decimal |
LastTradePrice | decimal |
RejectReason | string |
IsLockedIn | Boolean |
OMSId | integer |
GetDepositTickets
Retorna informação sobre depósito solicitado.
Request:
{ "OMSId": 1, "OperatorId": 1, "RequestCode": "866f21fe-3461-41d1-91aa-5689bc38503f", "AccountId": 4 } |
String | Value |
OMSId | integer |
OperatorId | integer |
“RequestCode” | string |
“AccountId” | integer |
Response:
{ "AssetManagerId": 1, "AccountId": 4, "AssetId": 2, "AssetName": "US Dollar", "Amount": 10, "OMSId": 1, "RequestCode": "866f21fe-3461-41d1-91aa-5689bc38503f", "RequestIP": "90.171.32.77", "RequestUser": 1, "RequestUserName": "admin", "OperatorId": 1, "Status": "New", "FeeAmt": 0, "UpdatedByUser": 1, "UpdatedByUserName": "admin", "TicketNumber": 67, "DepositInfo": "{ "Full Name":"Test", "language":"en", "Bank Name":"" }", "CreatedTimestamp": "2017-12-14T15:13:31Z", "LastUpdateTimeStamp": "2017-12-14T15:13:31Z", "Comments": [], "Attachments": [] }
|
String | Value |
AssetManagerId | integer |
AccountId | integer |
AssetId | decimal |
AssetName | decimal |
Amount | decimal |
OMSId | integer |
RequestCode | string |
RequestIP | string |
RequestUser | integer |
RequestUserName | string |
OperatorId | integer |
Status | string |
FeeAmt | decimal |
UpdatedByUser | integer |
UpdatedByUserName | string |
TicketNumber | integer |
DepositInfo | string |
CreatedTimestamp | string |
LastUpdateTimestamp | string |
Comments | string |
Attachments | string |
Versão
API Websocket documento v0.1.4 – Outubro de 2021
Foxbit 2021