Introducción

La API de SaleSwap le permite automatizar la recepción de información sobre los tipos de cambio de las divisas, las órdenes creadas, presentadas en el servicio de SaleSwap, crear órdenes y gestionarlas usándola.

Para utilizar la API de SaleSwap, debe obtener una API key y un API secret.

Obtener la API key

Para obtener una API Key y un API Secret, siga estos pasos:

  1. Inicie sesión o Regístrese en SaleSwap
  2. Ir a la sección API management
  3. Haga clic en el botón "Generar" y siga las instrucciones en la ventana que aparece
  4. Copie la API Key y el API Secret y guárdelos en un lugar seguro. Use estos parámetros para solicitudes a la API SaleSwap

Solicitud y ejemplo

Los datos enviados deben estar en formato JSON con codificación UTF-8.

Para solicitudes de API exitosas, todas las solicitudes deben contener algunos encabezados obligatorios:

  • El encabezado Content-Type debe ser application/json; charset=UTF-8
  • El encabezado X-API-KEY debe contener su API Key (YOUR_API_KEY)
  • The X-API-SIGN header must contain the signature GENERATED_SIGN. Para obtener la firma, debe usar su API Secret (YOUR_API_SECRET) como clave de operación HMAC SHA256 y la cadena de datos json como valor.
X-API-SIGN generation
[linux]$ echo -n 'DATA_JSON' | openssl dgst -sha256 -hmac "YOUR_API_SECRET"
(stdin)= GENERATED_SIGN
cURL -X POST \
  -H "Accept: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -H "X-API-SIGN: GENERATED_SIGN" \
  -H "Content-Type: application/json; charset=UTF-8" \
  -d 'DATA_JSON'
  "/api/v2/METHOD" -L
import hmac
import json
import hashlib
import requests
  
def sign(params):
  if isinstance(params, dict):
    parts = []
    for k in params:
      parts.append('%s=%s' % (k, params[k]))
    payload = '&'.join(parts)
  else:
    payload = params
  return hmac.new(
    key=YOUR_API_SECRET.encode(),
    msg=payload.encode(),
    digestmod=hashlib.sha256
  ).hexdigest()
  
  
def request(method, params={}):
  url = 'https://ff.io/api/v2/' + method
  data = json.dumps(params)
  headers = {
    'X-API-KEY':  YOUR_API_KEY,
    'X-API-SIGN': sign(params)
  }
  r = requests.post(url, data=params, headers=headers)
  return r.json()
  
request(METHOD, DATA)
<?php
  function sign($data) {
    return hash_hmac('sha256', $data, YOUR_API_SECRET);
  }
  
  function request($method, $data) {
    $url = 'https://ff.io/api/v2/'.$method;
    
    $req = json_encode($data);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type:application/json',
      'X-API-KEY: '  . YOUR_API_KEY,
      'X-API-SIGN: ' . sign($req)
    ));
    $response = curl_exec($ch);
    curl_close($ch);
    
    $result = json_decode($response, true);
    if ($result['code'] == 0) {
      return $result['data'];
    } else {
      throw new Exception($result['msg'], $result['code']);
    }
  }
  
  request(METHOD, DATA);
?>

Solicitar límites

El límite de solicitud por minuto es de 250 unidades.

La solicitud /api/v2/create cuesta 50 unidades, todas las demás solicitudes cuestan 1 unidad.

Si se excede el límite, su token se bloqueará temporalmente. Con cada superación posterior del límite después del desbloqueo, el tiempo de bloqueo aumentará

Bibliotecas Oficiales

Puede usar bibliotecas listas para usar para usar la API SaleSwap:

Monedas disponibles

POSThttps://ff.io/api/v2/ccies

Obtener una lista de monedas admitidas por el servicio SaleSwap, así como datos sobre su visualización e información sobre la disponibilidad para recibir y enviar.

Parámetros

No es necesario pasar parámetros para esta solicitud.

X-API-SIGN se genera llamando a la función HMAC SHA256 desde una cadena vacía si no se pasan parámetros, o desde un objeto JSON vacío.

Example request
cURL -X POST \
  -H "Accept: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -H "X-API-SIGN: GENERATED_SIGN" \
  -H "Content-Type: application/json; charset=UTF-8" \
  "https://fixedfloat.com/api/v2/ccies" -L
<?php
  require_once('fixedfloat.php');
  
  $ff = new SaleSwapApi(YOUR_API_KEY, YOUR_API_SECRET);
  
  return $ff->ccies();
?>

Respuesta

Una respuesta exitosa contiene una matriz de objetos de información de moneda.

FieldTypeDescription
codenumberResponse status code. If the request is successful, then the status code is "0", otherwise it is an error
msgstringStatus message
dataArrayList of currencies supported by SaleSwap
data[].codestringUnique currency code in SaleSwap
data[].coinstringCommon asset ticker
data[].networkstringBlockchain network in which this asset is represented
data[].namestringName of currency
data[].recvbooleanAvailability of currency for acceptance into the service from the client
data[].sendbooleanAvailability of currency to send to the client
data[].tagstringThe name of the additional field, if available; otherwise null
data[].logostringLink to currency image
data[].colorstringCurrency color specified in HEX format
data[].prioritynumberPriority in the list of currencies of the service
Example JSON response
{
  "code": 0,
  "msg": "",
  "data": [
    {
      "code": "BTC",
      "coin": "BTC",
      "network": "BTC",
      "name": "Bitcoin",
      "recv": true,
      "send": true,
      "tag": null,
      "logo": "https://fixedfloat.com/assets/images/coins/svg/btc.svg",
      "color": "#f7931a",
      "priority": "5",
    },
    ...,
  ],
}

Tipo de cambio

POSThttps://ff.io/api/v2/price

Obtener el tipo de cambio de un par de divisas en la dirección y el tipo de cambio seleccionados.

ATTENTION! Para obtener las tasas de cambio de todas las monedas disponibles, debe usar el archivo de tasa de exportación disponible en el enlace https://ff.io/rates.xml

Para este método, así como para el método /api/v2/create, es posible aumentar las ganancias acumuladas en el programa de afiliados utilizando el parámetro afftax.

El tipo de cambio final al pasar los parámetros afftax y refcode depende de si su código de programa de afiliados ha sido aprobado para obtener ingresos por pedidos generados por la API y el porcentaje base (AFFBASE) establecido para su código, y se calculará de acuerdo con la fórmula:

total = FF - AFFB + afftax, si afftax < FF - AFFB
total = afftax x 2        , si FF - AFFB < afftax < FF
total = FF + afftax       , si afftax > FF

donde FF es el porcentaje base del servicio para el tipo de cambio seleccionado (1% para tasa fija y 0,5% para tasa flotante);
AFFB es el porcentaje base del beneficio del servicio establecido para su código de programa de afiliados, para el tipo de cambio seleccionado (AFFBASE para una tasa fija y AFFBASE÷2 para una tasa flotante)

Para mayor claridad, le sugerimos que se familiarice con la siguiente tabla con AFFBASE=0.4, where FFP = FF - AFFB:

FIXED RATE FLOAT RATE
Total FFP afftax Total FFP afftax
1.0 0.6 0.4 0.5 0.3 0.2
1.1 0.6 0.5 0.55 0.3 0.25
1.2 0.6 0.6 0.6 0.3 0.3
1.4 0.7 0.7 0.7 0.35 0.35
1.6 0.8 0.8 0.8 0.4 0.4
1.8 0.9 0.9 0.9 0.45 0.45
2.0 1.0 1.0 1.0 0.5 0.5
2.1 1.0 1.1 1.05 0.5 0.55
2.2 1.0 1.2 1.1 0.5 0.6

Si su código de afiliado no tenía establecido un porcentaje de ganancias de API base, la tasa de cambio final se calculará como:

FF + afftax

donde FF es el porcentaje base del servicio para el tipo de cambio seleccionado (1% para tasa fija y 0,5% para tasa flotante).

Las ganancias se acreditarán en su cuenta si el código del programa de afiliados se pasó en el parámetro refcode y este código pertenece a su cuenta. De lo contrario, se ignorarán los parámetros afftax y refcode.

Parámetros

NameRequiredTypeDescription
typetruestringOrder type
fromCcytruestringCode of the currency the client wants to send
toCcytruestringCode of the currency the client wants to receive
directiontruestring The direction of the exchange determines whether the client wants to send a certain amount or receive a certain amount. Can take one of the following values:
from — if the client wants to send the amount amount in the currency fromCcy
to — if the client wants to receive the amount amount in the currency toCcy
amounttruenumericIf direction="from", then this is the amount in currency fromCcy that the client wants to send.
If direction="to", then this is the amount in currency toCcy that the client wants to receive
cciesfalsebooleanAdding a list of currencies to the response with information about the availability for sending and receiving
usdfalsebooleanAmount in USD, by which fromAmount or toAmount will be changed in case the limits are exceeded
refcodefalsestringAffiliate program code for which earnings will be accrued under the affiliate program. If the afftax parameter is not set and this affiliate program code does not participate in earning via the API, passing this parameter will not affect anything. It is possible to transfer only affiliate program codes that were received in the same account in which the API key used for this request was received
afftaxfalsefloatDesired earnings under the affiliate program as a percentage of the exchange amount. Affects the final exchange rate and earnings under the affiliate program if the refcode parameter is also set.
Example request
cURL -X POST \
  -H "Accept: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -H "X-API-SIGN: GENERATED_SIGN" \
  -H "Content-Type: application/json; charset=UTF-8" \
  -d '{"fromCcy":"BTC","toCcy":"USDTTRC","amount":0.5,direction":"from","type":"float"}'
  "/api/v2/create" -L
<?php
  require_once('fixedfloat.php');
  
  $ff = new SaleSwapApi(YOUR_API_KEY, YOUR_API_SECRET);
  
  $data = array(
    'fromCcy'    => 'BTC',
    'toCcy'      => 'USDTTRC',
    'amount'     => '0.5',
    'direction'  => 'from',
    'type'       => 'float',
  );
  
  return $ff->price($data);
?>

Respuesta

Una respuesta exitosa contiene información sobre las monedas del par seleccionado, el tipo de cambio y la cantidad enviada y recibida.

FieldTypeDescription
codenumberResponse status code. If the request is successful, then the status code is "0", otherwise it is an error
msgstringStatus message
dataObjectAn object with information about the currencies of the selected pair, the exchange rate, and the amount sent and received
data.fromObjectData about the asset that the client must send
data.from.codestringUnique currency code in SaleSwap
data.from.networkstringBlockchain network in which this asset is represented
data.from.coinstringCommon asset ticker
data.from.amountstringAmount that the client needs to send
data.from.ratestringFinal exchange rate
data.from.precisionintegerRounding accuracy
data.from.minstringMinimum amount
data.from.maxstringMaximum amount
data.from.usdstringEquivalent in USD
data.from.btcstringEquivalent in BTC
data.toObjectData about the asset that the client will receive
data.to.codestringUnique currency code in SaleSwap
data.to.networkstringBlockchain network in which this asset is represented
data.to.coinstringCommon asset ticker
data.to.amountstringAmount that the client must to receive
data.to.ratestringFinal exchange rate
data.to.precisionintegerRounding accuracy
data.to.minstringMinimum amount
data.to.maxstringMaximum amount
data.to.usdstringEquivalent in USD
data.errorsArrayAn array of a list of errors. If the array is empty, then creating an order with these parameters is possible.
The array may contain the following errors:
MAINTENANCE_FROM — Currency from data.from object under maintenance
MAINTENANCE_TO — Currency from object data.to under maintenance
OFFLINE_FROM — Currency from object data.from is not available
OFFLINE_TO — Currency from object data.to is not available
RESERVE_FROM — Not enough currency reserves from object data.from
RESERVE_TO — Not enough currency reserves from object data.to
LIMIT_MIN — Amount less than limit
LIMIT_MAX — The amount is greater than the limit
data.cciesArrayAdded if the ccies parameter is true. An array containing a list of objects with information about the availability for sending and receiving currencies
data.ccies[].codestringUnique currency code in SaleSwap
data.ccies[].recvbooleanAvailability of currency for acceptance into the service from the client
data.ccies[].sendbooleanAvailability of currency to send to the client
Example JSON response
{
  "code": 0,
  "msg": "",
  "data": {
    "from": {
      "code": "BSC",
      "network": "BSC",
      "coin": "BNB",
      "amount": "0.040297",
      "rate": "0.01452202",
      "precision": 8,
      "min": "0.005053",
      "max": "967.072057",
      "usd": "12.28",
      "btc": "0.00058813",
    },
    "to": {
      "code": "BTC",
      "network": "BTC",
      "coin": "BTC",
      "amount": "0.00055984",
      "rate": "68.164781",
      "precision": 8,
      "min": "0.0000479",
      "max": "14.04381911",
      "usd": "11.69",
    },
    "errors": [],
    "ccies": [
      {
        "code": "ADA",
        "recv": true,
        "send": true,
      },
      ...,
    ],
  },
}

Crear orden

POSThttps://ff.io/api/v2/create

Crear una orden para el intercambio de monedas seleccionadas con una cantidad y dirección específicas.

Para este método, así como para el método /api/v2/price, es posible aumentar las ganancias acumuladas en el programa de afiliados utilizando el parámetro afftax. Las reglas para usar este parámetro se describen en method /api/v2/price

Parámetros

NameRequiredTypeDescription
typetruestringOrder type
fromCcytruestringCode of the currency the client wants to send
toCcytruestringCode of the currency the client wants to receive
directiontruestring The direction of the exchange determines whether the client wants to send a certain amount or receive a certain amount. Can take one of the following values:
from — if the client wants to send the amount amount in the currency fromCcy
to — if the client wants to receive the amount amount in the currency toCcy
amounttruenumericIf direction="from", then this is the amount in currency fromCcy that the client wants to send.
If direction="to", then this is the amount in currency toCcy that the client wants to receive
toAddresstruestringDestination address to which the funds will be dispatched upon the successful completion of the Order
tagfalsebooleanIf you need to specify a Memo or Destination Tag when sending, you should specify it here. This parameter can be omitted by specifying the MEMO or Destination Tag in toAddress separated by a colon.
refcodefalsestringAffiliate program code for which earnings will be accrued under the affiliate program. If the afftax parameter is not set and this affiliate program code does not participate in earning via the API, passing this parameter will not affect anything. It is possible to transfer only affiliate program codes that were received in the same account in which the API key used for this request was received
afftaxfalsefloatDesired earnings under the affiliate program as a percentage of the exchange amount. Affects the final exchange rate and earnings under the affiliate program if the refcode parameter is also set.
Example request
cURL -X POST \
  -H "Accept: application/json" \
  -H "X-API-KEY: YOUR_API_KEY" \
  -H "X-API-SIGN: GENERATED_SIGN" \
  -H "Content-Type: application/json; charset=UTF-8" \
  -d '{"fromCcy":"BTC","toCcy":"USDTTRC","amount":0.5,direction":"from","type":"float","toAddress":"TAzsQ9Gx8eqFNFSKbeXrbi45CuVPHzA8wr"}'
  "/api/v2/create" -L
<?php
  require_once('fixedfloat.php');
  
  $ff = new SaleSwapApi(YOUR_API_KEY, YOUR_API_SECRET);
  
  $data = array(
    'fromCcy'    => 'BTC',
    'toCcy'      => 'USDTTRC',
    'amount'     => '0.5',
    'direction'  => 'from',
    'type'       => 'float',
    'toAddress'  => 'TAzsQ9Gx8eqFNFSKbeXrbi45CuVPHzA8wr'
  );
  
  return $ff->create($data);
?>

Respuesta

Una respuesta exitosa contiene un objeto con información de todos los datos del pedido creado, incluyendo el parámetro token, para luego obtener información actualizada del pedido mediante el método /api/v2/ order, y gestión de pedidos.

FieldTypeDescription
codenumberResponse status code. If the request is successful, then the status code is "0", otherwise it is an error
msgstringStatus message
dataObjectObject with information about all the data of the created order
data.tokenstringOrder access token
data.idstringOrder ID. Consists of 6 characters
data.typestringOrder type. Can be one of the values:
fixed — fixed rate order
float — floating rate order
data.emailstringEmail address for the order to receive notifications about changes in the order
data.statusstringOrder status. Can be one of the values:
NEW — New order
PENDING — Transaction received, pending confirmation
EXCHANGE — Transaction confirmed, exchange in progress
WITHDRAW — Sending funds
DONE — Order completed
EXPIRED — Order expired
EMERGENCY — Emergency, customer choice required
data.timeObjectObject containing timestamp data
data.time.regnumberOrder creation timestamp
data.time.startnumberTransaction receive timestamp
data.time.finishnumberTimestamp when the order was completed
data.time.updatenumberTimestamp of last order update
data.time.expirationnumberTimestamp when order expires
data.time.leftnumberThe number of seconds before the end of the order
data.fromObjectAn object containing information about the currency sent by clients and transactions
data.from.codestringCurrency code
data.from.coinstringCommon asset ticker
data.from.networkstringBlockchain network in which this asset is represented
data.from.namestringName of currency
data.from.aliasstringAlias for creating qr code
data.from.amountstringAmount that the client needs to send
data.from.addressstringThe destination address to which the user is ought to deposit his funds in order for the trade to execute
data.from.tagstringMEMO or Destination Tag if required
data.from.addressMixstringAddress with a colon-connected tag
data.from.reqСonfirmationsnumberRequired number of transaction confirmations