forked from ezehy/starcashx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtradingdialog.cpp
1390 lines (1091 loc) · 52.9 KB
/
tradingdialog.cpp
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
#include "tradingdialog.h"
#include "ui_tradingdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include <qmessagebox.h>
#include <qtimer.h>
#include <rpcserver.h>
#include <QClipboard>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QVariant>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QJsonArray>
#include <QTime>
#include <openssl/hmac.h>
#include <stdlib.h>
using namespace std;
tradingDialog::tradingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::tradingDialog),
model(0)
{
ui->setupUi(this);
timerid = 0;
qDebug() << "Expected this";
ui->BtcAvailableLabel->setTextFormat(Qt::RichText);
ui->STARXAvailableLabel->setTextFormat(Qt::RichText);
ui->BuyCostLabel->setTextFormat(Qt::RichText);
ui->SellCostLabel->setTextFormat(Qt::RichText);
ui->BittrexBTCLabel->setTextFormat(Qt::RichText);
ui->BittrexSTARXLabel->setTextFormat(Qt::RichText);
ui->CSDumpLabel->setTextFormat(Qt::RichText);
ui->CSTotalLabel->setTextFormat(Qt::RichText);
ui->CSReceiveLabel->setTextFormat(Qt::RichText);
//Set tabs to inactive
ui->TradingTabWidget->setTabEnabled(0,false);
ui->TradingTabWidget->setTabEnabled(1,false);
ui->TradingTabWidget->setTabEnabled(3,false);
ui->TradingTabWidget->setTabEnabled(4,false);
ui->TradingTabWidget->setTabEnabled(5,false);
// Listen for keypress
connect(ui->PasswordInput, SIGNAL(returnPressed()),ui->LoadKeys,SIGNAL(clicked()));
/*OrderBook Table Init*/
CreateOrderBookTables(*ui->BidsTable,QStringList() << "SUM(BTC)" << "TOTAL(BTC)" << "STARX(SIZE)" << "BID(BTC)");
CreateOrderBookTables(*ui->AsksTable,QStringList() << "ASK(BTC)" << "STARX(SIZE)" << "TOTAL(BTC)" << "SUM(BTC)");
/*OrderBook Table Init*/
/*Market History Table Init*/
ui->MarketHistoryTable->setColumnCount(5);
ui->MarketHistoryTable->verticalHeader()->setVisible(false);
ui->MarketHistoryTable->setHorizontalHeaderLabels(QStringList()<<"DATE"<<"BUY/SELL"<<"BID/ASK"<<"TOTAL UNITS(STARX)"<<"TOTAL COST(BTC");
ui->MarketHistoryTable->setRowCount(0);
int Cellwidth = ui->MarketHistoryTable->width() / 5;
ui->MarketHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(1,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->MarketHistoryTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
/*Market History Table Init*/
/*STARXunt History Table Init*/
ui->TradeHistoryTable->setColumnCount(9);
ui->TradeHistoryTable->verticalHeader()->setVisible(false);
ui->TradeHistoryTable->setHorizontalHeaderLabels(QStringList() << "Date Time" << "Exchange" << "OrderType" << "Limit" << "QTY" << "QTY_Rem" << "Price" << "PricePerUnit" << "Closed");
ui->TradeHistoryTable->setRowCount(0);
Cellwidth = ui->TradeHistoryTable->width() / 9;
ui->TradeHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(1,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(6,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(7,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(8,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(9,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->TradeHistoryTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
/*STARXunt History Table Init*/
/*Open Orders Table*/
ui->OpenOrdersTable->setColumnCount(10);
ui->OpenOrdersTable->verticalHeader()->setVisible(false);
ui->OpenOrdersTable->setHorizontalHeaderLabels(QStringList() << "OrderId" << "Date Time" << "Exchange" << "OrderType" << "Limit" << "QTY" << "QTY_Rem" << "Price" << "PricePerUnit" << "Cancel Order");
ui->OpenOrdersTable->setRowCount(0);
Cellwidth = ui->TradeHistoryTable->width() / 9;
ui->OpenOrdersTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(6,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(7,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(8,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(9,Cellwidth);
ui->OpenOrdersTable->setColumnHidden(0,true);
ui->OpenOrdersTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->OpenOrdersTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
connect (ui->OpenOrdersTable, SIGNAL(cellClicked(int,int)), this, SLOT(CancelOrderSlot(int, int)));
/*Open Orders Table*/
}
void tradingDialog::InitTrading()
{ //todo - add internet connection/socket error checking.
//Get default exchange info for the qlabels
UpdaterFunction();
qDebug() << "Updater called";
if(this->timerid == 0)
{
//Timer is not set,lets create one.
this->timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(UpdaterFunction()));
this->timer->start(5000);
this->timerid = this->timer->timerId();
}
}
void tradingDialog::UpdaterFunction(){
//STARXst get the main exchange info in order to populate qLabels in maindialog. then get data
//required for the current tab.
int Retval = SetExchangeInfoTextLabels();
if (Retval == 0){
ActionsOnSwitch(-1);
}
}
QString tradingDialog::GetMarketSummary(){
QString Response = sendRequest("https://bittrex.com/api/v1.1/public/GetMarketSummary?market=btc-STARX");
return Response;
}
QString tradingDialog::GetOrderBook(){
QString Response = sendRequest("https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-STARX&type=both&depth=50");
return Response;
}
QString tradingDialog::GetMarketHistory(){
QString Response = sendRequest("https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-STARX&count=100");
return Response;
}
QString tradingDialog::CancelOrder(QString OrderId){
QString URL = "https://bittrex.com/api/v1.1/market/cancel?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&uuid=";
URL += OrderId;
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::BuySTARX(QString OrderType, double Quantity, double Rate){
QString str = "";
QString URL = "https://bittrex.com/api/v1.1/market/";
URL += OrderType;
URL += "?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-STARX&quantity=";
URL += str.number(Quantity,'i',8);
URL += "&rate=";
URL += str.number(Rate,'i',8);
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::SellSTARX(QString OrderType, double Quantity, double Rate){
QString str = "";
QString URL = "https://bittrex.com/api/v1.1/market/";
URL += OrderType;
URL += "?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-STARX&quantity=";
URL += str.number(Quantity,'i',8);
URL += "&rate=";
URL += str.number(Rate,'i',8);
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::Withdraw(double Amount, QString Address, QString Coin){
QString str = "";
QString URL = "https://bittrex.com/api/v1.1/account/withdraw?apikey=";
URL += this->ApiKey;
URL += "¤cy=";
URL += Coin;
URL += "&quantity=";
URL += str.number(Amount,'i',8);
URL += "&address=";
URL += Address;
URL += "&nonce=12345434";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetOpenOrders(){
QString URL = "https://bittrex.com/api/v1.1/market/getopenorders?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-STARX";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetBalance(QString Currency){
QString URL = "https://bittrex.com/api/v1.1/account/getbalance?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434¤cy=";
URL += Currency;
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetDepositAddress(){
QString URL = "https://bittrex.com/api/v1.1/account/getdepositaddress?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434¤cy=STARX";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetSTARXuntHistory(){
QString URL = "https://bittrex.com/api/v1.1/account/getorderhistory?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-STARX&count=10";
QString Response = sendRequest(URL);
return Response;
}
int tradingDialog::SetExchangeInfoTextLabels(){
//Get the current exchange information + information for the current open tab if required.
QString str = "";
QString Response = GetMarketSummary();
//Set the labels, parse the json result to get values.
QJsonObject obj = GetResultObjectFromJSONArray(Response);
//set labels to richtext to use css.
ui->Bid->setTextFormat(Qt::RichText);
ui->Ask->setTextFormat(Qt::RichText);
ui->volumet->setTextFormat(Qt::RichText);
ui->volumebtc->setTextFormat(Qt::RichText);
ui->Ask->setText("<b>Ask:</b> <span style='font-weight:bold; font-size:12px; color:Red'>" + str.number(obj["Ask"].toDouble(),'i',8) + "</span> BTC");
ui->Bid->setText("<b>Bid:</b> <span style='font-weight:bold; font-size:12px; color:Green;'>" + str.number(obj["Bid"].toDouble(),'i',8) + "</span> BTC");
ui->volumet->setText("<b>STARX Volume:</b> <span style='font-weight:bold; font-size:12px; color:blue;'>" + str.number(obj["Volume"].toDouble(),'i',8) + "</span> STARX");
ui->volumebtc->setText("<b>BTC Volume:</b> <span style='font-weight:bold; font-size:12px; color:blue;'>" + str.number(obj["BaseVolume"].toDouble(),'i',8) + "</span> BTC");
obj.empty();
return 0;
}
void tradingDialog::CreateOrderBookTables(QTableWidget& Table,QStringList TableHeader){
Table.setColumnCount(4);
Table.verticalHeader()->setVisible(false);
Table.setHorizontalHeaderLabels(TableHeader);
int Cellwidth = Table.width() / 4;
Table.horizontalHeader()->resizeSection(1,Cellwidth); // column 1, width 50
Table.horizontalHeader()->resizeSection(2,Cellwidth);
Table.horizontalHeader()->resizeSection(3,Cellwidth);
Table.horizontalHeader()->resizeSection(4,Cellwidth);
Table.setRowCount(0);
Table.horizontalHeader()->setResizeMode(QHeaderView::Stretch);
Table.horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
Table.horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * { font-weight :bold;}");
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel,QLabel &Available, QLabel &Pending, QString Currency,QString Response){
QString str;
BalanceLabel.setTextFormat(Qt::RichText);
Available.setTextFormat(Qt::RichText);
Pending.setTextFormat(Qt::RichText);
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
BalanceLabel.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Balance"].toDouble(),'i',8) + "</span> " + Currency);
Available.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Available"].toDouble(),'i',8) + "</span> " +Currency);
Pending.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Pending"].toDouble(),'i',8) + "</span> " +Currency);
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel, QString Response){
QString str;
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
BalanceLabel.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str.number(ResultObject["Available"].toDouble(),'i',8) + "</span>");
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel, QLabel &BalanceLabel2, QString Response, QString Response2){
QString str;
QString str2;
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
QJsonObject ResultObject2 = GetResultObjectFromJSONObject(Response2);
BalanceLabel.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str.number(ResultObject["Available"].toDouble(),'i',8) + "</span>");
BalanceLabel2.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str2.number(ResultObject2["Available"].toDouble(),'i',8) + "</span>");
}
void tradingDialog::ParseAndPopulateOpenOrdersTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->OpenOrdersTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->OpenOrdersTable->rowCount();
ui->OpenOrdersTable->insertRow(RowCount);
ui->OpenOrdersTable->setItem(itteration, 0, new QTableWidgetItem(obj["OrderUuid"].toString()));
ui->OpenOrdersTable->setItem(itteration, 1, new QTableWidgetItem(BittrexTimeStampToReadable(obj["Opened"].toString())));
ui->OpenOrdersTable->setItem(itteration, 2, new QTableWidgetItem(obj["Exchange"].toString()));
ui->OpenOrdersTable->setItem(itteration, 3, new QTableWidgetItem(obj["OrderType"].toString()));
ui->OpenOrdersTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Limit"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 5, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 6, new QTableWidgetItem(str.number(obj["QuantityRemaining"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 7, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 8, new QTableWidgetItem(str.number(obj["PricePerUnit"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 9, new QTableWidgetItem(tr("Cancel Order")));
//Handle the cancel link in open orders table
QTableWidgetItem* CancelCell;
CancelCell= ui->OpenOrdersTable->item(itteration, 9); //Set the wtablewidget item to the cancel cell item.
CancelCell->setForeground(QColor::fromRgb(255,0,0)); //make this item red.
CancelCell->setTextAlignment(Qt::AlignCenter);
itteration++;
}
obj.empty();
}
void tradingDialog::CancelOrderSlot(int row, int col){
QString OrderId = ui->OpenOrdersTable->model()->data(ui->OpenOrdersTable->model()->index(row,0)).toString();
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Cancel Order","Are you sure you want to cancel the order?",QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = CancelOrder(OrderId);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8());
QJsonObject ResponseObject = jsonResponse.object();
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed To Cancel Order",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
ui->OpenOrdersTable->model()->removeRow(row);
QMessageBox::information(this,"Success","You're order was cancelled.");
}
} else {
qDebug() << "Do Nothing";
}
}
void tradingDialog::ParseAndPopulateSTARXuntHistoryTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->TradeHistoryTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->TradeHistoryTable->rowCount();
ui->TradeHistoryTable->insertRow(RowCount);
ui->TradeHistoryTable->setItem(itteration, 0, new QTableWidgetItem(BittrexTimeStampToReadable(obj["TimeStamp"].toString())));
ui->TradeHistoryTable->setItem(itteration, 1, new QTableWidgetItem(obj["Exchange"].toString()));
ui->TradeHistoryTable->setItem(itteration, 2, new QTableWidgetItem(obj["OrderType"].toString()));
ui->TradeHistoryTable->setItem(itteration, 3, new QTableWidgetItem(str.number(obj["Limit"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 5, new QTableWidgetItem(str.number(obj["QuantityRemaining"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 6, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 7, new QTableWidgetItem(str.number(obj["PricePerUnit"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 8, new QTableWidgetItem(obj["Closed"].toString()));
itteration++;
}
obj.empty();
}
void tradingDialog::ParseAndPopulateOrderBookTables(QString OrderBook){
QString str;
QJsonObject obj;
QJsonObject ResultObject = GetResultObjectFromJSONObject(OrderBook);
int BuyItteration = 0,SellItteration = 0, BidRows = 0, AskRows = 0;
QJsonArray BuyArray = ResultObject.value("buy").toArray(); //get buy/sell object from result object
QJsonArray SellArray = ResultObject.value("sell").toArray(); //get buy/sell object from result object
double STARXSupply = 0;
double STARXDemand = 0;
double BtcSupply = 0;
double BtcDemand = 0;
ui->AsksTable->setRowCount(0);
foreach (const QJsonValue & value, SellArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
double a = (x * y);
STARXSupply += y;
BtcSupply += a;
AskRows = ui->AsksTable->rowCount();
ui->AsksTable->insertRow(AskRows);
ui->AsksTable->setItem(SellItteration, 0, new QTableWidgetItem(str.number(x,'i',8)));
ui->AsksTable->setItem(SellItteration, 1, new QTableWidgetItem(str.number(y,'i',8)));
ui->AsksTable->setItem(SellItteration, 2, new QTableWidgetItem(str.number(a,'i',8)));
ui->AsksTable->setItem(SellItteration, 3, new QTableWidgetItem(str.number(BtcSupply,'i',8)));
SellItteration++;
}
ui->BidsTable->setRowCount(0);
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
double a = (x * y);
STARXDemand += y;
BtcDemand += a;
BidRows = ui->BidsTable->rowCount();
ui->BidsTable->insertRow(BidRows);
ui->BidsTable->setItem(BuyItteration, 0, new QTableWidgetItem(str.number(BtcDemand,'i',8)));
ui->BidsTable->setItem(BuyItteration, 1, new QTableWidgetItem(str.number(a,'i',8)));
ui->BidsTable->setItem(BuyItteration, 2, new QTableWidgetItem(str.number(y,'i',8)));
ui->BidsTable->setItem(BuyItteration, 3, new QTableWidgetItem(str.number(x,'i',8)));
BuyItteration++;
}
ui->STARXSupply->setText("<b>Supply:</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(STARXSupply,'i',8) + "</span><b> STARX</b>");
ui->BtcSupply->setText("<span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(BtcSupply,'i',8) + "</span><b> BTC</b>");
ui->AsksCount->setText("<b>Ask's :</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(ui->AsksTable->rowCount()) + "</span>");
ui->STARXDemand->setText("<b>Demand:</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(STARXDemand,'i',8) + "</span><b> STARX</b>");
ui->BtcDemand->setText("<span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(BtcDemand,'i',8) + "</span><b> BTC</b>");
ui->BidsCount->setText("<b>Bid's :</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(ui->BidsTable->rowCount()) + "</span>");
obj.empty();
}
void tradingDialog::ParseAndPopulateMarketHistoryTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->MarketHistoryTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->MarketHistoryTable->rowCount();
ui->MarketHistoryTable->insertRow(RowCount);
ui->MarketHistoryTable->setItem(itteration, 0, new QTableWidgetItem(BittrexTimeStampToReadable(obj["TimeStamp"].toString())));
ui->MarketHistoryTable->setItem(itteration, 1, new QTableWidgetItem(obj["OrderType"].toString()));
ui->MarketHistoryTable->setItem(itteration, 2, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->MarketHistoryTable->setItem(itteration, 3, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->MarketHistoryTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Total"].toDouble(),'i',8)));
ui->MarketHistoryTable->item(itteration,1)->setBackgroundColor((obj["OrderType"] == QStringLiteral("BUY")) ? (QColor (150, 191, 70,255)) : ( QColor (201, 119, 153,255)));
itteration++;
}
obj.empty();
}
void tradingDialog::ActionsOnSwitch(int index = -1){
QString Response = "";
QString Response2 = "";
QString Response3 = "";
if(index == -1){
index = ui->TradingTabWidget->currentIndex();
}
switch (index){
case 0: //buy tab is active
Response = GetBalance("BTC");
Response2 = GetBalance("STARX");
Response3 = GetOrderBook();
if((Response.size() > 0 && Response != "Error") && (Response2.size() > 0 && Response2 != "Error")){
DisplayBalance(*ui->BtcAvailableLabel, *ui->STARXAvailableLabel, Response, Response2);
}
if ((Response3.size() > 0 && Response3 != "Error")) {
ParseAndPopulateOrderBookTables(Response3);
}
break;
case 1: //Cross send tab active
Response = GetBalance("STARX");
Response2 = GetBalance("BTC");
if((Response.size() > 0 && Response != "Error") && (Response2.size() > 0 && Response2 != "Error")){
DisplayBalance(*ui->BittrexSTARXLabel, *ui->BittrexBTCLabel, Response, Response2);
}
break;
case 2://market history tab
Response = GetMarketHistory();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateMarketHistoryTable(Response);
}
break;
case 3: //open orders tab
Response = GetOpenOrders();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateOpenOrdersTable(Response);
}
break;
case 4://account history tab
Response = GetSTARXuntHistory();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateSTARXuntHistoryTable(Response);
}
break;
case 5://show balance tab
Response = GetBalance("BTC");
if(Response.size() > 0 && Response != "Error"){
DisplayBalance(*ui->BitcoinBalanceLabel,*ui->BitcoinAvailableLabel,*ui->BitcoinPendingLabel, QString::fromUtf8("BTC"),Response);
}
Response = GetBalance("STARX");
if(Response.size() > 0 && Response != "Error"){
DisplayBalance(*ui->STARXBalanceLabel,*ui->STARXAvailableLabel_2,*ui->STARXPendingLabel, QString::fromUtf8("STARX"),Response);
}
break;
case 6:
break;
}
}
void tradingDialog::on_TradingTabWidget_tabBarClicked(int index)
{
//tab was clicked, interrupt the timer and restart after action completed.
this->timer->stop();
ActionsOnSwitch(index);
this->timer->start();
}
QString tradingDialog::sendRequest(QString url){
QString Response = "";
QString Secret = this->SecretKey;
// create custom temporary event loop on stack
QEventLoop eventLoop;
// "quit()" the event-loop, when the network request "finished()"
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
// the HTTP request
QNetworkRequest req = QNetworkRequest(QUrl(url));
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//make this conditional,depending if we are using private api call
req.setRawHeader("apisign",HMAC_SHA512_SIGNER(url,Secret).toStdString().c_str()); //set header for bittrex
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if (reply->error() == QNetworkReply::NoError) {
//success
Response = reply->readAll();
delete reply;
}
else{
//failure
qDebug() << "Failure" <<reply->errorString();
Response = "Error";
//QMessageBox::information(this,"Error",reply->errorString());
delete reply;
}
return Response;
}
QString tradingDialog::BittrexTimeStampToReadable(QString DateTime){
//Seperate Time and date.
int TPos = DateTime.indexOf("T");
int sPos = DateTime.indexOf(".");
QDateTime Date = QDateTime::fromString(DateTime.left(TPos),"yyyy-MM-dd"); //format to convert from
DateTime.remove(sPos,sizeof(DateTime));
DateTime.remove(0,TPos+1);
QDateTime Time = QDateTime::fromString(DateTime.right(TPos),"hh:mm:ss");
//Reconstruct time and date in our own format, one that QDateTime will recognise.
QString DisplayDate = Date.toString("dd/MM/yyyy") + " " + Time.toString("hh:mm:ss A"); //formats to convert to
return DisplayDate;
}
void tradingDialog::CalculateBuyCostLabel(){
double price = ui->BuyBidPriceEdit->text().toDouble();
double Quantity = ui->UnitsInput->text().toDouble();
double cost = ((price * Quantity) + ((price * Quantity / 100) * 0.25));
QString Str = "";
ui->BuyCostLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + Str.number(cost,'i',8) + "</span>");
}
void tradingDialog::CalculateSellCostLabel(){
double price = ui->SellBidPriceEdit->text().toDouble();
double Quantity = ui->UnitsInputSTARX->text().toDouble();
double cost = ((price * Quantity) - ((price * Quantity / 100) * 0.25));
QString Str = "";
ui->SellCostLabel->setText("<span style='font-weight:bold; font-size:12px; color:green'>" + Str.number(cost,'i',8) + "</span>");
}
void tradingDialog::CalculateCSReceiveLabel(){
//calculate amount of currency than can be transferred to bitcoin
QString balance = GetBalance("STARX");
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject BalanceObject = GetResultObjectFromJSONObject(balance);
QJsonObject obj;
double AvailableSTARX = BalanceObject["Available"].toDouble();
double Quantity = ui->CSUnitsInput->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( ((Quantity / x) - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= ((Price * y) - ((Price * y / 100) * 0.25));
} else {
Price = x;
Received += ((Price * (Quantity / x)) - ((Price * (Quantity / x) / 100) * 0.25));
Qty += (Quantity / x);
Quantity -= 0;
break;
}
}
QString ReceiveStr = "";
QString DumpStr = "";
QString TotalStr = "";
if ( Qty < AvailableSTARX )
{
ui->CSReceiveLabel->setText("<span style='font-weight:bold; font-size:12px; color:green'>" + ReceiveStr.number((ui->CSUnitsInput->text().toDouble() - 0.0002),'i',8) + "</span>");
ui->CSDumpLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + DumpStr.number(Price,'i',8) + "</span>");
ui->CSTotalLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + TotalStr.number(Qty,'i',8) + "</span>");
} else {
ReceiveStr = "N/A";
TotalStr = "N/A";
DumpStr = "N/A";
ui->CSReceiveLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + ReceiveStr + "</span>");
ui->CSDumpLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + DumpStr + "</span>");
ui->CSTotalLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + TotalStr + "</span>");
}
}
void tradingDialog::on_UpdateKeys_clicked(bool Save, bool Load)
{
this->ApiKey = ui->ApiKeyInput->text();
this->SecretKey = ui->SecretKeyInput->text();
QJsonDocument jsonResponse = QJsonDocument::fromJson(GetSTARXuntHistory().toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if ( ResponseObject.value("success").toBool() == false){
QMessageBox::information(this,"API Configuration Failed","Api configuration was unsuccesful.");
}else if ( ResponseObject.value("success").toBool() == true && Load){
QMessageBox::information(this,"API Configuration Complete","Your API keys have been loaded and the connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}else if ( ResponseObject.value("success").toBool() == true && Save){
QMessageBox::information(this,"API Configuration Complete","Your API keys have been saved and the connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}else{
QMessageBox::information(this,"API Configuration Complete","Api connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}
}
string tradingDialog::encryptDecrypt(string toEncrypt, string password) {
char * key = new char [password.size()+1];
std::strcpy (key, password.c_str());
key[password.size()] = '\0'; // don't forget the terminating 0
string output = toEncrypt;
for (unsigned int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
void tradingDialog::on_SaveKeys_clicked()
{
bool fSuccess = true;
boost::filesystem::path pathConfigFile = GetDataDir() / "APIcache.txt";
boost::filesystem::ofstream stream (pathConfigFile.string(), ios::out | ios::trunc);
// Qstring to string
string password = ui->PasswordInput->text().toUtf8().constData();
if (password.length() <= 6){
QMessageBox::information(this,"Error !","Your password is too short !");
fSuccess = false;
stream.close();
}
// qstrings to utf8, add to byteArray and convert to const char for stream
string Secret = ui->SecretKeyInput->text().toUtf8().constData();
string Key = ui->ApiKeyInput->text().toUtf8().constData();
string ESecret = "";
string EKey = "";
if (stream.is_open() && fSuccess)
{
ESecret = encryptDecrypt(Secret, password);
EKey = encryptDecrypt(Key, password);
stream << ESecret << '\n';
stream << EKey;
stream.close();
}
if (fSuccess) {
bool Save = true;
on_UpdateKeys_clicked(Save);
}
}
void tradingDialog::on_LoadKeys_clicked()
{
bool fSuccess = true;
boost::filesystem::path pathConfigFile = GetDataDir() / "APIcache.txt";
boost::filesystem::ifstream stream (pathConfigFile.string());
// Qstring to string
string password = ui->PasswordInput->text().toUtf8().constData();
if (password.length() <= 6){
QMessageBox::information(this,"Error !","Your password is too short !");
fSuccess = false;
stream.close();
}
QString DSecret = "";
QString DKey = "";
if (stream.is_open() && fSuccess)
{
int i =0;
for ( std::string line; std::getline(stream,line); )
{
if (i == 0 ){
DSecret = QString::fromUtf8(encryptDecrypt(line, password).c_str());
ui->SecretKeyInput->setText(DSecret);
} else if (i == 1){
DKey = QString::fromUtf8(encryptDecrypt(line, password).c_str());
ui->ApiKeyInput->setText(DKey);
}
i++;
}
stream.close();
}
if (fSuccess) {
bool Save = false;
bool Load = true;
on_UpdateKeys_clicked(Save, Load);
}
}
void tradingDialog::on_GenDepositBTN_clicked()
{
QString response = GetDepositAddress();
QJsonObject ResultObject = GetResultObjectFromJSONObject(response);
ui->DepositAddressLabel->setText(ResultObject["Address"].toString());
}
void tradingDialog::on_Sell_Max_Amount_clicked()
{
//calculate amount of BTC that can be gained from selling STARX available balance
QString responseA = GetBalance("STARX");
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
double AvailableSTARX = ResultObject["Available"].toDouble();
ui->UnitsInputSTARX->setText(str.number(AvailableSTARX,'i',8));
}
void tradingDialog::on_Buy_Max_Amount_clicked()
{
//calculate amount of currency than can be brought with the BTC balance available
QString responseA = GetBalance("BTC");
QString responseB = GetMarketSummary();
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
QJsonObject ResultObj = GetResultObjectFromJSONArray(responseB);
//Get the Bid ask or last value from combo
QString value = ui->BuyBidcomboBox->currentText();
double AvailableBTC = ResultObject["Available"].toDouble();
double CurrentASK = ResultObj[value].toDouble();
double Result = (AvailableBTC / CurrentASK);
double percentofnumber = (Result * 0.0025);
Result = Result - percentofnumber;
ui->UnitsInput->setText(str.number(Result,'i',8));
}
void tradingDialog::on_CS_Max_Amount_clicked()
{
double Quantity = ui->BittrexSTARXLabel->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject obj;
QString str;
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( (Quantity - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= y;
} else {
Price = x;
Received += ((Price * Quantity) - ((Price * Quantity / 100) * 0.25));
Qty += Quantity;
if ((Quantity * x) < 0.00055){
Quantity = (0.00055 / x);
}
break;
}
}
ui->CSUnitsInput->setText(str.number(Received,'i',8));
}
void tradingDialog::on_Withdraw_Max_Amount_clicked()
{
//calculate amount of currency than can be brought with the BTC balance available
QString responseA = GetBalance("STARX");
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);