I have a function that makes use of the current time (now). The Contract as a whole is a Crowdfunding token and the cost of tokens differ depending on the date and time that tokens are purchased.
How does one simulate different times when testing a Smart Contract? For instance, with regards to the code below, I would like to do unit testing to find out if the code for setting price is correct but I can't change the value of now.
Would it be a good solution to simply substitute the now keyword for another temporary testing variable, say now_sim and then manually changing now_sim during simulation?
if (now < (startTime + 1 days)) {
currentPrice = safeDiv(safeMul(price, 80), 100); // 20 % discount (x * 80 / 100)
}
else if (now < (startTime + 2 days)) {
currentPrice = safeDiv(safeMul(price, 90), 100); // 10 % discount (x * 90 / 100)
}
else if (now < (startTime + 12 days)) {
// 1 % reduction in the discounted rate from day 2 until day 12 (sliding scale per second)
// 8640000 is 60 x 60 x 24 x 100 (100 for 1%) (60 x 60 x 24 for seconds per day)
currentPrice = price - safeDiv(safeMul((startTime + 12 days) - now), price), 8640000);
}
else {
currentPrice = price;
}
If you use pyethereum for testing - which I highly recommend, it's lovely - you can directly alter the timestamp of the simulated block that is mining your transaction.
self.s = t.state()
self.s.block.timestamp = self.s.block.timestamp + 86400
self.s.mine(1)
some_val = your_contract.do_something(some_parameter)
self.assertEqual(some_val, whatever)
See a working example here (maybe a bit out-of-date): https://github.com/realitykeys/subjectivocracy/blob/master/contracts/test.py#L85
Related
I try to create an MQL4-script (an almost C++ related language, MQL4) where I want to divide a double value into 9 parts, where the fractions would be unequal, yet increasing
My current code attempts to do it this way (pseudo-code) :
Lots1 = 0.1;
Lots2 = (Lots1 / 100) * 120;//120% of Lot1
Lots3 = (Lots2 / 100) * 130;//130% of Lot2
Lots4 = (Lots3 / 100) * 140;//140% of Lot3
Lots5 = (Lots4 / 100) * 140;//140% of Lot4
Lots6 = (Lots5 / 100) * 160;//160% of Lot5
Lots7 = (Lots6 / 100) * 170;//170% of Lot6
Lots8 = (Lots7 / 100) * 180;//180% of Lot7
Lots9 = (Lots8 / 100) * 190;//190% of Lot8
...
or better :
double Lots = 0.1; // a Lot Size
double lot = Lots;
...
/* Here is the array with percentages of lots' increments
in order */
int AllZoneLots[8] = { 120, 130, 140, 140, 160, 170, 180, 190 }; // 120%, 130%,...
/* Here, the lot sizes are used by looping the array
and increasing the lot size by the count */
for( int i = 0; i < ArraySize( AllZoneLots ); i++ ) {
lots = AllZoneLots[i] * ( lots / 100 ) *;
// PlaceOrder( OP_BUY, lots );
}
But, what I want is to just have a fixed value of 6.7 split into 9 parts, like these codes do, yet to have the value increasing, rather than being same...
e.g, 6.7 split into :
double lots = { 0.10, 0.12, 0.16, 0.22, 0.31, 0.50, 0.85, 1.53, 2.91 };
/* This is just an example
of how to divide a value of 6.7 into 9, growing parts
This can be done so as to make equal steps in the values. If there are 9 steps, divide the value by 45 to get the first value, and the equal step x. Why? Because the sum of 1..9 is 45.
x = 6.7 / 45
which is 0.148889
The first term is x, the second term is 2 * x, the third term is 3 * x etc. They add up to 45 * x which is 6.7, but it's better to divide last. So the second term, say, would be 6.7 * 2 / 45;
Here is code which shows how it can be done in C, since MQL4 works with C Syntax:
#include <stdio.h>
int main(void) {
double val = 6.7;
double term;
double sum = 0;
for(int i = 1; i <= 9; i++) {
term = val * i / 45;
printf("%.3f ", term);
sum += term;
}
printf("\nsum = %.3f\n", sum);
}
Program output:
0.149 0.298 0.447 0.596 0.744 0.893 1.042 1.191 1.340
sum = 6.700
Not sure I understood right, but probably you need total of 3.5 shared between all lots.
And I can see only 8 lots not counting initial one.
totalPercentage = 0;
for(int i = 0; i < ArraySize(AllZoneLots); i++) {
totalPercentage += AllZoneLots[i];
}
double totalValue = 3.5;
// total value is total percentage, Lots1 - 100%, so:
Lots1 = totalValue / totalPercentage * 100.00;
Then you continue with your code.
If you want to include Lots1, you just add 100 to the total and do the same.
Q : How to divide a number into several, unequal, yet increasing numbers [ for sending a PlaceOrder( OP_BUY, lots ) contract XTO ]?
A : The problem is not as free as it might look for a first sight :
In metatrader Terminal ecosystem, the problem formulation has also to obey the externally decided factors ( that are mandatory for any XTO with an ambition not to get rejected, as being principally incompatible with the XTO Terms & Conditions set, and to get filled ~ "placed" At Market )
These factors are reportable via a call to:
MarketInfo( <_a_SymbolToReportSTRING>, MODE_MINLOT ); // a minimum permitted size
MarketInfo( <_a_SymbolToReportSTRING>, MODE_LOTSTEP ); // a mandatory size-stepping
MarketInfo( <_a_SymbolToReportSTRING>, MODE_MAXLOT ); // a maximum permitted size
Additionally, any such lot-size has to be prior of submitting an XTO also "normalised" for given number of decimal places, so as to successfully placed / accepted by the Trading-Server on the Broker's side. A failure to do so results in remotely rejected XTO-s ( which obviously come at a remarkable blocking / immense code-execution latency penalty one would always want to prevent from ever happening in real trading )
Last, but not least, any such XTO sizing has to be covered by a safe amount of leveraged equity ( checking the free-margin availability first, before ever sending any such XTO for reasons just mentioned above ).
The code:
While the initial pseudo-code above, does a progressive ( Martingale-alike ) lot-size scaling:
>>> aListOfFACTORs = [ 100, 120, 130, 140, 140, 160, 170, 180, 190 ]
>>> for endPoint in range( len( aListOfFACTORs ) ):
... product = 1.
... for item in aListOfFACTORs[:1+endPoint]:
... product *= item / 100.
... print( "Lots{0:} ~ ought be about {1:} times the amount of Lots1".format( 1 + endPoint, product ) )
...
Lots1 ~ ought be about 1.0 times the amount of Lots1
Lots2 ~ ought be about 1.2 times the amount of Lots1
Lots3 ~ ought be about 1.56 times the amount of Lots1
Lots4 ~ ought be about 2.184 times the amount of Lots1
Lots5 ~ ought be about 3.0576 times the amount of Lots1
Lots6 ~ ought be about 4.89216 times the amount of Lots1
Lots7 ~ ought be about 8.316672 times the amount of Lots1
Lots8 ~ ought be about 14.9700096 times the amount of Lots1
Lots9 ~ ought be about 28.44301824 times the amount of Lots1
the _MINLOT, _LOTSTEP and _MAXLOT put the game into a new light.
Any successful strategy is not free to chose the sizes. Given the said 9-steps and a fixed amount of the total-amount ~ 6.7 lots, the process can obey the stepping and total, plus, it must obey the MarketInfo()-reported sizing algebra
Given 9-steps are mandatory,
each one has to be at least _MINLOT-sized:
double total_amount_to_split = aSizeToSPLIT;
total_amount_to_split = Min( aSizeToSPLIT, // a wished-to-have-sizing
FreeMargin/LotInBaseCurr*sFty // a FreeMargin-covered size
);
int next = 0;
while ( total_amount_to_split >= _MINLOT )
{ total_amount_to_split -= _MINLOT;
lot_size[next++] = _MINLOT;
}
/*
###################################################################################
------------------------------------------------- HERE, WE HAVE 0:next lot_sizes
next NEED NOT == 9
If there is anything yet to split:
there is an integer amount of _LOTSTEP-s to distribute among 'em
HERE, and ONLY here, you have a freedom to decide about split/mapping
of the integer amount of _LOTSTEP-sized
additions to the _MINLOT "pre"-sets
in lot_size[]-s
YET, still no more than _MAXLOT is permissible for the above explained reasons
------------------------------------------------- CODE has to obey this, if XTO-s
are to
get a chance
###################################################################################
*/
I'm wondering the best way to simulate a sunrise/sunset on the y and z axis. At the moment it does what I want but is moving too fast (say every 3 seconds it's already completed an entire sun path and is already moving in reverse back to the origin).
I know this has to do with seconds variable combined with sin and cos, as this function is called and moves the light's position every frame. Basically I want it to be linked to my game's timer of 50:
50 seconds it's sunrise
25 seconds it's noon
0 seconds it's sunset/game over
Currently I have:
lightPosition = Point_E3d(0,
std::abs(100 *std::cos(seconds)),
-100 * std::sin(seconds));
Wondering what's the correct code format to achieve this effect.
This is just simple trigonometry. The period (Time until the function repeats) of sine(x * n) and cosine(x * n) are both 2*pi / n. In this case, n = 1, so the period is 6.28, meaning one full day (and night) will last 6.28 seconds. If you want to increase the period, multiply your seconds argument by a number smaller than one. A little bit of algebra shows that:
period of sin(x * n) = 2*pi / n
period of sin(.1256 * x) = 2*pi / .1256 = 6.28 / 0.1256 = 50
Therefore, take sine and cosine of seconds * 0.1256, rather than just seconds.
lightPosition = Point_E3d(0,
std::abs(100 *std::cos(seconds * 0.1256 )),
-100 * std::sin(seconds * 0.1256));
Note that this is also including the night time. If you want just the 12 hour day time period to last 50 seconds, multiply by half of 0.1256, aka 0.0628.
Hey all i stink at math here's what i want to do in QML:
I have a slider bar that I want the min left edge to be 30 and the max right edge to be 100
what math puts 30 on the left end but gives all the percentages in between 30-100 to reflect 0-100% on the screen?
Thanks,
Chris
Given a value between 30 and 100:
percent = 100 * (value - 30) / 70
Or more generally:
percent = 100 * (value - min) / (max - min)
I'd like to know if there's any way in C++ to calculate a proportion involving possibily negative values in both vars and extremes.
My goal is to sync a float text input widget with fixed extremes ( eg the user can input any double value between A (min) and B (max) with A,B=any_constant_real_number ) with a slider who can only slide between 0 and 100 ( to simplify ).
If A and B are positive everything is trivial. as
val_slider = ((val_textin-A)*100)/(B-A)
but as A and B can be assumed real it looks to me the only possibility is to use several if/cases, or huge formulas involving a lot of abs() and checks over 0-divisions, whose are quite error prone and very cost intense compared to such an easy task.
Is there any faster and shorter way to achieve the same in c/c++/stl?
Pardon my bad english. Any hint? Thank you.
Your formula should work fine with negative values of A and B as well, as log as A < B.
Example, if you want the user to be able to enter values from -100 to 100, and map these to a slider which goes from 0 - 100, when the user enters -90 you get:
((-90 - A) * 100) / (B - A) = ((-90 - (-100)) * 100) / (100 - (-100))
= 10 * 100 / 200
= 5
An input value of 50 results in a slider value of:
((50 - A) * 100) / (B - A) = ((50 - (-100)) * 100) / (100 - (-100))
= 150 * 100 / 200
= 75
I don't know C++, but I do know Math, so try:
val_slider = 100 * ( val_textin - A ) / ( B - A )
Hey wait. That's exactly what you have. Test case..
A=-200, B=+200, val_texin = 100 (75% of bar, right?)
val_slider = 100 * ( 100 - -200 ) / ( 200 - - 200 )
= ( 300 ) / ( 400 ) * 100
= 75
See, you got it right. The only thing that COULD happen is B==A, but that can't be accounted for with math and requires a single IF. If they are equal, val_slider is exactly B (or A, as they are equal).
I'm looking for a way to distribute a number across x units. I don't even know how to put this words so I'll give an example:
There's a tournament in which the total prize is $1000. I want that the top 20 winners/entrants will win something out of it.I need a mathematical algorithm/formula which will distibute it across those players, and which gives me the power to control certain other factors of the distribution.
A factor for example is that I want the top #1 winner will get $300. The top #2 winner will get smaller percentage of it. The total distribution must give everyone something, until the top #20 winner (the last one) which will get at least X$.
X$ is another factor I want to control.
Any idea? Does this problem has a name (and what's that name is)? Any code example?
Edit #1 - my first proposal:
#include <conio.h>
#include <vector>
#define TOTAL 100
#define WINNERS 15
#define FIRST_WINNER_PERCENTAGE 0.30
void distribute_1(::std::vector<double> * const prizes)
{
prizes->clear();
double total = TOTAL;
double winning_percentage = FIRST_WINNER_PERCENTAGE;
double slope = 0.5;
int winners = WINNERS;
double winning = 0;
for(int i = 0; i < winners; i++, total -= winning, winning_percentage /= 2)
{
winning = total * winning_percentage;
prizes->push_back(winning);
}
}
void distribute_2(::std::vector<double> * const prizes)
{
prizes->clear();
double total = TOTAL;
double winning_percentage = FIRST_WINNER_PERCENTAGE;
double slope = 0.5;
int winners = WINNERS;
double winning = 0;
for(int i = 0; i < winners; i++, total -= winning/*, winning_percentage /= 2*/)
{
winning = total * winning_percentage;
prizes->push_back(winning);
}
}
void distribute_3(::std::vector<double> * const prizes)
{
prizes->clear();
double total = TOTAL;
double winning_percentage = FIRST_WINNER_PERCENTAGE;
double slope = 0.0005;
int winners = WINNERS;
double winning = 0;
for(int i = 0; i < winners; i++, total -= winning, winning_percentage -= slope)
{
winning = total * winning_percentage;
prizes->push_back(winning);
}
}
void distribute_4(::std::vector<double> * const prizes)
{
prizes->clear();
double total = TOTAL;
double winning_percentage = FIRST_WINNER_PERCENTAGE;
double slope = 1 / WINNERS;
int winners = WINNERS;
double winning = 0;
for(int i = 0; i < winners; i++, total -= winning, winning_percentage -= slope)
{
winning = total * winning_percentage;
prizes->push_back(winning);
}
}
void main()
{
::std::vector<double> prizes;
distribute_1(&prizes);
distribute_2(&prizes);
distribute_3(&prizes);
distribute_4(&prizes);
double total_granted = 0;
for(int i = 0; i < WINNERS; i++)
{
total_granted += prizes[i];
printf("%lf\n", prizes[i]);
}
printf("-\n%lf\n", total_granted);
_getch();
}
This is as far as I could reach. The issue with this one is for example, if that if you set 'WINNERS' to 5 for example, the algorithm doesn't reach the 'TOTAL' amount (100 in this example) or even closer (I get a total of 83).
Cristy's solution:
#include <conio.h>
#include<iostream>
//using arithmetic progression
using namespace std;
int i;
float ratio;
float first_prize;
float s;
int main()
{
float money=1000;
const int total_prizes = 10;
float last_prize = 99;
float prizes[total_prizes+1];
/**/first_prize=2*money/total_prizes-last_prize; //last member of the progresion
ratio=(first_prize-last_prize)/(total_prizes-1);
prizes[total_prizes]=last_prize;
for(i=total_prizes-1;i>=1;i--){
prizes[i]=prizes[i+1]+ratio;
money-=prizes[i];
}
for(i=1;i<=total_prizes;i++){
printf("%d) %.2f\n",i,prizes[i]);
s+=prizes[i];
}
printf("TOTAL SUM:%.2f\n",s);
printf("Ratio: %.2f", ratio);
_getch();
}
It's 1:15 AM here and I'm solving maths :)).
Using arithmetic progression.
I made all using defines so you can easily change them.
#include<iostream>
//using arithmetic progression
using namespace std;
FILE *g=fopen("output.out","w");
#define last_prize 10
#define total_prizes 20
int i;
float prizes[total_prizes+1];
float money=1000;
float ratio;
float first_prize;
float s;
//a1=last_prize
//an=first_prize
int main(){
first_prize=2*money/total_prizes+last_prize; //last member of the progresion
ratio=(first_prize-last_prize)/(total_prizes-1);
prizes[total_prizes]=last_prize;
for(i=total_prizes-1;i>=1;i--)
prizes[i]=prizes[i+1]+ratio;
for(i=1;i<=total_prizes;i++){
fprintf(g,"%d) %.2f\n",i,prizes[i]);
s+=prizes[i];
}
fprintf(g,"TOTAL SUM:%.2f",s);
return 0;
}
OUTPUT:
1) 90.00
2) 85.79
3) 81.58
4) 77.37
5) 73.16
6) 68.95
7) 64.74
8) 60.53
9) 56.32
10) 52.11
11) 47.89
12) 43.68
13) 39.47
14) 35.26
15) 31.05
16) 26.84
17) 22.63
18) 18.42
19) 14.21
20) 10.00
TOTAL SUM:1000.00
As you can see they sum up to exactly 1000.00$ :D
Other results:
INPUT:
#define last_prize 30
#define total_prizes 5
OUTPUT:
1) 370.00
2) 285.00
3) 200.00
4) 115.00
5) 30.00
TOTAL SUM:1000.00
You could make a simple formula like.
#include<iostream>
using namespace std;
FILE *g=fopen("output.out","w");
int i;
int prizes[21];
int money=1000;
int main(){
for(i=1;i<=20;i++){
prizes[i]=(float)(15+(20-i))/100*money;
money-=prizes[i];
fprintf(g,"%d) %d\n",i,prizes[i]);
}
return 0;
}
This will output:
1) 340
2) 217
3) 141
4) 93
5) 62
6) 42
7) 29
8) 20
9) 14
10) 10
11) 7
12) 5
13) 4
14) 3
15) 2
16) 2
17) 1
18) 1
19) 1
20) 0
But you can change the values to anything you would like :).
This is just a fast&easy way to do this.
The starting ideea for this algorithm was:
1st prize: 30% from all the money (1000$) = ~330$
2nd prize: 30% from the rest (670$) = ~201
3rd prize: 30% from the rest... etc...
If you replace (15+(20-i)) with 20 let's say, you get this output:
Just change that value to get diffrent results.
1) 200
2) 160
3) 128
4) 102
5) 82
6) 65
7) 52
8) 42
9) 33
10) 27
11) 21
12) 17
13) 14
14) 11
15) 9
16) 7
17) 6
18) 4
19) 4
20) 3
EDIT:
And one more thing. After splitting all the money using that algorithms there may still be some money left (because the last one gets x% from the rest). You can add the left-over to the first place...
I had this problem for a pool - I wanted the 3 levels of individual prizes to have the same relative ratio (70%/20%/10%) but recognized the likelyhood of ties, so I had to account for that. I didn't want to just split the pot then award prizes since you might end up with ties for second and an individual second place winner getting less than the third place winner.
P(i) = Size of Prize
N(i) = Number of winners
1) Sum (over i) P(i)*N(i) = $1000
2) P(1)/P(2) = 70/20
3) P(2)/P(3) = 20/10
In my case, 3 equations in 3 unknowns - which I solved to get a unique solution.
For your example P(1) = $300. I would just specify successive ratios of prizes and solve the linear system of equations.
Also consider looking here for the distribution of golf prizes at the recent British Open Championship. I'm not saying that the PGA could do a better job than the talent at this website, but it a demonstration of your question in action.
Suppose total money M, you want distribute in n pools such that first person will get k times more than second and second gets k times more than third and so on. Suppose last one get x amount money then
x + k*x + k^2*x ... k^(n-1)*x = M
x(k^n-1)/(k-1) = M
Solve for x from this equation based on value of k you choose and distribute money :-)
Formula in first line of Cristy is wrong.
first_prize=2*money/total_prizes+last_prize;
It should be first_prize=2*money/total_prizes - last_prize;
Here is my solution in python, this will add residual amount to top winners.
starting_amount = (((winnings * 2) / float(no_of_winners)) - last_amount)
difference = (last_amount - starting_amount) / float(no_of_winners - 1)
for rank in range(1, no_of_winners + 1):
reward = starting_amount + difference * (rank - 1)
reward = round_amount(reward)
winnings -= reward
winning_amount[rank] = reward
residual_winnings = winnings
residual_shares = {1: 0.5, 2: 0.3, 3: 0.2}
if no_of_winners < 3:
winning_amount[1] += residual_winnings
else:
for rank in residual_shares:
reward = residual_winnings * residual_shares[rank]
reward = round_amount(reward)
winning_amount[rank] += reward
I spent a few hours trying to come up with an algorithm that will distribute prizes. Here is my solution based off things I saw on various forums. This code is in Ruby. This has worked great for me.
def self.get_prize_array(money,total_prizes)
prizes = []
p = 0.7 # tweek this for distribution of payout
n = total_prizes
l = money
(1..total_prizes).each do |r|
prizes[r-1] = ((1 - p) / (1 - p**n) * p**(r - 1)) * l # p**n is p to the nth power
end
return prizes
end