Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delay in API Res #230

Open
AsabCLS opened this issue Feb 20, 2024 · 1 comment
Open

Delay in API Res #230

AsabCLS opened this issue Feb 20, 2024 · 1 comment

Comments

@AsabCLS
Copy link

AsabCLS commented Feb 20, 2024

I'm trying to make a request of buy contract in a async ticksHistoryResponse, who is called in every response of the async ticksResponse. This ticksHistoryResponse function contains a condition that analyze the last 10 open, high, low and close prices of candles and the currently epoch, and make a buy request when all the condition are satisfied.

This function works good when i get in the computer and when i interact with it.

However, after a period of not interacting with the computer, the server responses are out of sync within 2 minutes, and the logs displayed on the console stop showing real-time information and show information from exactly 2 minutes ago. This causes purchase requests to be delayed.

I tried keeping tabs always on by enabling Chrome browser performance functions, but it didn't work. I'm calling the async functions through the await. Below is the script:

import DerivAPIBasic from "https://cdn.skypack.dev/@deriv/deriv-api/dist/DerivAPIBasic";

const token = "my_token";
const app_id = my_number_app;

function createWebSocket(app_id) {
let connection;

function connect() {
connection = new WebSocket(
wss://ws.derivws.com/websockets/v3?app_id=${app_id},
);

connection.onopen = function (event) {
  console.log("Conexão estabelecida:", event);
  connection;
};

connection.onmessage = function (event) {
  console.log("Mensagem recebida:", event.data);
};

connection.onclose = function (event) {
  console.log("Conexão fechada:", event);
  reconnect();
};

connection.onerror = function (event) {
  console.error("Erro na conexão:", event);
  reconnect();
};
return connection;

}

function reconnect() {
console.log("Tentando reconectar em 500 milisegundos...");
setTimeout(() => {
connect();
}, 500); // Tentar reconectar após 500 milisegundos
}
// Inicializa a conexão
return connect();
}

const a1 = createWebSocket(app_id);

let api = new DerivAPIBasic({ connection: a1 });

const onCloseObservable = api.onClose();
const onOpenObservable = api.onOpen();

// Subscrever aos eventos de fechamento
onCloseObservable.subscribe(() => {
console.log("Conexão fechada. Tentando reconectar...");

setTimeout(() => {
try {
window.location.reload();
console.log("Método reload() chamado.");
} catch (error) {
console.error("Erro ao tentar reconectar:", error);
}
}, 1000); // Tempo de espera de 1 segundos
});

window.addEventListener("offline", () => {
console.log("O dispositivo está offline.");
window.location.reload();
});

// Subscrever aos eventos de abertura
onOpenObservable.subscribe(() => {
autorization();
subscribeTicks();
ping()
console.log("Conexão aberta.");
});

const autorizacao = {
authorize: "my_token",
};
const autorization = async () => {
await api.authorize(autorizacao);
};

const ticks_history_request = {
ticks_history: "Any_VIX",
adjust_start_time: 1,
count: 10,
end: "latest",
start: 1,
style: "candles",
granularity: 60,
};

const ticks_request = {
...ticks_history_request,
subscribe: 1,
};

const ping = () => {
setInterval(() => {
api.ping();
}, 15000);
};

const balance1 = {
balance: 1,
subscribe: 1,
account: "current",
loginid: "my_loginid",
};

const balance2 = async () => {
api.balance(balance1);
};

const observable = api.onMessage(); // Assumindo que api.onMessage() retorna um Observable
let saldo;
let saldoAtual;
let balancinha;
let balanca3
const subscription1 = observable.subscribe((message) => {
// Exibe os dados recebidos no console para depuração

// Verifica se a estrutura da mensagem está conforme o esperado
if (
message &&
message.name === 'message' &&
message.data &&
message.data.balance &&
message.data.balance.balance !== undefined
) {
saldo = message.data.balance.balance
saldoAtual = parseFloat(saldo.toFixed(2));
balancinha = saldoAtual * 0.01
balanca3 = parseFloat(balancinha.toFixed(2))
}
});

const createBuyContract = async () => {

const buyContract = {
buy: 1,
price: 25000,
parameters: {
contract_type: "CALLE",
amount: balanca3,
basis: "stake",
symbol: "Any_VIX",
currency: "USD",
duration: 1,
duration_unit: "m",
},
};
return buyContract;
};

const buy = async () => {
const contract = await createBuyContract(); // Espera a resolução da função assíncrona
const buy1 = api.buy(contract);
return buy1
};

let timeepoch
let timeepoch2
let timeepoch3
let logs
const subscription2 = observable.subscribe((message) => {
// Exibe os dados recebidos no console para depuração
logs = console.log(message)

// Verifica se a estrutura da mensagem está conforme o esperado
if (
message &&
message.name === 'message' &&
message.data &&
message.data.ohlc &&
message.data.ohlc.epoch !== undefined
) {

timeepoch = message.data.ohlc.epoch;
timeepoch2 = parseInt(timeepoch.toFixed())
timeepoch3 = timeepoch2 % 60

}
});

const tickSubscriber = () => api.subscribe(ticks_request);

const ticksHistoryResponse = async (res) => {
const data = JSON.parse(res.data);
if (data.error !== undefined) {
console.log("Error : ", data.error.message);
}
if (data.msg_type === "candles") {

if (
  timeepoch3 = 0 &&
  (data.candles[data.candles.length - x].open - data.candles[data.candles.length - x].close) / (data.candles[data.candles.length - x].high - data.candles[data.candles.length - x].low) >= 0.05 &&
  data.candles[data.candles.length - x].open > data.candles[data.candles.length - x].close
) {
  console.log("Buy");
  console.log(timeepoch);
  logs;
  await buy();
} else {
  console.log("Dbuy");
  logs
}

}
}

const ticksResponse = async (res) => {
const data = JSON.parse(res.data);
// This example returns an object with a selected amount of past ticks.
if (data.error !== undefined) {
console.log("Error : ", data.error.message);
}
// Allows you to monitor ticks.
if (data.msg_type === "ohlc") {

await getTicksHistory();

}
if (data.msg_type === "ping") {
console.log("ping");
}
if (data.msg_type === "buy") {
console.log(data.buy);
}
if (data.msg_type === "authorize") {
console.log(data.authorize.email);
await balance2();
}
if (data.msg_type === "balance") {
console.log(data.balance.balance);
}
};

const subscribeTicks = async () => {
a1.addEventListener("message", ticksResponse);
await tickSubscriber();
};

const unsubscribeTicks = async () => {
a1.removeEventListener("message", ticksResponse, false);
await tickSubscriber().unsubscribe();
};

const getTicksHistory = async () => {
a1.addEventListener("message", ticksHistoryResponse);
await api.ticksHistory(ticks_history_request);
};

const subscribe_ticks_button = document.querySelector("#ticks");
subscribe_ticks_button.addEventListener("click", subscribeTicks);

const unsubscribe_ticks_button = document.querySelector("#ticks-unsubscribe");
unsubscribe_ticks_button.addEventListener("click", unsubscribeTicks);

const ticks_history_button = document.querySelector("#ticks-history");
ticks_history_button.addEventListener("click", getTicksHistory);

@AsabCLS
Copy link
Author

AsabCLS commented Feb 25, 2024

After analyzing the logs further, I realized that it is only at second 0 that data from 2 minutes ago is returned. in the following seconds, the data returned is the real-time data. Why does this happen?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant