Convert Python time to Dart

Asked

Viewed 24 times

-1

I’m making an application for study I took the data from this api

  • https://www.mercadobitcoin.com.br/trade-api/#get_order and I’m converting to Dart. I have the error of

    {"status_code": 203, "error_message": "Valor do *tapi_nonce* n\u00e3o \u00e9 um n\u00famero natural.", "server_unix_timestamp": "1629579792"}

    Could you give me a hand.
  • Follow the code in Dart

Python code for Dart
import time
tapi_nonce = str(int(time.time()))

import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'acesso.dart';
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

void main() async {
  DateTime inicio = DateTime.parse('2021-01-01');
  DateTime fim = DateTime.now();
  int tm_year = fim.year;
  String tm_mon = fim.month.toString();
  int tm_mday = fim.day;
  int tm_hour = fim.hour;
  String tm_min = fim.minute.toString();
  String tm_sec = fim.second.toString();
  int tm_wday = fim.weekday;
  int tm_yday = fim.difference(inicio).inDays;
  int tm_isdst = 0;
  if (tm_mon != 10.toString() ||
      tm_mon != 11.toString() ||
      tm_mon != 12.toString()) {
    tm_mon = '0$tm_mon';
  }
  if (tm_sec.length < 2) {
    tm_sec = '0$tm_sec';
  }
  if (tm_min.length < 2) {
    tm_min = '0$tm_min';
  }
  DateTime dateFormat =
      DateTime.parse('$tm_year-$tm_mon-$tm_mday $tm_hour:$tm_min:$tm_sec');

  String? tapi = dateFormat.millisecondsSinceEpoch.toString();
  var tapi2 = tapi.substring(0, 10);

  final hash = sha512.convert(utf8.encode('$MB_TAPI_SECRET'));
  var key = utf8.encode('$MB_TAPI_SECRET');
  var bytes = utf8.encode("$MB_TAPI_SECRET");
  var hmacSha256 = Hmac(sha512, key); // HMAC-SHA256
  var digest = hmacSha256.convert(bytes);
  var headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'TAPI-ID': MB_TAPI_ID,
    'TAPI-MAC': '$digest',
  };
  String rota =
      "$REQUEST_HOST$REQUEST_PATH/?tapi_method=list_orderbook&tapi_nonce=$tapi&coin_pair=BRLBTC&full=false ";
  try {
    var response = await http.post(
      Uri.parse(rota),
      headers: headers,
    );
    print(response.statusCode);
    print(response.body);
  } catch (e) {
    print(e);
  }
}

the python code

import dependencias

hmac = dependencias.hmac
hashlib = dependencias.hashlib
json = dependencias.json
time = dependencias.time
client = dependencias.client
acesso = dependencias.acesso
schedule = dependencias.schedule

# Constantes
MB_TAPI_ID = acesso.MB_TAPI_ID
MB_TAPI_SECRET = acesso.MB_TAPI_SECRET
REQUEST_HOST = acesso.REQUEST_HOST
REQUEST_PATH = acesso.REQUEST_PATH

# Nonce
# Para obter variação de forma simples
# timestamp pode ser utilizado:
#     **import time**
#     **tapi_nonce = str(int(time.time()))**


def listaOrderBook():

    tapi_nonce = str(int(dependencias.time.time()))
    # Parâmetros
    params = {
        'tapi_method': 'list_orderbook',
        'tapi_nonce': tapi_nonce,
        'coin_pair': 'BRLBTC',
        'full': 'false'


    }
    params = dependencias.urlencode(params)

    # Gerar MAC
    params_string = REQUEST_PATH + '?' + params
    H = hmac.new(bytes(MB_TAPI_SECRET, encoding='utf8'),
                 digestmod=hashlib.sha512)

    H.update(params_string.encode('utf-8'))
    tapi_mac = H.hexdigest()

    # Gerar cabeçalho da requisição
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'TAPI-ID': MB_TAPI_ID,
        'TAPI-MAC': tapi_mac
    }
    # Realizar requisição POST
    try:
        conn = client.HTTPSConnection(REQUEST_HOST)
        conn.request("POST", REQUEST_PATH, params, headers)
        print(REQUEST_PATH, params, headers)
        # Print response data to console
        response = conn.getresponse()
        response = response.read()

        response_json = json.loads(response)
        print('status: {}'.format(response_json['status_code']))
        print(json.dumps(response_json, indent=4))
    finally:
        if conn:
            conn.close()


listaOrderBook()
# schedule.every(2).seconds.do(listaOrderBook)
# while 2:
#     schedule.run_pending()
#     time.sleep(2)
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.