Skip to content

Commit

Permalink
Merge pull request #110 from farabi-deriv/farabi/bot-2280/update-accu…
Browse files Browse the repository at this point in the history
…mulators-feature

Farabi/bot-2280/update-accumulators-feature
  • Loading branch information
shafin-deriv authored Nov 4, 2024
2 parents 107d637 + 572db8d commit a45ffae
Show file tree
Hide file tree
Showing 21 changed files with 452 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ const ContractCardHeader = ({
const is_sold = !!contract_info.is_sold || is_contract_sold;
const is_accumulator = isAccumulatorContract(contract_type);
const is_smarttrader_contract = isSmartTraderContract(contract_type);
const { isDesktop } = useDevice();
const { isMobile } = useDevice();
const is_turbos = isTurbosContract(contract_type);
const is_multipliers = isMultiplierContract(contract_type);
const is_high_low = isHighLow({ shortcode });
Expand Down Expand Up @@ -102,7 +102,8 @@ const ContractCardHeader = ({
<div
className={classNames('dc-contract-card__grid', 'dc-contract-card__grid-underlying-trade', {
'dc-contract-card__grid-underlying-trade--trader': !is_bot,
'dc-contract-card__grid-underlying-trade--trader--accumulator': isDesktop && is_accumulator,
'dc-contract-card__grid-underlying-trade--trader--accumulator':
!(isMobile || is_bot) && is_accumulator,
'dc-contract-card__grid-underlying-trade--trader--sold':
(is_accumulator || is_turbos || is_multipliers) && is_sold,
})}
Expand Down
5 changes: 5 additions & 0 deletions src/constants/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export type TContract = {
};

export type TContractType =
| 'ACCU'
| 'ASIANU'
| 'ASIAND'
| 'CALL'
Expand Down Expand Up @@ -44,6 +45,10 @@ type TSupportedContracts = {
};

export const getSupportedContracts = (is_high_low: boolean): TSupportedContracts => ({
ACCU: {
name: 'Accumulators',
position: 'top',
},
ASIANU: {
name: localize('Asian Up'),
position: 'top',
Expand Down
17 changes: 16 additions & 1 deletion src/external/bot-skeleton/constants/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ export const config = () => ({
CURRENCY: ['USD', 'EUR', 'GBP', 'AUD', ...CRYPTO_CURRENCIES],
},
opposites: {
ACCUMULATOR: [
{
ACCU: localize('Buy'),
},
],
MULTIPLIER: [
{
MULTUP: localize('Up'),
Expand Down Expand Up @@ -219,6 +224,7 @@ export const config = () => ({
callputspread: ['callputspread'],
highlowticks: ['highlowticks'],
runs: ['runs'],
accumulator: ['accumulator'],
},
TRADE_TYPE_CATEGORY_NAMES: {
callput: localize('Up/Down'),
Expand All @@ -231,6 +237,7 @@ export const config = () => ({
highlowticks: localize('High/Low Ticks'),
runs: localize('Only Ups/Only Downs'),
multiplier: localize('Multipliers'),
accumulator: localize('Accumulators'),
},
BARRIER_CATEGORIES: {
euro_atm: ['callput', 'callputequal'],
Expand All @@ -240,6 +247,7 @@ export const config = () => ({
asian: ['asians'],
reset: ['reset'],
lookback: ['lookback'],
accumulator: ['accumulator'],
},
DEFAULT_DURATION_DROPDOWN_OPTIONS: [
[localize('Ticks'), 't'],
Expand Down Expand Up @@ -306,7 +314,14 @@ export const config = () => ({
DISABLED: {
SYMBOLS: ['1HZ150V', '1HZ250V'],
SUBMARKETS: ['crash_index', 'non_stable_coin', 'step_index'],
BARRIER_TRADE_TYPES: ['higherlower', 'touchnotouch', 'endsinout', 'staysinout', 'callputspread'],
BARRIER_TRADE_TYPES: [
'higherlower',
'touchnotouch',
'endsinout',
'staysinout',
'callputspread',
'accumulator',
],
PREDICTION_TRADE_TYPES: ['highlowticks'],
},
DEFAULT: {
Expand Down
39 changes: 39 additions & 0 deletions src/external/bot-skeleton/scratch/accumulators-proposal-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { api_base } from '../services/api';
import DBotStore from './dbot-store';

export const DEFAULT_PROPOSAL_REQUEST = {
amount: undefined,
basis: 'stake',
contract_type: 'ACCU',
currency: undefined,
symbol: undefined,
growth_rate: undefined,
proposal: 1,
subscribe: 1,
};

export const forgetAccumulatorsProposalRequest = async instance => {
if (instance && !instance.is_bot_running) {
await api_base?.api?.send({ forget_all: 'proposal' });
instance.subscription_id_for_accumulators = null;
instance.is_proposal_requested_for_accumulators = false;
window.Blockly.accumulators_request = {};
}
};

export const handleProposalRequestForAccumulators = instance => {
const top_parent_block = instance?.getTopParent();
const market_block = top_parent_block?.getChildByType('trade_definition_market');
const symbol = market_block?.getFieldValue('SYMBOL_LIST');
const currency = DBotStore.instance.client.currency;
const growth_rate = instance?.getFieldValue('GROWTHRATE_LIST') || 0.01;
const amount = instance?.childBlocks_?.[0]?.getField('NUM')?.getValue() || 0;
const proposal_request = {
...DEFAULT_PROPOSAL_REQUEST,
amount,
currency,
symbol,
growth_rate,
};
window.Blockly.accumulators_request = proposal_request;
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ import './check_direction';
import './tick_analysis';
import './last_digit';
import './lastDigitList';
import './stat';
import './stat_list';
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { localize } from '@deriv-com/translations';
import { modifyContextMenu } from '../../../utils';

Blockly.Blocks.stat = {
init() {
this.jsonInit(this.definition());
},
definition() {
return {
message0: localize('Current Stat'),
output: 'Number',
outputShape: Blockly.OUTPUT_SHAPE_ROUND,
colour: Blockly.Colours.Base.colour,
colourSecondary: Blockly.Colours.Base.colourSecondary,
colourTertiary: Blockly.Colours.Base.colourTertiary,
tooltip: localize('Returns the Current Stat'),
category: Blockly.Categories.Tick_Analysis,
};
},
meta() {
return {
display_name: localize('Current Stat'),
description: localize('This block gives you the Current Stat value.'),
};
},
customContextMenu(menu) {
modifyContextMenu(menu);
},
};

Blockly.JavaScript.javascriptGenerator.forBlock.stat = () => [
'Bot.getCurrentStat()',
Blockly.JavaScript.javascriptGenerator.ORDER_ATOMIC,
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { localize } from '@deriv-com/translations';
import { modifyContextMenu } from '../../../utils';

Blockly.Blocks.stat_list = {
init() {
this.jsonInit(this.definition());
},
definition() {
return {
message0: localize('Current stat list'),
output: 'Array',
outputShape: Blockly.OUTPUT_SHAPE_ROUND,
colour: Blockly.Colours.Base.colour,
colourSecondary: Blockly.Colours.Base.colourSecondary,
colourTertiary: Blockly.Colours.Base.colourTertiary,
tooltip: localize('Returns the list of last digits of 1000 recent tick values'),
category: Blockly.Categories.Tick_Analysis,
};
},
meta() {
return {
display_name: localize('Current stat list'),
description: localize('This block gives you a list of the cuurent stats of the last 1000 tick values.'),
};
},
customContextMenu(menu) {
modifyContextMenu(menu);
},
};

Blockly.JavaScript.javascriptGenerator.forBlock.stat_list = () => [
'Bot.getStatList()',
Blockly.JavaScript.javascriptGenerator.ORDER_ATOMIC,
];
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ import './epoch';
import './timeout';
import './todatetime';
import './totimestamp';
import './tickdelay';
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { localize } from '@deriv-com/translations';
import DBotStore from '../../../../dbot-store';
import { evaluateExpression, modifyContextMenu } from '../../../../utils';

Blockly.Blocks.tick_delay = {
init() {
this.jsonInit(this.definition());
const { client } = DBotStore.instance;
if (client && client.is_logged_in) {
this.workspace_to_code = Blockly.JavaScript.javascriptGenerator.workspaceToCode(Blockly.derivWorkspace);
}
},
definition() {
return {
message0: localize('{{ stack_input }} Run after {{ number }} tick(s)', {
stack_input: '%1',
number: '%2',
}),
args0: [
{
type: 'input_statement',
name: 'TICKDELAYSTACK',
},
{
type: 'input_value',
name: 'TICKDELAYVALUE',
},
],
colour: Blockly.Colours.Base.colour,
colourSecondary: Blockly.Colours.Base.colourSecondary,
colourTertiary: Blockly.Colours.Base.colourTertiary,
previousStatement: null,
nextStatement: null,
tooltip: localize('Run the blocks inside after a given number of ticks'),
category: Blockly.Categories.Time,
};
},
meta() {
return {
display_name: localize('Tick Delayed run'),
description: localize(
'This block delays execution for a given number of ticks. You can place any blocks within this block. The execution of other blocks in your strategy will be paused until the instructions in this block are carried out.'
),
};
},
customContextMenu(menu) {
modifyContextMenu(menu);
},
getRequiredValueInputs() {
return {
TICKDELAYVALUE: input_value => {
const evaluated_result = evaluateExpression(input_value);
if (evaluated_result === 'invalid_input') {
// this was done to check if any equation or varible assignment is present in the code.
if (this.workspace_to_code && this.workspace_to_code.includes(input_value)) {
return false;
}
this.error_message = localize('Invalid Input {{ input_value }}.', { input_value });
return true;
}

if (evaluated_result < 0) {
this.error_message = localize('Values cannot be negative. Provided value: {{ input_value }}.', {
input_value,
});
return true;
}
},
};
},
};

Blockly.JavaScript.javascriptGenerator.forBlock.tick_delay = block => {
const stack = Blockly.JavaScript.javascriptGenerator.statementToCode(block, 'TICKDELAYSTACK');
const ticks_value =
Blockly.JavaScript.javascriptGenerator.valueToCode(
block,
'TICKDELAYVALUE',
Blockly.JavaScript.javascriptGenerator.ORDER_ATOMIC
) || '1';

const code = `Bot.getDelayTickValue(${ticks_value})\n${stack}\n`;
return code;
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { getCurrencyDisplayCode, getDecimalPlaces } from '@/components/shared';
import { localize } from '@deriv-com/translations';
import { config } from '../../../../constants/config';
import ApiHelpers from '../../../../services/api/api-helpers';
import { handleProposalRequestForAccumulators } from '../../../accumulators-proposal-handler';
import DBotStore from '../../../dbot-store';
import { modifyContextMenu, runGroupedEvents, runIrreversibleEvents } from '../../../utils';

Expand Down Expand Up @@ -102,6 +103,7 @@ window.Blockly.Blocks.trade_definition_accumulator = {
return;
}

handleProposalRequestForAccumulators(this);
const trade_definition_block = this.workspace
.getAllBlocks(true)
.find(block => block.type === 'trade_definition');
Expand Down
4 changes: 4 additions & 0 deletions src/external/bot-skeleton/scratch/dbot.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { compareXml, observer as globalObserver } from '../utils';
import { getSavedWorkspaces, saveWorkspaceToRecent } from '../utils/local-storage';
import { isDbotRTL } from '../utils/workspace';
import main_xml from './xml/main.xml';
import { forgetAccumulatorsProposalRequest } from './accumulators-proposal-handler';
import { loadBlockly } from './blockly';
import DBotStore from './dbot-store';
import { isAllRequiredBlocksEnabled, updateDisabledBlocks, validateErrorOnBlockDelete } from './utils';
Expand Down Expand Up @@ -52,6 +53,8 @@ class DBot {
const symbol = market_block.getFieldValue('SYMBOL_LIST');
const category = this.getFieldValue('TRADETYPECAT_LIST');
const trade_type = this.getFieldValue('TRADETYPE_LIST');
const is_trade_type_accumulator = trade_type === 'accumulator';
if (!is_trade_type_accumulator) forgetAccumulatorsProposalRequest(that);

if (is_symbol_list_change) {
contracts_for.getTradeTypeCategories(market, submarket, symbol).then(categories => {
Expand Down Expand Up @@ -365,6 +368,7 @@ class DBot {
this.interpreter = null;
this.interpreter = Interpreter();
await this.interpreter.bot.tradeEngine.watchTicks(this.symbol);
forgetAccumulatorsProposalRequest(this);
}

/**
Expand Down
25 changes: 17 additions & 8 deletions src/external/bot-skeleton/scratch/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -631,14 +631,12 @@ const download_option = {
};

export const excludeOptionFromContextMenu = (menu, exclude_items) => {
if (exclude_items && exclude_items.length > 0) {
for (let i = menu.length - 1; i >= 0; i--) {
const menu_text = localize(menu[i].text);
if (exclude_items.includes(menu_text)) {
menu.splice(i, 1);
} else {
menu[i].text = menu_text;
}
for (let i = 0; i <= menu.length - 1; i++) {
const menu_text = localize(menu[i].text);
if (exclude_items.includes(menu_text)) {
menu.splice(i, 1);
} else {
menu[i].text = menu_text;
}
}
};
Expand Down Expand Up @@ -680,6 +678,17 @@ export const modifyContextMenu = (menu, add_new_items = []) => {
}
};

export const evaluateExpression = value => {
if (!value) return 'invalid_input';
try {
// eslint-disable-next-line no-new-func
const result = new Function(`return ${value.trim()}`)();
return isNaN(result) ? 'invalid_input' : result;
} catch (e) {
return 'invalid_input';
}
};

export const appendCollapsedMainBlocksFields = block_instance => {
try {
// Return if the block is not collapsed
Expand Down
Loading

0 comments on commit a45ffae

Please sign in to comment.