556 lines
17 KiB
JavaScript
556 lines
17 KiB
JavaScript
import express from 'express'
|
|
import cors from 'cors'
|
|
|
|
import fetch from 'node-fetch';
|
|
const app = express()
|
|
|
|
|
|
import pg from 'pg';
|
|
const client = new pg.Client("postgresql://crate@crate1.home.neb:5432/oversite")
|
|
|
|
|
|
client.connect()
|
|
|
|
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 accounts = {
|
|
'1': {
|
|
'ACCT': '101-001-8005237-001',
|
|
'APIKEY': 'e88218d201bd344c2dc3c469f8f8d1f3-e77504680a17f51f0baecf9dababa40b'
|
|
},
|
|
'4': {
|
|
'ACCT': '101-001-8005237-002',
|
|
'APIKEY': 'e88218d201bd344c2dc3c469f8f8d1f3-e77504680a17f51f0baecf9dababa40b'
|
|
},
|
|
'2': {
|
|
'APIKEY': 'b954456a3f4ac735de2555e1af50abf7-ed83ace2f9fb86412b76608daefc73a5',
|
|
'ACCT': '101-001-23367262-002'
|
|
},
|
|
'3': {
|
|
'APIKEY': 'd4ea6095fe8017841279416437520aee-fa23a0556fb501520ceedbff5f405267',
|
|
'ACCT': '101-002-26241098-001'
|
|
}
|
|
}
|
|
|
|
|
|
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];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async function getTransactionsAll(account, acct_id, api_key) {
|
|
for (const rg of [...Array(32).keys()]) {
|
|
try {
|
|
f = rg * 1000 + 1;
|
|
to = f + 1000;
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/transactions/idrange?from=${f}&to=${to}`,
|
|
method: 'get',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
}
|
|
});
|
|
|
|
for (const t of response.data.transactions) {
|
|
qty = 0;
|
|
tp = "";
|
|
if (typeof(t['instrument']) !== undefined) {
|
|
tp = t['instrument']
|
|
}
|
|
if (typeof(t['units']) !== undefined) {
|
|
qty = t['units']
|
|
}
|
|
await client.query(`insert into orders (order_id, account_id, tpair, order_type, order_ref, order_reason, order_date, order_data, quantity) values ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [t.id, account, tp, t.type, t.batchID, t.reason, t.time, t, qty]);
|
|
|
|
}
|
|
|
|
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
|
|
}
|
|
}
|
|
async function getTransactions(account, acct_id, api_key) {
|
|
// for (const rg of [...Array(32).keys()]) {
|
|
try {
|
|
const res = await client.query(`SELECT max(order_id) as order_id from orders where account_id = ${account}`)
|
|
f = res.rows[0].order_id;
|
|
to = f + 1000;
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/transactions/idrange?from=${f}&to=${to}`,
|
|
method: 'get',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
}
|
|
});
|
|
|
|
for (const t of response.data.transactions) {
|
|
qty = 0;
|
|
tp = "";
|
|
if (typeof(t['instrument']) !== undefined) {
|
|
tp = t['instrument']
|
|
}
|
|
if (typeof(t['units']) !== undefined) {
|
|
qty = t['units']
|
|
}
|
|
await client.query(`insert into orders (order_id, account_id, tpair, order_type, order_ref, order_reason, order_date, order_data, quantity) values ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [t.id, account, tp, t.type, t.batchID, t.reason, t.time, t, qty]);
|
|
|
|
}
|
|
|
|
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async function getTrades(acct_id, api_key) {
|
|
try {
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/openTrades`,
|
|
method: 'get',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
}
|
|
});
|
|
return (response)
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
async function getTradesByInstrument(acct_id, api_key, instrument) {
|
|
try {
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/trades?instrument=${instrument}`,
|
|
method: 'get',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
}
|
|
});
|
|
//console.log(response)
|
|
if (response.data.trades.length == 0) {
|
|
return
|
|
} else {
|
|
|
|
return (response.data.trades[0])
|
|
}
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
async function getPositions(acct_id, api_key) {
|
|
try {
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/openPositions`,
|
|
method: 'get',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
}
|
|
});
|
|
return (response);
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
async function order(acct_id, api_key, instrument, quantity) {
|
|
try {
|
|
|
|
|
|
let dist = "0.001"
|
|
let pdist = "0.001"
|
|
|
|
if (instrument.includes("JPY")) {
|
|
dist = "0.1"
|
|
pdist = "0.1"
|
|
}
|
|
|
|
|
|
let data = {
|
|
"order": {
|
|
/*"trailingStopLossOnFill": {
|
|
"timeInForce": "GTC",
|
|
"distance": dist
|
|
},*/
|
|
/*"takeProfitOnFill": {
|
|
"distance": pdist
|
|
},*/
|
|
"timeInForce": "FOK",
|
|
"instrument": instrument,
|
|
"units": quantity,
|
|
"type": "MARKET",
|
|
"positionFill": "DEFAULT"
|
|
}
|
|
};
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/orders`,
|
|
method: 'post',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
},
|
|
data: data
|
|
});
|
|
|
|
return (response)
|
|
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
async function closeOrder(acct_id, api_key, tradeID) {
|
|
try {
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/trades/${tradeID}/close`,
|
|
method: 'put',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
},
|
|
});
|
|
console.log(response.data);
|
|
return (response);
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
|
|
}
|
|
|
|
async function trailingStopLoss(acct_id, api_key, instrument) {
|
|
const trade = await getTradesByInstrument(acct_id, api_key, instrument)
|
|
const tradeID = trade.id;
|
|
console.log(tradeID);
|
|
if (!tradeID) {
|
|
return
|
|
}
|
|
dist = "0.00164"
|
|
if (instrument.includes("JPY")) {
|
|
dist = "0.16"
|
|
}
|
|
try {
|
|
data = {
|
|
"trailingStopLoss": {
|
|
"timeInForce": "GTC",
|
|
"distance": dist
|
|
}
|
|
};
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/trades/${tradeID}/orders`,
|
|
method: 'put',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
},
|
|
data: data
|
|
});
|
|
console.log(data)
|
|
console.log(response.data);
|
|
return (response);
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
|
|
}
|
|
|
|
async function stopLoss(acct_id, api_key, tradeID, price) {
|
|
try {
|
|
data = {
|
|
"stopLoss": {
|
|
"timeInForce": "GTC",
|
|
"distance": "0.30"
|
|
//"price": price
|
|
}
|
|
};
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/trades/${tradeID}/orders`,
|
|
method: 'put',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
},
|
|
data: data
|
|
});
|
|
console.log(data)
|
|
console.log(response.data);
|
|
return (response);
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
|
|
}
|
|
|
|
async function takeProfit(acct_id, api_key, tradeID, dist) {
|
|
try {
|
|
data = {
|
|
"takeProfit": {
|
|
"timeInForce": "GTC",
|
|
"distance": dist
|
|
}
|
|
};
|
|
const response = await axios.request({
|
|
url: `${APIURL}/accounts/${acct_id}/trades/${tradeID}/orders`,
|
|
method: 'put',
|
|
headers: {
|
|
'Authorization': `Bearer ${api_key}`
|
|
},
|
|
data: data
|
|
});
|
|
return (response);
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
|
|
}
|
|
|
|
app.get('/closeAll', async (req, res) => {
|
|
|
|
for (const account of Object.keys(accounts)) {
|
|
let trades = await getTrades(accounts[account]['ACCT'], accounts[account]['APIKEY'])
|
|
for (const t of trades.data['trades']) {
|
|
await closeOrder(accounts[account]['ACCT'], accounts[account]['APIKEY'], t['id'])
|
|
}
|
|
}
|
|
|
|
res.json('done')
|
|
})
|
|
|
|
|
|
app.get('/tradesData', async (req, res) => {
|
|
|
|
let r = [];
|
|
for (const account of Object.keys(accounts)) {
|
|
let response = await getTrades(accounts[account]['ACCT'], accounts[account]['APIKEY'])
|
|
try {
|
|
//Object.(response.data['trades']).forEach(([a, t]) =>{
|
|
response.data['trades'].forEach((t) => {
|
|
|
|
t["Account"] = account;
|
|
delete t['lastTransactionID'];
|
|
delete t['trailingStopLossOrder'];
|
|
console.log(t);
|
|
r.push(t)
|
|
});
|
|
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json(r)
|
|
})
|
|
|
|
|
|
app.get('/transactionsAll/:account', async (req, res) => {
|
|
let account = req.params.account;
|
|
let r = {}
|
|
let response = await getTransactionsAll(account, accounts[account]['ACCT'], accounts[account]['APIKEY'])
|
|
try {
|
|
r = {};
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json("ok")
|
|
})
|
|
app.get('/transactions', async (req, res) => {
|
|
|
|
let r = {}
|
|
for (const account of Object.keys(accounts)) {
|
|
let response = await getTransactions(account, accounts[account]['ACCT'], accounts[account]['APIKEY'])
|
|
try {
|
|
r = {};
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json("ok")
|
|
})
|
|
|
|
app.get('/trades', async (req, res) => {
|
|
|
|
let r = {}
|
|
for (const account of Object.keys(accounts)) {
|
|
let response = await getTrades(accounts[account]['ACCT'], accounts[account]['APIKEY'])
|
|
try {
|
|
r[account] = response.data;
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json(r)
|
|
})
|
|
|
|
app.get('/accounts/:user_id', async (req, res) => {
|
|
accts = await client.query(`select * from accounts where user_id = ${req.params.user_id} `);
|
|
res.header('Access-Control-Allow-Origin', '*');
|
|
res.json(accts.rows);
|
|
})
|
|
|
|
app.get('/accounts', async (req, res) => {
|
|
accts = await client.query(`select * from accounts `);
|
|
res.header('Access-Control-Allow-Origin', '*');
|
|
r = {};
|
|
console.log(accts);
|
|
for (const a of accts.rows) {
|
|
if (typeof(r[a['user_id']]) === 'undefined') {
|
|
r[a['user_id']] = [a];
|
|
} else {
|
|
r[a['user_id']].push(a);
|
|
}
|
|
}
|
|
res.json(r);
|
|
})
|
|
|
|
app.get('/accounts/del/:user_id/:account_id', async (req, res) => {
|
|
await client.query(`delete from accounts where user_id = ${req.params.user_id} and id = ${req.params.account_id}`);
|
|
res.header('Access-Control-Allow-Origin', '*');
|
|
res.json('ok');
|
|
})
|
|
|
|
app.get('/accounts/add/:user_id/:a_number/:akey', async (req, res) => {
|
|
await client.query(`insert into accounts (user_id, account_number, apikey, account_type) values (${req.params.user_id},'${req.params.a_number}','${req.params.akey}', 'oanda')`)
|
|
res.header('Access-Control-Allow-Origin', '*');
|
|
res.json('ok');
|
|
})
|
|
|
|
app.get('/trailingStop/:instrument', async (req, res) => {
|
|
const response = await trailingStopLoss(ACCT, APIKEY, req.params.instrument);
|
|
console.log(response);
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json(response.data)
|
|
})
|
|
|
|
app.get('/tradesByInstrument/:instrument', async (req, res) => {
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
r = "";
|
|
|
|
data = await client.query(`select * from orders where account_id = 2 and order_date > now()- interval '1 day'`);
|
|
|
|
for (const row of data.rows) {
|
|
delete(row['order_data']);
|
|
r += `${Object.values(row).join(',')} \n`;
|
|
}
|
|
//r[account] = await getTradesByInstrument(accounts[2]['ACCT'], accounts[2]['APIKEY'], req.params.instrument);
|
|
res.header('Content-Type', 'text/csv');
|
|
res.send(r);
|
|
})
|
|
|
|
app.get('/prices', async (req, res) => {
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json(PRICES);
|
|
})
|
|
app.get('/state', async (req, res) => {
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json(STATE);
|
|
})
|
|
|
|
app.get('/order/:instrument/:quantity', async (req, res) => {
|
|
let r = {};
|
|
for (const account of Object.keys(accounts)) {
|
|
let td = await getTradesByInstrument(accounts[account]['ACCT'], accounts[account]['APIKEY'], req.params.instrument);
|
|
|
|
if (td == null || (td['state'] != "OPEN" && td['state'] != "PENDING")) {
|
|
let response = await order(accounts[account]['ACCT'], accounts[account]['APIKEY'], req.params.instrument, req.params.quantity);
|
|
console.log(response["data"]);
|
|
if (typeof(response["data"]["orderFillTransaction"]) !== "undefined") {
|
|
let delta = 0.0012;
|
|
if (req.params.instrument.includes("JPY")) {
|
|
delta = 0.12;
|
|
}
|
|
STATE[account][req.params.instrument]["base"] = response["data"]["orderFillTransaction"]["price"] + delta;
|
|
STATE[account][req.params.instrument]["trigger"] = (response["data"]["orderFillTransaction"]["price"] + delta) * 1.05;
|
|
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]["watch"] = "ask";
|
|
} else {
|
|
STATE[account][req.params.instrument]["watch"] = "bid";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
res.header('Access-Control-Allow-Origin', '*')
|
|
res.json("ok")
|
|
})
|
|
|
|
app.listen(port, host, () => {
|
|
console.log(`osapi started`);
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
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"]
|
|
};
|
|
}
|
|
} catch (e) {
|
|
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error(err.stack);
|
|
}
|
|
|
|
|
|
|
|
|
|
setTimeout(processTP, 1500 );
|