fixed the interval issue

This commit is contained in:
artin 2023-07-28 11:16:12 +00:00
parent d204e94330
commit 47a8474808

197
index.mjs
View File

@ -5,6 +5,8 @@ import fetch from "node-fetch";
const app = express();
import pg from "pg";
const client = new pg.Client(
"postgresql://crate@crate1.home.neb:5432/oversite"
);
@ -15,11 +17,16 @@ const port = 3000;
const host = "0.0.0.0";
const STATE = {};
const PRICES = {};
import axios from "axios";
const APIURL = "https://api-fxpractice.oanda.com/v3";
const STREAMURL = "https://stream-fxpractice.oanda.com/v3";
const APIURL_DEMO = "https://api-fxpractice.oanda.com/v3";
const STREAMURL_DEMO = "https://stream-fxpractice.oanda.com/v3";
const accounts = {
"1": {
ACCT: "101-001-8005237-001",
@ -40,59 +47,80 @@ const accounts = {
};
function processTP() {
for (const pair of PRICES) {
for (const acct of STATE) {
if (STATE[acct][pair]["watch"] == "ask") {
if (PRICES[pair]["ask"] >= STATE[acct][pair]["trigger"]) {
STATE[acct][pair]["trigger"] = PRICES[pair]["ask"];
STATE[acct][pair]["TP"] = true;
} else if (
STATE[acct][pair]["TP"] == true &&
PRICES[pair]["ask"] < STATE[acct][pair]["trigger"] * 0.95
) {
closeOrder(
accounts[acct]["ACCT"],
accounts[acct]["APIKEY"],
STATE[acct][pair]["trade_id"]
);
delete STATE[acct][pair];
}
} else if (STATE[acct][pair]["watch"] == "bid") {
if (PRICES[pair]["bid"] <= STATE[acct][pair]["trigger"]) {
STATE[acct][pair]["trigger"] = PRICES[pair]["bid"];
STATE[acct][pair]["TP"] = true;
} else if (
STATE[acct][pair]["TP"] == true &&
PRICES[pair]["bid"] > STATE[acct][pair]["trigger"] * 1.05
) {
closeOrder(
accounts[acct]["ACCT"],
accounts[acct]["APIKEY"],
STATE[acct][pair]["trade_id"]
);
delete STATE[acct][pair];
try {
for (const pair in PRICES) {
for (const acct in STATE) {
//console.log(`acct:${acct} pair:${pair}`);
//console.log(STATE[acct][pair]);
if (typeof(STATE[acct][pair]) !== 'undefined' && STATE[acct][pair]["watch"] == "ask") {
if (PRICES[pair]["ask"] >= STATE[acct][pair]["trigger"]) {
STATE[acct][pair]["trigger"] = PRICES[pair]["ask"];
STATE[acct][pair]["TP"] = true;
STATE[acct][pair]["TPVal"] = STATE[acct][pair]["trigger"] - STATE[acct][pair]["base"];
STATE[acct][pair]["TPVal"] = STATE[acct][pair]["TPVal"] * 0.32;
STATE[acct][pair]["TPVal"] = STATE[acct][pair]["TPVal"] + STATE[acct][pair]["base"];
} else if (
STATE[acct][pair]["TP"] == true &&
PRICES[pair]["ask"] < STATE[acct][pair]["TPVal"]
) {
closeOrder(
accounts[acct]["ACCT"],
accounts[acct]["APIKEY"],
STATE[acct][pair]["trade_id"]
);
delete STATE[acct][pair];
}
} else if (typeof(STATE[acct][pair]) !== 'undefined' && STATE[acct][pair]["watch"] == "bid") {
if (PRICES[pair]["bid"] <= STATE[acct][pair]["trigger"]) {
STATE[acct][pair]["trigger"] = PRICES[pair]["bid"];
STATE[acct][pair]["TP"] = true;
STATE[acct][pair]["TPVal"] = STATE[acct][pair]["base"] - STATE[acct][pair]["trigger"];
STATE[acct][pair]["TPVal"] = STATE[acct][pair]["TPVal"] * 0.32;
STATE[acct][pair]["TPVal"] = STATE[acct][pair]["base"] - STATE[acct][pair]["TPVal"];
} else if (
STATE[acct][pair]["TP"] == true &&
PRICES[pair]["bid"] > STATE[acct][pair]["TPVal"]
) {
closeOrder(
accounts[acct]["ACCT"],
accounts[acct]["APIKEY"],
STATE[acct][pair]["trade_id"]
);
delete STATE[acct][pair];
}
}
}
}
} catch (e) {
console.log("error prices");
console.log(e);
}
}
async function saveState() {
await client.query(`insert into osapi_state (account_state,prices, state_time) values ($1, now())`, [STATE, PRICE]);
function saveState() {
client.query(`insert into osapi_state (account_state,prices, state_time) values ($1,$2, now())`, [STATE, PRICES]);
}
setInterval(processTP, 1500);
setInterval(saveState, 6000);
async function loadState() {
let res = await client.query(`select account_state from osapi_state order by state_time desc limit 1`);
if (result.rows.length !== 0) {
if (res.rows.length !== 0) {
STATE = res['rows'][0];
console.log(STATE);
}
}
loadState()
async function getTransactionsAll(account, acct_id, api_key) {
console.log("getTransactionsAll");
for (const rg of [...Array(32).keys()]) {
try {
let f = rg * 1000 + 1;
@ -125,7 +153,8 @@ async function getTransactionsAll(account, acct_id, api_key) {
}
}
async function getTransactions(account, acct_id, api_key) {
// for (const rg of [...Array(32).keys()]) {
console.log("getTransactions");
try {
const res = await client.query(
`SELECT max(order_id) as order_id from orders where account_id = ${account}`
@ -160,6 +189,7 @@ async function getTransactions(account, acct_id, api_key) {
}
async function getTrades(acct_id, api_key) {
console.log("getTrades");
try {
const response = await axios.request({
url: `${APIURL}/accounts/${acct_id}/openTrades`,
@ -174,6 +204,7 @@ async function getTrades(acct_id, api_key) {
}
}
async function getTradesByInstrument(acct_id, api_key, instrument) {
console.log("getTradesByInstrument");
try {
const response = await axios.request({
url: `${APIURL}/accounts/${acct_id}/trades?instrument=${instrument}`,
@ -209,6 +240,7 @@ async function getPositions(acct_id, api_key) {
}
async function order(acct_id, api_key, instrument, quantity) {
console.log("order");
try {
let dist = "0.001";
let pdist = "0.001";
@ -347,6 +379,16 @@ async function takeProfit(acct_id, api_key, tradeID, dist) {
}
app.get("/closeAll", async (req, res) => {
for (const acct in STATE) {
for (const pair in STATE[acct]) {
closeOrder(
accounts[acct]["ACCT"],
accounts[acct]["APIKEY"],
STATE[acct][pair]["trade_id"]
);
delete STATE[acct][pair];
}
}
for (const account of Object.keys(accounts)) {
let trades = await getTrades(
accounts[account]["ACCT"],
@ -539,18 +581,18 @@ app.get("/order/:instrument/:quantity", async (req, res) => {
if (typeof(STATE[account][req.params.instrument]) === 'undefined') {
STATE[account][req.params.instrument] = {};
}
STATE[account][req.params.instrument]["base"] =
response["data"]["orderFillTransaction"]["price"] + delta;
STATE[account][req.params.instrument]["TP"] = false;
STATE[account][req.params.instrument]["qty"] = req.params.quantity;
STATE[account][req.params.instrument]["trade_id"] =
response["data"]["orderFillTransaction"]["tradeOpened"]["tradeID"];
if (req.params.quantity > 0) {
STATE[account][req.params.instrument]["base"] = response["data"]["orderFillTransaction"]["price"] + delta;
STATE[account][req.params.instrument]["watch"] = "ask";
STATE[account][req.params.instrument]["trigger"] = (response["data"]["orderFillTransaction"]["price"] + delta) * 1.05;
STATE[account][req.params.instrument]["trigger"] = (response["data"]["orderFillTransaction"]["price"] + delta) * 1.5;
} else {
STATE[account][req.params.instrument]["base"] = response["data"]["orderFillTransaction"]["price"] - delta;
STATE[account][req.params.instrument]["watch"] = "bid";
STATE[account][req.params.instrument]["trigger"] = (response["data"]["orderFillTransaction"]["price"] + delta) * 0.95;
STATE[account][req.params.instrument]["trigger"] = (response["data"]["orderFillTransaction"]["price"] + delta) * 0.5;
}
}
}
@ -565,41 +607,50 @@ app.listen(port, host, () => {
});
const response = await fetch(
"https://stream-fxpractice.oanda.com/v3/accounts/101-001-8005237-001/pricing/stream?instruments=GBP_CAD%2CNZD_CAD%2CEUR_CHF%2CEUR_CAD%2CNZD_CHF%2CCHF_JPY%2CUSD_CHF%2CAUD_JPY%2CEUR_USD%2CNZD_USD%2CUSD_JPY%2CGBP_AUD%2CEUR_AUD%2CCAD_JPY%2CEUR_GBP%2CAUD_CAD%2CEUR_JPY%2CAUD_CHF%2CCAD_CHF%2CGBP_JPY%2CUSD_CAD%2CNZD_JPY%2CUSD_SGD%2CAUD_USD%2CGBP_CHF%2CAUD_NZD%2CGBP_USD", {
method: "GET",
headers: {
Authorization: "Bearer e88218d201bd344c2dc3c469f8f8d1f3-e77504680a17f51f0baecf9dababa40b",
},
}
);
try {
for await (const chunk of response.body) {
try {
const x = JSON.parse(chunk.toString());
if (x["type"] == "PRICE") {
let delta = x["asks"][0]["price"] - x["bids"][0]["price"];
client.query(
`insert into pricing (instrument, price_data, tick, bid,ask,spread) values ($1,$2,$3,$4,$5,$6)`,
[
x["instrument"],
x,
x["time"],
x["asks"][0]["price"],
x["bids"][0]["price"],
delta.toFixed(6),
]
);
PRICES[x["instrument"]] = {
ask: x["asks"][0]["price"],
bid: x["bids"][0]["price"],
};
async function price_stream() {
const response = await fetch(
`${STREAMURL_DEMO}/accounts/101-001-8005237-001/pricing/stream?instruments=GBP_CAD%2CNZD_CAD%2CEUR_CHF%2CEUR_CAD%2CNZD_CHF%2CCHF_JPY%2CUSD_CHF%2CAUD_JPY%2CEUR_USD%2CNZD_USD%2CUSD_JPY%2CGBP_AUD%2CEUR_AUD%2CCAD_JPY%2CEUR_GBP%2CAUD_CAD%2CEUR_JPY%2CAUD_CHF%2CCAD_CHF%2CGBP_JPY%2CUSD_CAD%2CNZD_JPY%2CUSD_SGD%2CAUD_USD%2CGBP_CHF%2CAUD_NZD%2CGBP_USD`, {
method: "GET",
headers: {
Authorization: "Bearer e88218d201bd344c2dc3c469f8f8d1f3-e77504680a17f51f0baecf9dababa40b",
},
}
);
try {
for await (const chunk of response.body) {
try {
const x = JSON.parse(chunk.toString());
if (x["type"] == "PRICE") {
let delta = x["asks"][0]["price"] - x["bids"][0]["price"];
client.query(
`insert into pricing (instrument, price_data, tick, bid,ask,spread) values ($1,$2,$3,$4,$5,$6)`,
[
x["instrument"],
x,
x["time"],
x["asks"][0]["price"],
x["bids"][0]["price"],
delta.toFixed(6),
]
);
PRICES[x["instrument"]] = {
ask: x["asks"][0]["price"],
bid: x["bids"][0]["price"],
};
}
} catch (e) {
}
} catch (e) {}
}
} catch (err) {
console.log("pricing error");
console.error(err);
console.error(err.stack);
}
} catch (err) {
console.error(err.stack);
return await price_stream();
}
setTimeout(processTP, 1500);
setTimeout(saveState, 60000);
await price_stream();