Merge with json-dicts

This commit is contained in:
Reckless_Satoshi 2022-01-09 04:35:19 -08:00
commit 185e0af496
No known key found for this signature in database
GPG Key ID: 9C4585B561315571
10 changed files with 101 additions and 45 deletions

8
api/currencies.json Normal file
View File

@ -0,0 +1,8 @@
{
"1":"USD",
"2":"EUR",
"3":"ETH",
"4":"AUD",
"5":"BRL",
"6":"CAD"
}

View File

@ -61,7 +61,7 @@ class Logics():
if order.is_explicit: if order.is_explicit:
satoshis_now = order.satoshis satoshis_now = order.satoshis
else: else:
exchange_rate = get_exchange_rate(Order.Currencies(order.currency).label) exchange_rate = get_exchange_rate(Order.currency_dict[str(order.currency)])
premium_rate = exchange_rate * (1+float(order.premium)/100) premium_rate = exchange_rate * (1+float(order.premium)/100)
satoshis_now = (float(order.amount) / premium_rate) * 100*1000*1000 satoshis_now = (float(order.amount) / premium_rate) * 100*1000*1000
@ -350,4 +350,4 @@ class Logics():
return False, {'bad_request':'You cannot confirm the fiat payment at this stage'} return False, {'bad_request':'You cannot confirm the fiat payment at this stage'}
order.save() order.save()
return True, None return True, None

View File

@ -8,7 +8,7 @@ from django.utils.html import mark_safe
from decouple import config from decouple import config
from pathlib import Path from pathlib import Path
from .utils import get_exchange_rate from .utils import get_exchange_rate
import json
MIN_TRADE = int(config('MIN_TRADE')) MIN_TRADE = int(config('MIN_TRADE'))
MAX_TRADE = int(config('MAX_TRADE')) MAX_TRADE = int(config('MAX_TRADE'))
@ -64,11 +64,6 @@ class Order(models.Model):
BUY = 0, 'BUY' BUY = 0, 'BUY'
SELL = 1, 'SELL' SELL = 1, 'SELL'
class Currencies(models.IntegerChoices):
USD = 1, 'USD'
EUR = 2, 'EUR'
ETH = 3, 'ETH'
class Status(models.IntegerChoices): class Status(models.IntegerChoices):
WFB = 0, 'Waiting for maker bond' WFB = 0, 'Waiting for maker bond'
PUB = 1, 'Public' PUB = 1, 'Public'
@ -88,7 +83,10 @@ class Order(models.Model):
FAI = 15, 'Failed lightning network routing' FAI = 15, 'Failed lightning network routing'
MLD = 16, 'Maker lost dispute' MLD = 16, 'Maker lost dispute'
TLD = 17, 'Taker lost dispute' TLD = 17, 'Taker lost dispute'
currency_dict = json.load(open('./api/currencies.json'))
currency_choices = [(int(val), label) for val, label in list(currency_dict.items())]
print(currency_choices)
# order info # order info
status = models.PositiveSmallIntegerField(choices=Status.choices, null=False, default=Status.WFB) status = models.PositiveSmallIntegerField(choices=Status.choices, null=False, default=Status.WFB)
@ -97,7 +95,7 @@ class Order(models.Model):
# order details # order details
type = models.PositiveSmallIntegerField(choices=Types.choices, null=False) type = models.PositiveSmallIntegerField(choices=Types.choices, null=False)
currency = models.PositiveSmallIntegerField(choices=Currencies.choices, null=False) currency = models.PositiveSmallIntegerField(choices=currency_choices, null=False)
amount = models.DecimalField(max_digits=9, decimal_places=4, validators=[MinValueValidator(0.00001)]) amount = models.DecimalField(max_digits=9, decimal_places=4, validators=[MinValueValidator(0.00001)])
payment_method = models.CharField(max_length=35, null=False, default="not specified", blank=True) payment_method = models.CharField(max_length=35, null=False, default="not specified", blank=True)
@ -133,7 +131,7 @@ class Order(models.Model):
def __str__(self): def __str__(self):
# Make relational back to ORDER # Make relational back to ORDER
return (f'Order {self.id}: {self.Types(self.type).label} BTC for {float(self.amount)} {self.Currencies(self.currency).label}') return (f'Order {self.id}: {self.Types(self.type).label} BTC for {float(self.amount)} {self.currency_dict[str(self.currency)]}')
@receiver(pre_delete, sender=Order) @receiver(pre_delete, sender=Order)
def delelete_HTLCs_at_order_deletion(sender, instance, **kwargs): def delelete_HTLCs_at_order_deletion(sender, instance, **kwargs):
@ -204,7 +202,7 @@ class MarketTick(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2, default=None, null=True, validators=[MinValueValidator(0)]) price = models.DecimalField(max_digits=10, decimal_places=2, default=None, null=True, validators=[MinValueValidator(0)])
volume = models.DecimalField(max_digits=8, decimal_places=8, default=None, null=True, validators=[MinValueValidator(0)]) volume = models.DecimalField(max_digits=8, decimal_places=8, default=None, null=True, validators=[MinValueValidator(0)])
premium = models.DecimalField(max_digits=5, decimal_places=2, default=None, null=True, validators=[MinValueValidator(-100), MaxValueValidator(999)], blank=True) premium = models.DecimalField(max_digits=5, decimal_places=2, default=None, null=True, validators=[MinValueValidator(-100), MaxValueValidator(999)], blank=True)
currency = models.PositiveSmallIntegerField(choices=Order.Currencies.choices, null=True) currency = models.PositiveSmallIntegerField(choices=Order.currency_choices, null=True)
timestamp = models.DateTimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now_add=True)
# Relevant to keep record of the historical fee, so the insight on the premium can be better analyzed # Relevant to keep record of the historical fee, so the insight on the premium can be better analyzed
@ -221,7 +219,7 @@ class MarketTick(models.Model):
elif order.taker_bond.status == LNPayment.Status.LOCKED: elif order.taker_bond.status == LNPayment.Status.LOCKED:
volume = order.last_satoshis / 100000000 volume = order.last_satoshis / 100000000
price = float(order.amount) / volume # Amount Fiat / Amount BTC price = float(order.amount) / volume # Amount Fiat / Amount BTC
premium = 100 * (price / get_exchange_rate(Order.Currencies(order.currency).label) - 1) premium = 100 * (price / get_exchange_rate(Order.currency_dict[str(order.currency)]) - 1)
tick = MarketTick.objects.create( tick = MarketTick.objects.create(
price=price, price=price,

View File

@ -1,5 +1,5 @@
from django.urls import path from django.urls import path
from .views import MakerView, OrderView, UserView, BookView, InfoView from .views import MakerView, OrderView, UserView, BookView, InfoView, get_currencies_json
urlpatterns = [ urlpatterns = [
path('make/', MakerView.as_view()), path('make/', MakerView.as_view()),
@ -8,4 +8,5 @@ urlpatterns = [
path('book/', BookView.as_view()), path('book/', BookView.as_view()),
# path('robot/') # Profile Info # path('robot/') # Profile Info
path('info/', InfoView.as_view()), path('info/', InfoView.as_view()),
path('currencies/', get_currencies_json),
] ]

View File

@ -21,6 +21,9 @@ from datetime import timedelta
from django.utils import timezone from django.utils import timezone
from decouple import config from decouple import config
import json
from django.http import HttpResponse
EXP_MAKER_BOND_INVOICE = int(config('EXP_MAKER_BOND_INVOICE')) EXP_MAKER_BOND_INVOICE = int(config('EXP_MAKER_BOND_INVOICE'))
FEE = float(config('FEE')) FEE = float(config('FEE'))
@ -349,6 +352,7 @@ class BookView(ListAPIView):
def get(self,request, format=None): def get(self,request, format=None):
currency = request.GET.get('currency') currency = request.GET.get('currency')
print("currency:", currency)
type = request.GET.get('type') type = request.GET.get('type')
queryset = Order.objects.filter(currency=currency, type=type, status=int(Order.Status.PUB)) queryset = Order.objects.filter(currency=currency, type=type, status=int(Order.Status.PUB))
if len(queryset)== 0: if len(queryset)== 0:
@ -382,7 +386,10 @@ class InfoView(ListAPIView):
context['total_volume'] = None context['total_volume'] = None
return Response(context, status.HTTP_200_OK) return Response(context, status.HTTP_200_OK)
def get_currencies_json(request):
currency_dict = json.load(open('./api/currencies.json'))
return HttpResponse(json.dumps(currency_dict),content_type="application/json")

View File

@ -9,7 +9,9 @@ export default class BookPage extends Component {
orders: new Array(), orders: new Array(),
currency: 1, currency: 1,
type: 1, type: 1,
currencies_dict: {"1":"USD"}
}; };
this.getCurrencyDict()
this.getOrderDetails() this.getOrderDetails()
this.state.currencyCode = this.getCurrencyCode(this.state.currency) this.state.currencyCode = this.getCurrencyCode(this.state.currency)
} }
@ -44,11 +46,19 @@ export default class BookPage extends Component {
}) })
this.getOrderDetails(); this.getOrderDetails();
} }
getCurrencyDict() {
fetch('/api/currencies')
.then((response) => response.json())
.then((data) =>
this.setState({
currencies_dict: data
}));
}
// Gets currency code (3 letters) from numeric (e.g., 1 -> USD) // Gets currency code (3 letters) from numeric (e.g., 1 -> USD)
// Improve this function so currencies are read from json // Improve this function so currencies are read from json
getCurrencyCode(val){ getCurrencyCode(val){
return (val == 1 ) ? "USD": ((val == 2 ) ? "EUR":"ETH") return this.state.currencies_dict[val.toString()]
} }
// pretty numbers // pretty numbers
@ -156,9 +166,10 @@ export default class BookPage extends Component {
}} }}
onChange={this.handleCurrencyChange} onChange={this.handleCurrencyChange}
> >
<MenuItem value={1}>USD</MenuItem> {
<MenuItem value={2}>EUR</MenuItem> Object.entries(this.state.currencies_dict)
<MenuItem value={3}>ETH</MenuItem> .map( ([key, value]) => <MenuItem value={parseInt(key)}>{value}</MenuItem> )
}
</Select> </Select>
</FormControl> </FormControl>
</Grid> </Grid>

View File

@ -37,7 +37,9 @@ export default class MakerPage extends Component {
payment_method: this.defaultPaymentMethod, payment_method: this.defaultPaymentMethod,
premium: 0, premium: 0,
satoshis: null, satoshis: null,
currencies_dict: {"1":"USD"}
} }
this.getCurrencyDict()
} }
handleTypeChange=(e)=>{ handleTypeChange=(e)=>{
@ -46,10 +48,9 @@ export default class MakerPage extends Component {
}); });
} }
handleCurrencyChange=(e)=>{ handleCurrencyChange=(e)=>{
var code = (e.target.value == 1 ) ? "USD": ((e.target.value == 2 ) ? "EUR":"ETH")
this.setState({ this.setState({
currency: e.target.value, currency: e.target.value,
currencyCode: code, currencyCode: this.getCurrencyCode(e.target.value),
}); });
} }
handleAmountChange=(e)=>{ handleAmountChange=(e)=>{
@ -108,6 +109,20 @@ export default class MakerPage extends Component {
& (data.id ? this.props.history.push('/order/' + data.id) :""))); & (data.id ? this.props.history.push('/order/' + data.id) :"")));
} }
getCurrencyDict() {
fetch('/api/currencies')
.then((response) => response.json())
.then((data) =>
this.setState({
currencies_dict: data
}));
}
getCurrencyCode(val){
return this.state.currencies_dict[val.toString()]
}
render() { render() {
return ( return (
<Grid container spacing={1}> <Grid container spacing={1}>
@ -163,9 +178,10 @@ export default class MakerPage extends Component {
}} }}
onChange={this.handleCurrencyChange} onChange={this.handleCurrencyChange}
> >
<MenuItem value={1}>USD</MenuItem> {
<MenuItem value={2}>EUR</MenuItem> Object.entries(this.state.currencies_dict)
<MenuItem value={3}>ETH</MenuItem> .map( ([key, value]) => <MenuItem value={parseInt(key)}>{value}</MenuItem> )
}
</Select> </Select>
</FormControl> </FormControl>
</Grid> </Grid>

View File

@ -68,8 +68,10 @@ export default class OrderPage extends Component {
this.state = { this.state = {
isExplicit: false, isExplicit: false,
delay: 5000, // Refresh every 5 seconds delay: 5000, // Refresh every 5 seconds
currencies_dict: {"1":"USD"}
}; };
this.orderId = this.props.match.params.orderId; this.orderId = this.props.match.params.orderId;
this.getCurrencyDict();
this.getOrderDetails(); this.getOrderDetails();
} }
@ -78,7 +80,6 @@ export default class OrderPage extends Component {
fetch('/api/order' + '?order_id=' + this.orderId) fetch('/api/order' + '?order_id=' + this.orderId)
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
console.log(data) &
this.setState({ this.setState({
statusCode: data.status, statusCode: data.status,
statusText: data.status_message, statusText: data.status_message,
@ -111,7 +112,6 @@ export default class OrderPage extends Component {
}); });
} }
// These are used to refresh the data // These are used to refresh the data
componentDidMount() { componentDidMount() {
this.interval = setInterval(this.tick, this.state.delay); this.interval = setInterval(this.tick, this.state.delay);
@ -132,8 +132,6 @@ export default class OrderPage extends Component {
this.setState({ delay: Number(e.target.value) }); this.setState({ delay: Number(e.target.value) });
} }
// Gets currency code (3 letters) from numeric (e.g., 1 -> USD) // Gets currency code (3 letters) from numeric (e.g., 1 -> USD)
// Improve this function so currencies are read from json // Improve this function so currencies are read from json
getCurrencyCode(val){ getCurrencyCode(val){
@ -158,6 +156,22 @@ export default class OrderPage extends Component {
.then((response) => response.json()) .then((response) => response.json())
.then((data) => (console.log(data) & this.getOrderDetails(data.id))); .then((data) => (console.log(data) & this.getOrderDetails(data.id)));
} }
getCurrencyDict() {
fetch('/api/currencies')
.then((response) => response.json())
.then((data) =>
this.setState({
currencies_dict: data
}));
}
// Gets currency code (3 letters) from numeric (e.g., 1 -> USD)
// Improve this function so currencies are read from json
getCurrencyCode(val){
console.log("---------------------------------")
console.log(val)
return this.state.currencies_dict[val.toString()]
}
handleClickCancelOrderButton=()=>{ handleClickCancelOrderButton=()=>{
console.log(this.state) console.log(this.state)

View File

@ -160,31 +160,31 @@ export default class TradeBox extends Component {
) )
} }
showInputInvoice(){ // showInputInvoice(){
} // }
showWaitingForEscrow(){ // showWaitingForEscrow(){
} // }
showWaitingForBuyerInvoice({ // showWaitingForBuyerInvoice({
}) // })
showFiatSentButton(){ // showFiatSentButton(){
} // }
showFiatReceivedButton(){ // showFiatReceivedButton(){
} // }
showOpenDisputeButton(){ // showOpenDisputeButton(){
} // }
showRateSelect(){ // showRateSelect(){
} // }
render() { render() {
@ -220,7 +220,7 @@ export default class TradeBox extends Component {
{/* */} {/* */}
{/* */} {/* */}
</Paper> </Paper>
</Grid> </Grid>
</Grid> </Grid>

View File

@ -8,5 +8,6 @@ urlpatterns = [
path('make/', index), path('make/', index),
path('book/', index), path('book/', index),
path('order/<int:orderId>', index), path('order/<int:orderId>', index),
path('wait/', index), path('wait/', index),
path('currencies/',index)
] ]