PluginInstance.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. #include "pch.h"
  2. #include "PluginInstance.h"
  3. #define REDIS_TIMER_ID (1)
  4. CPluginInstance::CPluginInstance()
  5. : m_enable(false)
  6. , m_redis_error_notified(false)
  7. {
  8. }
  9. CPluginInstance::~CPluginInstance()
  10. {
  11. Stop();
  12. }
  13. void CPluginInstance::Release()
  14. {
  15. delete this;
  16. }
  17. MTAPIRES CPluginInstance::Start(IMTServerAPI * server)
  18. {
  19. MTAPIRES ret = MT_RET_OK;
  20. if (!server) return MT_RET_ERR_PARAMS;
  21. m_api = server;
  22. if ((m_config = m_api->PluginCreate()) == nullptr)
  23. return MT_RET_ERR_MEM;
  24. ret = m_api->About(m_info);
  25. if (ret != MT_RET_OK)
  26. m_api->LoggerOut(MTLogOK, L"Server info failed [%d]", ret);
  27. if ((ret = m_api->PluginSubscribe(this)) != MT_RET_OK)
  28. {
  29. m_api->LoggerOut(MTLogAtt, L"Plugin subscribe failed [%d]", ret);
  30. return ret;
  31. }
  32. if (ret = m_api->OrderSubscribe(this) != MT_RET_OK)
  33. {
  34. m_api->LoggerOut(MTLogAtt, L"Order subscribe failed [%d]", ret);
  35. return ret;
  36. }
  37. //if (ret = m_api->DealSubscribe(this) != MT_RET_OK)
  38. //{
  39. // m_api->LoggerOut(MTLogAtt, L"Deal subscribe failed [%d]", ret);
  40. // return ret;
  41. //}
  42. if (ret = m_api->TradeSubscribe(this) != MT_RET_OK)
  43. {
  44. m_api->LoggerOut(MTLogAtt, L"Trade subscribe failed [%d]", ret);
  45. return ret;
  46. }
  47. if ((ret = LoadParam()) != MT_RET_OK)
  48. {
  49. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  50. return ret;
  51. }
  52. return MT_RET_OK;
  53. }
  54. MTAPIRES CPluginInstance::Stop()
  55. {
  56. MTAPIRES ret = MT_RET_OK;
  57. std::lock_guard<decltype(m_lock)> lk(m_lock);
  58. m_followers.clear();
  59. if (m_api == nullptr)
  60. return MT_RET_OK;
  61. if (m_config != nullptr)
  62. {
  63. m_config->Release();
  64. m_config = nullptr;
  65. }
  66. if ((ret = m_api->PluginUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  67. m_api->LoggerOut(MTLogErr, L"Failed to unsubscribe from plugin config updates [%s (%u)]",
  68. SMTFormat::FormatError(ret), ret);
  69. if ((ret = m_api->OrderUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  70. m_api->LoggerOut(MTLogErr, L"Failed to unsubscribe order sink [%s (%u)]",
  71. SMTFormat::FormatError(ret), ret);
  72. //if ((ret = m_api->DealUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  73. // m_api->LoggerOut(MTLogErr, L"failed to unsubscribe deal [%s (%u)]",
  74. // SMTFormat::FormatError(ret), ret);
  75. if ((ret = m_api->TradeUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  76. m_api->LoggerOut(MTLogErr, L"Failed to unsubscribe trade sink [%s (%u)]",
  77. SMTFormat::FormatError(ret), ret);
  78. m_api = nullptr;
  79. m_enable = false;
  80. stop_redis();
  81. if (m_work_thread.joinable())
  82. m_work_thread.join();
  83. return MT_RET_OK;
  84. }
  85. void CPluginInstance::OnPluginUpdate(const IMTConPlugin * plugin)
  86. {
  87. int ret = MT_RET_OK;
  88. if ((ret = LoadParam()) != MT_RET_OK)
  89. {
  90. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  91. }
  92. }
  93. //void CPluginInstance::OnOrderAdd(const IMTOrder * order)
  94. //{
  95. // if (order == nullptr) return;
  96. //
  97. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  98. // if (!m_enable) return;
  99. // if (order->Login() != m_trader) return;
  100. //
  101. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  102. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  103. //}
  104. //void CPluginInstance::OnOrderUpdate(const IMTOrder * order)
  105. //{
  106. // if (order == nullptr) return;
  107. //
  108. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  109. // if (!m_enable) return;
  110. // if (order->Login() != m_trader) return;
  111. //
  112. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  113. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  114. //}
  115. void CPluginInstance::OnOrderDelete(const IMTOrder * order)
  116. {
  117. if (order == nullptr) return;
  118. std::lock_guard<decltype(m_lock)> lk(m_lock);
  119. if (!m_enable) return;
  120. if (order->Login() != m_trader) return;
  121. m_api->LoggerOut(MTLogOK, L"OnOrderDelete, login: %lld, ord: %lld, pos: %lld, state: %d, vol_init: %lld, vol_cur: %lld",
  122. order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  123. if (order->Type() != IMTOrder::OP_BUY
  124. && order->Type() != IMTOrder::OP_SELL)
  125. {
  126. // 不是buy或者sell,不跟,直接退出
  127. return;
  128. }
  129. char order_buf[128];
  130. sprintf(order_buf, "%lld", order->PositionID());
  131. UINT64 position = order->PositionID();
  132. UINT64 order_id = order->Order();
  133. IMTAccount* account = m_api->UserCreateAccount();
  134. IMTOrder* new_order = m_api->OrderCreate();
  135. ScopeGuard guard([account, new_order, this]
  136. {
  137. if (account)
  138. account->Release();
  139. if (new_order)
  140. new_order->Release();
  141. m_redis_client->commit();
  142. });
  143. // 订单在进入filled状态时,也会产生一个order delete回调
  144. if (order->Order() == order->PositionID())
  145. {
  146. // 如果是新建订单,那么写入新纪录
  147. char login_buf[128] = { 0 };
  148. char req_buf[128] = { 0 };
  149. for (auto login : m_followers)
  150. {
  151. if (m_api->UserAccountGet(login, account) != MT_RET_OK)
  152. {
  153. // TODO: 这里失败直接跳过没有做其他处理,下一次进来可能依然会遇到一样的问题
  154. continue;
  155. }
  156. sprintf(login_buf, "%lld", login);
  157. UINT level = (UINT)(account->Balance() / m_step);
  158. UINT volume = round((double)level * order->VolumeCurrent() / 10000) * 100;
  159. UINT volume_ext = round((double)level * order->VolumeCurrentExt() / 10000) * 100;
  160. UINT init_volume = round((double)level * order->VolumeInitial() / 10000) * 100;
  161. UINT init_volume_ext = round((double)level * order->VolumeInitialExt() / 10000) * 100;
  162. UINT64 new_order_id = 0;
  163. m_api->LoggerOut(MTLogOK, L"add order, vol_init: %lld, vol_cur: %lld", init_volume, volume);
  164. char msg[1024] = { 0 };
  165. sprintf(msg, "orig_position=&lld&login=%lld&source_login=1005&symbol=%s&action=200&type=%d&volume=%lld&price_order=%lf",
  166. order->PositionID(), login, ws2s(order->Symbol()).c_str(), order->Type(), init_volume, order->PriceOrder());
  167. m_redis_client->publish("dealer_send", msg, [this, position, login, order_id](cpp_redis::reply& r)
  168. {
  169. // 记录下login order等信息
  170. m_api->LoggerOut(MTLogErr, L"original position #%lld, original order #%lld, login %lld, failed to excute dealer_send",
  171. );
  172. });
  173. // dealer send之后需要另外一边记录request id
  174. // 尚未完成建仓,目前position id不填,仅完成订单后记录
  175. new_order->Clear();
  176. new_order->VolumeInitial(init_volume);
  177. new_order->VolumeCurrent(volume);
  178. new_order->Login(login);
  179. new_order->Symbol(order->Symbol());
  180. new_order->Type(order->Type());
  181. new_order->Digits(order->Digits());
  182. new_order->DigitsCurrency(order->DigitsCurrency());
  183. new_order->ContractSize(order->ContractSize());
  184. new_order->PriceOrder(order->PriceOrder());
  185. new_order->PriceCurrent(order->PriceCurrent());
  186. new_order->StateSet(order->State());
  187. new_order->TimeSetup(order->TimeSetup());
  188. new_order->TimeSetupMsc(order->TimeSetupMsc());
  189. new_order->TimeDone(order->TimeDone());
  190. new_order->TimeDoneMsc(order->TimeDoneMsc());
  191. // --
  192. new_order->PriceSL(order->PriceSL());
  193. new_order->PriceTP(order->PriceTP());
  194. new_order->Comment(order->Comment());
  195. new_order->ActivationFlags(order->ActivationFlags());
  196. new_order->ActivationMode(order->ActivationMode());
  197. new_order->ActivationPrice(order->ActivationPrice());
  198. new_order->ActivationTime(order->ActivationTime());
  199. new_order->PriceTrigger(order->PriceTrigger());
  200. new_order->RateMargin(order->RateMargin()); //
  201. new_order->ReasonSet(order->Reason()); //
  202. new_order->TypeFill(order->TypeFill()); //
  203. new_order->TypeTime(order->TypeTime()); //
  204. MTAPIRES ret = m_api->HistoryAdd(new_order);
  205. if (ret != MT_RET_OK)
  206. {
  207. m_api->LoggerOut(MTLogErr, L"%lld failed to add order, original order #%lld [%d]", login, order->Login(), ret);
  208. }
  209. else
  210. {
  211. new_order_id = new_order->Order();
  212. }
  213. m_api->LoggerOut(MTLogOK, L"%lld add order #%lld, original order #%lld [%d]", login, new_order_id, order->Order());
  214. // TODO: 现在做法是,如果level为0,后面都不管
  215. // 如果跟单失败,那么position id也为0,所以后面也不应该处理
  216. position_context context;
  217. context.level = level;
  218. context.cur_ord = new_order_id;
  219. context.position_id = new_order_id; // 建仓,order id = position id
  220. int direction = 1;
  221. if (order->Type() == IMTOrder::OP_SELL)
  222. direction = -1;
  223. context.volume = direction * order->VolumeInitial();
  224. m_redis_client->hset(order_buf, login_buf, std::string((char*)&context, sizeof(position_context)), [this](cpp_redis::reply& r)
  225. {
  226. if (r.ko())
  227. {
  228. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  229. }
  230. });
  231. // 可以在退出前提交
  232. // m_redis_client->commit();
  233. }
  234. }
  235. else
  236. {
  237. // 如果不是新建订单,先使用position id先检查记录是否存在
  238. char login_buf[128];
  239. for (auto login : m_followers)
  240. {
  241. sprintf(login_buf, "%lld", login);
  242. auto fut = m_redis_client->hget(order_buf, login_buf);
  243. m_redis_client->sync_commit();
  244. auto reply = fut.get();
  245. m_api->LoggerOut(MTLogOK, L"request cache, key %s, field %s", s2ws(order_buf).c_str(), s2ws(login_buf).c_str());
  246. // 如果不存在,忽略
  247. if (reply.ko()) continue;
  248. if (reply.is_null()) continue;
  249. m_api->LoggerOut(MTLogOK, L"get context, login: %lld", login);
  250. // 获取context
  251. position_context context;
  252. memcpy(&context, reply.as_string().c_str(), sizeof(position_context));
  253. // 按建仓时的叙述,如果level或者position为0,亦忽略该记录
  254. if (context.level == 0) continue;
  255. if (context.position_id == 0) continue;
  256. m_api->LoggerOut(MTLogOK, L"get context, order: #%lld, position: #%lld", context.cur_ord, context.position_id);
  257. // 如果存在,则继续操作
  258. UINT volume = round((double)context.level * order->VolumeCurrent() / 10000) * 100;
  259. UINT volume_ext = round((double)context.level * order->VolumeCurrentExt() / 10000) * 100;
  260. UINT init_volume = round((double)context.level * order->VolumeInitial() / 10000) * 100;
  261. UINT init_volume_ext = round((double)context.level * order->VolumeInitialExt() / 10000) * 100;
  262. UINT64 new_order_id = 0;
  263. new_order->Clear();
  264. new_order->VolumeInitial(init_volume);
  265. new_order->VolumeCurrent(volume); // 这里是状态START,如果是状态4的FILLED时,volume current为0
  266. //new_order->VolumeCurrent(init_volume);
  267. new_order->Login(login);
  268. new_order->Symbol(order->Symbol());
  269. new_order->Type(order->Type());
  270. new_order->Digits(order->Digits());
  271. new_order->DigitsCurrency(order->DigitsCurrency());
  272. new_order->ContractSize(order->ContractSize());
  273. new_order->PriceOrder(order->PriceOrder());
  274. new_order->PriceCurrent(order->PriceCurrent());
  275. new_order->StateSet(order->State());
  276. new_order->TimeSetup(order->TimeSetup());
  277. new_order->TimeSetupMsc(order->TimeSetupMsc());
  278. new_order->TimeDone(order->TimeDone());
  279. new_order->TimeDoneMsc(order->TimeDoneMsc());
  280. new_order->PositionID(context.position_id);
  281. new_order->PriceSL(order->PriceSL());
  282. new_order->PriceTP(order->PriceTP());
  283. new_order->Comment(order->Comment());
  284. new_order->ActivationFlags(order->ActivationFlags());
  285. new_order->ActivationMode(order->ActivationMode());
  286. new_order->ActivationPrice(order->ActivationPrice());
  287. new_order->ActivationTime(order->ActivationTime());
  288. new_order->PriceTrigger(order->PriceTrigger());
  289. new_order->RateMargin(order->RateMargin()); //
  290. new_order->ReasonSet(order->Reason()); //
  291. new_order->TypeFill(order->TypeFill()); //
  292. new_order->TypeTime(order->TypeTime()); //
  293. MTAPIRES ret = m_api->HistoryAdd(new_order);
  294. if (ret != MT_RET_OK)
  295. {
  296. m_api->LoggerOut(MTLogErr, L"%lld failed to add order, original order #%lld [%d]", login, order->Order(), ret);
  297. // FIXME: 如果做单失败该怎么办
  298. continue;
  299. }
  300. new_order_id = new_order->Order();
  301. m_api->LoggerOut(MTLogOK, L"%lld add order #%lld, original order #%lld", login, new_order_id, order->Order());
  302. // 完成之后,写入新纪录
  303. context.cur_ord = new_order_id;
  304. int direction = 1;
  305. if (order->Type() == IMTOrder::OP_SELL)
  306. direction = -1;
  307. context.volume += direction * order->VolumeInitial();
  308. m_api->LoggerOut(MTLogOK, L"write cache, key %s, field %s", s2ws(order_buf).c_str(), s2ws(login_buf).c_str());
  309. m_redis_client->hset(order_buf, login_buf, std::string((char*)&context, sizeof(position_context)), [this](cpp_redis::reply& r)
  310. {
  311. if (r.ko())
  312. {
  313. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  314. }
  315. });
  316. // 下一次get会调用commit
  317. }
  318. }
  319. }
  320. //void CPluginInstance::OnOrderClean(const UINT64 login)
  321. //{
  322. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  323. // if (!m_enable) return;
  324. // if (login != m_trader) return;
  325. //
  326. // m_api->LoggerOut(MTLogOK, L"OnOrderClean, Login: %d", login);
  327. //}
  328. //void CPluginInstance::OnDealAdd(const IMTDeal * deal)
  329. //{
  330. // if (deal == nullptr) return;
  331. //
  332. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  333. // if (!m_enable) return;
  334. // if (deal->Login() != m_trader) return;
  335. //
  336. // m_api->LoggerOut(MTLogOK, L"OnDealAdd, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  337. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  338. //}
  339. //void CPluginInstance::OnDealUpdate(const IMTDeal * deal)
  340. //{
  341. // if (deal == nullptr) return;
  342. //
  343. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  344. // if (!m_enable) return;
  345. // if (deal->Login() != m_trader) return;
  346. //
  347. // m_api->LoggerOut(MTLogOK, L"OnDealUpdate, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  348. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  349. //}
  350. //void CPluginInstance::OnDealDelete(const IMTDeal * deal)
  351. //{
  352. // if (deal == nullptr) return;
  353. //
  354. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  355. // if (!m_enable) return;
  356. // if (deal->Login() != m_trader) return;
  357. //
  358. // m_api->LoggerOut(MTLogOK, L"OnDealDelete, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  359. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  360. //}
  361. //void CPluginInstance::OnDealClean(const UINT64 login)
  362. //{
  363. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  364. // if (!m_enable) return;
  365. // if (login != m_trader) return;
  366. //
  367. // m_api->LoggerOut(MTLogOK, L"OndealClean, Login: %d", login);
  368. //}
  369. //void CPluginInstance::OnDealPerform(const IMTDeal * deal, IMTAccount * account, IMTPosition * position)
  370. //{
  371. // // position为nullptr时,说明该deal不是由交易本身触发
  372. // // account是deal完成后的用户状况
  373. // // position是交易完成后的持仓状况
  374. // // 对于deal是关闭一个持仓的情况,该position的volume会是0
  375. // if (position == nullptr
  376. // || deal == nullptr
  377. // || account == nullptr)
  378. // return;
  379. //
  380. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  381. // if (!m_enable) return;
  382. // if (deal->Login() != m_trader) return;
  383. //
  384. // //m_api->LoggerOut(MTLogOK, L"OnDealPerform, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  385. // // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  386. //
  387. // // FIXME: 需要检查现在的deal是否和之前的order对应。如果没有记录到,则没法根本无法正常跟单以及平仓
  388. // char order_buf[128];
  389. // sprintf(order_buf, "%lld", deal->PositionID());
  390. // IMTDeal* new_deal = m_api->DealCreate();
  391. //
  392. // std::vector<std::string>* fields = nullptr;
  393. //
  394. // ScopeGuard guard([new_deal, &fields, this]
  395. // {
  396. // new_deal->Release();
  397. // if (fields)
  398. // {
  399. // fields->clear();
  400. // delete fields;
  401. // fields = nullptr;
  402. // }
  403. //
  404. // // 退出前调用commit
  405. // m_redis_client->commit();
  406. // });
  407. //
  408. // char login_buf[128];
  409. // for (auto login : m_followers)
  410. // {
  411. // ScopeGuard g([position, &fields, this, login, login_buf]()
  412. // {
  413. // if (position->Volume() == 0)
  414. // {
  415. // if (fields == nullptr)
  416. // fields = new(std::vector<std::string>);
  417. //
  418. // m_api->LoggerOut(MTLogOK, L"add field %lld to be delete", login);
  419. // fields->push_back(login_buf);
  420. // }
  421. // });
  422. //
  423. // sprintf(login_buf, "%lld", login);
  424. // auto fut = m_redis_client->hget(order_buf, login_buf);
  425. // m_redis_client->sync_commit();
  426. // auto reply = fut.get();
  427. //
  428. // m_api->LoggerOut(MTLogOK, L"%lld add deal, original deal #%lld", login, deal->Deal());
  429. //
  430. // // 如果不存在,忽略
  431. // if (reply.ko()) continue;
  432. // if (reply.is_null()) continue;
  433. //
  434. // // 获取context
  435. // position_context context;
  436. // memcpy(&context, reply.as_string().c_str(), sizeof(position_context));
  437. //
  438. // // 按建仓时的叙述,如果level或者position为0,亦忽略该记录
  439. // if (context.level == 0) continue;
  440. // if (context.position_id == 0) continue;
  441. //
  442. // uint64_t volume = context.level * deal->Volume() / 100;
  443. // uint64_t volume_ext = context.level * deal->VolumeExt() / 100;
  444. // uint64_t volume_closed = context.level * deal->VolumeClosed() / 100;
  445. // uint64_t volume_closed_ext = context.level * deal->VolumeClosed() / 100;
  446. //
  447. // double prop = (double)volume / deal->Volume();
  448. // double profit = deal->Profit() * prop;
  449. // double commission = deal->Commission() * prop;
  450. // double storage = deal->Storage() * prop;
  451. // double raw_profit = deal->ProfitRaw() * prop;
  452. //
  453. // m_api->LoggerOut(MTLogOK, L"add new deal, volume %lld, volume closed %lld, order #%lld, position #%lld", volume, volume_closed, context.cur_ord, context.position_id);
  454. //
  455. // new_deal->Clear();
  456. // new_deal->Assign(deal);
  457. //
  458. // new_deal->Login(login);
  459. // new_deal->DealSet(0);
  460. // new_deal->Volume(volume);
  461. // new_deal->VolumeExt(volume_ext);
  462. // new_deal->VolumeClosed(volume_closed);
  463. // new_deal->VolumeClosedExt(volume_closed_ext);
  464. // new_deal->ProfitRaw(raw_profit);
  465. // new_deal->Profit(profit);
  466. // new_deal->Commission(commission);
  467. // new_deal->Storage(storage);
  468. // new_deal->Order(context.cur_ord);
  469. // new_deal->PositionID(context.position_id);
  470. //
  471. // MTAPIRES ret = m_api->DealAdd(new_deal);
  472. // if (ret != MT_RET_OK)
  473. // {
  474. // // TODO: 有没有更多的错误处理?
  475. // m_api->LoggerOut(MTLogErr, L"%lld cannot add deal [%d] to order #%lld, original deal: #%lld", login, ret, context.cur_ord, deal->Deal());
  476. // continue;
  477. // }
  478. //
  479. // m_api->LoggerOut(MTLogOK, L"add deal #%lld, original deal #%lld", new_deal->Deal(), deal->Deal());
  480. //
  481. // m_redis_client->publish("mt5_balance_fix", login_buf, [this](cpp_redis::reply r)
  482. // {
  483. // if (r.ko())
  484. // {
  485. // m_api->LoggerOut(MTLogErr, L"redis publish: %s", r.error().c_str());
  486. // }
  487. // });
  488. // // commit 在退出前完成
  489. // }
  490. //
  491. // m_api->LoggerOut(MTLogOK, L"deal #%lld, position #%lld, volume %lld", deal->Deal(), position->Position(), position->Volume());
  492. // if (position->Volume() == 0)
  493. // {
  494. // // 如果平仓,则删除hash值
  495. // if (position->Volume() == 0 && fields != nullptr)
  496. // {
  497. // m_redis_client->hdel(order_buf, *fields, [this](cpp_redis::reply& r)
  498. // {
  499. // if (r.ko())
  500. // {
  501. // // TODO 错误处理
  502. // try
  503. // {
  504. // m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  505. // }
  506. // catch (...)
  507. // {
  508. // }
  509. // }
  510. // });
  511. // }
  512. //
  513. // // TODO 当position中的volume为0时,持仓被彻底平调,被跟订单是否也该检查
  514. // }
  515. //}
  516. void CPluginInstance::OnTradeRequestAdd(const IMTRequest * request, const IMTConGroup * group, const IMTConSymbol * symbol, const IMTPosition * position, const IMTOrder * order)
  517. {
  518. if (request == nullptr
  519. || group == nullptr
  520. || symbol == nullptr)
  521. {
  522. return;
  523. }
  524. }
  525. MTAPIRES CPluginInstance::LoadParam()
  526. {
  527. MTAPIRES res = MT_RET_OK;
  528. IMTConParam* param = NULL;
  529. CMTStr128 tmp;
  530. if (!m_api || !m_config) return MT_RET_ERR_PARAMS;
  531. if ((res = m_api->PluginCurrent(m_config)) != MT_RET_OK)
  532. {
  533. m_api->LoggerOut(MTLogErr, L"failed to get current plugin configuration [%s (%u)]",
  534. SMTFormat::FormatError(res), res);
  535. return res;
  536. }
  537. if ((param = m_api->PluginParamCreate()) == NULL)
  538. {
  539. m_api->LoggerOut(MTLogErr, L"failed to create plugin parameter object");
  540. return MT_RET_ERR_MEM;
  541. }
  542. ScopeGuard param_release([param]()
  543. {
  544. param->Release();
  545. });
  546. std::lock_guard<decltype(m_lock)> lk(m_lock);
  547. //m_api->LoggerOut(MTLogOK, L"Load redis server params");
  548. if ((res = m_config->ParameterGet(L"Redis Server", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  549. {
  550. return(MT_RET_ERR_PARAMS);
  551. }
  552. std::string redis_server = ws2s(param->ValueString());
  553. if ((res = m_config->ParameterGet(L"Redis Port", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  554. {
  555. return(MT_RET_ERR_PARAMS);
  556. }
  557. int redis_port = param->ValueInt();
  558. //if ((res = m_config->ParameterGet(L"Redis User", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  559. //{
  560. // return(MT_RET_ERR_PARAMS);
  561. //}
  562. //std::string redis_user = ws2s(param->ValueString());
  563. if ((res = m_config->ParameterGet(L"Redis Password", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  564. {
  565. return(MT_RET_ERR_PARAMS);
  566. }
  567. std::string redis_password = ws2s(param->ValueString());
  568. if (m_redis_server != redis_server
  569. || m_redis_port != redis_port
  570. //|| m_redis_user != redis_user
  571. || m_redis_password != redis_password)
  572. {
  573. m_redis_server = redis_server;
  574. m_redis_port = redis_port;
  575. //m_redis_user = redis_user;
  576. m_redis_password = redis_password;
  577. stop_redis();
  578. if (start_redis())
  579. {
  580. if (!m_work_thread.joinable())
  581. {
  582. m_work_thread = std::thread(&CPluginInstance::keep_alive, this);
  583. }
  584. }
  585. else
  586. {
  587. m_api->LoggerOut(MTLogErr, L"failed to connect to redis server");
  588. return MT_RET_ERR_CONNECTION;
  589. }
  590. }
  591. //m_api->LoggerOut(MTLogOK, L"Load trade params");
  592. if ((res = m_config->ParameterGet(L"Trader", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  593. {
  594. return(MT_RET_ERR_PARAMS);
  595. }
  596. m_trader = param->ValueInt();
  597. if ((res = m_config->ParameterGet(L"Step", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  598. {
  599. return(MT_RET_ERR_PARAMS);
  600. }
  601. m_step = param->ValueInt();
  602. if ((res = m_config->ParameterGet(L"Tolerance", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  603. {
  604. return(MT_RET_ERR_PARAMS);
  605. }
  606. m_tolerance = param->ValueInt();
  607. if ((res = m_config->ParameterGet(L"Groups", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  608. {
  609. return(MT_RET_ERR_PARAMS);
  610. }
  611. wcsncpy(m_groups, param->ValueString(), 1024);
  612. //if ((res = m_config->ParameterGet(L"Logins", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  613. //{
  614. // return(MT_RET_ERR_PARAMS);
  615. //}
  616. //m_logins = param->ValueString();
  617. res = LoadLogins();
  618. if (res != MT_RET_OK)
  619. {
  620. m_api->LoggerOut(MTLogErr, L"failed to load clients [%d]", res);
  621. return res;
  622. }
  623. //m_api->LoggerOut(MTLogOK, L"Load param success");
  624. m_enable = true;
  625. return MT_RET_OK;
  626. }
  627. MTAPIRES CPluginInstance::LoadLogins()
  628. {
  629. m_followers.clear();
  630. IMTConGroup* group = m_api->GroupCreate();
  631. ScopeGuard group_guard([&]()
  632. {
  633. group->Release();
  634. });
  635. if (group == nullptr) return MT_RET_ERR_MEM;
  636. UINT total = m_api->GroupTotal();
  637. MTAPIRES ret = MT_RET_OK;
  638. std::vector<std::wstring> groups;
  639. for (int i = 0; i < total; i++)
  640. {
  641. ret = m_api->GroupNext(i, group);
  642. if (ret != MT_RET_OK) break;
  643. if (CheckGroup(m_groups, group->Group()) == FALSE) continue;
  644. m_api->LoggerOut(MTLogOK, L"group %s matched config", group->Group());
  645. groups.push_back(group->Group());
  646. }
  647. for (auto& group : groups)
  648. {
  649. UINT64* logins = nullptr;
  650. UINT total_users = 0;
  651. ret = m_api->UserLogins(group.c_str(), logins, total_users);
  652. m_api->LoggerOut(MTLogOK, L"add group %s, total users: %d", group.c_str(), total_users);
  653. if (ret == MT_RET_OK && logins != nullptr)
  654. {
  655. for (int i = 0; i < total_users; ++i)
  656. {
  657. m_api->LoggerOut(MTLogOK, L"add %d to list", logins[i]);
  658. m_followers.push_back(logins[i]);
  659. }
  660. }
  661. if (logins)
  662. {
  663. m_api->Free(logins);
  664. }
  665. }
  666. return ret;
  667. }
  668. bool CPluginInstance::start_redis()
  669. {
  670. try
  671. {
  672. m_redis_error_notified = false;
  673. if (m_redis_client)
  674. {
  675. if (m_redis_client->is_connected())
  676. return true;
  677. }
  678. m_redis_client.reset(new cpp_redis::client);
  679. m_redis_client->connect
  680. (
  681. m_redis_server,
  682. m_redis_port,
  683. [this](const std::string& host, std::size_t port, cpp_redis::connect_state status)
  684. {
  685. if (status == cpp_redis::connect_state::ok)
  686. {
  687. m_api->LoggerOut(MTLogOK, L"redis server connected");
  688. }
  689. },
  690. 500,
  691. 10000000,
  692. 1000
  693. );
  694. if (m_redis_password != "")
  695. {
  696. auto fut = m_redis_client->auth(m_redis_password);
  697. m_redis_client->sync_commit();
  698. auto reply = fut.get();
  699. if (reply.is_error())
  700. {
  701. m_api->LoggerOut(MTLogErr, L"connect: authentication failed");
  702. return false;
  703. }
  704. }
  705. }
  706. catch (tacopie::tacopie_error& e)
  707. {
  708. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  709. return false;
  710. }
  711. catch (std::exception& e)
  712. {
  713. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  714. return false;
  715. }
  716. catch (...)
  717. {
  718. m_api->LoggerOut(MTLogErr, L"failed to connect to server");
  719. return false;
  720. }
  721. return true;
  722. }
  723. void CPluginInstance::stop_redis()
  724. {
  725. try
  726. {
  727. if (m_redis_client)
  728. {
  729. // 使用sync commit保证操作全部提交
  730. m_redis_client->sync_commit();
  731. m_redis_client->disconnect();
  732. m_redis_client.reset();
  733. }
  734. }
  735. catch (tacopie::tacopie_error& e)
  736. {
  737. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  738. }
  739. catch (std::exception& e)
  740. {
  741. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  742. }
  743. catch (...)
  744. {
  745. m_api->LoggerOut(MTLogErr, L"stop redis: unknown error");
  746. }
  747. }
  748. void CPluginInstance::keep_alive()
  749. {
  750. using namespace std::chrono_literals;
  751. int counter = 500;
  752. while (m_enable)
  753. {
  754. if (counter-- <= 0)
  755. {
  756. counter = 500;
  757. std::lock_guard<decltype(m_lock)> lk(m_lock);
  758. if (m_redis_client)
  759. {
  760. if (m_redis_client->is_connected())
  761. {
  762. m_redis_client->ping([this](cpp_redis::reply& r)
  763. {
  764. if (r.ko())
  765. {
  766. m_redis_error_notified = true;
  767. if (!m_redis_error_notified)
  768. {
  769. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  770. }
  771. }
  772. });
  773. }
  774. else
  775. {
  776. m_redis_error_notified = true;
  777. if (!m_redis_error_notified)
  778. {
  779. m_api->LoggerOut(MTLogErr, L"redis server not connected");
  780. }
  781. stop_redis();
  782. start_redis();
  783. }
  784. }
  785. }
  786. std::this_thread::sleep_for(16ms);
  787. }
  788. }