forked from SOCIT/bitcoin-rolling-bot-php
/
arbot.php
1685 lines (1510 loc) · 82.1 KB
/
arbot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre>
<?php>
////////////////////////////////////////////////////////////////////
//Programs
////////////////////////////////////////////////////////////////////
//A - Currency Arbitrage, Choose UtoU or BtoB arbitrage through L
//B - Portfolio Balancing, Maintain 50% of two currencies at all times
//C - Custom trailing/advancing sell/sell bot for gna
//D - Buy Down, Buy 1/2 spread each .5 drop and sell 1 each $1 gain
//E - Rolling sell/sell on dips and spikes V1,1.1,1.2,V2,2.1
//F - 24 Hour high/low balancing bot, maintain (high-last)/(high-low) balance in USD and (last-low)/(high-low) in BTC
//G - EMA triggered rolling with Fibonacci shares and high/low balancing combination with micro-trade re-balancing.
//H - Custom Rolling bot based on dynamic thresholds
//I - Micro-Trade rolling bot with variable buy and sell orders and iterations
//J - Revamped micro-rebalance engine added as option - balances based on distance to high low
////////////////////////////////////////////////////////////////////
//Advance and Tail last price with orders ( commision + profit/2 )
//Set order amounts to min < all < max
//Buy as price falls
//Sell as price rises
//USE triple EMA + last to determine trends
//USE distance from high/low to determine funds to sell/buy
//NOTE Buy at last - threshold ( amount is min ( maxtrade, rebalance percentage )
//NOTE num orders is set for buy and sell, use $incriment for order difference
//NOTE 100 orders sell would be price1+.01+.01 etc
//Don't sell unless last > EMA1 > EMA2 > EMA3
//Don't buy unless last < EMA1 < EMA2 < EMA3
//Use micro-orders to play on spikes and dips
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//USER CONFIGURABLE
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//FEATURES
$DEBUG = TRUE; //Should the program Print Debug information
$simulate = FALSE; //RUNS IN SIMULATION MODE, NO TRADES ARE MADE just PRINT OUTPUT
$exchange = "G"; //Pick an exchange to run on
if ($exchange == "G") {$GOX = TRUE;$BTCE = FALSE;}
if ($exchange == "E") {$BTCE = TRUE;$GOX = FALSE;}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//ENGINE Selection
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
$ENGINE = "M";
//H - Hybrid Engine
//E - EMA engine
//S - Static Engine
//B - Filled Engine
//FF - 50/50 Balance Engine
//JOSH - JOSH's Trading Engine
//JUDE - JUDE's Trading Engine
//M - Micro-roll engine
//F
$HYBRID = $STATIC = $EMA = $BALANCE = $JOSH = $FF = $F = FALSE;
switch ($ENGINE) {
case "H":
$HYBRID = TRUE;
break;
case "E":
$EMA = TRUE;
//EMA times to use
$ema1Time = 5;
$ema2Time = 11;
$ema3Time = 22;
$ema1M = 2 / ( $ema1Time +1 );
$ema2M = 2 / ( $ema2Time +1 );
$ema3M = 2 / ( $ema3Time +1 );
break;
case "S":
$STATIC = TRUE;
break;
case "M":
$MICRO = TRUE;
////////////////////////////////////////////////////////////////////
//MICRO-TRADE SETTINGS
//array(0.023360861,0.035041292,0.040881508,0.055482046,0.06862253,0.089793311,0.113519186,0.146552904,0.186795638,0.239950723); //0,1,1.5,N1+N2/2,N2+N3/2... Modified Fibonacci shares 10 rounds.
/*
method fib - calculates fibonacci shares
1,2,3,5,8,13 multiplier X = 1/(sum of all numbers)*{series X}
method fib tame - calculates fibonacci shares with a divisor for n3+.
$microBuyAmountMultiplier = engineMultiplier('fibtame',4,$microBuyDivisor);
n1=1,n2=n1+n1/x,n3=n1+n2/x,etc.
method pow - exponential increase by iteration
2^x,2^x+1
method random - calculates random numbers
method double - doubles the amount each order
1,2,4,8,16
method cos - makes an arc using iteration and cos
method acos - makes a reverse arc using iteration and acos
method s arc, start at .5 move up to 1 move down to .5 move up for the remainder
4 points, 1 is half, 2 is full, 3 is half, 4 is last which should be tame,
*/
$microSellDivisor = 10; //number of Sell orders to place
$microBuyDivisor = 10; //Number of Buy orders to place
$microIteration = .5;//USD$ iteration for multiple orders
$microAmount = .01; //Amount of BTC per mini buy/sell round
$microProfit = .005; //The profit threshold, this is the minimum profit per trade to make,
$microStopLoss = 1; //The stop loss percent, Sell out at a loss
$microReBuy = .10; //The price change to rebuy after a loss
$microBuyAmountMultiplier = engineMultiplier('double',2,$microBuyDivisor);
if ($GOX){
$microSellDivisor = 10; //number of Sell orders to place
$microBuyDivisor = 10; //Number of Buy orders to place
$microIteration = .5;//USD$ iteration for multiple orders
$microAmount = .01; //Amount of BTC per mini buy/sell round
$microProfit = .004; //The profit threshold, this is the minimum profit per trade to make,
$microStopLoss = 1; //The stop loss percent, Sell out at a loss
$microReBuy = .1; //The price change to rebuy after a loss
$microBuyAmountMultiplier = engineMultiplier('rand',2,$microBuyDivisor);
}
$microSellCancel = TRUE; //Cancel orders every sell or keep old sell orders?
////////////////////////////////////////////////////////////////////
//NOT USER CONFIGURABLE
$engineProfit = $microProfit;
$engineAmount = $microAmount;
$engineSellDivisor = $microSellDivisor;
$engineBuyDivisor = $microBuyDivisor;
$countMicroBuy = $countMicroSell = 1;
$countMicroBuyTotal = $countMicroSellTotal = 0;
$microBuy = $microSell = FALSE;
$microThreshold = .60; // dynamic threshold defined arbitrarily.
$microTicker = 0; //This stores the last price used to calculate mini-trades
break;
case "B":
$BALANCE = TRUE;
$balanceBuy = $balanceSell = FALSE;
$balanceAmount = .025; //Amount of micro-balance trades
$balanceThreshold = .05; // .05 = 5% //Rebalancing leway - set to 1 to disable
break;
case "FF":
$BALANCE = TRUE;
$FF = TRUE;
break;
case "JOSH":
$JOSH = TRUE;
$joshAmount = 5; //In BTC
$joshThreshold = 5; //In USD
$joshStopLoss = .05; //as a percentage
$joshReBuy = .05; //as a percentage
break;
case "JUDE":
$JUDE = TRUE;
break;
}
//Stop Loss
$stop = array('target','ticker','over','under','count' => 0);
//Maximum play amounts (that's play not investment) this is after all technically a beta idea
$maxUSD = 500; //The maximum amount of USD to use -> includes B held * last price!
$maxBTC = 1; //The maximum amount of BTC to use
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//Main Trade Engine Settings
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
$amountTrade = .256; //maxpertrade current engine 20130530
$sellDivisor = 3; //The number of sell orders to place
$buyDivisor = 3; //The number of buy orders to place
$tradeIteration = .10; //If not using compound interest, the amount to differ between trades when using sell/buy divisor above 1
$compoundInterest = FALSE; //Use $incriment or profit^(1+x)
$threshold = .60; //The price change threshold UNUSED as this is set later.
$profitTrade = .025; //The profit threshold, this is the minimum profit per trade to make,
$thresholdOrders = 0; //If using order based triggers vs static or EMA
$maxPendingOrders = 0; //Keep this many orders active when canceling
$maxOrders = 100;//$maxOrders = max orders to pull should be set? 100?
//Send email reports when orders are placed
$emailRCPTo = "SET IN KEY.PHP INCLUDE FILE";
$btceKey = ''; // your API-key
$btceSecret = ''; // your Secret-key
$emailSubject = "BTCbot Trade on {$exchange}";
//Time between runs
$nanosleep = 500000000; //nanoseconds
$sleepCancel = 500000; //nanoseconds to sleep between order cancellations
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//END USER CONFIGURABLE
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
$minBidBTC = .01; //Minimum Bids the exchange will accept (BTC-E Mins)
$engineAmount = ( min($microAmount/$microSellDivisor,$microAmount/$microBuyDivisor) > $minBidBTC ? $microAmount : $minBidBTC );
//DEBUG need to add multiplier array lowest to this
if ($exchange == "E") $exchangeCommision = .002; //The exchange commision percent (as 1 - commision as decimal)
if ($exchange == "G") $exchangeCommision = .0001; //Gox Commision
//BTC-E Currency pairs & bid ask JSON names
$btcesymbol = array("btc_usd", "ltc_btc", "ltc_usd");
$btcebidorask = array("bids", "asks");
if (@$BTCE) $exchangeBuySell = array("buy","sell");
if (@$GOX) $exchangeBuySell = array("bid","ask");
$executeTrade = $postTrade = FALSE;
$SELL = $BUY = TRUE;
$DOT = $STOPLOSS = FALSE; //pretty output \n bool
//COUNTERS
$countIteration=1; //Iteration Counter
$countOrder = 0; //Order counter
$countError = 0; //Error counter
$countDuplicate = 0; //Duplicate last price counter
$countBuys = $countSells = 0; //The buy rate counter / incriments per buy rate so this isn't the number of buy orders but the number of buy rates tried
$countTrades = 0; //Trade execution counter
$countTickers = 0;
$b = $s = 0;
$countInValid = $countValid = 0;
$countCancelled = $countFilledBuy = $countFilledSell = $countFilled = $countFilledIterationBuy = $countFilledIterationSell = 0;
// Tickers
$ticker = $tickerLast = $tickers = array();
//get the incriment from our file
$nonce = readInc();// + 1;
//order cancel timer
$startTime = time();
$dateStart = date('Ymd H:i:s');
////////////////////////////////////////////////////////////////////
//Calculate $microBuyAmountMultiplier $engineMultiplier
////////////////////////////////////////////////////////////////////
function engineMultiplier($method=NULL,$iteration=NULL,$divisor=NULL)
{
switch ($method)
{
case "rand":
for ($i=1;$i<=$divisor;$i++){
$array[$i] = rand(1,$iteration);
}
$return = engineMultiplierPercentage($array);
break;
case "fib":
$first = 1; $second = 2;
$array[0] = $first;
$array[1] = $second;
for ($i=2;$i<=$divisor+1;$i++){
$final = $first + $second;
$first = $second;
$second = $final;
$array[$i] = $final;
}
$return = engineMultiplierPercentage($array);
break;
case "fibtame":
$first = 1; $second = $first + $first/$iteration;
$array[0] = $first;
$array[1] = $second;
for ($i=2;$i<=$divisor+1;$i++){
$final = $first + $second/$iteration;
$first = $second;
$second = $final;
$array[$i] = $final;
}
$return = engineMultiplierPercentage($array);
break;
case "exp":
$array[1] = 1;
$array[2] = 2;
for ($i=3;$i<=$divisor;$i++){
$array[$i] = pow($i,$iteration);
}
$return = engineMultiplierPercentage($array);
break;
case "double":
$array[0] = 1;
$array[1] = 2;
for ($i=2;$i<=$divisor;$i++){
$array[$i] = $array[$i-1]*2;
}
$return = engineMultiplierPercentage($array);
break;
case "cos":
//DEBUG fix so array 0 exists.
$array[1] = -1.5;
//print_r($array);
for ($i=3;$i<=$divisor+1;$i++){
$array[$i-1] = abs(cos($array[1] + ( (3/($divisor-1)) * ($i-2) )));
}
$array[1] = abs(cos(-1.5));
//print_r($array);
$return = engineMultiplierPercentage($array);
break;
}
return $return;
}
function engineMultiplierPercentage($array)
{
$percentage = 1/array_sum($array);
foreach ($array as $key => $value)
{
$return[$key] = $value * $percentage;
}
return $return;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////Begin Infinite Loop.////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
while ( 'the answer to life the universe and everything' != '41'){
//include('key.php');
writeInc($nonce); //Write the nonce variable
$countIteration++; //incriment the iteration counter
$countDuplicate = $countOrder = $countError = 0; // New run reset the duplicate counter
$executeTrade = FALSE; //reset trade BOOL for next run
$return = $orderList = $TradeHistory = $rate = $amount = $type = array(); //remove previous values from trade arrays
////////////////////////////////////////////////////////////////////
//Poll data
////////////////////////////////////////////////////////////////////
$tickerOld['ticker']['last'] = @$ticker['ticker']['last']; //change the ticker to the last ticker
$ticker = array();
$sleep=rand(1, 10); //set a random sleep timer
while ( empty($ticker) ){
if (@$GOX) {
$ticker = json_decode(send( 'https://data.mtgox.com/api/2/BTCUSD/money/ticker' ), TRUE );
$ticker['ticker']['last'] = $ticker['data']['last']['value'];
}
if (@$BTCE) $ticker = json_decode(send( 'https://btc-e.com/api/2/btc_usd/ticker' ), TRUE );
if( !@$ticker ){
print_r($return);
$ticker = $return = $orderList = $TradeHistory = array();
//$sleep=rand(6, 36)*(++$countError);
$countError++;
print "\nError pulling data. Error #: {$countError} \n";
sleep(5);
continue;
}
////////////////////////////////////////////////////////////////////
//Duplicate Ticker
if ( $tickerOld['ticker']['last'] == $ticker['ticker']['last'] ){
$ticker = $return = $orderList = $TradeHistory = array();
if ( $countDuplicate == 59 ? print "\n." : print "." );
if ( $countDuplicate == 59 ? $countDuplicate = 0 : NULL );
$DOT = TRUE;
$countDuplicate++;
//Static Timer
time_nanosleep(0, $nanosleep);
continue;
}
////////////////////////////////////////////////////////////////////
//Calculate SMA & EMA
if ( $ticker['ticker']['last'] > 0 && $tickerOld['ticker']['last'] !== $ticker['ticker']['last'] && $EMA ){ //the later test of dup ticker should never be tested.
$countTickers++;
$tickers[$countTickers] = $ticker['ticker']['last'];
$ema1 = $ema2 = $ema3 = NULL; //= $countTickers
$ema1 = array_sum( array_slice($tickers, -1, 1, true)) * $ema1M + (array_sum (array_slice($tickers, ($ema1Time*-1)-1, $ema1Time, true))/$ema1Time) *(1-$ema1M);
$ema2 = array_sum( array_slice($tickers, -1, 1, true)) * $ema2M + (array_sum (array_slice($tickers, ($ema2Time*-1)-1, $ema2Time, true))/$ema2Time) *(1-$ema2M);
$ema3 = array_sum( array_slice($tickers, -1, 1, true)) * $ema3M + (array_sum (array_slice($tickers, ($ema3Time*-1)-1, $ema3Time, true))/$ema3Time) *(1-$ema3M);
if ( $countTickers < $ema1Time + 1 ){//&& $EMA) {
if (@$DEBUG && $DOT) {print "\n"; $DOT = FALSE; }
print "Building EMA1 - Waiting for ";
print ($ema1Time + 1) - $countTickers;
print " more tickers\n ";
} elseif ( $countTickers < $ema2Time + 1 ){//&& $EMA) {
if (@$DEBUG && $DOT) {print "\n"; $DOT = FALSE; }
print "Building EMA2 - Waiting for ";
print ($ema2Time + 1) - $countTickers;
print " more tickers\n ";
} elseif ( $countTickers < $ema3Time + 1 ){//&& $EMA) {
if (@$DEBUG && $DOT) {print "\n"; $DOT = FALSE; }
print "Building EMA3 - Waiting for ";
print ($ema3Time + 1) - $countTickers;
print " more tickers\n ";
}
if ( $countTickers < $ema3Time + 1 ) { //If we haven't built ema3 and we are using ema
$tickerOld['ticker']['last'] = $ticker['ticker']['last'];
$ticker = $return = $orderList = $TradeHistory = array();
continue; //restart the loop until we build emas
}
//IF we wont execute a trade, print the ticker and then continue
//if (
//($ticker['ticker']['last'] >= $microTicker - $microThreshold && $ticker['ticker']['last'] <= $microTicker + $microThreshold) //We won't execute a microtrade
//&& ($EMA !(($ema1 > $ema2 && $ema2 > $ema3 ) && $SELL) // We won't buy
// && !(($ema1 < $ema2 && $ema2 < $ema3 ) && $SELL )//We won't sell
// ) //END EMA
// || ( $BALANCE
// && $currentBalanceUSD-$reBalanceUSD > 0
// && $currentBalanceBTC-$reBalanceBTC > 0)
// )//END BALANCE
//
// && $tickerOld['ticker']['last'] !== $ticker['ticker']['last'] //The ticker isn't a dup, (Should never be tested here)
// && $ticker['ticker']['last'] > 0 //The ticker is valid (should ever be tested here)
// && $countIteration > 2 ){ //This is a valid iteration
// $tmp4 = round($ticker['ticker']['last'],2); //round the ticker
// if ( $countDuplicate >= 59-6 ) {
// for ($countDuplicate=$countDuplicate; $countDuplicate < 59 ; $countDuplicate++) {
// print ".";
// }
// print "\n";
// $countDuplicate = 0;
// }
// print "{$tmp4}";
// $countDuplicate = $countDuplicate + 6;
// $tickerOld['ticker']['last'] = $ticker['ticker']['last'];
// $ticker = $return = $orderList = $TradeHistory = array();
// $tmp1 = $tmp2 = $tmp3 = $tmp4 = NULL;
//}
}//IMPLIED ELSE continue processing
}//END while ( empty($ticker) )
////////////////////////////////////////////////////////////////////
//Poll All data for trading
//reset the data points and pull all at once (GOX should be an exception because of rate limiting.)
$ticker = $return = $orderList = $TradeHistory = array(); //blank the tickers
while( empty($ticker) || empty($return) || empty($orderList) || empty($TradeHistory) ){
if ($BTCE){
$ticker = json_decode(send( 'https://btc-e.com/api/2/btc_usd/ticker' ), TRUE ); // BTCE Ticker
$orderList = json_decode(btce_query("OrderList", array("active" => 1, "pair" => "btc_usd")), TRUE);
$TradeHistory = json_decode(btce_query("TradeHistory", array("count" => $maxOrders, "pair" => "btc_usd")), TRUE);
$return = json_decode(btce_query('getInfo'), TRUE); //BTCE account info
}
if ($GOX){
$ticker = json_decode(send( 'https://data.mtgox.com/api/2/BTCUSD/money/ticker' ), TRUE ); //GOX Ticker
$ticker['ticker']['last'] = $ticker['data']['last']['value'];
$ticker['ticker']['buy'] = $ticker['data']['buy']['value'];
$ticker['ticker']['sell'] = $ticker['data']['sell']['value'];
$ticker['ticker']['high'] = $ticker['data']['high']['value'];
$ticker['ticker']['low'] = $ticker['data']['low']['value'];
$return = json_decode(mtgox_query('BTCUSD/money/info'), TRUE); //GOX account Info
( $return['result'] == "success" ? $return['success'] = 1 : $return['success'] = 0); //Translate GOX to BTCE
$return['return']['funds']['btc'] = $return['data']['Wallets']['BTC']['Balance']['value'];//Translate GOX to BTCE
$return['return']['funds']['usd'] = $return['data']['Wallets']['USD']['Balance']['value'];//Translate GOX to BTCE
$orderList = json_decode(mtgox_query('BTCUSD/money/orders'), TRUE);
$TradeHistory = json_decode(mtgox_query('BTCUSD/money/trades/fetch'), TRUE); //GOX account Info
$TradeHistory['return'] = $TradeHistory['data'];
unset($TradeHistory['data']);
foreach ( $TradeHistory['return'] as $key => $value){
$TradeHistory['return'][$key]['type'] = $TradeHistory['return'][$key]['trade_type'];
$TradeHistory['return'][$key]['rate'] = $TradeHistory['return'][$key]['price'];
$TradeHistory['return'][$key]['order_id'] = $key; //PHP Notice:
}
}
//Verify the ticker changed
if( !@$ticker || !@$return || !@$orderList || !@$TradeHistory || @$return['success'] !== 1 ){
print_r($return);
$ticker = $return = $orderList = $TradeHistory = array();
//$sleep=rand(6, 36)*(++$countError);
$countError++;
print "\nError pulling data. Error #: {$countError} \n";
sleep(5);
}
}
//Translate Gox data to btc-e Format
if (@$GOX){
$orderList['success'] = ( $orderList['result'] == "success" ? $orderList['success'] = 1 : $orderList['success'] = 0);
$orderList['return'] = array();
$orderList['return'] = $orderList['data'];
$orderList['data'] = NULL;
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//Setup Thresholds for kicking off trades
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
if ( $ticker['ticker']['last'] > 1 ){ //if the ticker is valid
if (@$GOX) {
if ( $return['data']['Trade_Fee'] > 0 ) $exchangeCommision = $return['data']['Trade_Fee']/100; //Gox Commision
}
$threshold = ceil( $ticker['ticker']['last']*( (1/(1-$exchangeCommision)/(1-$profitTrade/2)) -1) * 100) /100 ;
$microThreshold = ceil( $ticker['ticker']['last']*( (1/(1-$exchangeCommision)/(1-$microProfit/2)) -1) * 100) /100 ;
if (!@$microTicker || @$microTicker < 1 ) {
$microTicker = $ticker['ticker']['last'];
$microThresholdBuy = $microTicker + $microThreshold; //Buy Above Last to create trailing buys - Micro-Dip
$microThresholdSell = $microTicker - $microThreshold; //Sell below last to create advancing sells - Micro-Spike
}
if (!@$thresholdBuy || @$thresholdBuy < 1 ) $thresholdBuy = $ticker['ticker']['last'] + $threshold; //We set buy orders when the price increases (trailing buy)
if (!@$thresholdSell || @$thresholdSell < 1 ) $thresholdSell = $ticker['ticker']['last'] - $threshold; //We set sell orders when the price decreases (advancing sell)
} else { exit; }
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//Calculate Cost, Balances, and print summary of information.
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//DEBUG need to calculate cost in $sellDivisor iterations for amounts that will be traded.
//DEBUG REFERENCE FILLED ORDERS! Prevent calculating cost based on filled sell orders!
$BTCO = $USDO = 0;
$sellOrders = $buyOrders = array(); //blank the order books for each new run (Infinite Loop issue)
$b = $s = 0; //FIXED order clearing if no open orders
if ( $orderList['success'] > 0 ){
foreach ( $orderList['return'] as $key => $value){
if (@$GOX){
$tmp1 = $value['amount']['value'];
$value['amount'] = NULL;
$value['amount'] = $tmp1;
$value['rate'] = $value['price']['value'];
$tmp1 = NULL; $tmp1 = $value['amount'] * $value['rate'];
$tmp1 = NULL;
}
if ( $value['type'] == $exchangeBuySell[1] ){
$BTCO = $BTCO + $value['amount']; //BTC = sum of sell orders and amounts //PHP Fatal error: Unsupported operand types in /arbot/buydownbotBTCG.php on line 281
$sellOrders[$s] = $value['rate'];
$s++;
}
//if ( $value['type'] == $exchangeBuySell[1] && $value['amount'] == $engineAmount ){
// $reserveBTC = ( $reserveBTC - $value['amount'] >= 0 ? $reserveBTC - $value['amount'] : 0); //
//
//}
if ( $value['type'] == $exchangeBuySell[0] ) {
$USDO = $USDO + $value['amount'] * $value['rate']; //USD = sum of buy orders amount*rate
$buyOrders[$b] = $value['rate'];
$b++;
}
//if ( $value['type'] == $exchangeBuySell[0] && $value['amount'] == $engineAmount) {
// //FIXED reserve usd wasnt decreasing
// $reserveUSD = ( $reserveUSD - $value['amount'] * $value['rate'] >= 0 ? $reserveUSD - $value['amount'] * $value['rate'] : 0 ); //USD = sum of buy orders amount*rate
//}
}
/*if ( $countIteration < 3 && $ORDERS ){
rsort($buyOrders); //ReverseSort orders and discard keys
sort($sellOrders); //Sort orders and discard keys
if ( !@$thresholdBuy ) $thresholdBuy = ( count($sellOrders) <= $thresholdOrders ? @$sellOrders[$countOrder] : @$sellOrders[$thresholdOrders] ); //Fill Xth order before trading
if ( !@$thresholdSell ) $thresholdSell = ( count($buyOrders) <= $thresholdOrders ? @$buyOrders[$countOrder] : @$buyOrders[$thresholdOrders] ); //Fill Xth order before trading
}*/
//SOLVED this is set in the threshold section now.
} else {
if ( $orderList['error'] !== "no orders" ) {
print_r($orderList);
}
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Calculate FUNDS
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
$USDB = $BTCB = $USDT = $BTCT = $BTC = $USD = 0;
//Calculate the TOTAL we have in orders and balance and USD/last BTCTotal
if ($GOX) $BTCT = $return['return']['funds']['btc'] + $return['return']['funds']['usd']/$ticker['ticker']['last'];
if ($BTCE) $BTCT = $return['return']['funds']['btc'] + $BTCO + $return['return']['funds']['usd']/$ticker['ticker']['last'] + $USDO/$ticker['ticker']['last'];
//Calculate the TOTAL USD we have in buy orders, sell orders, BTC balance, USD Balance
if ($GOX) $USDT = ($return['return']['funds']['btc'])*$ticker['ticker']['last'] + $return['return']['funds']['usd'];
if ($BTCE) $USDT = ($return['return']['funds']['btc'] + $BTCO)*$ticker['ticker']['last'] + $USDO + $return['return']['funds']['usd'];
//Calculate the BALANCE we have in orders and funds BTCBalance USDBalance
if ($GOX) $BTCB = $return['return']['funds']['btc'];
if ($BTCE) $BTCB = $return['return']['funds']['btc'] + $BTCO;
if ($GOX) $USDB = $return['return']['funds']['usd'];
if ($BTCE) $USDB = $return['return']['funds']['usd'] + $USDO;
//Calculate the TRADE amount we have in funds and orders BTCTrade USDTrade
$BTC = ( $BTCB >= $maxBTC ? $maxBTC - $BTCO : $BTCB - $BTCO );
$USD = ( $USDB >= $maxUSD ? $maxUSD - $USDO : $USDB - $USDO );
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Calculate BTC Cost of BTCBalance
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
$dollarCostTotal = $dollarCostShares = $idealSellRate = $idealSellAmount = $dollarCostAverage = $countBuys = 0;
$countFilledIterationBuy = $countFilledIterationSell = $countFilledIteration = 0;
$costBalance = array( "total" => 0, "shares" => 0, "average" => 0, "ideal" => 0);
$costFilled = array( "total" => 0, "shares" => 0, "average" => 0, "ideal" => 0);
$profitFilled = array( "total" => 0, "shares" => 0, "average" => 0, "ideal" => 0);
$BTCremaining = $BTCB;
if ($BALANCE) $BTCremaining = $BTC*($currentBalanceBTC-$reBalanceBTC);
foreach ( $TradeHistory['return'] as $key => $value){
//DEBUG use this information to calculate trades/costs/profits
if ( $value['type'] == $exchangeBuySell[0] && $BTCremaining >= $minBidBTC ) {
$costBalance['total'] = $costBalance['total'] + $value['rate']*$value['amount'];
$costBalance['shares'] = $costBalance['shares'] + $value['amount'];//$amountTrade[0]; Total shares analysed not / spread
$BTCremaining = $BTCremaining - $value['amount'];
$countBuys++;
}
/*
{
"success":1,
"return":{
"166830":{
"pair":"btc_usd",
"type":"sell",
"amount":1,
"rate":1,
"order_id":343148,
"is_your_order":1,
"timestamp":1342445793
}
}
}*/
//DEBUG gox compatibility
if ( @$ordersPlaced && array_key_exists ( $value['order_id'] , $ordersPlaced )){ //PHP Notice: Undefined index: order_id in /arbot/buydownbotBTCG.php on line 532
$filledOrders[$value['order_id']] = array(); //Define the array
$filledOrders[$value['order_id']] = $ordersPlaced[$value['order_id']]; //Store the order info in the array
$ordersFilledIteration[$countIteration-1] = array(); //Define the last iteration array
$ordersFilledIteration[$countIteration-1][$value['order_id']] = array(); //Define the last iteration array
$ordersFilledIteration[$countIteration-1][$value['order_id']] = $ordersPlaced[$value['order_id']]; //Store the order info in the array
unset($ordersPlaced[$value['order_id']]);
$countFilled++;$countFilledIteration++;
if ($value['type'] == $exchangeBuySell[0]){
$costFilled['total'] = $costFilled['total'] + $value['rate']*$value['amount'];
$costFilled['shares'] = $costFilled['shares'] + $value['amount'];//$amountTrade[0]; Total shares analysed not / spread
$countFilledBuy++;$countFilledIterationBuy++;
}
if ($value['type'] == $exchangeBuySell[1]){
$profitFilled['total'] = $profitFilled['total'] + $value['rate']*$value['amount'];
$profitFilled['shares'] = $profitFilled['shares'] + $value['amount'];//$amountTrade[0]; Total shares analysed not / spread
$countFilledSell++;$countFilledIterationSell++;
}
}
}
if (@$costBalance['shares'] > 0){
$costBalance['average'] = $costBalance['total']/$costBalance['shares']; //Total cost / Number of shares is purchase price
$costBalance['ideal'] = ( ($costBalance['total'])/(1-$exchangeCommision)/(1-$exchangeCommision)/(1-$engineProfit) )/$costBalance['shares'];//Average cost + UtoB commision + BtoU Commision is 0% profit sell rate
$stop['target'] = $costBalance['ideal']*.998*.998*(1-$microStopLoss);
} else $stop['target'] = 0;
if (@$costFilled['shares'] > 0){
$costFilled['average'] = $costFilled['total']/$costFilled['shares']; //Total cost / Number of shares is purchase price
$costFilled['ideal'] = ($costFilled['average'])/(1-$exchangeCommision)/(1-$exchangeCommision)/(1-$engineProfit);//Average cost + UtoB commision + BtoU Commision is 0% profit sell rate
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Primary output header block
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
$message = "\n";
if (@$DEBUG && $DOT) {print "\n"; $DOT = FALSE; }
print "\n\n\n\n\n";
print "**********************************************************\n"; //Print Separator
print "----------------------------------------------------------\n"; //Print Separator
print "**********************************************************\n"; //Print Separator
print " Started:{$dateStart}\n";
//$dateCurrent = date('Ymd H:i:s');
print " Current:".date('Ymd H:i:s')."\n"; //Print Separator
$elapsed = time() - $startTime;
$tmp1 = $elapsed/ 86400 % 1;
$tmp2 = $elapsed/ 3600 % 24;
$tmp3 = $elapsed/ 60 % 60;
$tmp4 = $elapsed % 60;
print " Runtime: {$tmp1}:Days {$tmp2}:H {$tmp3}:M {$tmp4}:S\n";
print "----------------------------------------------------------\n"; //Print Separator
//$tmp1 = round($stop['target'],2);
$tmp1 = ( $STOPLOSS ? "ACTIVE" : ( $stop['target'] == 0 ? "NO INVESTMENT" : round($stop['target'],2)) );
print "Iteration: {$countIteration} Ticker:\${$ticker['ticker']['last']} *****StopLoss:{$tmp1}*****\n"; //Print Separator
print "----------------------------------------------------------\n"; //Print Separator
print "---------------- Trade Target Information ----------------\n";
print "Threshold: Fees:{$exchangeCommision}% Trades:{$threshold} Micro:{$microThreshold}\n";
if (@$ORDERS || @$STATIC) print "Targets: Over:\${$thresholdBuy} Last:\${$ticker['ticker']['last']} Under:\${$thresholdSell}\n";
if ($MICRO && !$STOPLOSS ) print "Micro-Targets: Over:\${$microThresholdBuy} Tick:\${$microTicker} Under:\${$microThresholdSell}\n";
if ($STOPLOSS) print "Rebuy Targets: Over:{$stop['over']} Tick:{$stop['ticker']} Under:{$stop['under']}\n";
print "----------------------------------------------------------\n"; //Print Separator
print "------------------- Funds Information -------------------\n";
$tmp1 = round($BTCT,2);$tmp2 = round($USDT,2);
print " Cash Out: BTC:{$tmp1} USD:\${$tmp2}\n";
$tmp1 = round($BTCB,2);$tmp2 = round($USDB,2);
print " Balance: BTC:{$tmp1} USD:\${$tmp2}\n";
print " Maximums: BTC:{$maxBTC} USD:\${$maxUSD}\n";
$engineAmount = max($BTCB,$USDB/$ticker['ticker']['last']);
$engineAmount = min ($engineAmount,$microAmount);
$engineAmount = round($engineAmount,8);
$tmp1 = round($engineAmount,2);
//DEBUG not compatible with other engines, needed to create a tradeAmount or a buyamount and sellamount.
print " EngineAmount:{$tmp1} Sells:{$engineSellDivisor} Buys:{$engineBuyDivisor} Profit:{$engineProfit}\n ";
$tmp1 = round($BTC,2);$tmp2 = round($USD,2);
print " Tradable: BTC:{$tmp1} USD:\${$tmp2}\n";
print "----------------------------------------------------------\n"; //Print Separator
print "------------------- Order Information -------------------\n";
print " Open: Buys:{$b} Sells:{$s}\n";
print " Placed:Valid:{$countValid} Invalid:{$countInValid} Cancelled:{$countCancelled}\n";
print "Completed: Buys:{$countFilledBuy} Total:{$countFilled} Sells:{$countFilledSell} \n";
print " Last Run: Buys:{$countFilledIterationBuy} Total:{$countFilledIteration} Sells:{$countFilledIterationSell}\n";
print "----------------------------------------------------------\n"; //Print Separator
print "------------------- Cost Information -------------------\n";
if (@$costBalance['shares'] > 0){
$tmp1 = round($costBalance['total'],2);
$tmp2 = round($costBalance['shares'],2);
$tmp3 = round($costBalance['average'],2);
$tmp4 = round($costBalance['ideal'],2);
print "Balance Costs: Total:{$tmp1} Shares:{$tmp2} Average:{$tmp3} Ideal:{$tmp4}\n";
$tmp1 = $tmp2 = $tmp3 = $tmp4 = NULL;
} else $costBalance['ideal'] = $ticker['ticker']['last'] * 2;
if (@$costFilled['shares'] > 0){
$tmp1 = round($costFilled['total'],2);
$tmp2 = round($costFilled['shares'],2);
$tmp3 = round($costFilled['average'],2);
$tmp4 = round($costFilled['ideal'],2);
print "Order Costs: Total:{$tmp1} Shares:{$tmp2} Average:{$tmp3} Ideal:{$tmp4}\n";
$tmp1 = $tmp2 = $tmp3 = $tmp4 = NULL;
}
if ( (@$costFilled['shares'] == 0) && (@$costBalance['shares'] == 0)){
print "Order Costs: Not holding any BTC! \n";
}
print "----------------------------------------------------------\n"; //Print Separator
print "------------------- Profit Information -------------------\n";
if ( $countIteration < 3 ){
$profit = array('initial' => array('balanceBTC' => $BTCB,'balanceUSD' => $USDB,'ticker' => $ticker['ticker']['last'], 'totalBTC' => $BTCT, 'totalUSD' => $USDT ) );
}
//
$profit['buy'] = array('amountBTC' => 0, 'amountUSD' => 0);
$profit['sell'] = array('amountBTC' => 0, 'amountUSD' => 0);
if (@$filledOrders){
foreach ( $filledOrders as $key => $value ){
if ( $value['type'] == $exchangeBuySell[0] ){
$profit['buy']['amountBTC'] = $profit['buy']['amountBTC'] + $value['amount'];
$profit['buy']['amountUSD'] = $profit['buy']['amountUSD'] + $value['rate'] * $value['amount'];
}
if ( $value['type'] == $exchangeBuySell[1] ){
$profit['sell']['amountBTC'] = $profit['sell']['amountBTC'] + $value['amount'];
$profit['sell']['amountUSD'] = $profit['sell']['amountUSD'] + $value['rate'] * $value['amount'];
}
}
//FIXED PHP Warning: Division by zero in /arbot/buydownbotBTC.php on line 659
if ( $profit['buy']['amountBTC'] > 0 ) $profit['buy']['cost'] = round($profit['buy']['amountUSD']/$profit['buy']['amountBTC'],2);
if ( $profit['sell']['amountBTC'] > 0 ) $profit['sell']['cost'] = round($profit['sell']['amountUSD']/$profit['sell']['amountBTC'],2);
}
//Initial Balance
$tmp1 = round($profit['initial']['balanceBTC'],2);
$tmp2 = round($profit['initial']['balanceUSD'],2);
print "Initial Balance: BTC:{$tmp1} USD:{$tmp2} Rate:{$profit['initial']['ticker']} \n";
//Current Balance
$tmp1 = round($BTCB,2);
$tmp2 = round($USDB,2);
print "Current Balance: BTC:{$tmp1} USD:{$tmp2} Rate:{$ticker['ticker']['last']}\n";
//Difference
$tmp1 = round($USDB - $profit['initial']['balanceUSD'],2);
$tmp2 = round($BTCB - $profit['initial']['balanceBTC'],2);
$tmp3 = round(($ticker['ticker']['last'] - $profit['initial']['ticker']),2);
print " Difference: BTC:{$tmp2} USD:{$tmp1} Rate:{$tmp3}\n";
if (@$profit['buy']['amountBTC'] > 0){
//BTC purchased {amountBTC} {costBTC} {totalcost}
$tmp1 = round($profit['buy']['amountBTC'],2);
$tmp2 = round($profit['buy']['cost'],2);
$tmp3 = round($profit['buy']['amountUSD'],2);
print " Trade Buys: BTC:{$tmp1} Rate:{$tmp2} Total:{$tmp3}\n";
}
if (@$profit['sell']['amountBTC'] > 0){
//BTC sold {amountBTC} {costBTC} {totalprofit}
$tmp1 = round($profit['sell']['amountBTC'],2);
$tmp2 = round($profit['sell']['cost'],2);
$tmp3 = round($profit['sell']['amountUSD'],2);
print " Trade Sells: BTC:{$tmp1} Rate:{$tmp2} Total:{$tmp3}\n";
}
//Gains
//sell - buy + BTCholdings*last*commision - initialBTCbalance*initialLast*commision
$tmp1 = round($profit['sell']['amountUSD'] - $profit['buy']['amountUSD'] + ($BTCB*$ticker['ticker']['last']*.998) - ($profit['initial']['balanceBTC']*$profit['initial']['ticker']*.998),2);
$tmp2 = round($USDT - $profit['initial']['totalUSD'] - $tmp1,2);
print " Profit From Trading:{$tmp1} \n";
print " Unrealized Gains:{$tmp2} \n";
//BTC Appreciation = start btc * start rate - startbtc * current rate
$tmp1 = round($profit['initial']['totalBTC'] * $profit['initial']['ticker'],2);
$tmp2 = round($profit['initial']['totalBTC'] * $ticker['ticker']['last'],2);
$tmp4 = round($tmp1 - $tmp2,2);
print " BTC Appreciation: Start:{$tmp1} Current:{$tmp2} Difference:{$tmp4}\n";
//Run Value = profit - appreciation
//$tmp1 = round($profit['initial']['balanceBTC']*$profit['initial']['ticker']*.998 + $profit['initial']['balanceUSD'],2);
$tmp3 = round($USDT - $profit['initial']['totalUSD'],2);
print " Program Value:{$tmp3}\n";
$message = $message . " Program Value:{$tmp3}\n";
$tmp1 = $tmp2 = $tmp3 = $tmp4 = 0;
print "----------------------------------------------------------\n"; //Print Separator
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////TRADE ENGINES/////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////Micro-Roll ENGINE/////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DEBUG $stop target ticker over under count
//SOLVED Need to record amounts and rates to prevent cancellation
//DEBUG Need to set a stop loss to cancel all orders, sell all B and restart (use main trade engine)
//SOLVED Need to prevent duplicate rate orders
//SOLVED Need to use MINI for this section and MICRO for balance trades or Micro for this and balance for balance trades.
//SOLVED you should never set sell orders if you don't have buy orders, you should always have buy orders,
//SOLVED you shouldn't need to set rate at threshold*count,
//SOLVED just use duplicate rate protection and set to iteration higher each time.
if ($MICRO){
print "------------------- Micro-Trade Block -------------------\n";
//print " Stop-Loss: Under:\${$microThresholdSell}\n";
//print " Stop-Loss: Over:\${$microThresholdBuy} Tick:\${$microTicker} Under:\${$microThresholdSell}\n";
print "Checking Micro-Trades: ";
if ($STOPLOSS){
if ( $ticker['ticker']['last'] > $stop['over'] || $ticker['ticker']['last'] < $stop['under'] ){
$STOPLOSS = FALSE;
$REBUY = TRUE;
//Rebuy orders
print "\n *********************************************** \n";
print "\n *****Stop Loss in Lifted - Trades Resumed ***** \n";
print "\n *********************************************** \n";
$microTicker = $ticker['ticker']['last'];
$microThresholdBuy = $microTicker + $microThreshold;//$rate[$countOrder - floor($tmp1/2)]; //array_sum($tmp0) / count($tmp0); //Fill an order first $microTicker + $microThreshold;//*$countMicroSell;//Trailing Buy orders, if this sell order fills, Buy More
$microThresholdSell = $microTicker - $microThreshold; //Sell again if last drops below to create advancing sells - Micro-Spike
print "New-Micro-Targets: Over:\${$microThresholdBuy} Tick:\${$microTicker} Under:\${$microThresholdSell}\n";
} else {
print "\n *********************************************** \n";
print "\n ****** Stop Loss Active - Trades Frozen ******* \n";
print "\n *********************************************** \n";
}
}
if ( $ticker['ticker']['last'] < $stop['target'] && !$STOPLOSS ){
$STOPLOSS = TRUE; $REBUY = FALSE;
print "\n *********************************************** \n";
print "\n ***** Stop Loss Activated - Trades Frozen ***** \n";
print "\n *********************************************** \n";
$stop = array('target' ,'ticker' => $ticker['ticker']['last'],'over' => $ticker['ticker']['last']*(1+$microReBuy) ,'under' => $ticker['ticker']['last']*(1-$microReBuy),'count' => $stop['count']++ );
print_r($stop);
print "DEBUG THIS SECTION OF CODE";
print "BTC: COST: LAST:\n";
print "Rebuy Targets: Over:{$stop['over']} Tick:{$stop['ticker']} Under:{$stop['under']}\n";
}
//$stop['target'] = $costBalance['ideal']*.998*.998*(1-$microStopLoss);
$microBTCRemaining = $BTCB;
$microUSDRemaining = $USDB;
////////////////////////////////////////////////////////////////////
// First run cancel, buy and sell
if ( $countIteration < 3 && !$STOPLOSS ){
print "First Run Trades.\n";
$microTicker = $ticker['ticker']['last'];
//First Run, Cancel Orders
cancelOrders($exchangeBuySell[0]);
cancelOrders($exchangeBuySell[1]);
//First Run, Check USD, BTC, costBalance, place buy and sell.
//DEBUG check funds for buy and sell trades.
if ( $BTCB >= $minBidBTC ){
$executeTrade = TRUE; //turn on trading
$tmp1 = 0;
$microSellPrice = max($costBalance['ideal'],$ticker['ticker']['last']);
while ( $tmp1 <= ($BTCB/$engineAmount)*$microSellDivisor && $microBTCRemaining >= $minBidBTC ){
$type[$countOrder] = $exchangeBuySell[1];
$rate[$countOrder] = $microSellPrice + .01*$tmp1;
$rate[$countOrder] = ceil($rate[$countOrder]*100)/100;
$amount[$countOrder] = max($BTCB/(($BTCB/$engineAmount)*$microSellDivisor),$minBidBTC); //sell everything
$amount[$countOrder] = floor($amount[$countOrder]*pow(10,8))/pow(10,8);
//$amount[$countOrder] = min($amount[$countOrder],$BTCB);
$amount[$countOrder] = ($BTCB < $amount[$countOrder] ? $BTCB : $amount[$countOrder] ); //if we don't have that much B
print "Micro-Selling {$amount[$countOrder]}B at a rate of {$rate[$countOrder]}\n";
$microBTCRemaining = $microBTCRemaining - $amount[$countOrder];
$countOrder++;$tmp1++;
}
$countMicroSellTotal++;
}
if ( $USDB >= $minBidBTC*$ticker['ticker']['last'] ){
$executeTrade = TRUE; //turn on trading
$tmp1 = 0;
while ( $tmp1 <= $microBuyDivisor && $microUSDRemaining >= ($ticker['ticker']['last']-$microThreshold-$microIteration*$tmp1)*$minBidBTC ){
$type[$countOrder] = $exchangeBuySell[0];
$rate[$countOrder] = $ticker['ticker']['last'] - $microThreshold - $microIteration*$tmp1;
$rate[$countOrder] = floor($rate[$countOrder]*100)/100;
$amount[$countOrder] = max( ($engineAmount*$microBuyAmountMultiplier[$tmp1]) ,$minBidBTC);
$amount[$countOrder] = floor($amount[$countOrder]*pow(10,8))/pow(10,8);
print "Micro-Buying {$amount[$countOrder]}B at a rate of {$rate[$countOrder]}\n";
$microUSDRemaining = $microUSDRemaining - $amount[$countOrder] * $rate[$countOrder];
$countOrder++;$tmp1++;
}
$countMicroBuyTotal++;
}
}
////////////////////////////////////////////////////////////////////
// Stop Loss and Rebuy
if ( $STOPLOSS ){
if ( $BTCB > $minBidBTC && $STOPLOSS ) { //in case we lifted stop loss above.
cancelOrders($exchangeBuySell[0]);
cancelOrders($exchangeBuySell[1]);
print "\n *********************************************** \n";
print "\n **** Stop Loss Activated - Liquidating BTC **** \n";
print "\n *********************************************** \n";
$tmp1 = $tmp2 = 0;
while ( $tmp1 <= $microSellDivisor ){
$executeTrade = TRUE;
$type[$countOrder] = $exchangeBuySell[1];
$rate[$countOrder] = $ticker['ticker']['last'] - $microThreshold - $microIteration*$tmp1;
$rate[$countOrder] = floor($rate[$countOrder]*100)/100;
//If we cancel orders first, we don't need repeat order protection
//while ( in_array($rate[$countOrder],$sellOrders) ){
// $rate[$countOrder] = $ticker['ticker']['last'] - $microThreshold - $microIteration*$tmp2;
// $rate[$countOrder] = ceil($rate[$countOrder]*100)/100;
// $tmp2++;
//}
$amount[$countOrder] = max($BTCB/$microSellDivisor,$minBidBTC);
$amount[$countOrder] = floor($amount[$countOrder]*pow(10,8))/pow(10,8);
print "Micro-Selling {$amount[$countOrder]}B at a rate of {$rate[$countOrder]}\n";
$BTC = $BTC - $amount[$countOrder];
$countOrder++;$tmp1++;
}
$tmp1 = $tmp2 = 0;
}
}
////////////////////////////////////////////////////////////////////
// Micro-Trade Engine Primary
if ($countIteration > 2 && !$STOPLOSS ){ // && !$REBUY){ DEBUG Haven't build rebuy code yet, use primary engine
$countOrder = 0;
//If ticker is above Buy or Below Sell or we filled an order (Needs to be a buy order!)
if ( $countFilledIterationSell > 0 || $ticker['ticker']['last'] > $microThresholdBuy || $ticker['ticker']['last'] < $microThresholdSell || $countFilledIterationBuy > 0 || $b == 0 || $BTC > $minBidBTC || $ticker['ticker']['last'] >= $costBalance['ideal']) {
if ( $BTC > $minBidBTC || $USDB >= ($ticker['ticker']['last'] - $microThreshold)*$minBidBTC || $countFilledIterationBuy > 0 ){
//FIXED change USD test from micro amount to minbidbtc.
//FIXED changed micro, test, from btc > amount to btc > minbid to sell after an error.
if ( $countFilledIterationBuy > 0 ) print "Buy Order Filled.\n";
if ( $USDB >= ($ticker['ticker']['last'] - $microThreshold)*$engineAmount ) print "USD Funds Available {$USDB}.\n";
if ( $BTC > $minBidBTC ) print "BTC Funds Available {$BTC}.\n";
if ( $b == 0 ) print "No open buy orders.\n"; //FIXED added B == 0 will rebuy after stoploss.
if ( $ticker['ticker']['last'] > $microThresholdBuy || $ticker['ticker']['last'] < $microThresholdSell) print "Threshold Crossed.\n";
if ( $ticker['ticker']['last'] >= $costBalance['ideal'] ) print "Balance Ideal sell price crossed. Selling.\n";
//Iteration: 170 Ticker:$119.682 *****StopLoss:118*****
//Balance Costs: Total:118.1 Shares:0.99 Average:118.95 Ideal:119.67
//Checking Micro-Trades: No Trades.
////////////////////////////////////////////////////////////////////
// Sell Code Block
//DEBUG changed all amounts to BTC from BTCB as we are not cancelling orders here
if ( $BTC > $minBidBTC || ($ticker['ticker']['last'] >= $costBalance['ideal'] && $costBalance['ideal'] > 0) || $ticker['ticker']['last'] < $microThresholdSell){ //Sell
//----------------------------------------------------------
//------------------- Cost Information -------------------
//Order Costs: Not holding any BTC!
//----------------------------------------------------------
//------------------- Profit Information -------------------
//Initial Balance: BTC:0 USD:580.06 Rate:121.26682
//Current Balance: BTC:0 USD:580.06 Rate:121.44665
// Difference: BTC:0 USD:0 Rate:0.18
// Profit From Trading:0
// Unrealized Gains:0
// BTC Appreciation: Start:580.06 Current:580.92 Difference:-0.86
// Program Value:0
//----------------------------------------------------------
//------------------- Micro-Trade Block -------------------
//Checking Micro-Trades: USD Funds Available 580.05604.
//Balance Ideal sell price crossed. Selling.
print "\n";
if ($countFilledIterationBuy > 0 && !$microSellCancel ) { //We filled orders last run
NULL;
//Set amount
$microSellAmount = $costFilled['shares']*.998;//Lol i put total //DEBUG Needs to be reduced for commision?
$microSellAmount = $BTC; //My .998 multiplier was acurate to to many decimals? its either this or floor.
//Set price
$microSellPrice = $costFilled['ideal'];
} elseif ($ticker['ticker']['last'] >= $costBalance['ideal'] || $microSellCancel) {// We didn't fill orders but have BTC or want to cancel
//------------------- Micro-Trade Block -------------------
//Checking Micro-Trades: USD Funds Available 2202.166858729.