Skip to content
This repository has been archived by the owner on Feb 22, 2024. It is now read-only.

Mahdiyeh/Fix: get trader tokens from copytrading_list api #1594

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 79 additions & 48 deletions src/copytrade/copytrade.es6
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import validateToken from 'websockets/validateToken';
import { init as instrumentPromise } from '../instruments/instruments';

// While using copy trader, this cannot be NULL
const getLoggedInUserId = () => local_storage.get("oauth")[0].id;
const loggedInUserId = local_storage.get("oauth")[0].id;

const TRADE_TYPES = trade_types;

Expand All @@ -22,7 +22,7 @@ const form_error_messages = {
REFRESH_FAILED: 'Refresh failed'.i18n(),
};

const getStorageName = () => `copyTrade_${getLoggedInUserId()}`;
const getStorageName = () => `copyTrade_${loggedInUserId}`;

const DEFAULT_TRADE_TYPES = TRADE_TYPES.slice(0, 2).map(m => m.api_code);

Expand All @@ -34,9 +34,9 @@ const defaultCopySettings = (traderApiToken) => ({
trade_types: _.cloneDeep(DEFAULT_TRADE_TYPES),
});

const defaultTraderDetails = (traderApiToken, loginid) => ({
const defaultTraderDetails = (traderApiToken, loginid, started) => ({
open: false,
started: false,
started,
disableStart: false,
loginid,
yourCopySettings: defaultCopySettings(traderApiToken),
Expand All @@ -58,7 +58,7 @@ const updateLocalStorage = _.debounce(scope => {

let GROUPED_INTRUMENTS = null; // For nice display purpose only
let DEFAULT_ASSETS = null;
//Get instrument list
// Get instrument list
instrumentPromise().then(instruments => {
GROUPED_INTRUMENTS = _.flatten(instruments.map(m => {
const displayName = m.display_name;
Expand All @@ -84,7 +84,7 @@ instrumentPromise().then(instruments => {
DEFAULT_ASSETS = assets.filter(f => f.code === 'R_10').map(m => m.code);
});

const refreshTraderStats = (loginid, token, scope) => {
const refreshTraderStats = (loginid, token, scope, started = false) => {
return new Promise((resolve, reject) => {
liveapi
.send({
Expand All @@ -95,15 +95,19 @@ const refreshTraderStats = (loginid, token, scope) => {
if (copyStatData.copytrading_statistics) {
const traderTokenDetails = _.find(scope.traderTokens, f =>
f.yourCopySettings && f.yourCopySettings.copy_start === token);
//Check if we already added this trader. If yes, then merge the changes
// Check if we already added this trader. If yes, then merge the changes
if (traderTokenDetails) {
_.merge(traderTokenDetails.traderStatistics, copyStatData.copytrading_statistics);
// check if copy trading is started
if (started) {
traderTokenDetails.started = true;
}
}
//If not added, then add this along with default yourCopySettings object
// If not added, then add this along with default yourCopySettings object
else {
scope.traderTokens.push(_.merge({
traderStatistics: copyStatData.copytrading_statistics,
}, defaultTraderDetails(token, loginid)));
}, defaultTraderDetails(token, loginid, started)));
}
}
updateLocalStorage(scope);
Expand Down Expand Up @@ -153,16 +157,16 @@ const state = {
state.traderTokens[index].disableStart = true;
const newStarted = !state.traderTokens[index].started;
if (newStarted) {
//Start copying
//if started, revert back to last saved changes(in case user changed anything)
// Start copying
// If started, revert back to last saved changes(in case user changed anything)
const fromLocalStorage = local_storage.get(getStorageName());
if (fromLocalStorage) {
const currentTraderTokenDetails_localSto = fromLocalStorage.traderTokens[index];
if (currentTraderTokenDetails_localSto) {
const newObj = {};
_.merge(newObj, state.traderTokens[index], currentTraderTokenDetails_localSto);
state.traderTokens.splice(index, 1);
//Have to apply this trick in order to trigger update of UI using rivetsjs.
// Have to apply this trick in order to trigger update of UI using rivetsjs.
_.defer(() => {
state.traderTokens.splice(index, 0, newObj);
const settingsToSend = _.cloneDeep(newObj.yourCopySettings);
Expand All @@ -189,7 +193,7 @@ const state = {
}
}
} else {
//Stop copying
// Stop copying
liveapi.send({
copy_stop: state.traderTokens[index].yourCopySettings.copy_start
})
Expand Down Expand Up @@ -265,13 +269,13 @@ const state = {
}
},
addToken: (event, scope) => {
//If searchToken.token is empty, do nothing
// If searchToken.token is empty, do nothing
if (!scope.searchToken.token) {
$.growl.error({ message: form_error_messages.ENTER_VALID_TOKEN });
return;
}

//If already added, throw error
// If already added, throw error
if (_.some(state.traderTokens, f => f.yourCopySettings.copy_start === scope.searchToken.token)) {
$.growl.error({ message: form_error_messages.TOKEN_ALREADY_ADDED });
return;
Expand Down Expand Up @@ -315,40 +319,27 @@ const initConfigWindow = () => {
modal: false,
width: 600,
open: () => {
//Refresh all token details
const copyTrade = local_storage.get(getStorageName());
if (copyTrade) {
_.merge(state, copyTrade);
state.traderTokens = _.cloneDeep(state.traderTokens); // This is needed to trigger rivetsjs render
}
state.is_loading = true;

liveapi
.cached
.send({ get_settings: 1 })
.then((settings) => {
state.is_loading = false;
state.allowCopy.allow_copiers = settings.get_settings.allow_copiers;
})
.catch((e) => {
state.is_loading = false;
$.growl.error({ message: e.message });
});
//Refresh locally stored trader statistics
if (copyTrade) {
(async function () {
for (let traderToken of copyTrade.traderTokens) {
try {
const loginid = traderToken.loginid;
const token = traderToken.yourCopySettings.copy_start;
await refreshTraderStats(loginid, token, state);
} catch (e) {
console.error(e);
$.growl.error({ message: form_error_messages.REFRESH_FAILED });
}
}
})();
}
liveapi.cached.authorize().then((data) => {
if (data.authorize.loginid === local_storage.get('authorize').loginid) {
liveapi
.cached
.send({ get_settings: 1 })
.then((settings) => {
state.allowCopy.allow_copiers = settings.get_settings.allow_copiers;
if (settings.get_settings.allow_copiers) {
state.is_loading = false;
} else {
// Update trader tokens and refresh locally stored trader statistics
getTraderList();
}
})
.catch((e) => {
state.is_loading = false;
$.growl.error({ message: e.message });
});
}
});
},
close: () => {
win_view && win_view.unbind();
Expand All @@ -367,6 +358,40 @@ const initConfigWindow = () => {
win.dialog( 'open' );
};

const getTraderList = () => {
liveapi
.cached
.send({
copytrading_list : 1
}).then(list => {
const traderTokens = list.copytrading_list.traders;
if (!traderTokens.length) {state.is_loading = false;}
try {
for (let traderToken of traderTokens) {
const loginid = traderToken.loginid;
const token = traderToken.token;
refreshTraderStats(loginid, token, state, true)
.then(() => {
state.is_loading = false;
})
.catch((e)=> {
console.error(e)
state.is_loading = false;
$.growl.error({ message: form_error_messages.REFRESH_FAILED });
})
}
} catch (e) {
state.is_loading = false;
console.error(e);
$.growl.error({ message: form_error_messages.REFRESH_FAILED });
}
}).catch(error => {
console.log(error);
state.is_loading = false;
$.growl.error({ message: error.message})
})
};

const disableKeypressChars = (...input_el_ids) => {
if (input_el_ids.length > 0) {
const comma_separated_ids = input_el_ids.join(', ');
Expand All @@ -386,6 +411,12 @@ export const init = ($menuLink) => {
}
else { win.moveToTop(); }
});
liveapi.events.on("logout", () => {
const storageName = getStorageName();
if (storageName && local_storage.get(storageName)) {
local_storage.remove(storageName);
}
});
};

export default { init }
Expand Down