autotrade::Market::Simulated, autotrade-sim.pl: Support for strategy simulation on...
[autotrade.git] / autotrade-sim.pl
blob623ba01ca1d68944b62bfb2a988e0edbaf9339b9
1 #!/usr/bin/perl
3 # Automated Bitcoin Trader - Simulator
4 # (c) Petr Baudis <pasky@ucw.cz> 2011
6 # Feeds the trader simulated data based on RateHistory database. You can
7 # import historical data using
8 # curl 'http://bitcoincharts.com/t/trades.csv?start=0&end='$(date +%s)'&symbol=mtgoxUSD' | ./import-csv.pl
10 # You can render the generated plot using
11 # gnuplot -persist -e 'plot "sim.plot" using 2 with lines title "buy", "sim.plot" using 3 with lines title "sell", "sim.plot" using 4 with lines title "btc", "sim.plot" using 5 with lines title "usd" axes x1y2, "sim.plot" using 6 with lines title "total" axes x1y2'
13 # Usage: ./autotrate-sim.pl START_BALANCE STARTTIME STEP ENDTIME
15 use warnings;
16 use strict;
19 use autotrade::MarketTools;
21 my ($usdbal, $start, $step, $stop) = @ARGV;
23 use autotrade::SQL;
24 use autotrade::RateHistory;
25 use autotrade::Market::Simulated;
26 use autotrade::Trader::LowHigh;
27 use autotrade::Trader::Slope;
29 my $dbh = autotrade::SQL::db_connect("autotrade-sim.sqlite");
30 $dbh->do("PRAGMA synchronous = OFF");
31 $dbh->do("DELETE FROM bitcoin_values");
32 my $rh = autotrade::RateHistory->new(dbh => $dbh);
33 my $m = autotrade::Market::Simulated->new(bal_btc => 0, bal_usd => str_curr($usdbal), rh => $rh);
34 my $t = autotrade::Trader::Slope->new(dbh => $dbh, rh => $rh, m => $m, time_window => 1200, raise_threshold => 0.25, fall_threshold => -0.25);
36 open PLOT, ">sim.plot";
38 while ($start < $stop) {
39 printf "%d: %s\n", $start, scalar localtime($start);
40 my ($md, $n);
41 do {
42 $md = $m->market_data($start);
43 } while ($t->beat($md, $start));
44 printf PLOT "%d %s %s %s %s %s\n", time,
45 curr_str($md->rate_buybtc()), curr_str($md->rate_sellbtc()),
46 curr_str($m->bal_btc()), curr_str($m->bal_usd()),
47 curr_str(curr_conv($m->bal_btc(), $md->rate_buybtc()) + $m->bal_usd());
48 $start += $step;
49 print "\n";
52 printf "=== Final balance: %s BTC, %s USD => %s USD\n",
53 curr_str($m->bal_btc()), curr_str($m->bal_usd()), curr_str(curr_conv($m->bal_btc(), $m->market_data($start)->rate_buybtc()) + $m->bal_usd());