Skip to content
This repository was archived by the owner on Feb 22, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
b044a3a
Consider InvalidOfferings as a warning rather than error
aaimio Jan 10, 2020
94a58f3
Stop bot on every sell error except InvalidOfferings
aaimio Jan 13, 2020
baf5edb
Prevent collision
aaimio Jan 13, 2020
f25f7af
camelCase
aaimio Jan 13, 2020
d672486
Merge pull request #2323 from aaron-binary/resale-issue
Feb 3, 2020
b800694
Merge pull request #2402 from binary-com/dev
Feb 3, 2020
d66ba15
Consider AuthorizationRequired + InvalidToken as unrecoverable errors
aaimio Feb 4, 2020
9c4a1e2
Catch errors on subscribing to POC
aaimio Feb 4, 2020
6a0318b
Log codes over entire messages
aaimio Feb 4, 2020
8bbeb73
Create reset_animation event
aaimio Feb 4, 2020
c634728
Fallback to main if defaultStrat undefined
aaimio Feb 4, 2020
3cef0e3
Create custom TrackJSError
aaimio Feb 4, 2020
c4aa9b7
Update error handling, emit as Error event
aaimio Feb 4, 2020
c682f73
Use TrackJSErrors over custom func
aaimio Feb 4, 2020
4dc9782
Remove impossible import
aaimio Feb 4, 2020
b4c0347
Update naming
aaimio Feb 4, 2020
3105555
Linting
aaimio Feb 4, 2020
cac920d
Unknown contract proposal
Feb 4, 2020
a68c343
logic update for checkproposalisready
Feb 5, 2020
c18bb15
Incorporate changes
sam-binary Feb 10, 2020
b21c0cb
Merge pull request #2409 from aaron-binary/trackjs-errors
Feb 10, 2020
8f4f87c
Merge pull request #2438 from binary-com/dev
Feb 10, 2020
648394b
Pass DOM rather than text
aaimio Feb 10, 2020
56ae3ef
Merge pull request #2411 from sam-binary/unknown-contract-proposal
Feb 10, 2020
f314008
Merge pull request #2441 from aaron-binary/bot-hotfix
Feb 10, 2020
a8a5f49
Merge pull request #2442 from binary-com/dev
Feb 10, 2020
811356a
Verify default strategy
aaimio Feb 11, 2020
22ac865
Merge pull request #2445 from aaron-binary/strategy-param-hotfix
Feb 11, 2020
89b3ab1
Merge branch 'dev' into beta
aaimio Feb 11, 2020
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
4 changes: 3 additions & 1 deletion src/botPage/bot/Interpreter.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ const unrecoverableErrors = [
'NotDefaultCurrency',
'PleaseAuthenticate',
'FinancialAssessmentRequired',
'AuthorizationRequired',
'InvalidToken',
];
const botInitialized = bot => bot && bot.tradeEngine.options;
const botStarted = bot => botInitialized(bot) && bot.tradeEngine.tradeOptions;
const shouldRestartOnError = (bot, errorName = '') =>
!unrecoverableErrors.includes(errorName) && botInitialized(bot) && bot.tradeEngine.options.shouldRestartOnError;

const shouldStopOnError = (bot, errorName = '') => {
const stopErrors = ['SellNotAvailable'];
const stopErrors = ['SellNotAvailableCustom'];
if (stopErrors.includes(errorName) && botInitialized(bot)) {
return true;
}
Expand Down
13 changes: 8 additions & 5 deletions src/botPage/bot/TradeEngine/OpenContract.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { roundBalance } from '../../common/tools';
import { doUntilDone } from '../tools';
import { contractStatus, contractSettled, contract as broadcastContract } from '../broadcast';
import { sell, openContractReceived } from './state/actions';
import { observer } from '../../../common/utils/observer';

const AFTER_FINISH_TIMEOUT = 5;

Expand Down Expand Up @@ -43,7 +44,6 @@ export default Engine =>
this.store.dispatch(openContractReceived());
if (!this.isExpired) {
this.resetSubscriptionTimeout();

}
}
});
Expand All @@ -61,10 +61,13 @@ export default Engine =>

this.unsubscribeOpenContract();

doUntilDone(() => this.api.subscribeToOpenContract(contractId)).then(r => {
({
proposal_open_contract: { id: this.openContractId },
} = r);
doUntilDone(() =>
this.api.subscribeToOpenContract(contractId).then(response => {
this.openContractId = response.proposal_open_contract.id;
})
).catch(error => {
observer.emit('reset_animation');
observer.emit('Error', error);
});
}
resetSubscriptionTimeout(timeout = this.getContractDuration() + AFTER_FINISH_TIMEOUT) {
Expand Down
20 changes: 10 additions & 10 deletions src/botPage/bot/TradeEngine/Proposal.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { translate } from '../../../common/i18n';
import { tradeOptionToProposal, doUntilDone, getUUID } from '../tools';
import { tradeOptionToProposal, doUntilDone } from '../tools';
import { proposalsReady, clearProposals } from './state/actions';

export default Engine =>
Expand Down Expand Up @@ -49,13 +49,7 @@ export default Engine =>
this.proposalTemplates.map(proposal =>
doUntilDone(() =>
this.api
.subscribeToPriceForContractProposal({
...proposal,
passthrough: {
contractType: proposal.contract_type,
uuid : getUUID(),
},
})
.subscribeToPriceForContractProposal(proposal)
// eslint-disable-next-line consistent-return
.catch(e => {
if (e && e.name === 'RateLimit') {
Expand Down Expand Up @@ -127,8 +121,14 @@ export default Engine =>
checkProposalReady() {
const proposals = this.data.get('proposals');

if (proposals && proposals.size === this.proposalTemplates.length) {
this.startPromise.then(() => this.store.dispatch(proposalsReady()));
if (proposals && proposals.size) {
const isSameWithTemplate = this.proposalTemplates.every(p =>
this.data.hasIn(['proposals', p.passthrough.uuid])
);

if (isSameWithTemplate) {
this.startPromise.then(() => this.store.dispatch(proposalsReady()));
}
}
}
isNewTradeOption(tradeOption) {
Expand Down
37 changes: 27 additions & 10 deletions src/botPage/bot/TradeEngine/Sell.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,43 @@ export default Engine =>
}

if (!this.isSellAtMarketAvailable()) {
if (this.hasEntryTick) {
const error = new Error(translate('Resale of this contract is not offered.'));
error.name = 'SellNotAvailable';
throw error;
} else {
return Promise.resolve();
}
notify('warn', translate('Resale of this contract is not offered.'));
return Promise.resolve();
}

const onSuccess = ({ sell: { sold_for: soldFor } }) => {
const onSuccess = soldFor => {
delayIndex = 0;
contractStatus('purchase.sold');
notify('info', `${translate('Sold for')}: ${soldFor}`);
return this.waitForAfter();
};

const action = () => this.api.sellContract(this.contractId, 0);
const action = () =>
this.api
.sellContract(this.contractId, 0)
.then(response => {
onSuccess(response.sell.sold_for);
})
.catch(response => {
const {
error: { error },
} = response;
if (error.code === 'InvalidOfferings') {
// "InvalidOfferings" may occur when user tries to sell the contract too close
// to the expiry time. We shouldn't interrupt the bot but instead let the contract
// finish.
notify('warn', error.message);
return Promise.resolve();
}
// In all other cases, throw a custom error that will stop the bot (after the current contract has finished).
// See interpreter for SellNotAvailableCustom.
const customError = new Error(error.message);
customError.name = 'SellNotAvailableCustom';
throw customError;
});

if (!this.options.timeMachineEnabled) {
return doUntilDone(action).then(onSuccess);
return doUntilDone(action);
}

return recoverFromError(
Expand Down
4 changes: 4 additions & 0 deletions src/botPage/bot/tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export const tradeOptionToProposal = tradeOption =>
duration : tradeOption.duration,
amount : roundBalance({ currency: tradeOption.currency, balance: tradeOption.amount }),
contract_type: type,
passthrough : {
contractType: type,
uuid : getUUID(),
},
};
if (tradeOption.prediction !== undefined) {
proposal.selected_tick = tradeOption.prediction;
Expand Down
1 change: 1 addition & 0 deletions src/botPage/common/const.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ const config = {
aid: 'derivbot-248506',
api: 'AIzaSyBDYQ7IIgGxM14IeAV5JrtaJNYjxB4A5jo',
},
quick_strategies: ['martingale', 'dalembert'],
};

export async function updateConfigCurrencies() {
Expand Down
9 changes: 1 addition & 8 deletions src/botPage/common/error.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import { observer as globalObserver } from '../../common/utils/observer';
import { translate } from '../../common/i18n';

/* eslint-disable import/prefer-default-export */
export const createError = (name, message) => {
const e = new Error(message);
e.name = name;
return e;
};

export const createErrorAndEmit = (name, message) => {
globalObserver.emit('ui.log.warn', `${translate(message)}`);
return createError(name, message);
};
4 changes: 4 additions & 0 deletions src/botPage/view/TradeInfoPanel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ class AnimateTrade extends Component {
$('.stage-tooltip.top:eq(0)').removeClass('running');
this.setState({ indicatorMessage: this.indicatorMessages.stopped });
});
globalObserver.register('reset_animation', () => {
resetAnimation();
this.setState({ indicatorMessage: this.indicatorMessages.stopped });
});

$('#stopButton').click(() => {
$('.stage-tooltip.top:eq(0)').removeClass('running');
Expand Down
74 changes: 43 additions & 31 deletions src/botPage/view/blockly/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,17 @@ import {
saveBeforeUnload,
removeParam,
updateRenamedFields,
getPreviousStrat,
} from './utils';
import Interpreter from '../../bot/Interpreter';
import { createErrorAndEmit } from '../../common/error';
import { translate, xml as translateXml } from '../../../common/i18n';
import { getLanguage } from '../../../common/lang';
import { observer as globalObserver } from '../../../common/utils/observer';
import { showDialog } from '../../bot/tools';
import GTM from '../../../common/gtm';
import { parseQueryString } from '../../../common/utils/tools';
import { TrackJSError } from '../logger';
import config from '../../common/const';

const disableStrayBlocks = () => {
const topBlocks = Blockly.mainWorkspace.getTopBlocks();
Expand Down Expand Up @@ -180,20 +182,29 @@ export const load = (blockStr, dropEvent = {}) => {
throw new Error();
}
} catch (err) {
throw createErrorAndEmit('FileLoad', unrecognisedMsg());
const error = new TrackJSError('FileLoad', unrecognisedMsg(), err);
globalObserver.emit('Error', error);
return;
}

let xml;
try {
xml = Blockly.Xml.textToDom(blockStr);
} catch (e) {
throw createErrorAndEmit('FileLoad', unrecognisedMsg());
const error = new TrackJSError('FileLoad', unrecognisedMsg(), e);
globalObserver.emit('Error', error);
return;
}

const blocklyXml = xml.querySelectorAll('block');

if (!blocklyXml.length) {
throw createErrorAndEmit('FileLoad', 'XML file contains unsupported elements. Please check or modify file.');
const error = new TrackJSError(
'FileLoad',
translate('XML file contains unsupported elements. Please check or modify file.')
);
globalObserver.emit('Error', error);
return;
}

if (xml.hasAttribute('is_dbot')) {
Expand Down Expand Up @@ -227,7 +238,12 @@ export const load = (blockStr, dropEvent = {}) => {
const blockType = block.getAttribute('type');

if (!Object.keys(Blockly.Blocks).includes(blockType)) {
throw createErrorAndEmit('FileLoad', 'XML file contains unsupported elements. Please check or modify file');
const error = new TrackJSError(
'FileLoad',
translate('XML file contains unsupported elements. Please check or modify file.')
);
globalObserver.emit('Error', error);
throw error;
}
});

Expand All @@ -240,7 +256,8 @@ export const load = (blockStr, dropEvent = {}) => {
loadWorkspace(xml);
}
} catch (e) {
throw createErrorAndEmit('FileLoad', translate('Unable to load the block file'));
const error = new TrackJSError('FileLoad', translate('Unable to load the block file'), e);
globalObserver.emit('Error', error);
}
};

Expand Down Expand Up @@ -343,9 +360,6 @@ export default class _Blockly {
window.addEventListener('resize', renderInstance, false);
renderInstance();
addBlocklyTranslation().then(() => {
const defaultStrat = parseQueryString().strategy;
const xmlFile = `xml/${defaultStrat}.xml`;

const loadDomToWorkspace = dom => {
repaintDefaultColours();
overrideBlocklyDefaultShape();
Expand All @@ -359,29 +373,27 @@ export default class _Blockly {
}, 0);
};

let defaultStrat = parseQueryString().strategy;

if (!defaultStrat || !config.quick_strategies.includes(defaultStrat)) {
const previousStrat = getPreviousStrat();

if (previousStrat) {
const previousStratDOM = Blockly.Xml.textToDom(previousStrat);
loadDomToWorkspace(previousStratDOM);
resolve();
return;
}

defaultStrat = 'main';
}

const xmlFile = `xml/${defaultStrat}.xml`;
const getFile = xml => {
importFile(xml)
.then(dom => {
loadDomToWorkspace(dom.getElementsByTagName('xml')[0]);
resolve();
})
.catch(text => {
if (text) {
const previousStrat = Blockly.Xml.textToDom(text);
loadDomToWorkspace(previousStrat);
resolve();
} else {
getFile('xml/main.xml');
}

if (defaultStrat) {
globalObserver.emit('Notify', {
className: 'warn',
message : translate('The strategy you tried to load is invalid'),
position : 'right',
});
}
});
importFile(xml).then(dom => {
loadDomToWorkspace(dom.getElementsByTagName('xml')[0]);
resolve();
});
};

getFile(xmlFile);
Expand Down
11 changes: 5 additions & 6 deletions src/botPage/view/blockly/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { saveAs } from '../shared';
import config from '../../common/const';
import { translate } from '../../../common/i18n';
import { observer as globalObserver } from '../../../common/utils/observer';
import { TrackJSError } from '../logger';

export const isMainBlock = blockType => config.mainBlocks.indexOf(blockType) >= 0;

Expand Down Expand Up @@ -97,12 +98,8 @@ export const strategyHasValidTradeTypeCategory = xml => {
return false;
});
if (!validTradeTypeCategory) {
const errorMessage = translate('The strategy you tried to import is invalid.');
globalObserver.emit('ui.log.error', errorMessage);

if (window.trackJs) {
trackJs.track(errorMessage);
}
const error = new TrackJSError('FileLoad', translate('The strategy you tried to import is invalid.'));
globalObserver.emit('Error', error);
}
return validTradeTypeCategory;
};
Expand Down Expand Up @@ -574,3 +571,5 @@ export const removeParam = key => {

window.history.pushState({}, window.title, rtn);
};

export const getPreviousStrat = () => localStorage.getItem('previousStrat');
Loading