Skip to content

Commit

Permalink
Merge pull request #149 from diogomatoschaves/frontend_updates
Browse files Browse the repository at this point in the history
Frontend updates. Handle Negative Equity case
  • Loading branch information
diogomatoschaves authored Feb 15, 2024
2 parents 9a1fce4 + c010f65 commit 89cd256
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 21 deletions.
2 changes: 1 addition & 1 deletion dashboard/src/apiCalls/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const getPositions = async (page) => {
}
})

if (response.status === 401 || response.status === 422) throw Error
if (response.status === 401 || response.status === 422) throw Error(response.status)

return await response.json()
}
Expand Down
23 changes: 14 additions & 9 deletions dashboard/src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class App extends Component<Props, State> {
}
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))

this.updateTrades()

Expand Down Expand Up @@ -355,7 +355,7 @@ class App extends Component<Props, State> {
}, {})
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

getTotalEquityTimeSeries = () => {
Expand All @@ -368,7 +368,7 @@ class App extends Component<Props, State> {
}
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

getAccountBalance = () => {
Expand All @@ -384,7 +384,7 @@ class App extends Component<Props, State> {
}
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

updatePipelinesMetrics = () => {
Expand All @@ -394,7 +394,7 @@ class App extends Component<Props, State> {
pipelinesMetrics: response
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

updateTrades = (page?: number, pipelineId?: string) => {
Expand All @@ -412,7 +412,7 @@ class App extends Component<Props, State> {
}
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

updatePipelines = () => {
Expand All @@ -430,7 +430,7 @@ class App extends Component<Props, State> {
}
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

updatePositions = () => {
Expand All @@ -446,10 +446,15 @@ class App extends Component<Props, State> {
}
})
})
.catch(() => this.logoutUser())
.catch((error) => this.logoutUser(error.message))
}

logoutUser = () => {
logoutUser = (statusCode: string) => {

if (!["401", "422"].includes(statusCode)) {
return
}

const {removeToken, updateMessage} = this.props
updateMessage({text: 'Token Expired', success: false})
removeToken()
Expand Down
2 changes: 1 addition & 1 deletion dashboard/src/utils/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export const validateParams = (strategy: any) => {
const paramValue = paramData.options ? paramData.options[params[param]] : params[param]

let typedParam
if (strategy.params[param].type) {
if (strategy.optionalParams[param].type) {
const typedParam = eval(strategy.optionalParams[param].type.func)(paramValue)
if (typedParam !== typedParam || typeof (typedParam) !== paramData.type.type) {
return {
Expand Down
32 changes: 25 additions & 7 deletions execution/exchanges/binance/futures/_trading.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from database.model.models import Pipeline
from execution.exchanges.binance import BinanceTrader
from execution.service.blueprints.market_data import filter_balances
from execution.service.cron_jobs.save_pipelines_snapshot import save_portfolio_value_snapshot, save_pipeline_snapshot
from execution.service.cron_jobs.save_pipelines_snapshot import save_pipeline_snapshot
from execution.service.helpers.exceptions import SymbolAlreadyTraded, SymbolNotBeingTraded, NoUnits, NegativeEquity, \
InsufficientBalance
from execution.service.helpers.exceptions.leverage_setting_fail import LeverageSettingFail
Expand Down Expand Up @@ -123,9 +123,26 @@ def close_pos(self, symbol, date=None, row=None, header='', **kwargs):
raise NoUnits

if self.units[symbol] < 0:
self.buy_instrument(symbol, date, row, units=-self.units[symbol], header=header, reducing=True, **kwargs)
self.buy_instrument(
symbol,
date,
row,
units=-self.units[symbol],
header=header,
reducing=True,
stop_trading=True,
**kwargs)
else:
self.sell_instrument(symbol, date, row, units=self.units[symbol], header=header, reducing=True, **kwargs)
self.sell_instrument(
symbol,
date,
row,
units=self.units[symbol],
header=header,
reducing=True,
stop_trading=True,
**kwargs
)

self._set_position(symbol, 0, previous_position=1, **kwargs)

Expand All @@ -143,7 +160,8 @@ def _execute_order(
header='',
**kwargs
):
reducing = "reducing" in kwargs
reducing = kwargs.get('reducing', False)
stop_trading = kwargs.get('stop_trading', False)

units = self._convert_units(amount, units, symbol)

Expand Down Expand Up @@ -177,7 +195,7 @@ def _execute_order(

self.report_trade(order, units, going, header, symbol=symbol)

self.check_negative_equity(symbol, reducing=reducing)
self.check_negative_equity(symbol, reducing=reducing, stop_trading=stop_trading)

@binance_error_handler(num_times=2)
def _convert_units(self, amount, units, symbol, units_factor=1):
Expand Down Expand Up @@ -260,7 +278,7 @@ def _get_symbol_info(self, symbol):
def close_pipeline(pipeline_id):
Pipeline.objects.filter(id=pipeline_id).update(active=False, open_time=None)

def check_negative_equity(self, symbol, reducing):
if reducing:
def check_negative_equity(self, symbol, reducing, stop_trading=False):
if reducing and not stop_trading:
if self.current_balance[symbol] < 0:
raise NegativeEquity(self.current_balance[symbol])
5 changes: 4 additions & 1 deletion execution/service/helpers/decorators/handle_app_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from flask import jsonify

from execution.service.helpers.exceptions import *
from shared.utils.exceptions import SymbolInvalid, NoSuchPipeline, EquityRequired
from shared.utils.exceptions import NoSuchPipeline, EquityRequired


def handle_app_errors(_func=None):
Expand Down Expand Up @@ -44,6 +44,9 @@ def wrapper(*args, **kwargs):
except InsufficientBalance as e:
logging.info(e.message)
return jsonify(Responses.INSUFFICIENT_BALANCE(e.message))
except NegativeEquity as e:
logging.info(e.message)
return jsonify(Responses.NEGATIVE_EQUITY(e.message))

return wrapper

Expand Down
15 changes: 13 additions & 2 deletions execution/tests/service/test_execution_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,20 +350,31 @@ def test_failed_execute_order(
assert res.json == expected_value

@pytest.mark.parametrize(
"params,expected_value",
"endpoint,params,expected_value",
[
pytest.param(
"/execute_order",
{
"pipeline_id": 1,
"signal": 1
},
Responses.NEGATIVE_EQUITY('Pipeline 1 has reached negative equity.'),
id="NEGATIVE_EQUITY-execute-order",
),
pytest.param(
"/stop_symbol_trading",
{
"pipeline_id": 1,
"signal": 1
},
Responses.NEGATIVE_EQUITY('Pipeline 1 has reached negative equity.'),
id="NEGATIVE_EQUITY-stop_symbol_trading",
),
]
)
def test_failed_execute_order_negative_equity(
self,
endpoint,
params,
expected_value,
mock_binance_futures_trader_raise_negative_equity_error,
Expand All @@ -373,7 +384,7 @@ def test_failed_execute_order_negative_equity(
create_inactive_pipeline,
):

res = client.post(f"/execute_order", json=params)
res = client.post(endpoint, json=params)

assert res.json == expected_value

Expand Down
2 changes: 2 additions & 0 deletions execution/tests/setup/fixtures/internal_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ def stop_symbol_trading(self, pipeline_id, header='', **kwargs):
)
if self.raise_symbol_not_being_traded:
raise SymbolNotBeingTraded('BTCUSDT')
elif self.raise_negative_equity_error:
raise NegativeEquity(1)

def trade(self, symbol, signal, amount, header='', **kwargs):
if self.raise_error_trade:
Expand Down

0 comments on commit 89cd256

Please sign in to comment.